tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
#[allow(clippy::wildcard_imports)]
use super::*;
use crate::relationships::RelationKind;
use crate::time_tracking::{TimeEntry, TimeEntryExtensions};

#[test]
fn status_helpers() {
    let s = Status::new("in progress");
    assert!(s.is("in progress"));
    assert!(!s.is("in_progress"));
    assert_eq!(s.display(), "in progress");
    assert_eq!(Status::default(), Status::new("todo"));
}

#[test]
fn status_survives_unknown_column_name() {
    let parsed: Status = serde_yaml::from_str("\"renamed-column\"").unwrap();
    assert_eq!(parsed.display(), "renamed-column");
}

#[test]
fn priority_roundtrips_lowercase_and_parses_case_insensitively() {
    // An unset priority round-trips as the empty string and is *not* the
    // default: `priority: ''` says "no priority", which is a different
    // statement from the `medium` a missing field yields.
    let undefined: Priority = "".parse().unwrap();
    assert!(undefined.is_undefined());
    assert_eq!(undefined.to_string(), "", "and it writes back as ''");
    assert!(
        !Priority::default().is_undefined(),
        "the default is medium, not unset"
    );
    assert!(
        !Priority::Other("urgent".into()).is_undefined(),
        "only the empty string is unset"
    );
    assert_eq!("low".parse::<Priority>().unwrap(), Priority::Low);
    assert_eq!("HIGH".parse::<Priority>().unwrap(), Priority::High);
    assert_eq!(Priority::default(), Priority::Medium);
    assert_eq!(Priority::Low.to_string(), "low");
}

#[test]
fn unknown_priority_is_preserved_not_normalized() {
    let urgent: Priority = serde_yaml::from_str("\"urgent\"").unwrap();
    assert_eq!(urgent.to_string(), "urgent");
    let yaml = serde_yaml::to_string(&urgent).unwrap();
    assert!(yaml.contains("urgent"));
}

#[test]
fn issue_roundtrip_preserves_every_field_including_number_and_body() {
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 7,
        title: "Add documentation for the feature".into(),
        status: Status::new("todo"),
        labels: vec!["docs".into(), "onboarding".into()],
        priority: Priority::High,
        assignee: Some("alice".into()),
        estimate: Some("2".into()),
        commit: Some("abc123".into()),
        gitlab_id: Some("gl-9".into()),
        linear_id: Some("LIN-9".into()),
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-05-10".into(),
        type_: None,
        updated: "2026-05-10".into(),
        filename: String::new(),
        body: "Describe the issue here.\n\n![diagram](./assets/diagram.png)".into(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let contents = issue.to_file_contents();
    let parsed = Issue::parse(&contents).unwrap();
    assert_eq!(parsed, issue);
    issue.body.clear();
    assert_ne!(parsed, issue);
}

#[test]
fn typed_relationships_round_trip_preserves_entries_verbatim() {
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 9,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![
            Relationship::new(9, 12, RelationKind::Blocks, "Twelve"),
            Relationship::new(9, 47, RelationKind::Related, "Forty seven"),
        ],
        related_issues: vec![],
        history: History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec!["docs/x.md".into(), "specs/y/spec.md".into()],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: String::new(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let contents = issue.to_file_contents();
    let parsed = Issue::parse(&contents).unwrap();
    assert_eq!(parsed.relationships.len(), 2);
    assert_eq!(parsed.relationships[0].kind, RelationKind::Blocks);
    assert_eq!(parsed.relationships[0].display, "blocks #12 Twelve");
    // The stable id survives the round trip, which is what makes an edit
    // addressable after a rewrite.
    assert_eq!(parsed.relationships[0].id, issue.relationships[0].id);
    assert_eq!(parsed.files, ["docs/x.md", "specs/y/spec.md"]);
    // Byte-stable through read -> write -> read.
    assert_eq!(parsed.to_file_contents(), contents);
    // A stored edge never carries the input-only `blocked_by` kind.
    assert!(
        parsed
            .relationships
            .iter()
            .all(|r| r.kind != RelationKind::BlockedBy)
    );
    issue.relationships.clear();
}

#[test]
fn related_issues_round_trip_verbatim_and_omit_when_empty() {
    // The key is modelled, so it is parsed into the field (never captured as
    // unknown) and re-emitted exactly once, in struct position. Entries are
    // byte-verbatim: a path must not be re-quoted or re-ordered.
    let original = "---\nnumber: 3\ntitle: T\nstatus: todo\nlabels: []\n\
priority: medium\nfiles: []\nrelated_issues:\n- '42'\n\
- '../other/2026-01-01-x.md'\n- 'https://gitlab.com/foo/bar#7'\n\
created: 2026-01-01\nupdated: 2026-01-01\n---\n\nbody\n";
    let issue = Issue::parse(original).unwrap();
    assert_eq!(
        issue.related_issues,
        vec![
            "42".to_string(),
            "../other/2026-01-01-x.md".to_string(),
            "https://gitlab.com/foo/bar#7".to_string(),
        ]
    );
    assert!(
        capture_extra_frontmatter(&issue.frontmatter()).is_empty(),
        "a modelled key must not also be captured as unknown"
    );
    let rendered = issue.to_file_contents();
    assert_eq!(
        rendered.matches("\nrelated_issues:").count(),
        1,
        "written exactly once:\n{rendered}"
    );
    assert_eq!(Issue::parse(&rendered).unwrap(), issue);
    // Empty is omitted, so a file without the key round-trips byte-identically.
    let mut empty = issue.clone();
    empty.related_issues.clear();
    assert!(!empty.frontmatter().contains("related_issues"));
}

#[test]
fn type_round_trips_verbatim_and_omits_when_absent() {
    let original = "---\nnumber: 3\ntitle: T\nstatus: todo\nlabels: []\n\
type: bug\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nbody\n";
    let issue = Issue::parse(original).unwrap();
    assert_eq!(issue.type_.as_deref(), Some("bug"));
    assert!(
        capture_extra_frontmatter(&issue.frontmatter()).is_empty(),
        "a modelled key must not also be captured as unknown"
    );
    let rendered = issue.to_file_contents();
    assert_eq!(rendered.matches("\ntype:").count(), 1, "{rendered}");
    assert_eq!(Issue::parse(&rendered).unwrap(), issue);
    // Absent is omitted.
    let mut none = issue.clone();
    none.type_ = None;
    assert!(!none.frontmatter().contains("type:"));
}

#[test]
fn empty_relationships_is_omitted_while_files_keeps_its_inline_empty_list() {
    // The empty-list shape is decided once and pinned here: the typed field
    // is **omitted** when empty, because it is new and a meaningless
    // `relationships: []` would otherwise appear on every issue file. The
    // pre-existing `files: []` convention is untouched.
    let issue = Issue {
        projects: None,
        id: None,
        number: 4,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        history: History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: String::new(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let fm = issue.frontmatter();
    assert!(!fm.contains("relationships"), "got:\n{fm}");
    assert!(fm.contains("files: []"), "got:\n{fm}");
}

#[test]
fn an_unknown_relation_kind_in_frontmatter_is_rejected() {
    // The old field tolerated any string, so a non-numeric entry parsed
    // happily. The typed vocabulary is closed, so an unknown kind is a
    // parse error rather than a coerced default (C-001).
    let yaml = "\
number: 1
title: T
status: todo
relationships:
- id: rel_1
  from: 1
  to: 2
  kind: depends_on
created: '2026-01-01'
updated: '2026-01-01'
";
    let err = serde_yaml::from_str::<Issue>(yaml).unwrap_err();
    assert!(
        err.to_string().contains("depends_on"),
        "the unknown kind is named: {err}"
    );
}

#[test]
fn a_legacy_links_key_parses_but_sets_the_retired_flag() {
    // Tolerant on read so existing repositories still load, and flagged so
    // the service can report it. The value is never read as typed data.
    let yaml = "\
number: 1
title: T
status: todo
links:
- '12'
- 47
created: '2026-01-01'
updated: '2026-01-01'
";
    let issue = Issue::parse(&format!("---\n{yaml}---\n\nbody\n")).unwrap();
    assert!(issue.has_retired_links_key);
    assert!(
        issue.relationships.is_empty(),
        "C-001: legacy values are never reinterpreted as typed edges"
    );
}

#[test]
fn missing_dates_default_to_today() {
    let yaml = "number: 2\ntitle: Hi\nstatus: todo\n";
    let issue: Issue = serde_yaml::from_str(yaml).unwrap();
    assert_eq!(issue.created, today());
    assert_eq!(issue.updated, today());
}

#[test]
fn body_is_preserved_verbatim() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 1,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-02".into(),
        type_: None,
        updated: "2026-01-02".into(),
        filename: String::new(),
        body: "line one\n\nline two\n```\ncode\n```".into(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let contents = issue.to_file_contents();
    let parsed = Issue::parse(&contents).unwrap();
    assert_eq!(parsed.body, issue.body);
}

#[test]
fn assignee_at_prefix_is_stripped_on_read_and_restored_on_write() {
    let yaml = "number: 3\ntitle: T\nstatus: todo\nassignee: \"@alice\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n";
    let issue: Issue = serde_yaml::from_str(yaml).unwrap();
    assert_eq!(issue.assignee.as_deref(), Some("alice"));
    let rerendered = issue.frontmatter();
    assert!(
        rerendered.contains("assignee: \"@alice\"") || rerendered.contains("assignee: '@alice'")
    );
}

#[test]
fn full_identity_assignee_round_trips_verbatim() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 5,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: Some("Herbert Maschke <thyseus@pm.me>".into()),
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: String::new(),
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let fm = issue.frontmatter();
    assert!(
        fm.contains("Herbert Maschke <thyseus@pm.me>"),
        "identity must be stored verbatim, got:\n{fm}"
    );
    assert!(
        !fm.contains("@Herbert Maschke"),
        "identity must not be @-prefixed, got:\n{fm}"
    );
    let parsed = Issue::parse(&issue.to_file_contents()).unwrap();
    assert_eq!(parsed, issue);
}

#[test]
fn bare_handle_assignee_writes_legacy_at_prefix_and_reads_back_bare() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 6,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: Some("alice".into()),
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: String::new(),
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let fm = issue.frontmatter();
    assert!(
        fm.contains("assignee: \"@alice\"") || fm.contains("assignee: '@alice'"),
        "legacy @-prefixed bytes expected, got:\n{fm}"
    );
    let parsed = Issue::parse(&issue.to_file_contents()).unwrap();
    assert_eq!(parsed.assignee.as_deref(), Some("alice"));
}

#[test]
fn assignee_read_accepts_both_bare_and_at_prefixed_handles() {
    let legacy = "number: 7\ntitle: T\nstatus: todo\nassignee: \"@alice\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n";
    let bare = "number: 7\ntitle: T\nstatus: todo\nassignee: \"alice\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n";
    let from_legacy: Issue = serde_yaml::from_str(legacy).unwrap();
    let from_bare: Issue = serde_yaml::from_str(bare).unwrap();
    assert_eq!(from_legacy.assignee.as_deref(), Some("alice"));
    assert_eq!(from_bare.assignee.as_deref(), Some("alice"));
}

#[test]
fn angle_bracket_identity_without_name_written_verbatim() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 8,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: Some("<thyseus@pm.me>".into()),
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: String::new(),
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let fm = issue.frontmatter();
    assert!(
        fm.contains("<thyseus@pm.me>"),
        "identity-like value must be verbatim, got:\n{fm}"
    );
    assert!(
        !fm.contains("@<thyseus"),
        "identity-like value must not be @-prefixed, got:\n{fm}"
    );
}

#[test]
fn all_none_frontmatter_only_contains_required_keys() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 4,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: String::new(),
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let fm = issue.frontmatter();
    assert!(fm.contains("number:"));
    assert!(fm.contains("title:"));
    assert!(fm.contains("status:"));
    assert!(fm.contains("labels:"));
    assert!(fm.contains("priority:"));
    assert!(fm.contains("created:"));
    assert!(fm.contains("updated:"));
    for key in ["assignee", "estimate", "commit", "gitlab_id", "linear_id"] {
        assert!(!fm.contains(key), "frontmatter must omit {key}, got:\n{fm}");
    }
}

#[test]
fn filename_stem_matches_contract_format() {
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 1,
        title: "Fix !Login crash?".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-05-10".into(),
        type_: None,
        updated: "2026-05-10".into(),
        filename: String::new(),
        body: String::new(),
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    assert_eq!(issue.filename_stem(), "2026-05-10-fix-login-crash");
    // With an id, the id follows the date (#1587).
    issue.id = Some("A1B2C3D4".into());
    assert_eq!(issue.filename_stem(), "2026-05-10-A1B2C3D4-fix-login-crash");
}

#[test]
fn bump_updated_stamps_today() {
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 1,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2020-01-01".into(),
        type_: None,
        updated: "2020-01-01".into(),
        filename: String::new(),
        body: String::new(),
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    issue.bump_updated();
    assert_eq!(issue.updated, today());
    assert_ne!(issue.updated, "2020-01-01");
}

#[test]
fn parse_rejects_malformed_frontmatter() {
    assert!(Issue::parse("no delimiter\n").is_err());
    assert!(Issue::parse("---\na: 1\n").is_err()); // unterminated
    assert!(Issue::parse("---\nbroken: [").is_err()); // bad yaml, unterminated
}

#[test]
fn a_crlf_issue_file_parses() {
    // #1299: a file checked out with `core.autocrlf=true` must not be reported
    // as unparseable, and its History section must be recognised as a section
    // rather than left in the body where the next write appends a second one.
    let crlf = "---\r\nnumber: 7\r\ntitle: T\r\nstatus: todo\r\ncreated: 2026-01-01\r\nupdated: 2026-01-01\r\n---\r\n\r\n## History\r\n\r\n- 2026-01-01T00:00:00Z - alice - relationship_added\r\n";
    let issue = Issue::parse(crlf).unwrap();
    assert_eq!(issue.number, 7);
    assert_eq!(issue.title, "T");
    assert_eq!(issue.history.len(), 1, "the CRLF History section is parsed");
    assert!(issue.body.trim().is_empty(), "body: {:?}", issue.body);
}

#[test]
fn an_lf_issue_is_unaffected_by_the_crlf_tolerance() {
    let lf = "---\nnumber: 7\ntitle: T\nstatus: todo\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nbody\n";
    let issue = Issue::parse(lf).unwrap();
    assert_eq!(issue.number, 7);
    assert_eq!(issue.body.trim(), "body");
}

#[test]
fn today_is_an_iso_calendar_date() {
    let t = today();
    assert_eq!(t.len(), 10);
    let parts: Vec<&str> = t.split('-').collect();
    assert_eq!(parts.len(), 3);
    assert_eq!(parts[0].len(), 4);
    assert_eq!(parts[1].len(), 2);
    assert_eq!(parts[2].len(), 2);
}

#[test]
fn civil_from_days_epoch_is_1970_01_01() {
    assert_eq!(civil_from_days(0), (1970, 1, 1));
}

// ------------------------------------------------------------------
// WP01 — Comment data model & body lifecycle
// ------------------------------------------------------------------

fn issue(body: &str) -> Issue {
    Issue {
        projects: None,
        id: None,
        number: 1,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        history: History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: body.to_string(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    }
}

// --- T001: parse body → description + comments ---

#[test]
fn comments_empty_when_no_section() {
    let i = issue("Some description text.\n");
    assert_eq!(i.description(), "Some description text.");
    assert_eq!(i.comments(), [] as [crate::model::Comment; 0]);
}

#[test]
fn comments_parsed_from_section() {
    let i = issue(
        "Hello\n\n## Comments\n\n\
             ### @alice (2026-09-13)\n\n\
             First comment.\n\n\
             ### bob (2026-09-14)\n\n\
             Second comment.\n",
    );
    assert_eq!(i.description(), "Hello");
    let cs = i.comments();
    assert_eq!(cs.len(), 2);
    assert_eq!(cs[0].author, "@alice");
    assert_eq!(cs[0].date, "2026-09-13");
    assert_eq!(cs[1].author, "bob");
    assert_eq!(cs[1].date, "2026-09-14");
}

#[test]
fn code_fence_boundary_not_treated_as_boundary() {
    let body = "Description\n\n\
             ```\n\
             ## Comments\n\
             ```\n\n\
             ## Comments\n\n\
             ### eve (2026-10-01)\n\n\
             real comment\n";
    let i = issue(body);
    let cs = i.comments();
    assert_eq!(cs.len(), 1);
    assert_eq!(cs[0].author, "eve");
    assert_eq!(cs[0].date, "2026-10-01");
    assert_eq!(cs[0].text, "\nreal comment");
    assert!(
        i.description().contains("## Comments"),
        "code-blocked heading must be in description"
    );
}

#[test]
fn blank_lines_preserved_in_comment_text() {
    let i = issue(
        "## Comments\n\n\
             ### @alice (2026-09-13)\n\n\
             line one\n\nline two\n\n\n\
             line three\n",
    );
    let cs = i.comments();
    assert_eq!(cs.len(), 1);
    let text = &cs[0].text;
    assert!(
        text.contains("\nline two"),
        "internal blank lines must be preserved: got {text:?}"
    );
    assert!(
        text.contains("line three"),
        "must contain all lines: got {text:?}"
    );
}

#[test]
fn comments_empty_when_section_has_no_heads() {
    let i = issue("## Comments\n\n\n");
    assert_eq!(i.comments(), [] as [crate::model::Comment; 0]);
}

// --- T002: add_comment ---

#[test]
fn add_first_comment_to_empty_body() {
    let mut i = issue("");
    i.add_comment("@alice", "Hello world");
    assert_eq!(i.description(), "");
    let cs = i.comments();
    assert_eq!(cs.len(), 1);
    assert_eq!(cs[0].author, "@alice");
    assert_eq!(cs[0].text, "\nHello world");
    assert!(i.body.contains("## Comments"));
}

#[test]
fn second_comment_appended_after_first() {
    let mut i = issue("");
    i.add_comment("@alice", "first");
    i.add_comment("bob", "second");
    let cs = i.comments();
    assert_eq!(cs.len(), 2);
    let pos_a = i.body.find("### @alice");
    let pos_b = i.body.find("### bob");
    assert!(pos_a < pos_b, "first comment must precede second");
}

#[test]
fn whitespace_only_comment_discarded() {
    let mut i = issue("Hello\n");
    let before = i.body.clone();
    i.add_comment("@alice", "   \n  ");
    assert_eq!(i.body, before, "whitespace-only text must not change body");
}

#[test]
fn description_unchanged_after_add_comment() {
    let mut i = issue("Description text.\n");
    i.add_comment("@alice", "a comment");
    assert_eq!(i.description(), "Description text.");
}

#[test]
fn literal_comments_heading_in_code_block_not_touched() {
    let mut i = issue("```\n## Comments\n```\n");
    i.add_comment("@alice", "new");
    assert!(
        i.body.contains("```\n## Comments\n```"),
        "code-block heading must be preserved: {0:?}",
        i.body
    );
    assert!(i.body.contains("### @alice"), "must contain new comment");
}

// --- T003: roundtrip / NFR-005 ---

#[test]
fn roundtrip_preserves_comment_data() {
    let mut i = issue(
        "## Comments\n\n\
             ### @alice (2026-09-13)\n\n\
             Original comment.\n",
    );
    i.add_comment("bob", "Second comment");
    let file = i.to_file_contents();
    let parsed = Issue::parse(&file).unwrap();
    assert_eq!(parsed.description(), i.description());
    let cs = parsed.comments();
    assert_eq!(cs.len(), 2);
    assert_eq!(cs[0].author, "@alice");
    assert_eq!(cs[1].author, "bob");
    assert_eq!(cs[1].text, "\nSecond comment");
}

#[test]
fn three_comments_in_file_order() {
    let mut i = issue("");
    i.add_comment("a", "one");
    i.add_comment("b", "two");
    i.add_comment("c", "three");
    let cs = i.comments();
    assert_eq!(
        cs.iter().map(|c| c.author.as_str()).collect::<Vec<_>>(),
        ["a", "b", "c"]
    );
    assert_eq!(
        i.body,
        format!(
            "## Comments\n\n### a ({0})\n\none\n\n### b ({0})\n\ntwo\n\n### c ({0})\n\nthree\n",
            today()
        )
    );
}

#[test]
fn preserves_hand_authored_comment_markdown() {
    let body = "## Comments\n\n\
             ### @alice (2026-09-13)\n\n\
             **bold** and _italic_\n\n\
             - item 1\n- item 2\n\n";
    let i = issue(body);
    let cs = i.comments();
    assert_eq!(cs.len(), 1);
    assert!(cs[0].text.contains("**bold**"));
    assert!(cs[0].text.contains("- item 1"));
}

#[test]
fn description_code_block_heading_not_boundary() {
    let mut i = issue("Intro text here\n\n```\n## Comments\n```\n");
    let before = i.body.clone();
    i.add_comment("eve", "real");
    assert_eq!(i.description(), "Intro text here\n\n```\n## Comments\n```");
    let cs = i.comments();
    assert_eq!(cs.len(), 1);
    assert_eq!(cs[0].author, "eve");
    assert!(
        i.body.starts_with(&before),
        "code-block heading must be preserved"
    );
}

// ------------------------------------------------------------------
// WP02 — Planning fields, dates & file format
// ------------------------------------------------------------------

#[test]
fn planning_fields_round_trip() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 12,
        title: "Ship cycle one".into(),
        status: Status::new("in progress"),
        labels: vec!["release".into()],
        priority: Priority::High,
        assignee: Some("alice".into()),
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec!["specs/p/spec.md".into()],
        cycles: Some(vec!["Cycle 1".into(), "Sprint hardening".into()]),
        milestones: Some(vec!["v1.0".into()]),
        reviewer: Some("Bob <bob@example.com>".into()),
        start_date: Some("2026-09-07".into()),
        due_date: Some("2026-09-18".into()),
        created: "2026-09-07".into(),
        type_: None,
        updated: "2026-09-07".into(),
        filename: String::new(),
        body: "body".into(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let contents = issue.to_file_contents();
    let parsed = Issue::parse(&contents).unwrap();
    assert_eq!(parsed, issue);
    assert_eq!(
        parsed.cycles.clone().unwrap(),
        ["Cycle 1", "Sprint hardening"]
    );
    assert_eq!(parsed.milestones.clone().unwrap(), ["v1.0"]);
    assert_eq!(parsed.reviewer.as_deref(), Some("Bob <bob@example.com>"));
    assert_eq!(parsed.start_date.as_deref(), Some("2026-09-07"));
    assert_eq!(parsed.due_date.as_deref(), Some("2026-09-18"));
}

#[test]
fn planning_fields_absent_on_legacy_serialize_nothing() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 3,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: "body".into(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let fm = issue.frontmatter();
    for needle in ["cycles", "milestones", "reviewer", "start_date", "due_date"] {
        assert!(!fm.contains(needle), "{needle} must be omitted, got:\n{fm}");
    }
    let parsed = Issue::parse(&issue.to_file_contents()).unwrap();
    assert!(parsed.cycles.is_none());
    assert!(parsed.milestones.is_none());
    assert!(parsed.reviewer.is_none());
    assert!(parsed.start_date.is_none());
    assert!(parsed.due_date.is_none());
}

#[test]
fn empty_planning_lists_serialize_as_omitted() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 3,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec![],
        cycles: Some(vec![]),
        milestones: Some(vec![]),
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: "body".into(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let fm = issue.frontmatter();
    assert!(!fm.contains("cycles"), "{fm}");
    assert!(!fm.contains("milestones"), "{fm}");
}

#[test]
fn duplicate_planning_list_entries_collapse_on_write() {
    let issue = Issue {
        projects: None,
        id: None,
        number: 3,
        title: "T".into(),
        status: Status::default(),
        labels: vec![],
        priority: Priority::default(),
        assignee: None,
        estimate: None,
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        relationships: vec![],
        related_issues: vec![],
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        files: vec![],
        cycles: Some(vec!["A".into(), "A".into(), "B".into()]),
        milestones: Some(vec!["m".into(), "m".into()]),
        reviewer: None,
        start_date: None,
        due_date: None,
        created: "2026-01-01".into(),
        type_: None,
        updated: "2026-01-01".into(),
        filename: String::new(),
        body: "body".into(),
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        parent: None,
        series: None,
        health: None,
        archived: false,
        entered_at: None,
        source: None,
    };
    let fm = issue.frontmatter();
    let parsed = Issue::parse(&issue.to_file_contents()).unwrap();
    assert_eq!(parsed.cycles.clone().unwrap(), ["A", "B"]);
    assert_eq!(parsed.milestones.clone().unwrap(), ["m"]);
    assert_eq!(fm.matches("- A").count(), 1, "{fm}");
    assert_eq!(fm.matches("- m").count(), 1, "{fm}");
}

#[test]
fn legacy_fixture_round_trips_with_only_the_retired_key_removed() {
    // Canonical fixtures captured from the real corpus before WP02
    // (tests/fixtures/legacy-01.md, legacy-02.md).
    //
    // Each file carries one `links: []` line, and that line is the
    // **approved breaking change** (C-001): the typed model replaces the
    // generic bag and does not re-emit the retired key. So the round trip
    // for these particular fixtures is deliberately not byte-identical, and
    // must not pretend to be. The exact, intended delta is the one removed
    // line and nothing else: every other byte, including the
    // `## Mission Progress` and `## Comments` body sections, survives.
    //
    // The fixtures carry the key **empty**, so it is not *reported* — an
    // empty value has nothing to lose, and reporting it made `tix lint`
    // reject the whole corpus. The key is still never re-emitted, which is
    // what this test is about, and that is unchanged.
    for name in ["legacy-01.md", "legacy-02.md"] {
        let path = format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
        let original = std::fs::read_to_string(&path).unwrap();
        let issue = Issue::parse(&original).unwrap();
        assert!(
            !issue.has_retired_links_key,
            "{name} carries an *empty* retired key, so there is nothing to report"
        );
        assert!(
            issue.relationships.is_empty(),
            "C-001: the legacy value is never read as typed edges"
        );

        let kept: Vec<&str> = original
            .lines()
            .filter(|line| !line.starts_with("links:"))
            .collect();
        let expected = format!("{}\n", kept.join("\n"));

        let round = issue.to_file_contents();
        assert_eq!(
            round, expected,
            "{name} must differ from the legacy file by exactly the retired `links:` line"
        );
        assert!(
            !round.contains("links:"),
            "the retired key is never re-emitted"
        );
        // Byte-stable from here on: the new form round-trips exactly.
        assert_eq!(
            Issue::parse(&round).unwrap().to_file_contents(),
            round,
            "{name} must be byte-stable once in the new format"
        );
        assert!(issue.cycles.is_none() && issue.milestones.is_none());
        assert!(issue.reviewer.is_none());
        assert!(issue.start_date.is_none() && issue.due_date.is_none());
    }
}

#[test]
fn a_file_in_the_current_format_round_trips_byte_identically() {
    // NFR-003: a file the current code writes must survive read -> write
    // -> read with no change at all. This is the guarantee the legacy
    // fixtures cannot make, because they predate the format change.
    let original = concat!(
        "---\n",
        "number: 7\n",
        "title: Current\n",
        "status: todo\n",
        "labels: []\n",
        "priority: medium\n",
        "created: '2026-01-01'\n",
        "updated: '2026-01-01'\n",
        "---\n",
        "\n",
        "## History\n",
        "\n",
        "- 2026-01-02T03:04:05Z \u{2014} alice \u{2014} relationship_added \u{2014} created blocks: blocks #9 Nine\n",
        "\n",
        "Prose that follows the section.\n",
    );
    let issue = Issue::parse(original).unwrap();
    assert!(!issue.has_retired_links_key);
    assert_eq!(issue.history.len(), 1, "the History section is parsed");
    assert_eq!(issue.history.events()[0].actor, "alice");
    assert_eq!(
        issue.history.events()[0].kind,
        HistoryEventKind::RelationshipAdded
    );
    assert!(
        issue.body.contains("Prose that follows"),
        "prose after the section is preserved in the body: {:?}",
        issue.body
    );

    let rendered = issue.to_file_contents();
    assert!(rendered.contains("## History"), "{rendered}");
    assert!(
        rendered.contains(" \u{2014} alice \u{2014} relationship_added \u{2014} "),
        "the rendered entry uses the documented spaced form: {rendered}"
    );
    // Idempotent: rendering the re-parsed form changes nothing. Asserting
    // idempotence rather than equality with the hand-written fixture keeps
    // the guarantee honest about what it covers.
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered,
        "a file in the current format round-trips byte-identically"
    );
}

#[test]
fn validate_date_accepts_real_calendar_dates() {
    assert!(validate_date("2026-09-18"));
    assert!(validate_date("1970-01-01"));
    assert!(validate_date("2024-02-29")); // leap year
    assert!(!validate_date("2023-02-29")); // not leap
    assert!(!validate_date("2026-02-30"));
    assert!(!validate_date("2026-13-01"));
    assert!(!validate_date("2026-00-01"));
    assert!(!validate_date("2026-01-00"));
    assert!(!validate_date("2026-1-01"));
    assert!(!validate_date("2026-01-1"));
    assert!(!validate_date("1969-12-31")); // pre-1970 rejected
    assert!(!validate_date("2026/01/01"));
    assert!(!validate_date("today"));
    assert_eq!(days_in_month(2024, 2), 29);
    assert_eq!(days_in_month(2023, 2), 28);
    assert_eq!(days_in_month(2026, 4), 30);
    assert_eq!(days_in_month(2026, 1), 31);
}

#[test]
fn lexicographic_order_equals_chronological_order() {
    assert!(date_lte("2026-01-05", "2026-01-12"));
    assert!(date_lte("2026-01-05", "2026-01-05"));
    assert!(!date_lte("2026-01-12", "2026-01-05"));
    assert!(date_lte("2025-12-31", "2026-01-01"));
}

#[test]
fn validate_issue_dates_enforces_format_and_ordering() {
    assert!(validate_issue_dates(None, None).is_ok());
    assert!(validate_issue_dates(Some("2026-09-07"), None).is_ok());
    assert!(validate_issue_dates(None, Some("2026-09-18")).is_ok());
    assert!(validate_issue_dates(Some("2026-09-07"), Some("2026-09-18")).is_ok());
    assert!(validate_issue_dates(Some("2026-09-18"), Some("2026-09-18")).is_ok());
    let e = validate_issue_dates(Some("2026-09-18"), Some("2026-09-07")).unwrap_err();
    assert!(e.to_string().contains("due_date"), "naming both: {e}");
    assert!(e.to_string().contains("start_date"), "naming both: {e}");
    assert!(validate_issue_dates(Some("2026-13-01"), None).is_err());
    assert!(validate_issue_dates(None, Some("2026-02-30")).is_err());
}

#[test]
fn malformed_planning_fields_load_without_panic() {
    // Storage is tolerant (T007): garbage in the new optional fields must
    // parse without panic and be preserved as-is on the parsed value;
    // validation is a separate, explicit concern.
    let invalid = "---\nnumber: 1\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\nstart_date: not-a-date\ndue_date: \"2026-02-30\"\nreviewer: nobody\ncycles:\n- \"\"\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nbody\n";
    let issue = Issue::parse(invalid).unwrap();
    assert_eq!(issue.start_date.as_deref(), Some("not-a-date"));
    assert_eq!(issue.due_date.as_deref(), Some("2026-02-30"));
    assert_eq!(issue.reviewer.as_deref(), Some("nobody"));
    assert_eq!(issue.cycles.clone().unwrap(), [""]);
}

#[test]
fn set_dates_validates_before_mutating() {
    let mut issue = issue("body");
    issue
        .set_dates(Some("2026-09-07".into()), Some("2026-09-18".into()))
        .unwrap();
    assert_eq!(issue.start_date.as_deref(), Some("2026-09-07"));
    assert_eq!(issue.due_date.as_deref(), Some("2026-09-18"));
    let before = issue.clone();
    let err = issue.set_dates(Some("2026-09-18".into()), Some("2026-09-07".into()));
    assert!(err.is_err());
    assert_eq!(issue, before, "failed set_dates must not partially mutate");
}
// ------------------------------------------------------------------
// Final-review probes, promoted to tests where they pin real behavior
// ------------------------------------------------------------------

/// Frontmatter with one extra line inserted before the closing delimiter.
fn frontmatter_with(extra: &str) -> String {
    format!("---\nnumber: 1\ntitle: T\nstatus: todo\n{extra}---\n\nBody.\n")
}

#[test]
fn retired_key_detection_matches_only_the_exact_key_name() {
    // The detector parses the frontmatter and looks for a top-level `links`
    // key, because the key is not part of the model and so cannot be seen
    // after deserialization. A key that merely *contains* `links` is not the
    // retired key, and a line inside a block scalar is content, not a key.
    for (extra, expect) in [
        // Populated: reported, because the value is no longer readable.
        ("links:\n- '12'\n", true),
        ("related_links: []\n", false),
        ("links_count: 3\n", false),
        ("# links: []\n", false),
        // A quoted key is still the same key, so it IS the retired key —
        // the earlier line scan missed these entirely.
        ("\"links\":\n- '12'\n", true),
        // Empty: present, but nothing to lose, so not reported. Reporting it
        // rejected every issue file this repository has ever written.
        ("links: []\n", false),
        ("links: ~\n", false),
        ("priority: medium\n", false),
        // A nested `links:` is not the retired top-level key.
        ("meta:\n  links: []\n", false),
        // A line inside a block scalar is content, not a key.
        ("notes: |\n  links: see the docs\n", false),
    ] {
        let issue = Issue::parse(&frontmatter_with(extra)).unwrap();
        assert_eq!(
            issue.has_retired_links_key, expect,
            "frontmatter line {extra:?}"
        );
    }
}

#[test]
fn retired_key_detection_agrees_with_itself_on_the_fallback_path() {
    // The line-scan fallback is reachable: `serde_yaml` rejects duplicate
    // keys when building a `Mapping` but `Issue` tolerates a duplicate
    // *unknown* key, so such a file parses and lands on the fallback. Both
    // paths must agree that a nested `links:` is not the retired key — the
    // fallback used to match it at any indentation and disagree with the
    // primary path, so the same file was reported or not depending on which
    // path ran.
    for (extra, expect) in [
        ("meta:\n  links: []\n", false),
        ("meta:\n  links: []\nzzz: 1\nzzz: 2\n", false),
        ("links: []\nzzz: 1\nzzz: 2\n", true),
    ] {
        let issue = Issue::parse(&frontmatter_with(extra)).unwrap();
        assert_eq!(
            issue.has_retired_links_key, expect,
            "frontmatter {extra:?} must be judged the same way on both paths"
        );
    }
}

#[test]
fn a_history_heading_inside_prose_stays_prose() {
    // Only a section at the *front* of the body is the History section, the
    // position data-model §8 pins. A heading further down is ordinary prose
    // and must survive a read/write round trip untouched.
    let raw = "---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\nProse first.\n\n## History\n\n- 2026-01-01T00:00:00Z \u{2014} a \u{2014} relationship_added \u{2014} d\n";
    let issue = Issue::parse(raw).unwrap();
    assert!(
        issue.history.is_empty(),
        "a mid-body heading is not History"
    );
    assert!(
        issue.body.contains("## History"),
        "and it stays in the body: {:?}",
        issue.body
    );
    // And it round-trips as prose, not as a section.
    let rendered = issue.to_file_contents();
    assert!(rendered.contains("## History"));
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered
    );
}

/// The three heading cases the cycle-7 review found **unpinned**: a trailing
/// tab, leading whitespace, and extra words after the heading. All three
/// behave correctly — they are now pinned so the next change to the heading
/// rule has to move a test rather than a comment.
///
/// The pair that matter is the tab against the leading space, because they sit
/// on opposite sides of the stated rule ("trailing whitespace is ignored;
/// leading whitespace is not") and nothing tested it.
#[test]
fn the_heading_rule_ignores_trailing_whitespace_and_nothing_else() {
    let event = "2026-01-01T00:00:00Z \u{2014} a \u{2014} relationship_added \u{2014} d";
    let with = |heading: &str| {
        format!("---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n{heading}\n\n- {event}\n")
    };

    for (heading, recognised, why) in [
        ("## History", true, "the exact heading"),
        (
            "## History\t",
            true,
            "a trailing tab is trailing whitespace",
        ),
        ("## History  ", true, "so are trailing spaces"),
        (
            "   ## History",
            false,
            "leading whitespace is explicitly not ignored",
        ),
        (
            "## History extra words",
            false,
            "nothing else may introduce the section",
        ),
    ] {
        let issue = Issue::parse(&with(heading)).unwrap();
        assert_eq!(issue.history.is_empty(), !recognised, "{heading:?} — {why}");
        if recognised {
            assert_eq!(issue.history.len(), 1, "{heading:?} holds one event");
        } else {
            assert!(
                issue.body.contains("History"),
                "{heading:?} stays body prose: {:?}",
                issue.body
            );
        }
    }
}

/// The two non-recognised heading shapes above are **undiagnosed**: `tix lint`
/// reports a mispositioned `## History` only when the heading matches exactly,
/// so `   ## History` and `## History extra words` fall through both checks
/// silently.
///
/// That is defensible rather than a defect — neither is a section, so there is
/// no audit trail to lose, and §8 already says a heading appearing in an
/// issue's prose is ordinary text. It is pinned here so the silence is a
/// recorded decision: if a future change makes either shape *recognised*, this
/// test is where that has to be noticed, because `tix lint` will not notice.
#[test]
fn a_non_section_history_heading_is_undiagnosed() {
    for heading in ["   ## History", "## History extra words"] {
        let raw = format!("---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n{heading}\n\nBody.\n");
        let issue = Issue::parse(&raw).unwrap();
        assert!(issue.history.is_empty(), "{heading:?} is not a section");
        // The misposition diagnostic keys on the exact heading, so it does not
        // fire for either of these.
        assert!(
            !is_history_heading(&format!(
                "{heading}
"
            )),
            "{heading:?} is not the History heading at all"
        );
    }
}

/// A front-position section whose first list-shaped line is followed by prose
/// retains **no** entries, and the parser must not silently delete the
/// heading while demoting every line to body prose.
///
/// This is #1336, found while applying the §8 corrections for #1309. The
/// entries loop kept an ambiguous line when `plausible_entry ||
/// after_all_entries` and broke otherwise; `- step one` is list-shaped but
/// not an entry and the line after it is prose, so both disjuncts were false
/// and the section ended — with the heading already consumed. `tix view`
/// showed no `## History`, every line was prose, and `tix lint` was silent
/// because the heading *is* at the front. An ordinary to-do bullet above
/// ordinary prose silently deleted an audit trail.
///
/// The fix: when nothing is retained, return the body verbatim, heading and
/// all, so a parse → render → parse round trip is lossless.
#[test]
fn a_front_position_section_survives_when_nothing_is_retained() {
    let raw = "---\nnumber: 9\ntitle: T\nstatus: todo\n---\n\n## History\n\n- step one\n\nNow the real body text, with no entry shape at all.\n\n- 2026-01-01T00:00:00Z \u{2014} Bob \u{2014} transition_accepted \u{2014} todo -> done\n";
    let issue = Issue::parse(raw).unwrap();
    assert!(
        issue.history.is_empty(),
        "no entry was recognised: {:?}",
        issue.history
    );
    // Nothing was retained, so the section is handed back whole as body.
    for line in [
        "## History",
        "- step one",
        "Now the real body text, with no entry shape at all.",
        "- 2026-01-01T00:00:00Z \u{2014} Bob \u{2014} transition_accepted \u{2014} todo -> done",
    ] {
        assert!(
            issue.body.contains(line),
            "the body must keep {line:?}: {:?}",
            issue.body
        );
    }

    // Round trip: render then reparse. The second parse sees the same
    // ambiguous section and must land on the same body, so the bytes are a
    // fixed point rather than a one-shot rescue.
    let rendered = issue.to_file_contents();
    assert!(
        rendered.contains("## History"),
        "the heading survives rendering:\n{rendered}"
    );
    let reparsed = Issue::parse(&rendered).unwrap();
    assert!(reparsed.history.is_empty());
    assert_eq!(reparsed.body, issue.body, "body survives the round trip");
}

#[test]
fn a_blank_actor_round_trips_because_its_position_is_fixed() {
    // `render` writes an empty actor field when no identity was recorded. If
    // `parse` demanded a non-empty field it would reject the writer's own
    // output — and before the parse became non-fatal, that made the whole
    // file, and therefore every issue in the repository, unreadable.
    let event = HistoryEvent::new(
        "2026-01-01T00:00:00Z",
        "",
        HistoryEventKind::RelationshipAdded,
        "d",
    );
    let line = event.render();
    assert!(
        line.contains("\u{2014}  \u{2014}"),
        "render writes a blank, fixed-position actor field: {line}"
    );
    assert_eq!(
        HistoryEvent::parse(&line).expect("the writer's own output must parse"),
        event
    );
}

#[test]
fn a_blank_line_inside_the_section_does_not_end_it() {
    // A blank line between list entries is the most ordinary thing a human
    // or a Markdown formatter produces. Terminating the section there would
    // silently demote audit entries to body prose — they would vanish from
    // `history`, reappear as the issue's description, and the next append
    // would write *before* them, so file order would stop being append
    // order.
    let raw = concat!(
        "---\n",
        "number: 1\n",
        "title: T\n",
        "status: todo\n",
        "---\n",
        "\n",
        "## History\n",
        "\n",
        "- 2026-01-01T00:00:00Z \u{2014} a \u{2014} relationship_added \u{2014} first\n",
        "\n",
        "- 2026-01-01T00:00:01Z \u{2014} a \u{2014} relationship_added \u{2014} second\n",
        "\n",
        "Tail prose.\n",
    );
    let issue = Issue::parse(raw).unwrap();
    assert_eq!(
        issue.history.events().len(),
        2,
        "both entries are History events, not one event plus prose"
    );
    assert_eq!(issue.history.unparsed().len(), 0);
    assert_eq!(
        issue.body, "Tail prose.\n",
        "the prose after the section is still the body"
    );
    // Append order is preserved: a new event lands last, not first.
    let mut issue = issue;
    issue
        .history
        .append_now("a", HistoryEventKind::RelationshipRemoved, "third");
    let rendered = issue.to_file_contents();
    let first = rendered.find("first").unwrap();
    let second = rendered.find("second").unwrap();
    let third = rendered.find("third").unwrap();
    assert!(
        first < second && second < third,
        "file order is append order"
    );
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered
    );
}

#[test]
fn m3_body_bullets_after_the_section_stay_body() {
    // M3. The section has no end-of-section delimiter, and an earlier rule
    // accepted *any* `- ` line as an entry attempt. So ordinary prose
    // bullets were absorbed into the audit log: `body` became empty, the
    // blank line separating the section from the body was deleted on the
    // first write, and `tix lint` then blamed the author for "unparseable
    // entries" they never wrote. Trigger was a plain
    // `tix edit --body "- step one\n- step two"`.
    let raw = concat!(
        "---\n",
        "number: 1\n",
        "title: T\n",
        "status: todo\n",
        "---\n",
        "\n",
        "## History\n",
        "\n",
        "- 2026-01-01T00:00:00Z \u{2014} a \u{2014} relationship_added \u{2014} d1\n",
        "\n",
        "- Reproduction: run it\n",
        "- Expected: it works\n",
    );
    let issue = Issue::parse(raw).unwrap();
    assert_eq!(issue.history.events().len(), 1, "only the real event");
    assert!(
        issue.history.unparsed().is_empty(),
        "prose bullets are not mistaken for entries: {:?}",
        issue.history.unparsed()
    );
    assert_eq!(
        issue.body, "- Reproduction: run it\n- Expected: it works\n",
        "the bullets stay body prose"
    );
    // And the write does not restructure the file.
    let rendered = issue.to_file_contents();
    assert!(rendered.contains("- Reproduction: run it"));
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered
    );
}

#[test]
fn m3_a_stray_line_inside_the_section_keeps_the_events_after_it() {
    // The mirror image of the case above, and the reason the boundary is
    // resolved by looking ahead rather than by shape alone. A hand-edited
    // non-entry line *inside* the section must not demote the real events
    // after it: they would vanish from the audit trail, reappear as the
    // issue's description, and the next append would be written *before*
    // them, so file order would stop being append order.
    let raw = concat!(
        "---\n",
        "number: 1\n",
        "title: T\n",
        "status: todo\n",
        "---\n",
        "\n",
        "## History\n",
        "\n",
        "- 2026-01-01T00:00:00Z \u{2014} a \u{2014} relationship_added \u{2014} d1\n",
        "  garbage hand edit   \n",
        "- 2026-01-01T00:00:01Z \u{2014} a \u{2014} relationship_added \u{2014} d2\n",
    );
    let mut issue = Issue::parse(raw).unwrap();
    assert_eq!(
        issue.history.events().len(),
        2,
        "the event after the stray line is still an event"
    );
    let unparsed = issue.history.unparsed();
    assert_eq!(unparsed.len(), 1, "and the stray line is kept, not dropped");
    // Compared **raw**. The earlier version trimmed before comparing, which
    // is why it could not see either the injected blank line or the loss of
    // the leading indentation and trailing spaces — the exact properties it
    // claimed to check. The fixture carries both on purpose.
    assert_eq!(
        unparsed[0], "  garbage hand edit   ",
        "preserved byte-for-byte, including indentation and trailing space"
    );
    // And the render must not have inserted a blank line of its own.
    let rendered = issue.to_file_contents();
    assert!(
        rendered.contains("  garbage hand edit   \n"),
        "re-emitted exactly: {:?}",
        rendered
    );
    assert!(
        !rendered.contains("garbage hand edit   \n\n"),
        "and no blank line is injected after it: {:?}",
        rendered
    );
    issue
        .history
        .append_now("bob", HistoryEventKind::RelationshipAdded, "d3");
    let rendered = issue.to_file_contents();
    let d1 = rendered.find("d1").unwrap();
    let d2 = rendered.find("d2").unwrap();
    let d3 = rendered.find("d3").unwrap();
    assert!(d1 < d2 && d2 < d3, "file order is still append order");
}

#[test]
fn m3_a_bullet_that_looks_like_an_entry_is_recognised_for_diagnosis() {
    // An entry hand-typed with ASCII hyphens has no U+2014 separator, so it
    // cannot be recognised as an entry and must not be absorbed into the
    // body silently. `looks_like_history_entry` is what lets `tix lint`
    // report it.
    assert!(looks_like_history_entry(
        "- 2026-01-01T00:00:00Z \u{2014} a \u{2014} relationship_added \u{2014} d"
    ));
    // Recognition requires the separator. An entry typed with ASCII hyphens
    // is **not** recognised, deliberately: this predicate decides whether a
    // line is moved into the audit log, and the looser timestamp heuristic
    // absorbed ordinary body to-do items.
    assert!(
        !looks_like_history_entry("- 2026-01-01T00:00:00Z - a - relationship_added - d"),
        "an ASCII-hyphen line is not recognised, so it stays in the body"
    );
    assert!(
        !looks_like_history_entry("- Reproduction: run it"),
        "ordinary prose is not an entry"
    );
    assert!(!looks_like_history_entry("just a paragraph"));
    assert!(!looks_like_history_entry("-no space after the dash"));

    // The *reporting* predicate is separate and deliberately looser: it only
    // makes `tix lint` say something, it never moves a line.
    assert!(looks_like_an_unrecognised_entry(
        "- 2026-01-01T00:00:00Z - a - relationship_added - d"
    ));
    assert!(!looks_like_an_unrecognised_entry(
        "- 2026-01-01T00:00:00Z \u{2014} a \u{2014} relationship_added \u{2014} d"
    ));
    assert!(
        !looks_like_an_unrecognised_entry("- Reproduction: run it"),
        "and ordinary prose is still not accused"
    );
}

#[test]
fn f5_every_list_marker_is_recognised_and_reported() {
    // Cycle-4, on the `*`/`1.` accept that cycle 3 recorded as "undiagnosed".
    // It was the *same* defect as F1 through a different marker: with only
    // `- ` treated as a list item, an entry written as
    // `* 2026-01-01T00:00:00Z — a — kind — d` was called prose, the section
    // ended, the heading was deleted, and the next append was rendered above
    // it. Silent, because a demoted line is body prose.
    //
    // This is not a widening of the entry grammar: `looks_like_history_entry`
    // still requires U+2014, so none of these can be read as a relationship.
    // It is about which lines get a fair hearing at end-of-section.
    // With the separator present but a non-`-` marker, the line is retained
    // verbatim and reported rather than parsed. Parsing it would re-emit it
    // with a `- ` marker, and rewriting the author's bytes is exactly the
    // auto-repair data-model §8 forbids. Retained-and-reported is the third
    // option between "parse and rewrite" and "demote and say nothing", and
    // it is the one that loses nothing.
    for marker in ["* ", "+ ", "1. ", "2) "] {
        let line = format!(
            "{marker}2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} d"
        );
        assert!(
            !looks_like_history_entry(&line),
            "{marker:?} is not the canonical form, so it is not an event"
        );
        let raw = format!("---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n## History\n\n{line}\n");
        let issue = Issue::parse(&raw).unwrap();
        assert!(
            issue.history.events().is_empty(),
            "{marker:?}: no event is fabricated"
        );
        assert_eq!(
            issue.history.unparsed(),
            vec![line.clone()],
            "{marker:?}: retained byte-for-byte, marker intact"
        );
        assert_eq!(issue.body, "", "{marker:?}: and not demoted to the body");
    }

    // The canonical marker with the separator is a real event, as before.
    let canonical = "- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} d";
    assert!(looks_like_history_entry(canonical));
    let canonical_raw =
        format!("---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n## History\n\n{canonical}\n");
    assert_eq!(
        Issue::parse(&canonical_raw).unwrap().history.events().len(),
        1,
        "the canonical form is an event"
    );

    // And every marker *without* the separator still gets a fair hearing
    // rather than being silently demoted.
    for marker in ["- ", "* ", "+ ", "1. "] {
        let line = format!("{marker}hand edited note");
        let raw = format!("---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n## History\n\n{line}\n");
        let issue = Issue::parse(&raw).unwrap();
        assert!(
            issue.history.events().is_empty(),
            "{marker:?}: no event is fabricated"
        );
        assert_eq!(
            issue.history.unparsed(),
            vec![line.clone()],
            "{marker:?}: retained verbatim in the section"
        );
        assert!(
            issue.body.is_empty(),
            "{marker:?}: and not demoted into the body, got {:?}",
            issue.body
        );
    }

    // The "and reported" half of this test's name, which the retention
    // assertions above did not check. Reporting for a line *inside* a section
    // goes through the unparsed loop; reporting for one in the *body* goes
    // through `looks_like_an_unrecognised_entry`. Both are asserted here so
    // the name is earned — cycle 5 found the retention half asserted and the
    // reporting half assumed.
    for marker in ["- ", "* ", "+ ", "1. "] {
        let line = format!("{marker}2026-01-01T00:00:00Z - alice - relationship_added - d");
        assert!(
            looks_like_an_unrecognised_entry(&line),
            "{marker:?}: reported as a mistyped entry"
        );
        // And the same line with a *different* marker shape is not, so the
        // assertion above is discriminating rather than trivially true.
        assert!(
            !looks_like_an_unrecognised_entry(&format!("2026. {line}")),
            "a bare sentence is never an entry"
        );
    }

    // A bare paragraph at end of section is still prose. That is the other
    // half of the rule and the reason `is_list_item` is not simply "true".
    // When *nothing* is retained the heading is handed back with the body
    // (see `a_front_position_section_survives_when_nothing_is_retained`),
    // so the paragraph is body prose *after* the preserved heading rather
    // than the whole body.
    for prose in [
        "just a closing paragraph",
        "Reproduction: run it",
        "see the thread for context",
    ] {
        let raw = format!("---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n## History\n\n{prose}\n");
        let issue = Issue::parse(&raw).unwrap();
        assert!(issue.history.is_empty(), "{prose:?}: no section content");
        assert!(
            issue.body.contains(prose),
            "{prose:?}: it is body prose: {:?}",
            issue.body
        );
    }
}

#[test]
fn an_unparseable_entry_never_fails_the_parse() {
    // The single most important property of the History section: it is
    // advertised as human-editable, so a hand edit will eventually produce a
    // line this parser cannot read. That must cost the *author* a lint
    // finding on their own issue, not the whole repository its readability.
    // A recognised entry attempt whose kind is unknown: kept verbatim inside
    // the section, so `tix lint` can report it.
    let bad_kind = "- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} bogus_kind \u{2014} d";
    let raw = format!("---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n## History\n\n{bad_kind}\n");
    let issue = Issue::parse(&raw).expect("one bad line must not fail the file");
    assert!(issue.history.events().is_empty(), "no event was fabricated");
    assert_eq!(issue.history.unparsed(), vec![bad_kind], "kept verbatim");
    assert_eq!(issue.body, "", "nothing leaked into the body");

    // An entry typed with ASCII hyphens is not *recognised*, but it is still a
    // list item at the end of the section, so it is retained verbatim and
    // reported rather than demoted. The earlier version of this test
    // asserted it stayed body text; cycle-4 F1 showed the alternative deletes
    // the `## History` heading and reorders the log around it, silently.
    // Retention is the disclosed failure mode, so it is the one chosen — and
    // `looks_like_history_entry` still returns false for it, so no event is
    // ever fabricated from it either.
    let ascii = "- 2026-01-01T00:00:00Z - alice - relationship_added - ascii";
    let raw2 = format!("---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n## History\n\n{ascii}\n");
    let issue2 = Issue::parse(&raw2).expect("and it must not fail the file either");
    assert!(issue2.history.events().is_empty(), "no event is fabricated");
    assert_eq!(issue2.history.unparsed(), vec![ascii], "kept verbatim");
    assert_eq!(issue2.body, "", "and not demoted into the body");

    let rendered = issue.to_file_contents();
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered,
        "and the file round-trips unchanged"
    );
}

#[test]
fn a_history_entry_keeps_an_em_dash_inside_its_detail() {
    // The line is split on the first three separators only, so a detail
    // containing an em dash survives rather than being truncated.
    let raw = "---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n## History\n\n- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} note \u{2014} dash inside\n\nTail.\n";
    let issue = Issue::parse(raw).unwrap();
    assert_eq!(issue.history.len(), 1);
    let event = &issue.history.events()[0];
    assert_eq!(event.timestamp, "2026-01-01T00:00:00Z");
    assert_eq!(event.actor, "alice");
    assert_eq!(event.kind, HistoryEventKind::RelationshipAdded);
    assert_eq!(event.detail, "note \u{2014} dash inside");
    // Idempotence rather than equality with the hand-written input: the
    // input omits keys serde always emits, so only the rendered form is a
    // meaningful byte-stability assertion.
    let rendered = issue.to_file_contents();
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered,
        "the entry round-trips byte-identically"
    );
    assert_eq!(
        Issue::parse(&rendered).unwrap().history.events()[0].detail,
        "note \u{2014} dash inside",
        "and the detail is stable across the round trip"
    );
}

// -----------------------------------------------------------------------
// WP02 / T006 + T007 — the `parent` field and its three History kinds
// -----------------------------------------------------------------------
//
// Requirement ids in the test names: C-001 (at most one parent), C-003 (no
// child data on the parent), C-004 (every change audited), C-007 (a parent is
// not a dependency edge), SC-004 (a rejected change writes nothing).

/// A file body, so a test's only variable is the frontmatter under test.
fn wp02_file(fm: &str) -> String {
    format!("---\n{fm}---\n\nBody text.")
}

/// The frontmatter every legacy file in the repository carries: no `parent:`
/// key at all. This is the pinned pre-mission byte form.
///
/// In the **canonical rendered form**, not a merely plausible one. The writer
/// unquotes strings and always emits `files: []`, so a hand-written fixture
/// with quotes in it is not byte-stable for reasons that have nothing to do
/// with `parent` — the first version of these tests failed for exactly that
/// reason and was measuring the renderer rather than the field.
const WP02_LEGACY_FM: &str = "number: 3\ntitle: Legacy issue\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n";

/// The same file, with a parent, canonical.
const WP02_PARENT_FM: &str = "number: 3\ntitle: Child\nstatus: todo\nlabels: []\npriority: medium\nparent: 7\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n";

#[test]
fn t006_a_file_with_a_parent_round_trips_byte_stably() {
    let original = wp02_file(WP02_PARENT_FM);
    let issue = Issue::parse(&original).expect("a parent parses");
    assert_eq!(
        issue.parent,
        Some(crate::id::IssueRef::Number(7)),
        "the parent alias is read as data"
    );

    // load -> save -> load, byte-identical at every hop.
    let once = issue.to_file_contents();
    assert_eq!(
        once, original,
        "the parent key is written where it was read"
    );
    let twice = Issue::parse(&once).unwrap().to_file_contents();
    assert_eq!(twice, once, "a second round trip changes nothing");
}

#[test]
fn t006_a_legacy_file_with_no_parent_key_serialises_to_its_pre_mission_bytes() {
    // The pinned legacy gate. If this fails, the field is leaking into files
    // that never had one.
    let original = wp02_file(WP02_LEGACY_FM);
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(issue.parent, None, "an absent key is no parent");
    let rendered = issue.to_file_contents();
    assert_eq!(rendered, original);
    assert!(
        !rendered.contains("parent:"),
        "a file that never had a parent must not grow a `parent:` key"
    );
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered
    );
}

#[test]
fn t006_the_parent_key_is_written_exactly_once() {
    // Regression: `parent` was added to [`Issue`] but not to
    // [`KNOWN_FRONTMATTER_KEYS`], so `capture_extra_frontmatter` also took it
    // for an unknown key and the writer emitted the key twice in one file. The
    // file still parsed. A count assertion is what notices.
    let rendered = Issue::parse(&wp02_file(WP02_PARENT_FM))
        .unwrap()
        .to_file_contents();
    assert_eq!(
        rendered.matches("\nparent:").count(),
        1,
        "`parent:` must be written once, got:\n{rendered}"
    );
    let reparsed = Issue::parse(&rendered).unwrap();
    assert_eq!(reparsed.to_file_contents(), rendered);
}

#[test]
fn known_frontmatter_keys_cover_every_written_key() {
    // The guard for `KNOWN_FRONTMATTER_KEYS`, which is a hand-maintained mirror
    // of the frontmatter field set — no macro can read a struct's own field
    // names. Both of its failure modes are silent, and in opposite directions:
    //
    // * a key **listed but not modelled** is dropped on write (data loss, the
    //   bug #1361 exists to remove);
    // * a key **modelled but not listed** is also captured as unknown and emitted
    //   a *second* time, so the file carries the same key twice. That is what
    //   `parent` did.
    //
    // The first version of this test was a one-directional subset check with a
    // fixture that left `relationships`, `cycles` and `milestones` unpopulated.
    // Deleting `"relationships"` from the list left it **green** while the
    // double-write defect was live, and so did adding a brand-new unregistered
    // field — both measured and confirmed. A test that cannot go red in the
    // states it claims to rule out is worse than none, because it is read as
    // proof.
    //
    // So this asserts **both directions**, populates every optional field so
    // the key set is complete, and adds two direct checks that do not consult
    // the list at all — the symptom, not the cause.
    let mut issue = Issue::parse(&wp02_file(
            "number: 1\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n",
        ))
        .unwrap();
    issue.id = Some("A1B2C3D4".into());
    issue.assignee = Some("@alice".into());
    issue.estimate = Some("1h".into());
    issue.commit = Some("abc1234".into());
    issue.gitlab_id = Some("7".into());
    issue.linear_id = Some("9".into());
    issue.mission = Some("m".into());
    issue.task = Some("T001".into());
    issue.reviewer = Some("@bob".into());
    issue.start_date = Some("2026-01-01".into());
    issue.due_date = Some("2026-02-01".into());
    issue.entered_at = Some("2026-03-01T10:00:00Z".into());
    issue.source = Some("import".into());
    issue.parent = Some(crate::id::IssueRef::Number(2));
    issue.cycles = Some(vec!["A".into()]);
    issue.milestones = Some(vec!["m".into()]);
    // WP03: the project association list, populated so the key set is complete.
    issue.projects = Some(vec!["p-1".into()]);
    // WP03 of `epics-work-items-01M3BYW4`: the epic reference list, populated
    // so the key set is complete (and so this guard goes red if a later field
    // is added without registering its key).
    issue.epics = Some(vec!["e-7c4a91".into()]);
    issue.files = vec!["docs/a.md".into()];
    issue.labels = vec!["one".into(), "two".into()];
    issue.relationships = vec![Relationship::new(1, 2, RelationKind::Blocks, "T")];
    issue.related_issues = vec!["#1".into()];
    issue.type_ = Some("bug".into());
    // WP02 of `project-issue-health-status-01M3C8HX`: the health projection,
    // populated so the key set stays complete (and so this guard goes red if a
    // later field is added without registering its key).
    issue.health = Some(HealthRef {
        state: Some("on_track".into()),
        source: Some("current".into()),
        policy_version: Some("health-v1".into()),
        updated_at: Some("2026-03-01T10:00:00Z".into()),
    });
    // WP02: the recurrence table, populated so the key set stays complete.
    issue.series = Some(SeriesRef {
        id: "s-abc".into(),
        name: Some("Nightly".into()),
        rule: Some(SeriesRule {
            kind: Some("daily".into()),
            anchor: Some("2026-01-01".into()),
            ..SeriesRule::default()
        }),
        ..SeriesRef::default()
    });

    // WP01 of `per-issue-time-tracking-01M3C9A4`: the current time entries,
    // populated so this fixture exercises every known key (and so the guard
    // goes red if the registration is ever dropped).
    issue.time_entries = vec![TimeEntry {
        id: "e-1a2b3c4d".into(),
        duration_minutes: Some(90),
        date: Some("2026-03-01".into()),
        author: "@alice".into(),
        note: Some("reviewed the parser".into()),
        extensions: TimeEntryExtensions::default(),
    }];

    let frontmatter = issue.frontmatter();
    let written: Vec<String> = frontmatter.lines().filter_map(top_level_key).collect();

    // -- The direct checks first ------------------------------------------
    //
    // These do not consult `KNOWN_FRONTMATTER_KEYS` at all, so they hold
    // whatever the list says, and they are what actually catches the defect:
    // the symptom rather than the cause. Ordered first so a regression reports
    // the real problem instead of a completeness count.
    //
    // A fully-populated canonical file must have **no unknown keys**. A key the
    // model owns but the list omits is captured as unknown and will be emitted
    // a second time.
    assert_eq!(
        capture_extra_frontmatter(&frontmatter),
        BTreeMap::new(),
        "a fully-populated canonical file must have NO unknown keys: a key the \
             model owns is being captured as unknown and will be emitted twice"
    );

    // And no top-level key may appear twice in a rendered file. This is the
    // defect stated as an assertion, with nothing to maintain but the writer.
    let mut sorted = written.clone();
    sorted.sort();
    let before = sorted.len();
    sorted.dedup();
    assert_eq!(
        before,
        sorted.len(),
        "a key is written more than once in:\n{frontmatter}"
    );

    // -- Direction 1: every written key is registered -----------------------
    for key in &written {
        assert!(
            KNOWN_FRONTMATTER_KEYS.contains(&key.as_str()),
            "`{key}` is written by the model but absent from KNOWN_FRONTMATTER_KEYS, \
                 so capture_extra_frontmatter treats it as unknown and the writer emits \
                 it twice. Add it to the list."
        );
    }

    // -- Direction 2: every registered key is one the model can write -------
    //
    // The opposite silent failure: a key listed but not modelled is dropped on
    // write, which is data loss.
    for key in KNOWN_FRONTMATTER_KEYS {
        if *key == "links" {
            continue; // Recognised but never re-emitted, by design (that C-001).
        }
        assert!(
            written.iter().any(|k| k == key),
            "`{key}` is listed as known but no field writes it, so the entry is \
                 wrong in the other direction: a key wrongly listed as known is \
                 dropped on write. Either model it or remove it from the list."
        );
    }

    // -- Completeness floor -------------------------------------------------
    //
    // Last, because it is a statement about the *fixture*, not about the code:
    // if a field is added and this test stops populating it, the two assertions
    // above silently cover less. Asserted so that cannot pass unnoticed.
    assert_eq!(
        written.len(),
        KNOWN_FRONTMATTER_KEYS.len() - 1,
        "the fixture must exercise every known key except the retired one; \
             got {written:?} against {KNOWN_FRONTMATTER_KEYS:?}"
    );

    for key in KNOWN_FRONTMATTER_KEYS {
        assert!(
            !key.is_empty() && !key.contains(char::is_whitespace),
            "`{key}` is not a usable top-level key"
        );
    }
}

#[test]
fn t006_an_explicitly_null_parent_is_the_absent_state() {
    // `parent:` with no value is the "no parent" state. It is dropped on
    // write, matching every other optional field in this frontmatter
    // (`assignee:`, `commit:`). Pinned rather than assumed, because the
    // legacy gate above is what would catch the blast radius if it changed.
    let issue = Issue::parse(&wp02_file("number: 3\ntitle: T\nstatus: todo\nparent:\n")).unwrap();
    assert_eq!(issue.parent, None);
    assert!(!issue.to_file_contents().contains("parent:"));
}

#[test]
fn t006_an_empty_string_parent_is_rejected_rather_than_read_as_a_reference() {
    // A YAML `""` is a *string*, not a number. Coercing it to `None` would
    // erase a real reference that a template or an editor emptied by
    // mistake, and the file would then read as a deliberate "no parent".
    let err = Issue::parse(&wp02_file("number: 3\ntitle: T\nparent: \"\"\n"))
        .expect_err("an empty-string parent is malformed, not a reference");
    assert!(
        err.to_string().contains("parent"),
        "the error must name the offending field, got: {err}"
    );
}

#[test]
fn t006_a_malformed_parent_value_is_rejected() {
    // The spellings that are genuinely rejected. Every one of these would be a
    // reference the user did not write if the parser were lenient about them.
    for (label, value) in [
        ("an empty string", "\"\""),
        ("a single-quoted number", "'7'"),
        ("a zero-padded number", "007"),
        ("an underscore-separated number", "1_000"),
        ("a float", "7.5"),
        ("a float written as an integer", "7.0"),
        ("scientific notation", "1e2"),
        ("a list", "[7]"),
        ("a map", "{a: 1}"),
        ("a bool", "true"),
        ("a negative", "-1"),
        ("a value beyond u32", "4294967296"),
    ] {
        let parsed = Issue::parse(&wp02_file(&format!(
            "number: 3\ntitle: T\nparent: {value}\n"
        )));
        assert!(
            parsed.is_err(),
            "{label} (`parent: {value}`) must be rejected, got {parsed:?}"
        );
    }
}

#[test]
fn t006_the_accepted_scalar_forms_are_pinned_because_they_are_surprising() {
    // An earlier version of the malformed-value test claimed "none may become
    // `Some(_)`" and listed seven spellings. It was **false**: measured, five
    // more scalar forms are read as numbers.
    //
    // Pinned here rather than left unstated, so the behaviour is a recorded
    // decision instead of a YAML accident. Whether these should be *accepted*
    // is an open question (filed as #1372): tightening the accepted set is a
    // parse-semantics change and belongs in a contract clause, not in a test
    // edit made quietly inside WP02.
    //
    // `!!str 7` is the sharp one. A value explicitly tagged as a *string* is read
    // as a number — the same class the empty-string test refuses. `0x1F`, `0o17`
    // and `0b111` are alternative radices, and `+7` is a leading sign.
    //
    // `parent: 0` deserves a note, because an earlier version of this comment
    // claimed "`0` is accepted although issue numbers start at 1" and a later
    // one said the reverse. The history: the claim was *wrong* when written —
    // `Store::resolve_next_number` returned `Ok(0)` for an empty directory, so
    // the first issue in every fresh repository was `#0`. Found by running the
    // binary, not by reading the code (tix #1376).
    //
    // `resolve_next_number` now starts at `1`, so the original comment is
    // finally accurate. **`0` still parses, and must.** The parser accepts any
    // `u32`; rejecting `0` here would contradict it, and an existing repository
    // can already contain an issue numbered `0` (this one does — it was written
    // before the fix, and renumbering it is a migration). Rejecting the value
    // would also refuse to *read* such a file, turning a numbering convention
    // into data loss.
    //
    // The general rule this test pins: the parser is not the allocator. What
    // `resolve_next_number` may *produce* is a separate question with a
    // separate answer, and this list asserts only that both `0` and `7` are
    // numbers.
    for (value, expected) in [
        ("0x1F", 31),
        ("0o17", 15),
        ("0b111", 7),
        ("+7", 7),
        ("0", 0),
    ] {
        let issue = Issue::parse(&wp02_file(&format!(
            "number: 3\ntitle: T\nparent: {value}\n"
        )))
        .unwrap_or_else(|e| panic!("`parent: {value}` is expected to parse: {e}"));
        assert_eq!(
            issue.parent,
            Some(crate::id::IssueRef::Number(expected)),
            "`parent: {value}` is pinned to {expected}"
        );
    }

    // And the two spellings of "no parent" that are not a null literal.
    for value in ["null", "~"] {
        let issue = Issue::parse(&wp02_file(&format!(
            "number: 3\ntitle: T\nparent: {value}\n"
        )))
        .unwrap();
        assert_eq!(issue.parent, None, "`parent: {value}` is the absent state");
    }
}

#[test]
fn t006_at_most_one_parent_is_expressible_because_the_field_is_not_a_list() {
    // C-001 is a *shape* guarantee, so it is asserted as a shape: a second
    // `parent:` key in the file is a duplicate-mapping error, not a silent
    // last-one-wins.
    let err = Issue::parse(&wp02_file("number: 3\ntitle: T\nparent: 7\nparent: 8\n"))
        .expect_err("two parents are not representable");
    assert!(err.to_string().contains("parent"), "got: {err}");
}

#[test]
fn t006_the_parent_key_is_distinct_from_mission_and_task() {
    // C-007 / research R2: a decomposition parent is not the Spec Kitty
    // governance pointer, and not a typed dependency edge. Asserted on the
    // *rendered keys*, not the struct fields, because only the keys are the
    // contract.
    let mut issue = Issue::parse(&wp02_file(
            "number: 3\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\nmission: some-mission\ntask: T003\nparent: 7\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n",
        ))
        .unwrap();
    // Set after parsing, because a typed relationship carries a generated id
    // that a hand-written fixture cannot supply. Without this the rendered file
    // has no `relationships:` key at all — an empty list is skipped — and the
    // assertion below would pass for the wrong reason.
    issue.relationships = vec![Relationship::new(3, 8, RelationKind::Blocks, "Eight")];
    assert!(
        issue.relationships.len() == 1,
        "the fixture must carry a relationship under test"
    );
    let fm = issue.frontmatter();
    // `relationships:` is in this list on purpose. WP02's own review guidance
    // asks whether the parent key is distinct from `mission`, `task` **and the
    // typed relationship key**; the first version of this test named only the
    // first two.
    for key in ["mission:", "task:", "relationships:", "parent:"] {
        assert_eq!(
            fm.matches(key).count(),
            1,
            "`{key}` must appear exactly once, got:\n{fm}"
        );
    }
    assert_eq!(issue.mission.as_deref(), Some("some-mission"));
    assert_eq!(issue.task.as_deref(), Some("T003"));
    assert_eq!(issue.parent, Some(crate::id::IssueRef::Number(7)));

    // And clearing one leaves the others alone: they are not aliases.
    issue.parent = None;
    let fm = issue.frontmatter();
    assert!(!fm.contains("parent:"));
    assert!(fm.contains("mission: some-mission"));
    assert!(fm.contains("task: T003"));
}

#[test]
fn t007_the_three_parent_event_kinds_round_trip_through_the_file() {
    // C-004: the audit trail is only an audit trail if the kinds survive it.
    for (kind, spelling) in [
        (HistoryEventKind::ParentSet, "parent_set"),
        (HistoryEventKind::ParentChanged, "parent_changed"),
        (HistoryEventKind::ParentCleared, "parent_cleared"),
    ] {
        assert_eq!(kind.as_str(), spelling);
        assert_eq!(
            HistoryEventKind::from_str(spelling).unwrap(),
            kind,
            "`{spelling}` must parse back to the same kind"
        );
    }
    // An unknown kind is rejected rather than coerced (this module's own
    // rule), so a typo in a hand-edited log cannot be quietly reclassified.
    assert!(HistoryEventKind::from_str("parent_changed_to").is_err());

    // Pin the *serde* spelling too. The enum derives `Serialize`/`Deserialize`
    // under `rename_all = "snake_case"` **and** carries `as_str`/`from_str`, so
    // there are two independent sources of the wire spelling and nothing tied
    // them together. `History` is `#[serde(skip)]` on `Issue`, so the derive is
    // currently unused on the file path — which is exactly why it could drift
    // unnoticed if the history ever became serialised.
    for (kind, spelling) in [
        (HistoryEventKind::ParentSet, "parent_set"),
        (HistoryEventKind::ParentChanged, "parent_changed"),
        (HistoryEventKind::ParentCleared, "parent_cleared"),
    ] {
        let yaml = serde_yaml::to_string(&kind).unwrap();
        assert_eq!(
            yaml.trim(),
            spelling,
            "the derived serde spelling must match `as_str`"
        );
        let back: HistoryEventKind = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(back, kind, "`{spelling}` must round trip through serde");
    }
}

#[test]
fn t007_parent_events_survive_a_history_section_round_trip() {
    let original = "---\nnumber: 3\ntitle: Child\nstatus: todo\nlabels: []\npriority: medium\nparent: 7\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n- 2026-01-02T03:04:05Z \u{2014} alice \u{2014} parent_set \u{2014} parent none -> #7\n\nProse after the section.\n";
    let issue = Issue::parse(original).unwrap();
    assert_eq!(issue.history.len(), 1);
    assert_eq!(issue.history.events()[0].kind, HistoryEventKind::ParentSet);
    assert_eq!(issue.to_file_contents(), original, "byte-stable");
}

#[test]
fn t007_issue_view_carries_the_parent_so_both_services_read_one_projection() {
    // The hierarchy service and the relationship service must not each build
    // their own view of an issue, or they can disagree about the same
    // snapshot.
    let issue = Issue::parse(&wp02_file(WP02_PARENT_FM)).unwrap();
    let view = issue.issue_view();
    assert_eq!(view.parent, Some(crate::id::IssueRef::Number(7)));
    assert_eq!(
        crate::hierarchy::HierarchyNode::parent_number(&view),
        Some(7)
    );
}

// ------------------------------------------------------------------
// WP03 T012 — the TransitionDecision record and its detail grammar
// ------------------------------------------------------------------

fn a_decision() -> TransitionDecision {
    TransitionDecision::new(
        "2026-09-29T12:00:00Z",
        "Herbert Maschke <thyseus@pm.me>",
        "todo",
        "in progress",
        "unstarted",
        "active",
        None,
    )
}

#[test]
fn t012_the_kind_spells_parses_and_renders() {
    assert_eq!(
        HistoryEventKind::TransitionAccepted.as_str(),
        "transition_accepted"
    );
    assert_eq!(
        "transition_accepted".parse::<HistoryEventKind>().unwrap(),
        HistoryEventKind::TransitionAccepted
    );
    assert_eq!(
        HistoryEventKind::TransitionAccepted.to_string(),
        "transition_accepted"
    );
}

#[test]
fn t012_an_unknown_kind_is_rejected_rather_than_coerced() {
    // T012 step 6. A silently reclassified audit entry is worse than a parse
    // failure, so this is the same contract the other kinds have — pinned
    // because the new kind is the newest addition to a closed set and the set
    // is exactly where a `catch-all => Ok(..)` would be introduced.
    let err = "transition_attempted"
        .parse::<HistoryEventKind>()
        .unwrap_err();
    assert!(
        err.to_string().contains("unknown History event kind"),
        "{err}"
    );
}

#[test]
fn t012_the_detail_grammar_renders_and_recovers_every_field() {
    let decision = a_decision();
    assert_eq!(
        decision.detail(),
        "todo -> in progress (unstarted -> active)",
        "the rendered form is the contract, so it is asserted literally"
    );
    let recovered = TransitionDecision::from_event(&decision.to_event()).unwrap();
    assert_eq!(recovered, decision, "a lossless round trip");
}

#[test]
fn t012_an_override_reason_round_trips() {
    let mut decision = a_decision();
    decision.override_reason = Some("reopening: filed against the wrong epic".into());
    assert_eq!(
        decision.detail(),
        "todo -> in progress (unstarted -> active); override: reopening: filed \
             against the wrong epic"
    );
    let recovered = TransitionDecision::from_event(&decision.to_event()).unwrap();
    assert_eq!(
        recovered.override_reason.as_deref(),
        Some("reopening: filed against the wrong epic")
    );
}

#[test]
fn t012_a_reason_containing_the_bare_marker_survives() {
    // The reason is split off at the first `") ; override: "`, so a reason may
    // contain the bare `"; override: "` without being truncated. This is the
    // test that caught the first implementation, which used `rsplit_once` on
    // the *bare* marker: the last occurrence inside the reason is the one that
    // split, leaving a head with no closing paren and failing to parse at all.
    let mut decision = a_decision();
    decision.override_reason = Some("typo; override: actually the right one".into());
    let recovered = TransitionDecision::from_event(&decision.to_event()).unwrap();
    assert_eq!(
        recovered.override_reason.as_deref(),
        Some("typo; override: actually the right one")
    );
    assert_eq!(recovered.to, "in progress", "and the fields still line up");
}

#[test]
fn t012_a_reason_containing_the_anchored_marker_survives() {
    // The discriminating test. `split_once` and `rsplit_once` agree on every
    // other input — the anchored marker appears exactly once unless the reason
    // contains it — so nothing else in this module can tell them apart, and the
    // first version of `t012_a_reason_containing_the_bare_marker_survives`
    // passed against both. This one cannot.
    let mut decision = a_decision();
    decision.override_reason = Some("quoting it: ); override: and again".into());
    let recovered = TransitionDecision::from_event(&decision.to_event()).unwrap();
    assert_eq!(
        recovered.override_reason.as_deref(),
        Some("quoting it: ); override: and again"),
        "the FIRST anchored marker is the split point, and the reason is the rest"
    );
    assert_eq!(recovered.from, "todo");
    assert_eq!(recovered.to, "in progress");
}

#[test]
fn t012_a_reason_containing_an_arrow_survives() {
    let mut decision = a_decision();
    decision.override_reason = Some("note: a -> b was meant to be a -> c".into());
    let recovered = TransitionDecision::from_event(&decision.to_event()).unwrap();
    assert_eq!(
        recovered.override_reason.as_deref(),
        Some("note: a -> b was meant to be a -> c")
    );
    assert_eq!(
        recovered.from, "todo",
        "the head is unaffected by the reason"
    );
    assert_eq!(recovered.to, "in progress");
}

#[test]
fn t012_a_blank_reason_renders_as_no_marker_at_all() {
    // A blank reason must not come back as `Some("")`, which would make
    // `from_event` and `detail()` disagree about whether an override exists.
    let mut decision = a_decision();
    decision.override_reason = Some("   ".into());
    assert_eq!(
        decision.detail(),
        "todo -> in progress (unstarted -> active)"
    );
    let recovered = TransitionDecision::from_event(&decision.to_event()).unwrap();
    assert!(recovered.override_reason.is_none());
}

#[test]
fn t012_a_column_named_with_an_arrow_is_a_documented_limit_not_a_silent_mis_split() {
    // WP03's doc comment originally claimed "a column named `a -> b` cannot
    // desynchronise the fields". It **can**, and this test is why that claim
    // was struck: the grammar is delimiter-based with no escaping, so `from`
    // parses as `"a"`. The limit is inherent — any unescaped separator has a
    // name it cannot represent — and is now documented on the type.
    //
    // What matters downstream is pinned here: the **categories** still parse
    // correctly, because they come from the bracketed tail rather than from
    // the arrow-separated head.
    let mut decision = a_decision();
    decision.from = "a -> b".into();
    decision.to = "in progress".into();
    let recovered = TransitionDecision::from_event(&decision.to_event()).unwrap();
    assert_eq!(recovered.from, "a", "the documented mis-split, pinned");
    assert_eq!(recovered.to_category, "active", "categories stay intact");
    assert_eq!(recovered.from_category, "unstarted");
}

#[test]
fn t012_a_malformed_detail_is_an_error_not_a_partial_record() {
    for bad in [
        "no arrows here",
        "todo -> in progress",                      // no bracketed categories
        "todo -> in progress (unstarted)",          // no category arrow
        "todo -> in progress (unstarted -> active", // no closing paren
        " -> in progress (unstarted -> active)",    // empty from
    ] {
        let event = HistoryEvent::new(
            "2026-09-29T12:00:00Z",
            "alice",
            HistoryEventKind::TransitionAccepted,
            bad,
        );
        assert!(
            TransitionDecision::from_event(&event).is_err(),
            "`{bad}` must not parse into a partial record"
        );
    }
}

#[test]
fn t012_from_event_refuses_a_different_kind() {
    let event = HistoryEvent::new(
        "2026-09-29T12:00:00Z",
        "alice",
        HistoryEventKind::ParentSet,
        "todo -> in progress (unstarted -> active)",
    );
    let err = TransitionDecision::from_event(&event).unwrap_err();
    assert!(
        err.to_string().contains("not a `transition_accepted`"),
        "a parent event is not a transition, however well-formed its detail: {err}"
    );
}

#[test]
fn t012_the_decision_survives_a_full_file_round_trip_byte_for_byte() {
    let mut decision = a_decision();
    decision.override_reason = Some("reopening".into());
    const FILE: &str = "---\nnumber: 1\ntitle: \"T\"\nstatus: \"in progress\"\nlabels: []\npriority: \"medium\"\nfiles: []\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody.";
    let mut issue = Issue::parse(FILE).unwrap();
    issue.history.append(decision.to_event());
    let rendered = issue.to_file_contents();
    let reparsed = Issue::parse(&rendered).unwrap();
    assert_eq!(
        reparsed.to_file_contents(),
        rendered,
        "byte-stable through the file, like every other History kind"
    );
    let events = reparsed.history.events();
    assert_eq!(events.len(), 1);
    assert_eq!(
        TransitionDecision::from_event(events[0]).unwrap(),
        decision,
        "and every field survives the file, not just the rendered text"
    );
}

#[test]
fn t012_a_same_column_record_is_recognisable_as_a_no_op() {
    // A hand-edited file can contain one of these even though the seam never
    // writes one; WP06 must be able to tell that apart from a real move.
    let mut decision = a_decision();
    decision.to = "todo".into();
    assert!(decision.is_no_op());
    let mut real = decision.clone();
    real.to = "in progress".into();
    assert!(!real.is_no_op());
}

// ------------------------------------------------------------------
// WP03 — project associations in the model (mission
// first-class-projects-01M3BYBW)
// ------------------------------------------------------------------

/// A minimal issue file whose only interesting key is `projects`.
fn project_file(projects_block: &str) -> String {
    format!(
        "---\nnumber: 1\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\n{projects_block}created: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody."
    )
}

#[test]
fn t011_projects_is_an_optional_id_list_that_round_trips_two_associations() {
    // C-003: multiple membership, shaped like `cycles`/`milestones`.
    let original = project_file("projects:\n- p-3f9a2c\n- p-7b1e04\n");
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(
        issue.projects,
        Some(vec!["p-3f9a2c".to_string(), "p-7b1e04".to_string()]),
        "the field holds several project ids"
    );
    let rendered = issue.to_file_contents();
    assert_eq!(
        rendered, original,
        "two associations round-trip byte-stably"
    );
    assert_eq!(
        Issue::parse(&rendered).unwrap().projects,
        issue.projects,
        "and survive a second read"
    );
}

#[test]
fn t011_an_issue_with_no_projects_serializes_with_no_key() {
    let no_key = project_file("");
    assert!(!no_key.contains("projects:"));
    let issue = Issue::parse(&no_key).unwrap();
    assert_eq!(issue.projects, None, "an absent key reads as absent");
    let rendered = issue.to_file_contents();
    assert_eq!(
        rendered, no_key,
        "a file that never had the field is untouched by a round trip"
    );
    assert!(!rendered.contains("projects:"));
}

#[test]
fn t011_an_empty_projects_list_is_written_as_absent() {
    let issue = Issue::parse(&project_file("projects: []\n")).unwrap();
    let rendered = issue.to_file_contents();
    assert!(
        !rendered.contains("projects:"),
        "the key is omitted when empty, exactly like cycles/milestones:\n{rendered}"
    );
    assert_eq!(Issue::parse(&rendered).unwrap().projects, None);
}

#[test]
fn t011_a_malformed_projects_value_is_rejected_not_coerced() {
    // A scalar where a list belongs.
    let scalar = project_file("projects: p-3f9a2c\n");
    assert!(
        Issue::parse(&scalar).is_err(),
        "a bare scalar is not a list of ids"
    );
    // A mapping where a string belongs.
    let mapping = project_file("projects:\n- id: p-1\n");
    assert!(
        Issue::parse(&mapping).is_err(),
        "each entry must be an id string, not a map"
    );
}

#[test]
fn t011_projects_is_distinct_from_cycles_milestones_mission_and_task() {
    // Four reference fields on one struct is exactly where an alias hides, so
    // the keys and the slots are both pinned.
    let mut issue = issue("Body.");
    issue.cycles = Some(vec!["c-one".into()]);
    issue.milestones = Some(vec!["m-one".into()]);
    issue.mission = Some("mission-x".into());
    issue.task = Some("WP03".into());
    issue.projects = Some(vec!["p-one".into()]);

    let rendered = issue.to_file_contents();
    for key in ["projects:", "cycles:", "milestones:", "mission:", "task:"] {
        assert_eq!(
            rendered.matches(key).count(),
            1,
            "`{key}` must appear exactly once, never aliased onto another field:\n{rendered}"
        );
    }

    let back = Issue::parse(&rendered).unwrap();
    assert_eq!(back.projects, Some(vec!["p-one".to_string()]));
    assert_eq!(back.cycles, Some(vec!["c-one".to_string()]));
    assert_eq!(back.milestones, Some(vec!["m-one".to_string()]));
    assert_eq!(back.mission, Some("mission-x".to_string()));
    assert_eq!(back.task, Some("WP03".to_string()));
}

#[test]
fn t011_an_issue_exposes_the_project_node_view_the_service_reads() {
    use crate::projects::ProjectNode;
    let mut issue = issue("Body.");
    issue.number = 9;
    issue.title = "Nine".into();
    issue.status = Status::new("doing");
    issue.projects = Some(vec!["p-1".into()]);
    assert_eq!(ProjectNode::number(&issue), 9);
    assert_eq!(ProjectNode::title(&issue), "Nine");
    assert_eq!(ProjectNode::status(&issue), "doing");
    assert_eq!(ProjectNode::project_ids(&issue), &["p-1".to_string()][..]);
    issue.projects = None;
    assert!(
        ProjectNode::project_ids(&issue).is_empty(),
        "absent is the empty slice, not a panic"
    );
}

#[test]
fn t012_project_kinds_render_and_parse() {
    assert_eq!(
        HistoryEventKind::ProjectAssociated.as_str(),
        "project_associated"
    );
    assert_eq!(
        HistoryEventKind::ProjectAssociated.to_string(),
        "project_associated"
    );
    assert_eq!(
        "project_associated".parse::<HistoryEventKind>().unwrap(),
        HistoryEventKind::ProjectAssociated
    );
    assert_eq!(
        HistoryEventKind::ProjectDissociated.as_str(),
        "project_dissociated"
    );
    assert_eq!(
        "project_dissociated".parse::<HistoryEventKind>().unwrap(),
        HistoryEventKind::ProjectDissociated
    );
}

#[test]
fn t012_from_project_maps_both_service_kinds() {
    use crate::projects::ProjectEventKind;
    assert_eq!(
        HistoryEventKind::from_project(ProjectEventKind::ProjectAssociated),
        HistoryEventKind::ProjectAssociated
    );
    assert_eq!(
        HistoryEventKind::from_project(ProjectEventKind::ProjectDissociated),
        HistoryEventKind::ProjectDissociated
    );
}

#[test]
fn t012_a_project_event_round_trips_through_the_file() {
    let mut issue = issue("Body.");
    issue.history.append(HistoryEvent::new(
        "2026-01-01T00:00:00Z",
        "alice",
        HistoryEventKind::ProjectAssociated,
        "project `p-1` associated",
    ));
    let rendered = issue.to_file_contents();
    let back = Issue::parse(&rendered).unwrap();
    let events = back.history.events();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].kind, HistoryEventKind::ProjectAssociated);
    assert_eq!(events[0].detail, "project `p-1` associated");
    assert_eq!(
        back.to_file_contents(),
        rendered,
        "byte-stable through the file, like every other History kind"
    );
}

#[test]
fn t012_an_unknown_project_style_kind_is_rejected() {
    assert!(
        "projects_changed".parse::<HistoryEventKind>().is_err(),
        "an unknown kind must be rejected, never coerced to a default"
    );
}

// ------------------------------------------------------------------
// WP03 — epic references in the model (mission
// epics-work-items-01M3BYW4)
// ------------------------------------------------------------------

#[test]
fn t013_epics_is_an_optional_id_list_that_round_trips_two_references() {
    // C-003: several references, shaped like `projects`/`cycles`/`milestones`.
    let original = project_file("epics:\n- e-7c4a91\n- e-2b8f30\n");
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(
        issue.epics,
        Some(vec!["e-7c4a91".to_string(), "e-2b8f30".to_string()]),
        "the field holds several epic ids"
    );
    let rendered = issue.to_file_contents();
    assert_eq!(rendered, original, "two references round-trip byte-stably");
    assert_eq!(
        Issue::parse(&rendered).unwrap().epics,
        issue.epics,
        "and survive a second read"
    );
}

#[test]
fn t013_an_issue_with_no_epics_serializes_with_no_key() {
    let no_key = project_file("");
    assert!(!no_key.contains("epics:"));
    let issue = Issue::parse(&no_key).unwrap();
    assert_eq!(issue.epics, None, "an absent key reads as absent");
    let rendered = issue.to_file_contents();
    assert_eq!(
        rendered, no_key,
        "a file that never had the field is untouched by a round trip"
    );
    assert!(!rendered.contains("epics:"));
}

#[test]
fn t013_an_empty_epics_list_is_written_as_absent() {
    let issue = Issue::parse(&project_file("epics: []\n")).unwrap();
    let rendered = issue.to_file_contents();
    assert!(
        !rendered.contains("epics:"),
        "the key is omitted when empty, exactly like projects/cycles/milestones:\n{rendered}"
    );
    assert_eq!(Issue::parse(&rendered).unwrap().epics, None);
}

#[test]
fn t013_a_malformed_epics_value_is_rejected_not_coerced() {
    // A scalar where a list belongs.
    let scalar = project_file("epics: e-7c4a91\n");
    assert!(
        Issue::parse(&scalar).is_err(),
        "a bare scalar is not a list of ids"
    );
    // A mapping where a string belongs.
    let mapping = project_file("epics:\n- id: e-1\n");
    assert!(
        Issue::parse(&mapping).is_err(),
        "each entry must be an id string, not a map"
    );
}

#[test]
fn t013_epics_is_distinct_from_projects_cycles_milestones_mission_task_and_files() {
    // Five list-valued reference fields on one struct is exactly where an alias
    // hides, so the keys and the slots are both pinned. `task` is the C-001
    // guard: an epic reference must never read as a task reference.
    let mut issue = issue("Body.");
    issue.cycles = Some(vec!["c-one".into()]);
    issue.milestones = Some(vec!["m-one".into()]);
    issue.mission = Some("mission-x".into());
    issue.task = Some("WP03".into());
    issue.projects = Some(vec!["p-one".into()]);
    issue.epics = Some(vec!["e-one".into()]);
    issue.files = vec!["docs/a.md".into()];

    let rendered = issue.to_file_contents();
    for key in [
        "epics:",
        "projects:",
        "cycles:",
        "milestones:",
        "mission:",
        "task:",
        "files:",
    ] {
        assert_eq!(
            rendered.matches(key).count(),
            1,
            "`{key}` must appear exactly once, never aliased onto another field:\n{rendered}"
        );
    }

    let back = Issue::parse(&rendered).unwrap();
    assert_eq!(back.epics, Some(vec!["e-one".to_string()]));
    assert_eq!(back.projects, Some(vec!["p-one".to_string()]));
    assert_eq!(back.cycles, Some(vec!["c-one".to_string()]));
    assert_eq!(back.milestones, Some(vec!["m-one".to_string()]));
    assert_eq!(back.mission, Some("mission-x".to_string()));
    assert_eq!(back.task, Some("WP03".to_string()));
    assert_eq!(back.files, vec!["docs/a.md".to_string()]);
}

#[test]
fn t013_an_issue_exposes_the_epic_node_view_the_service_reads() {
    use crate::epics::EpicNode;
    let mut issue = issue("Body.");
    issue.number = 9;
    issue.title = "Nine".into();
    issue.status = Status::new("doing");
    issue.epics = Some(vec!["e-1".into()]);
    assert_eq!(EpicNode::number(&issue), 9);
    assert_eq!(EpicNode::title(&issue), "Nine");
    assert_eq!(EpicNode::status(&issue), "doing");
    assert_eq!(EpicNode::epic_ids(&issue), &["e-1".to_string()][..]);
    issue.epics = None;
    assert!(
        EpicNode::epic_ids(&issue).is_empty(),
        "absent is the empty slice, not a panic"
    );
}

#[test]
fn t014_epic_kinds_render_and_parse() {
    assert_eq!(HistoryEventKind::EpicReferenced.as_str(), "epic_referenced");
    assert_eq!(
        HistoryEventKind::EpicReferenced.to_string(),
        "epic_referenced"
    );
    assert_eq!(
        "epic_referenced".parse::<HistoryEventKind>().unwrap(),
        HistoryEventKind::EpicReferenced
    );
    assert_eq!(
        HistoryEventKind::EpicDereferenced.as_str(),
        "epic_dereferenced"
    );
    assert_eq!(
        "epic_dereferenced".parse::<HistoryEventKind>().unwrap(),
        HistoryEventKind::EpicDereferenced
    );
}

#[test]
fn t014_from_epic_maps_both_service_kinds() {
    use crate::epics::EpicEventKind;
    assert_eq!(
        HistoryEventKind::from_epic(EpicEventKind::EpicReferenced),
        HistoryEventKind::EpicReferenced
    );
    assert_eq!(
        HistoryEventKind::from_epic(EpicEventKind::EpicDereferenced),
        HistoryEventKind::EpicDereferenced
    );
}

#[test]
fn t014_an_epic_event_round_trips_through_the_file() {
    let mut issue = issue("Body.");
    issue.history.append(HistoryEvent::new(
        "2026-01-01T00:00:00Z",
        "alice",
        HistoryEventKind::EpicReferenced,
        "epic `e-7c4a91` referenced",
    ));
    let rendered = issue.to_file_contents();
    let back = Issue::parse(&rendered).unwrap();
    let events = back.history.events();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].kind, HistoryEventKind::EpicReferenced);
    assert_eq!(events[0].detail, "epic `e-7c4a91` referenced");
    assert_eq!(
        back.to_file_contents(),
        rendered,
        "byte-stable through the file, like every other History kind"
    );
}

#[test]
fn t014_an_unknown_epic_style_kind_is_rejected() {
    assert!(
        "epics_changed".parse::<HistoryEventKind>().is_err(),
        "an unknown kind must be rejected, never coerced to a default"
    );
}

#[test]
fn t046_the_two_new_event_kinds_round_trip_through_their_spellings() {
    // FR-002's classes fold these two kinds, so a missing `as_str` entry or a
    // missing `FromStr` arm would write a line no reader could classify back.
    for (kind, spelling) in [
        (HistoryEventKind::EstimateChanged, "estimate_changed"),
        (
            HistoryEventKind::CycleMembershipChanged,
            "cycle_membership_changed",
        ),
    ] {
        assert_eq!(kind.as_str(), spelling);
        assert_eq!(
            HistoryEventKind::from_str(spelling).unwrap(),
            kind,
            "`{spelling}` must parse back to the same kind"
        );
        let yaml = serde_yaml::to_string(&kind).unwrap();
        assert_eq!(
            yaml.trim(),
            spelling,
            "the derived serde spelling must match `as_str`"
        );
    }
}

#[test]
fn t046_the_new_kinds_survive_a_full_file_round_trip() {
    let mut issue = issue("Body.");
    issue.history.append(HistoryEvent::new(
        "2026-01-01T00:00:00Z",
        "alice",
        HistoryEventKind::EstimateChanged,
        "estimate: none -> 3",
    ));
    issue.history.append(HistoryEvent::new(
        "2026-01-02T00:00:00Z",
        "alice",
        HistoryEventKind::CycleMembershipChanged,
        "cycles: none -> Default",
    ));
    let rendered = issue.to_file_contents();
    let back = Issue::parse(&rendered).unwrap();
    let events = back.history.events();
    assert_eq!(events.len(), 2);
    assert_eq!(events[0].kind, HistoryEventKind::EstimateChanged);
    assert_eq!(events[1].kind, HistoryEventKind::CycleMembershipChanged);
    assert_eq!(
        back.to_file_contents(),
        rendered,
        "byte-stable through the file, like every other History kind"
    );
}