tix-tracker 0.10.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
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
//! Issue data model and file-surface types.
//!
//! Mirrors `contracts/file-format.md` and `data-model.md` exactly. The
//! [`Issue`] struct is the Serde surface for the YAML frontmatter of an
//! issue file; the markdown body is carried in `body` and round-trips
//! verbatim. [`Status`], [`Priority`] and [`Labels`] are the value types
//! that appear in frontmatter.

use std::collections::{BTreeMap, HashSet};
use std::fmt;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::{Result, TixError};
use crate::relationships::{IssueView, Relationship};
use crate::slug::slugify;

/// A board column name. A newtype over the user-defined column strings from
/// `tix.toml`; unknown names survive deserialization because columns are
/// config-defined (a renamed column renders as a "Mismatched" pseudo-column,
/// never a crash).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Status(pub String);

impl Status {
    /// Create a status from a column name.
    pub fn new(name: impl Into<String>) -> Self {
        Status(name.into())
    }

    /// Whether this status equals `name` (exact, case-sensitive).
    pub fn is(&self, name: &str) -> bool {
        self.0 == name
    }

    /// The column name this status refers to.
    pub fn display(&self) -> &str {
        &self.0
    }
}

impl Default for Status {
    fn default() -> Self {
        Status("todo".to_string())
    }
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Issue priority.
///
/// The documented set is `low` / `medium` / `high` with `medium` as the
/// default (spec + data-model). Any other value is preserved as-is for
/// forward compatibility (data-model: "unknown values accepted as-is",
/// "preserved ... but not normalized"), so e.g. `urgent` round-trips
/// unchanged.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum Priority {
    Low,
    #[default]
    Medium,
    High,
    /// An unknown priority string, preserved verbatim (forward-compatible).
    ///
    /// The empty string is *not* treated as unknown: it is an explicitly unset
    /// priority, which `tix lint` accepts and which round-trips as `''`. It stays
    /// in this variant rather than getting a variant of its own because
    /// `Priority` is public API on a published crate, and adding a variant to a
    /// non-`#[non_exhaustive]` enum is a semver break for every downstream
    /// `match`. Use [`Priority::is_undefined`] rather than comparing the string.
    Other(String),
}

impl Priority {
    fn as_str(&self) -> &str {
        match self {
            Priority::Low => "low",
            Priority::Medium => "medium",
            Priority::High => "high",
            Priority::Other(s) => s,
        }
    }

    /// Whether the priority is explicitly **unset** — written `priority: ''`.
    ///
    /// Distinct from [`Priority::default`], which is `Medium`. An issue can
    /// therefore say "no priority" without being read as "medium", and without
    /// the value being silently rewritten on the next write.
    ///
    /// `tix lint` accepts this state; see [`crate::commands::lint`] for the
    /// check it is exempt from.
    pub fn is_undefined(&self) -> bool {
        matches!(self, Priority::Other(s) if s.is_empty())
    }
}

impl FromStr for Priority {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(match s.to_ascii_lowercase().as_str() {
            "low" => Priority::Low,
            "medium" => Priority::Medium,
            "high" => Priority::High,
            _ => Priority::Other(s.to_string()),
        })
    }
}

impl fmt::Display for Priority {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for Priority {
    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for Priority {
    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        let raw = String::deserialize(d)?;
        match raw.parse() {
            Ok(parsed) => Ok(parsed),
            Err(_) => Ok(Priority::Other(raw)),
        }
    }
}

/// Issue labels. Free-form strings kept exactly as authored (case and
/// spaces preserved); default `[]`.
pub type Labels = Vec<String>;

/// Assignee file-encoding rule (FR-027 / FR-014, `contracts/file-format.md`
/// rule 5).
///
/// - **In memory**: a manual handle is always bare (`alice`, never
///   `@alice`); a git-derived identity is the full `Name <email>` string,
///   verbatim.
/// - **Read** ([`de_assignee`]): a single leading `@` is stripped, so both
///   the legacy `@alice` bytes and the bare `alice` bytes normalize to the
///   same in-memory handle. A full identity / identity-like value never
///   starts with `@` and passes through untouched.
/// - **Write** ([`se_assignee`]): a value carrying an identity form (both `<`
///   and `>` present, e.g. `Name <email>`) is persisted verbatim — no forced
///   `@` and no mangling of the angle brackets. Any other value is a manual
///   handle and is persisted with a single leading `@`, byte-identical to the
///   legacy `@alice` files (C-010) and to what `contracts/cli.md` conformance
///   pins for `--assignee @alice`.
/// - `None` persists as `null` (omitted by `skip_serializing_if`).
///
/// The in-memory value stays display-neutral: the `@` cosmetic a CLI/TUI
/// renders around handles is their concern, not the model's.
fn de_assignee<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<Option<String>, D::Error> {
    let opt = Option::<String>::deserialize(d)?;
    Ok(opt.map(|v| v.strip_prefix('@').unwrap_or(&v).to_string()))
}

/// Serialize an assignee per the encoding rule documented on [`de_assignee`]:
/// identity-like values verbatim, manual handles `@`-prefixed (legacy bytes).
fn se_assignee<S: Serializer>(opt: &Option<String>, s: S) -> std::result::Result<S::Ok, S::Error> {
    match opt {
        None => s.serialize_none(),
        Some(value) => {
            let is_identity = value.contains('<') && value.contains('>');
            let full = if is_identity || value.starts_with('@') {
                value.clone()
            } else {
                format!("@{value}")
            };
            s.serialize_str(&full)
        }
    }
}

/// Serialization rule for the optional planning lists `cycles`/`milestones`
/// (`contracts/file-format-planning.md`): the key is omitted when absent or
/// empty (only non-empty lists serialize), and duplicate entries are
/// collapsed on write preserving first-seen order.
fn skip_planning_list(v: &Option<Vec<String>>) -> bool {
    v.as_deref().is_none_or(|items| items.is_empty())
}

fn se_planning_list<S: Serializer>(
    v: &Option<Vec<String>>,
    s: S,
) -> std::result::Result<S::Ok, S::Error> {
    let items: Vec<&String> = match v {
        Some(items) => {
            items
                .iter()
                .fold((Vec::new(), HashSet::new()), |(mut out, mut seen), item| {
                    if seen.insert(item.as_str()) {
                        out.push(item);
                    }
                    (out, seen)
                })
                .0
        }
        None => Vec::new(),
    };
    items.serialize(s)
}

/// Today's date as a local-free calendar date in `YYYY-MM-DD`.
///
/// Computed from the Unix epoch in UTC; `crate`-wide reproducible and
/// dependency-free. Later WPs reuse it for `created`/`updated` and the
/// date prefix of filenames.
pub fn today() -> String {
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let days = (secs / 86_400) as i64;
    let (y, m, d) = civil_from_days(days);
    format!("{y:04}-{m:02}-{d:02}")
}

/// The current UTC instant as RFC 3339 (`2026-09-27T10:14:02Z`), used for
/// [`HistoryEvent`] timestamps.
///
/// Dependency-free like [`today`]: the epoch seconds are converted through
/// [`civil_from_days`] and the time-of-day is derived arithmetically.
pub fn utc_now_rfc3339() -> String {
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let (y, m, d) = civil_from_days(days);
    format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
        rem / 3600,
        (rem % 3600) / 60,
        rem % 60
    )
}

/// Whether a frontmatter document still carries the retired `links:` key.
///
/// The key is not part of the model at all, so it cannot be detected after
/// deserialization, and it must never be *read* as typed data (C-001). The
/// frontmatter is therefore also parsed as a plain YAML mapping and checked for
/// a **top-level** `links` key.
///
/// A raw line scan was tried first and was wrong in both directions: it matched
/// an indented `links:` under some other key, and it missed a quoted `"links":`
/// key. Matching the parsed top-level key gets both right, and a line inside a
/// `|`/`>` block scalar is unambiguously not a key.
///
/// A frontmatter that will not parse as a mapping falls back to a line scan.
/// That fallback is **indentation-aware**, matching only column-0 keys.
///
/// It has to be. `serde_yaml` rejects duplicate keys when deserializing into a
/// `Mapping` but *tolerates* a duplicate unknown key when deserializing into
/// `Issue`, so a file can reach the fallback and still parse. An earlier
/// indentation-blind fallback then matched the *nested* `links:` in
/// `meta:\n  links: []` and reported a retired key on a file that has none —
/// the two code paths disagreeing about what "top-level" means, which is
/// precisely what the primary path was introduced to get right.
///
/// **An empty `links` is not a finding.** The key is reported because its *value*
/// is no longer readable, and an empty value has nothing to lose. Treating mere
/// presence as the defect made `tix lint` reject every issue file this repository
/// has ever written — they all carry a `links: []` from the old model — with no
/// way to make them valid short of hand-editing every file, because the mission
/// provides no migration for the key. A tool that declares its entire existing
/// corpus invalid on the strength of a field that was empty is not reporting a
/// problem, it is refusing to read its own data.
/// Every top-level key this model knows, in `Issue`'s declaration order, plus the
/// retired `links:` at the end.
///
/// The trailing `links` is not a field — see below — so "declaration order" holds
/// for the modelled keys and the retired key is simply appended.
///
/// Used by [`capture_extra_frontmatter`] to decide what is "unknown". Kept as an
/// explicit list rather than derived from the struct because a macro cannot read a
/// struct's own field names, and a mistake here is silent data loss: a key wrongly
/// listed as known is dropped on write, which is the bug #1361 exists to remove.
///
/// A mistake in the other direction is equally silent and was equally real: when
/// `parent` was added to [`Issue`] and not here, [`capture_extra_frontmatter`] took it
/// for an unknown key and the writer emitted `parent: 7` **twice** in one file — once
/// from the field, once spliced back from the capture. The file still parsed, so
/// nothing failed until a test compared bytes.
/// `known_frontmatter_keys_cover_every_written_key` derives the key set from a
/// fully-populated [`Issue`] and is the guard for it: adding a frontmatter field
/// without registering its key here is now a compile-clean, test-red change.
///
/// The retired `links:` is here on purpose. It is **recognised but never captured**,
/// so it is reported by its own `retired_links_key` finding and then dropped (C-001).
/// Capturing it would round-trip it and quietly undo the typed-relationship
/// migration — the data would come back, but the model would still not understand it.
pub const KNOWN_FRONTMATTER_KEYS: &[&str] = &[
    "number",
    "id",
    "title",
    "status",
    "labels",
    "type",
    "priority",
    "assignee",
    "estimate",
    "commit",
    "gitlab_id",
    "linear_id",
    "mission",
    "task",
    "relationships",
    "related_issues",
    "parent",
    // Mission `recurring-issues-01M3C7G7` (WP02): the series/occurrence table.
    "series",
    // Mission `project-issue-health-status-01M3C8HX` (WP02): the current health
    // projection. Registered here the moment the field was added — leaving it out is
    // the `parent` defect above, which wrote the key twice in one file.
    "health",
    "files",
    "cycles",
    "milestones",
    // Mission `first-class-projects-01M3BYBW` (WP03): the project association
    // list. Registered the moment the field was added — the `parent` defect above
    // is exactly what an unregistered new field does.
    "projects",
    // Mission `epics-work-items-01M3BYW4` (WP03): the epic reference list.
    // Registered the moment the field was added — an unregistered key is captured
    // as unknown and spliced back, so every file gains a duplicate block. The
    // `known_frontmatter_keys_cover_every_written_key` fixture populates it so this
    // guard can go red.
    "epics",
    "reviewer",
    "start_date",
    "due_date",
    "entered_at",
    "source",
    // Mission `per-issue-time-tracking-01M3C9A4` (WP01 T004): the issue's current
    // time entries. Registered the moment the field was added — an unregistered
    // key is captured as unknown and spliced back, so every file that carries one
    // gains a duplicate block (the `parent` defect above). The
    // `known_frontmatter_keys_cover_every_written_key` fixture populates it, so
    // this guard goes red if the registration ever drifts.
    "time_entries",
    "created",
    "updated",
    "links",
];

/// Capture every top-level frontmatter key this model does not know, as
/// `key -> raw source block` (#1361).
///
/// **Raw block, not a parsed value.** Re-serialising a parsed value would re-quote
/// and re-indent it, so a key written one way would come back another way and every
/// write would produce a diff. Splicing the original bytes keeps the round trip
/// byte-stable for content this model has no opinion about — which is the whole
/// point of preserving it.
///
/// A block is the key's own line plus every following line that continues it: an
/// indented line, or a block-sequence item. The scan is textual on purpose. A YAML
/// parse would be tidier, but the raw text is what has to be reproduced, and
/// re-deriving block boundaries from a parse is how a nested list ends up half
/// captured.
///
/// `links` is skipped. See [`KNOWN_FRONTMATTER_KEYS`].
pub fn capture_extra_frontmatter(frontmatter: &str) -> BTreeMap<String, String> {
    let mut out = BTreeMap::new();
    let mut current: Option<(String, String)> = None;
    for line in frontmatter.lines() {
        match top_level_key(line) {
            Some(key) => {
                if let Some((name, block)) = current.take() {
                    out.insert(name, block);
                }
                if KNOWN_FRONTMATTER_KEYS.contains(&key.as_str()) {
                    continue;
                }
                current = Some((key, line.to_string()));
            }
            None => {
                // A continuation line: indented, or a block-sequence item. A blank
                // line ends the block, because YAML does too.
                if let Some((_, block)) = current.as_mut() {
                    if line.trim().is_empty() {
                        current = None;
                    } else {
                        block.push('\n');
                        block.push_str(line);
                    }
                }
            }
        }
    }
    if let Some((name, block)) = current.take() {
        out.insert(name, block);
    }
    out
}

/// The key of a top-level YAML mapping entry, or `None` for a continuation line.
///
/// Only column 0 counts. An indented `key:` is part of a nested mapping, and a
/// `- item` is a sequence entry; treating either as a top-level key would end the
/// previous block early and capture a fragment.
fn top_level_key(line: &str) -> Option<String> {
    if !line.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
        return None;
    }
    let colon = line.find(':')?;
    let key = &line[..colon];
    if key.is_empty()
        || !key
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        return None;
    }
    Some(key.to_string())
}

fn frontmatter_has_retired_links_key(frontmatter: &str) -> bool {
    if let Ok(mapping) = serde_yaml::from_str::<serde_yaml::Mapping>(frontmatter) {
        let key = serde_yaml::Value::String("links".into());
        return match mapping.get(&key) {
            Some(value) => !links_value_is_empty(value),
            None => false,
        };
    }
    frontmatter.lines().any(|line| {
        if line.starts_with(' ') || line.starts_with('\t') {
            return false;
        }
        line.split_once(':')
            .map(|(key, _)| key.trim() == "links")
            .unwrap_or(false)
    })
}

/// Whether a `links:` value carries no entries, in the shapes the old model
/// wrote and the shapes a hand-edit can produce: `[]`, `~`/`null`, an empty
/// scalar, and a block sequence with no items (`links:\n` followed by the next
/// key). Anything else is populated and therefore a finding.
fn links_value_is_empty(value: &serde_yaml::Value) -> bool {
    match value {
        serde_yaml::Value::Null => true,
        serde_yaml::Value::Sequence(items) => items.is_empty(),
        serde_yaml::Value::String(s) => s.trim().is_empty() || s.trim() == "[]",
        serde_yaml::Value::Mapping(m) => m.is_empty(),
        serde_yaml::Value::Tagged(t) => links_value_is_empty(&t.value),
        _ => false,
    }
}

/// A strict `YYYY-MM-DD` calendar-date check (shape + real month/day with
/// per-month day counts and leap years, `year >= 1970`), so `2026-13-99`,
/// `2026-02-30` and `1969-12-31` are all flagged as malformed. The shared
/// validation path for date-bearing config and frontmatter fields (FR-007).
pub fn validate_date(s: &str) -> bool {
    let b = s.as_bytes();
    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
        return false;
    }
    for &c in &b[0..4] {
        if !c.is_ascii_digit() {
            return false;
        }
    }
    for &c in &[b[5], b[6], b[8], b[9]] {
        if !c.is_ascii_digit() {
            return false;
        }
    }
    let year = u32::from(b[0] - b'0') * 1000
        + u32::from(b[1] - b'0') * 100
        + u32::from(b[2] - b'0') * 10
        + u32::from(b[3] - b'0');
    let month = u32::from(b[5] - b'0') * 10 + u32::from(b[6] - b'0');
    let day = u32::from(b[8] - b'0') * 10 + u32::from(b[9] - b'0');
    if year < 1970 || !(1..=12).contains(&month) {
        return false;
    }
    day >= 1 && day <= days_in_month(year, month)
}

/// Real day count for a Gregorian month (leap-aware).
fn days_in_month(year: u32, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
            if leap { 29 } else { 28 }
        }
        _ => 0,
    }
}

/// Message-bearing [`validate_date`] for surfaces that want to explain what
/// was wrong. The error names the offending value; callers add field context.
fn validate_date_msg(s: &str) -> std::result::Result<(), String> {
    if validate_date(s) {
        Ok(())
    } else {
        Err(format!(
            "`{s}` is not a `YYYY-MM-DD` calendar date (year >= 1970)"
        ))
    }
}

/// Validate a `(start_date, due_date)` pair for an issue (FR-007, C-002).
///
/// Each present date must parse as a calendar date; when both are present,
/// `due_date >= start_date` must hold. Returns a config-class error naming
/// both fields on an ordering violation, matching
/// `contracts/file-format-planning.md`.
pub fn validate_issue_dates(start_date: Option<&str>, due_date: Option<&str>) -> Result<()> {
    if let Some(start) = start_date
        && validate_date_msg(start).is_err()
    {
        return Err(TixError::Config(format!(
            "start_date {start:?} must be a `YYYY-MM-DD` calendar date"
        )));
    }
    if let Some(due) = due_date {
        if validate_date_msg(due).is_err() {
            return Err(TixError::Config(format!(
                "due_date {due:?} must be a `YYYY-MM-DD` calendar date"
            )));
        }
        if let Some(start) = start_date
            && !date_lte(start, due)
        {
            return Err(TixError::Config(format!(
                "due_date {due:?} must be `>= start_date` {start:?}"
            )));
        }
    }
    Ok(())
}

/// Chronological order for two validated `YYYY-MM-DD` strings.
///
/// Plain lexicographic comparison equals chronological order for the
/// formats [`validate_date`] accepts (fixed-width zero-padded fields), so
/// later WPs (overdue, filters, cascade) reuse identical ordering logic.
pub fn date_lte(a: &str, b: &str) -> bool {
    a <= b
}

/// Convert days since the Unix epoch to a `(year, month, day)` civil date
/// (Howard Hinnant's `civil_from_days`).
fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097; // [0, 146096]
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11]
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12]
    (if m <= 2 { y + 1 } else { y }, m, d)
}

/// Parse a `### <author> (<YYYY-MM-DD>)` comment head into its parts.
///
/// The date is the trailing `(<YYYY-MM-DD>)` group; the author is everything
/// before it. A head without a well-formed trailing date still yields the
/// author (the date defaults to `""`), so malformed heads survive the parse
/// without crashing (`contracts/comments-format.md` rule "preserve verbatim").
fn parse_comment_head(after: &str) -> (String, String) {
    let (author, date) = match after.len() {
        len if len >= 12 && after.as_bytes()[len - 1] == b')' => {
            let close = len - 1;
            let open = after[..close].rfind(" (");
            match open {
                Some(open) => {
                    let maybe_date = &after[open + 2..close];
                    if maybe_date.len() == 10
                        && maybe_date.as_bytes()[4] == b'-'
                        && maybe_date.as_bytes()[7] == b'-'
                    {
                        (&after[..open], maybe_date)
                    } else {
                        (after, "")
                    }
                }
                None => (after, ""),
            }
        }
        _ => (after, ""),
    };
    (author.trim_end().to_string(), date.to_string())
}

/// A single issue comment, parsed from the `## Comments` body section.
///
/// Mirrors `contracts/comments-format.md`: each comment is a level-3 heading
/// `### <author> (<YYYY-MM-DD>)` followed by free text up to the next `###`
/// head or end of file. Blank lines inside `text` are preserved verbatim
/// (NFR-005); the model never normalizes hand-authored content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Comment {
    pub author: String,
    pub date: String,
    pub text: String,
}

/// The recurrence metadata an issue carries (`series:`), mission
/// `recurring-issues-01M3C7G7`.
///
/// The current-health half of the `health:` frontmatter key (mission
/// `project-issue-health-status-01M3C8HX`, WP02 T007).
///
/// Every field is the file's own spelling and every field is optional, so a partial
/// or hand-written block round-trips as written; the health layer interprets it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HealthRef {
    /// The current state, e.g. `on_track`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    /// How it was obtained: `current`, `derived`, or `override`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// The policy version the value was derived under, when it was derived.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_version: Option<String>,
    /// When the value was last updated, as the event recorded it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,
}

/// One table, two roles, told apart by which fields are set — the definition
/// carries `rule`, an occurrence carries `key`/`date`. A `role:` flag would be a
/// second source of truth a writer could disagree with, so there is none:
/// [`crate::recurrence::series::SeriesRef::role`] derives it.
///
/// Identity is (`id`, `date`) and never the issue number, the title, or the
/// filename (C-002): those are display values that move, and an occurrence that
/// moved with them would be generated twice.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SeriesRef {
    /// The stable series id. Required in both roles.
    pub id: String,
    /// The series' display name. Mutable label, never identity; on the
    /// definition, and copied onto an occurrence for readability.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The canonical local date key (`YYYY-MM-DD`) an occurrence was generated
    /// for. Set on occurrences only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,
    /// The occurrence's idempotency key (`<series-id>@<YYYY-MM-DD>`). Stored
    /// rather than re-derived, so a file whose key the current rule would no
    /// longer produce is still readable — and still a no-op (C-006).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    /// The schedule, as the file spells it. Set on the definition only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rule: Option<SeriesRule>,
    /// The lifecycle state. Set on the definition only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state: Option<crate::recurrence::series::SeriesLifecycle>,
    /// The generation cursor: the last date the generator considered. Set on the
    /// definition only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
    /// Occurrence dates the user explicitly skipped, so generation never
    /// recreates them (C-006). Set on the definition only.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skipped: Vec<String>,
}

/// The rule half of `series:`, as the file spells it (`data-model.md` §2).
///
/// Typed for the fields the contract names and **flat strings** for everything
/// else, so a cadence key this build does not know round-trips verbatim in
/// `extensions` instead of being dropped on the next edit. The typed rule with its
/// validation and its arithmetic is
/// [`crate::recurrence::rule::RecurrenceRule`], built from this by
/// [`crate::recurrence::series::Series::from_ref`] — the split exists so the issue
/// model stays `Eq` (the typed rule's preserved extensions hold floats, which have
/// no `Eq`) while the file keeps every key it was given.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeriesRule {
    /// The family: `daily`, `weekly`, `monthly`, `interval`, `cron-like`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// The cadence, where the family takes one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval: Option<u32>,
    /// The schedule origin, a canonical `YYYY-MM-DD` date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
    /// The timezone policy, e.g. `+02:00` or a named zone (refused by validation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    /// The cron-like expression, behind the reviewed parser gate.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expression: Option<String>,
    /// The unit an `interval` rule counts in: `days`, `weeks`, `months`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    /// Preserved unknown keys, exactly as they were written.
    #[serde(default, flatten)]
    pub extensions: BTreeMap<String, String>,
}

/// An issue: one markdown file with YAML frontmatter.
///
/// Field order and names are frozen by `contracts/file-format.md` FR-012.
/// `number` is a stored frontmatter key assigned by the storage layer at
/// create time by scanning the live issue set (issue #52; previously from
/// `tix.toml` `[state].next_number`, which is no longer persisted); this
/// module models and validates it but never allocates. `filename` and
/// `body` are memory-only (`#[serde(skip)]`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Issue {
    /// Human-facing sequential number: a convenience alias, allocated
    /// per-checkout as `max(number) + 1` and **allowed to collide** across
    /// branches (an agent's and a human's `tix create` may both produce `#7`).
    /// It is stable for every surviving issue in one store (C-007) but is not
    /// an identity — use [`Self::id`] for that.
    pub number: u32,
    /// Globally unique identity: 8 Crockford base32 characters (see
    /// [`crate::id`]), assigned at create and stored in the frontmatter and the
    /// filename prefix.
    ///
    /// Optional so every issue written before the id schema keeps parsing
    /// unchanged; such an issue simply has no canonical id yet (and its
    /// filename is not id-prefixed). New issues always carry one. Unlike
    /// `number`, this value never collides by accident: it is random across
    /// clones, so two branches creating issue #7 each still create two distinct
    /// issues.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Human title; drives the slug in the filename.
    #[serde(default)]
    pub title: String,
    /// Column (board workflow stage) the issue sits in.
    #[serde(default)]
    pub status: Status,
    /// Free-form labels.
    #[serde(default)]
    pub labels: Labels,
    /// Issue type (free-form, e.g. `bug`, `feature`).
    ///
    /// First-class since the type promotion; it used to be kept as a
    /// `[custom_attributes]` key. `tix lint` accepts a value only from the
    /// configured `custom_types` (or the built-in defaults). Optional, and
    /// skipped when absent so a file without it round-trips byte-identically.
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub type_: Option<String>,
    /// Priority; defaults to `medium`.
    #[serde(default)]
    pub priority: Priority,
    /// Assignee. In memory: bare handle (`alice`) or full `Name <email>`
    /// identity, verbatim. Files serialize per the rule documented on
    /// [`de_assignee`]/[`se_assignee`] (legacy `@alice` tolerated on read).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de_assignee",
        serialize_with = "se_assignee"
    )]
    pub assignee: Option<String>,
    /// Free-form estimate (e.g. `2`, `S`, `3d`); default `null`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub estimate: Option<String>,
    /// Git commit recorded when moved to `done` (FR-026).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commit: Option<String>,
    /// Remote GitLab issue id after export/import.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gitlab_id: Option<String>,
    /// Remote Linear issue id after export/import.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub linear_id: Option<String>,
    /// Spec Kitty mission slug (e.g. `v3-archive-review`) this issue belongs to, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mission: Option<String>,
    /// Spec Kitty work package id (e.g. `WP01`) this issue links to, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task: Option<String>,
    /// Typed relationships to other issues, replacing the retired generic
    /// `links: Vec<String>` bag (C-001).
    ///
    /// Each entry is a [`Relationship`]: a typed, directed edge with a stable
    /// id and a human-readable display name. The vocabulary is the closed
    /// four-kind set — `blocks`, `blocked_by`, `duplicates`, `related` — and
    /// the kind that reaches disk is always the canonical one, so `blocked_by`
    /// is normalized into `blocks` before it is stored and a pair is never
    /// stored twice. See [`crate::relationships`] for the direction
    /// convention, which this field does not restate.
    ///
    /// Files without the key parse (`default`). An empty list is **omitted**
    /// rather than written as `[]`: the typed field is new, so there is no
    /// legacy expectation to preserve for it, and omitting it keeps an issue
    /// with no relationships free of a meaningless key.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub relationships: Vec<Relationship>,
    /// General, cross-repository references to other issues, stored verbatim.
    ///
    /// Unlike [`Self::relationships`] (typed, number-keyed, local) this is a
    /// forward-only, user-authored list of free-form references. An entry is one
    /// of: a local issue number or selector (`42`, `#42`, a title/filename
    /// fragment); a relative or absolute path to another issue file (possibly in
    /// a sibling repository); or a repository URL (optionally with an issue
    /// reference). The grammar and resolution live in [`crate::related`].
    ///
    /// Entries are stored **verbatim** (trimmed) rather than as a re-serialized
    /// enum, so a path round-trips byte-stable; classification happens at
    /// read/render time. The list is never mirrored on write: it is user data,
    /// not a symmetric edge like the retired `links:`.
    ///
    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so every file
    /// without the key parses and round-trips byte-identically, and an empty list
    /// is omitted rather than written as `[]`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub related_issues: Vec<String>,
    /// This issue's **decomposition parent**, as an issue number.
    ///
    /// A parent is a decomposition — "this work is part of that" — and is a
    /// **distinct concept from a typed dependency edge**: `blocks` is a scheduling
    /// dependency, and conflating the two in one field is prohibited (C-007). It is
    /// also distinct from the `mission` and `task` Spec Kitty pointer fields, which
    /// are governance metadata and not a hierarchy (research R2).
    ///
    /// **At most one parent** (C-001). The type is a single `Option<u32>`, so two
    /// parents are not expressible; the field is not a list and no code path appends
    /// to it. Child membership is *derived* by inverting this pointer and is never
    /// stored on the parent (C-003) — see [`crate::hierarchy`], which owns that
    /// derivation.
    ///
    /// `#[serde(default)]` so every legacy file without the key parses unchanged,
    /// and skipped when absent so a file that never had a parent serialises
    /// byte-identically to its pre-mission form.
    ///
    /// The value is an issue **number**, not a selector: a selector may be a title
    /// fragment, and a title is not stable, so a stored title would silently break
    /// every child when the parent was retitled. Selectors are the *input* to
    /// `tix parent set`; the number is what lands in the file.
    ///
    /// A reference whose target no longer exists is **kept**, not cleared: it becomes
    /// the diagnosed `UnresolvedParentState` so it can be repaired.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent: Option<u32>,
    /// The recurrence metadata this issue carries (`series:`), when it is part of
    /// a series — either the **definition** (it owns the rule) or one of its
    /// **occurrences** (it carries the occurrence key). Mission
    /// `recurring-issues-01M3C7G7`, data-model §1/§3/§6; see
    /// [`crate::recurrence::series`] for the typed model and the index.
    ///
    /// One table with two roles decided by which fields are set, rather than a
    /// `role:` flag a writer could disagree with. Optional and skipped when
    /// absent, so every file that predates the mission parses unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub series: Option<SeriesRef>,
    /// The **current** health value (mission
    /// `project-issue-health-status-01M3C8HX`, WP02 T007).
    ///
    /// A projection of the append-only Health events, kept beside them so a surface
    /// can read the state without walking the History — and *only* the projection:
    /// the state, how it was obtained, the policy version, and when it was last
    /// updated. The **rationale lives in the event**, never here, because a
    /// frontmatter-only note is exactly the untracked value C-004 forbids.
    ///
    /// Optional and skipped when absent, so every file that predates the mission
    /// parses and re-serializes byte-identically. The state is the file's own
    /// spelling (like [`SeriesRule`]'s fields): validating it is the health layer's
    /// job, so a file carrying a value this build does not know still loads and is
    /// **reported** rather than becoming unreadable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health: Option<HealthRef>,
    /// Repo-relative file paths of the governing specification (e.g.
    /// `openspec/changes/<name>/specs/<cap>/spec.md`). Default `[]`.
    #[serde(default)]
    pub files: Vec<String>,
    /// Planning cycle names this issue belongs to (FR-005). Each entry must
    /// name a `[cycles.<name>]` config entry. `Option` so legacy files lack
    /// the key entirely; serialized only when non-empty.
    #[serde(
        default,
        skip_serializing_if = "skip_planning_list",
        serialize_with = "se_planning_list"
    )]
    pub cycles: Option<Vec<String>>,
    /// Milestone names this issue belongs to (FR-005). Each entry must name a
    /// milestone file in `milestones_dir`. Serialized only when non-empty.
    #[serde(
        default,
        skip_serializing_if = "skip_planning_list",
        serialize_with = "se_planning_list"
    )]
    pub milestones: Option<Vec<String>>,
    /// Project ids this issue is associated with (mission
    /// `first-class-projects-01M3BYBW`, decision `01M3BYD1F3NWB0ZYXT1AMJYYVY`).
    ///
    /// Holds project **ids**, never names: an id is allocated once and never
    /// changes, so a project rename cannot break an association (C-002, SC-005).
    /// An issue may carry **several** associations (C-003), so the field is
    /// list-valued; a single-valued `project` field is the rejected alternative
    /// (data-model §1, contract §6).
    ///
    /// The wire shape is the same as [`Self::cycles`]/[`Self::milestones`] — an
    /// `Option<Vec<String>>`, `#[serde(default)]` on read and serialized only when
    /// non-empty — so a file that never had an association round-trips
    /// byte-identically to its pre-mission form (NFR-002). The key is `projects`,
    /// which is **distinct** from `cycles`, `milestones`, `mission`, and `task`:
    /// four list/pointer reference fields on one struct is exactly where an
    /// accidental alias would hide, so no serde alias is declared for any of them.
    ///
    /// `(issue, project_id)` is unique. The service returns the resulting list and
    /// storage writes it verbatim; the shared `se_planning_list` renderer
    /// additionally collapses a duplicate that predates the field, preserving
    /// first-seen order.
    ///
    /// A reference whose project is no longer in the registry is **kept**, not
    /// dropped: it becomes the diagnosed missing reference so it can be repaired
    /// (C-005, contract §5).
    #[serde(
        default,
        skip_serializing_if = "skip_planning_list",
        serialize_with = "se_planning_list"
    )]
    pub projects: Option<Vec<String>>,
    /// Epic ids this issue is referenced by (mission
    /// `epics-work-items-01M3BYW4`, decision `01M3BYX33ZKN9BB275T0BNZJXD`).
    ///
    /// Holds epic **ids**, never names: an id is allocated once and never changes,
    /// so renaming an epic cannot break a reference (C-003). An issue may be
    /// referenced by **several** epics (C-003), so the field is list-valued; a
    /// single-valued `epic` field is the rejected alternative
    /// (`contracts/epic-registry.md` §3).
    ///
    /// The wire shape is the same as [`Self::projects`]/[`Self::cycles`]/
    /// [`Self::milestones`] — an `Option<Vec<String>>`, `#[serde(default)]` on read
    /// and serialized only when non-empty — so a file that never had a reference
    /// round-trips byte-identically to its pre-mission form (NFR-002). The key is
    /// `epics`, which is **distinct** from `projects`, `cycles`, `milestones`,
    /// `mission`, `task`, and `files`: five list-valued reference fields on one
    /// struct is exactly where an accidental alias would hide, so no serde alias is
    /// declared for any of them.
    ///
    /// This is **not** a task or work-item reference (C-001): there is no task
    /// record type, and a `task`-labelled issue is an ordinary member. The Spec
    /// Kitty `task` pointer field above is unrelated and untouched.
    ///
    /// `(issue, epic_id)` is unique. The service returns the resulting list and
    /// storage writes it verbatim; the shared `se_planning_list` renderer
    /// additionally collapses a duplicate that predates the field, preserving
    /// first-seen order.
    ///
    /// A reference whose epic is no longer in the registry is **kept**, not
    /// dropped: it becomes the diagnosed missing reference so it can be repaired
    /// (C-005, `contracts/epic-registry.md` §5).
    #[serde(
        default,
        skip_serializing_if = "skip_planning_list",
        serialize_with = "se_planning_list"
    )]
    pub epics: Option<Vec<String>>,
    /// Advisory reviewer identity (FR-006), free-form like `assignee`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reviewer: Option<String>,
    /// Planning start date, `YYYY-MM-DD` (FR-006).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_date: Option<String>,
    /// Planning due date, `YYYY-MM-DD`; must be `>= start_date` (FR-007).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub due_date: Option<String>,
    /// When the issue most recently entered the triage inbox, RFC 3339 UTC
    /// (`2026-09-30T09:12:44Z`), if it ever did.
    ///
    /// Mission `triage-inbox-review-flow-01M3C600`, data-model §2. Queue age is
    /// measured from here and from nothing else: `updated` moves on every edit and
    /// `created` predates the queue, so either would report a wait the issue did
    /// not have (research R4). Read it through [`crate::triage::entry_time`],
    /// which is the one documented fallback for an issue that has none.
    ///
    /// Optional and skipped when absent, so a repository that predates triage
    /// round-trips byte-identically instead of gaining a key on every file (C-001).
    ///
    /// Refreshed on re-entry, not merged — a defer restarts the wait (data-model
    /// §5) — and deliberately **not** stamped on every edit, which would turn it
    /// into a second `updated`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entered_at: Option<String>,
    /// Where the issue's current entry came from: `new`, `import`, `defer`, or
    /// any other origin the caller documents (data-model §2, `source`).
    ///
    /// Optional for the same reason as [`Self::entered_at`]. It describes *this*
    /// entry rather than the issue's permanent provenance, so it is rewritten
    /// whenever the issue re-enters.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// The issue's **current** time entries (mission
    /// `per-issue-time-tracking-01M3C9A4`, WP01 T004), under the frontmatter key
    /// `time_entries`.
    ///
    /// Each element is a [`crate::time_tracking::TimeEntry`]: actual effort at
    /// minute precision, with its own stable id, optional calendar date, author
    /// and note. This is the current projection only — corrections and deletions
    /// stay in the append-only History, never here (C-004) — and it is **not**
    /// the free-form `estimate` field above, which keeps its planning meaning
    /// (C-005). Nothing about an entry changes status or ownership (C-008).
    ///
    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so a file that
    /// never had an entry parses unchanged and round-trips byte-identically
    /// instead of gaining a `time_entries: []` key, which is the same rule
    /// [`Self::relationships`] and [`Self::related_issues`] follow.
    ///
    /// An entry that fails [`crate::time_tracking::TimeEntry::validate`] is kept
    /// in this list rather than dropped, so a malformed entry stays readable and
    /// reportable instead of blocking the issue or vanishing on the next
    /// unrelated write (C-005).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub time_entries: Vec<crate::time_tracking::TimeEntry>,
    /// Creation date, `YYYY-MM-DD`, the leading component of the filename.
    #[serde(default = "today")]
    pub created: String,
    /// Last-mutation date, `YYYY-MM-DD`.
    #[serde(default = "today")]
    pub updated: String,
    /// Issue file name — path relative to the issues dir. A new-schema name is
    /// `{date}-{id}-{slug}` (e.g. `alice/type/status/2026-05-10-A1B2C3D4-fix-login.md`),
    /// so a directory listing is creation order; a filename written before the
    /// id schema is `{date}-{slug}` (e.g. `2026-05-10-fix-login.md`, or grouped
    /// per C-010).
    #[serde(skip)]
    pub filename: String,
    /// Raw markdown body; memory-only, preserved verbatim.
    #[serde(skip)]
    pub body: String,
    /// The append-only `## History` section, parsed out of the body on read and
    /// re-rendered on write; memory-only like [`Issue::body`].
    ///
    /// The section is *stripped* from `body` during parsing, so `body` holds
    /// only the issue's own prose and the two never disagree. Rendering puts
    /// the section back immediately after the frontmatter, the position
    /// `data-model.md` §8 pins.
    #[serde(skip)]
    pub history: History,
    /// Whether the source frontmatter still carries a legacy `links:` key.
    ///
    /// The key is never read as typed data (C-001) and never migrated; it is
    /// recorded here so the service can report it as a
    /// `retired_links_key` validation result. Memory-only, like the rest of the
    /// file-surface state.
    #[serde(skip)]
    pub has_retired_links_key: bool,
    /// Top-level frontmatter keys this model does not know, as `key -> raw block`.
    ///
    /// #1361. Before this, an unknown key was dropped on every write: `Issue`
    /// deserialises a fixed set of keys and `frontmatter` re-emits exactly those, so
    /// a key `tix` does not recognise was deleted by the next unrelated `tix edit` —
    /// silently, because `tix lint` had no unknown-key rule at all.
    ///
    /// The value is the **raw source block**, not a parsed value, and that is the
    /// whole design. Re-serialising a parsed value would re-quote and re-indent it, so
    /// a key that was written one way would come back another way and every write
    /// would produce a spurious diff. Splicing the original bytes back in makes the
    /// round trip byte-stable for content this model has no opinion about.
    ///
    /// A `BTreeMap` rather than a `HashMap` so the render order is deterministic:
    /// `HashMap` iteration order would reshuffle these keys on every write and
    /// produce a diff in a file that had not changed.
    ///
    /// `Eq` is preserved (unlike `serde_yaml::Value`, which is not `Eq`), and the
    /// blocks are plain `String`s, so `Issue` keeps every one of its derives.
    ///
    /// The retired `links:` key is **excluded** — see [`Issue::parse`]. It is
    /// recognised, reported by its own finding, and dropped (C-001); round-tripping it
    /// would silently undo the typed-relationship migration.
    #[serde(skip)]
    pub extra_frontmatter: BTreeMap<String, String>,
    /// Whether the issue is archived (issue #1492).
    ///
    /// The **filename is the marker**, never a frontmatter field: an archived
    /// issue's markdown file is dot-prefixed in place
    /// (`docs/issues/<assignee>/.<file>.md`). This field is therefore derived
    /// state, not data — it mirrors the leading dot of [`Issue::filename`] and
    /// is set by [`crate::storage::Store::list_all`], never written to disk.
    /// `#[serde(skip)]` keeps it out of the frontmatter, and it defaults to
    /// `false` for every parse.
    #[serde(skip)]
    pub archived: bool,
}

// ---------------------------------------------------------------------------
// Append-only History section (WP02 T007)
// ---------------------------------------------------------------------------

/// The heading that introduces the History section, per `data-model.md` §8.
///
/// The section is recognised by a line whose trimmed content is exactly this —
/// nothing else introduces it.
pub const HISTORY_HEADING: &str = "## History";

/// The separator between the four fields of a rendered History entry
/// (U+2014 em dash).
const HISTORY_SEP: char = '\u{2014}';

/// What kind of mutation a [`HistoryEvent`] records.
///
/// Closed set per `data-model.md` §8. `blocked_move_acknowledged` is defined
/// here so WP04 consumes it without editing this file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HistoryEventKind {
    /// A relationship was created.
    RelationshipAdded,
    /// A relationship was removed.
    RelationshipRemoved,
    /// A relationship was retargeted or re-kinded.
    RelationshipRetargeted,
    /// A move toward completion was confirmed while blockers were open.
    BlockedMoveAcknowledged,
    /// An issue gained its first parent.
    ParentSet,
    /// An existing parent reference was repointed.
    ParentChanged,
    /// A parent reference was removed.
    ParentCleared,
    /// A status change was accepted by the transition service and applied.
    ///
    /// WP03. The name says *accepted* because acceptance is the only outcome that
    /// reaches the log: a rejected transition is completely inert and appends
    /// nothing (contract §3.5), and a re-applied transition is idempotent and also
    /// appends nothing. So the presence of this kind in a file **is** the record
    /// that the change was accepted — a name like `transition_attempted` would
    /// imply rejections are logged here too, and they are not.
    TransitionAccepted,
    /// A triage inbox issue was accepted into the normal workflow.
    ///
    /// WP03 (mission `triage-inbox-review-flow-01M3C600`). Four triage kinds
    /// rather than one `triage_decided` for the reason the parent kinds are
    /// separate: the *decision* is the thing an audit reader is looking for, and
    /// `triage_decided — decline …` makes them read the detail to learn which of
    /// four mutually exclusive actions was taken. They extend the one #169 log
    /// (research R5) — there is no second log and no triage-specific section.
    ///
    /// Only **applied** decisions reach the log: a refusal appends nothing and a
    /// repeated identical decision is a no-op (contract `decision-history.md`),
    /// exactly as with [`HistoryEventKind::TransitionAccepted`].
    TriageAccepted,
    /// A triage inbox issue was declined: moved to the configured declined
    /// column, never deleted or archived (C-003).
    TriageDeclined,
    /// A triage inbox issue was marked a duplicate of another issue.
    ///
    /// The event records the decision; the typed `duplicates` edge is the
    /// [`HistoryEventKind::RelationshipAdded`] entry. One decision, two kinds
    /// *only* because the relation already has its own kind and inventing a
    /// second spelling for it would leave the graph and the log disagreeing.
    TriageDuplicated,
    /// A triage inbox issue was deferred: it stays in the inbox with a
    /// refreshed entry time (data-model §5).
    TriageDeferred,
    /// The issue file was archived: renamed in place to a dot-prefixed name
    /// (issue #1492).
    Archived,
    /// An archived issue was restored to its active name (issue #1492).
    Restored,
    /// An issue's health state was updated, with an actor, a timestamp and a
    /// rationale (mission `project-issue-health-status-01M3C8HX`, WP02).
    ///
    /// One kind for an update and one for an override rather than one
    /// `health_changed` with a flag: the *decision* is what an audit reader looks
    /// for, and "somebody changed the health" makes them read the detail to learn
    /// whether it was a measurement or a person overruling one.
    HealthUpdated,
    /// A manual health override was applied over a derived value (WP02).
    HealthOverridden,
    /// An issue gained a project association (mission
    /// `first-class-projects-01M3BYBW`, WP03).
    ///
    /// Two dedicated kinds rather than one generic `projects_changed`, matching
    /// the three parent kinds and the four triage kinds: the *direction* of the
    /// change is what an audit reader is looking for, and `projects_changed —
    /// …` would make them read the detail to learn whether an association was
    /// added or removed. The service declares exactly these two as
    /// [`crate::projects::ProjectEventKind`], so the vocabulary is decided once
    /// and mapped here by [`Self::from_project`].
    ProjectAssociated,
    /// An issue lost a project association (WP03).
    ProjectDissociated,
    /// An issue gained an epic reference (mission
    /// `epics-work-items-01M3BYW4`, WP03).
    ///
    /// Two dedicated kinds rather than one generic `epics_changed`, matching the
    /// three parent kinds, the four triage kinds, and the two project kinds: the
    /// *direction* of the change is what an audit reader is looking for, and
    /// `epics_changed — …` would make them read the detail to learn whether a
    /// reference was added or removed. The service declares exactly these two as
    /// [`crate::epics::EpicEventKind`], so the vocabulary is decided once and
    /// mapped here by [`Self::from_epic`].
    EpicReferenced,
    /// An issue lost an epic reference (WP03).
    EpicDereferenced,
    /// A generated cycle was explicitly closed, capturing its snapshot.
    ///
    /// WP05 of mission `repeating-cycle-schedules-01M3C7W1`. These six kinds carry
    /// the same append-only grammar as every issue event, but they are written to a
    /// **generated cycle record's own body** (`docs/cycles/<stem>.md`), never to an
    /// issue: a cycle is not an issue, and the mission's evidence for one is its
    /// record, its snapshot and the cursor. One kind per action rather than one
    /// `cycle_lifecycle` with a flag, for the same reason the parent/triage/project
    /// kinds are split: the *decision* is what an audit reader looks for, and a
    /// generic kind would make them read the detail to learn which of five
    /// mutually-exclusive actions was taken.
    CycleClosed,
    /// A generated cycle's due date was extended by one cadence period.
    CycleExtended,
    /// A generated cycle's sequence was recorded as skipped.
    CycleSkipped,
    /// A schedule (and its affected instances) was paused.
    CyclePaused,
    /// A schedule (and its affected instances) was resumed.
    CycleResumed,
    /// A schedule's future instances were re-derived from its definition.
    CycleAdjusted,
    /// A closed cycle was explicitly reopened.
    ///
    /// WP04 of mission `cycle-capacity-planning-01M3C85C`. A closed cycle's capacity is
    /// the immutable snapshot captured at close (C-008), so reopening it — the one way
    /// its capacity may be configured again — is a capacity-affecting change and is
    /// recorded rather than performed silently. It extends the same cycle family as
    /// [`HistoryEventKind::CycleClosed`] and is written to the **generated cycle
    /// record's own body**, beside `cycle_closed`: a cycle's evidence is its record, its
    /// snapshot and the cursor, and there is no second log. One kind rather than a flag
    /// on `cycle_closed`, for the reason the other cycle kinds are split — the *decision*
    /// is what an audit reader looks for. An applied reopen appends exactly one entry;
    /// the prior snapshot and every prior event are retained verbatim.
    CycleReopened,
    /// A closed cycle's capacity was changed through the explicit reopen path.
    ///
    /// WP04. The edit's `detail` carries the reason, the prior snapshot's stable identity
    /// and the before/after calculation summaries (`data-model.md` §7), so the entry says
    /// what changed without the reader reconstructing it. Nothing rewrites the prior
    /// snapshot: the edit produces a new *current* calculation and this one line of
    /// evidence.
    CycleCapacityEdited,
    /// A time entry was created on an issue (mission
    /// `per-issue-time-tracking-01M3C9A4`, WP01 T047).
    ///
    /// Pre-declared here, like `blocked_move_acknowledged` above, so WP02's mutation
    /// service appends the event without editing this file. Three kinds rather than one
    /// `time_changed` for the reason the parent, triage, project and epic families are
    /// split: the *decision* is what an audit reader is looking for, and a generic kind
    /// would make them read the detail to learn whether an entry was added, corrected or
    /// removed. Only an **applied** mutation appends one (`contracts/time-entry.md`,
    /// data-model §2): a refused write appends nothing, and the `detail` carries the
    /// entry id and the created value so the entry is attributable after any later edit.
    TimeEntryCreated,
    /// A time entry's duration, date, author or note was corrected (WP01 T047).
    ///
    /// The `detail` carries the entry id and the before/after values, so the prior value
    /// remains attributable after the correction (C-004). Pre-declared with its siblings
    /// so WP02 never edits this file.
    TimeEntryUpdated,
    /// A time entry was deleted from an issue's current projection (WP01 T047).
    ///
    /// The entry leaves the issue's frontmatter and the event, with its prior value,
    /// stays in History — a deletion removes the current projection, never the evidence
    /// (C-004). Pre-declared with its siblings so WP02 never edits this file.
    TimeEntryDeleted,
    /// An issue's `estimate` value changed (mission
    /// `burndown-scope-analytics-01M3C9J1`, WP01 T046).
    ///
    /// FR-002 distinguishes scope growth from completion, and an estimate change moves
    /// the planned *size* of the work without changing how many issues are in scope —
    /// so it is a kind of its own rather than a flag on a membership or a status event,
    /// and the analytics classification folds it as `estimate_change`. This is the one
    /// class the mission's own table would otherwise never produce: no surface used to
    /// append an event for an estimate edit at all, so the class would have stayed
    /// permanently unknown in exactly the way the orphaned `cycle_capacity_edited`
    /// kind did.
    ///
    /// Appended by `tix edit --estimate` at the seam `--parent` already appends to,
    /// with the before/after values in `detail` (`estimate: <before> -> <after>`,
    /// `none` for an absent or blank value). An unchanged value appends **nothing**,
    /// and a refused edit appends nothing — the entry exists only for a change that
    /// was applied.
    EstimateChanged,
    /// An issue gained or lost a cycle membership (WP01 T046).
    ///
    /// One kind rather than two direction-split ones, and that is the documented
    /// exception to the split-by-direction convention the parent/triage/project/epic
    /// families follow: a single `--cycles` edit routinely adds one cycle *and* removes
    /// another, so "which direction?" has no single answer to split on. The direction is
    /// therefore in `detail` — `cycles: <before> -> <after>`, `none` for an empty list —
    /// which is what makes the change readable without replaying state.
    ///
    /// Appended by `tix edit --cycles` at the same seam, and only when the membership
    /// actually changed: an unchanged list appends nothing.
    CycleMembershipChanged,
}

impl HistoryEventKind {
    /// The canonical snake_case spelling written to the file.
    pub fn as_str(self) -> &'static str {
        match self {
            HistoryEventKind::RelationshipAdded => "relationship_added",
            HistoryEventKind::RelationshipRemoved => "relationship_removed",
            HistoryEventKind::RelationshipRetargeted => "relationship_retargeted",
            HistoryEventKind::BlockedMoveAcknowledged => "blocked_move_acknowledged",
            // Three dedicated kinds rather than one generic `parent_changed` (research
            // open question 2, resolved in `data-model.md` §6.1): "set" and "cleared" are
            // not changes *of* a parent, they are its beginning and its end, and
            // collapsing them leaves the audit trail unable to distinguish "gained a
            // parent" from "moved to a different one" without reconstructing state from
            // the detail text.
            HistoryEventKind::ParentSet => "parent_set",
            HistoryEventKind::ParentChanged => "parent_changed",
            HistoryEventKind::ParentCleared => "parent_cleared",
            HistoryEventKind::TransitionAccepted => "transition_accepted",
            HistoryEventKind::TriageAccepted => "triage_accepted",
            HistoryEventKind::TriageDeclined => "triage_declined",
            HistoryEventKind::TriageDuplicated => "triage_duplicated",
            HistoryEventKind::TriageDeferred => "triage_deferred",
            HistoryEventKind::Archived => "archived",
            HistoryEventKind::Restored => "restored",
            HistoryEventKind::HealthUpdated => "health_updated",
            HistoryEventKind::HealthOverridden => "health_overridden",
            HistoryEventKind::ProjectAssociated => "project_associated",
            HistoryEventKind::ProjectDissociated => "project_dissociated",
            HistoryEventKind::EpicReferenced => "epic_referenced",
            HistoryEventKind::EpicDereferenced => "epic_dereferenced",
            HistoryEventKind::CycleClosed => "cycle_closed",
            HistoryEventKind::CycleExtended => "cycle_extended",
            HistoryEventKind::CycleSkipped => "cycle_skipped",
            HistoryEventKind::CyclePaused => "cycle_paused",
            HistoryEventKind::CycleResumed => "cycle_resumed",
            HistoryEventKind::CycleAdjusted => "cycle_adjusted",
            HistoryEventKind::CycleReopened => "cycle_reopened",
            HistoryEventKind::CycleCapacityEdited => "cycle_capacity_edited",
            HistoryEventKind::TimeEntryCreated => "time_entry_created",
            HistoryEventKind::TimeEntryUpdated => "time_entry_updated",
            HistoryEventKind::TimeEntryDeleted => "time_entry_deleted",
            HistoryEventKind::EstimateChanged => "estimate_changed",
            HistoryEventKind::CycleMembershipChanged => "cycle_membership_changed",
        }
    }

    /// Whether this kind records a triage decision (WP03's four).
    ///
    /// The membership test the decision service's idempotence check and
    /// `not_in_triage`/`already_decided` split both ask, so "is this a triage
    /// decision?" has one answer rather than a four-way `matches!` at every
    /// call site — where a fifth kind would be forgotten first.
    #[must_use]
    pub fn is_triage_decision(self) -> bool {
        matches!(
            self,
            HistoryEventKind::TriageAccepted
                | HistoryEventKind::TriageDeclined
                | HistoryEventKind::TriageDuplicated
                | HistoryEventKind::TriageDeferred
        )
    }
}

impl fmt::Display for HistoryEventKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for HistoryEventKind {
    type Err = TixError;

    /// Parse a kind spelling. An unknown kind is **rejected**, never coerced
    /// to a default: a silently reclassified audit entry is worse than a
    /// parse failure, and the field is part of an append-only log.
    fn from_str(s: &str) -> Result<Self> {
        match s {
            "relationship_added" => Ok(HistoryEventKind::RelationshipAdded),
            "relationship_removed" => Ok(HistoryEventKind::RelationshipRemoved),
            "relationship_retargeted" => Ok(HistoryEventKind::RelationshipRetargeted),
            "blocked_move_acknowledged" => Ok(HistoryEventKind::BlockedMoveAcknowledged),
            "parent_set" => Ok(HistoryEventKind::ParentSet),
            "parent_changed" => Ok(HistoryEventKind::ParentChanged),
            "parent_cleared" => Ok(HistoryEventKind::ParentCleared),
            "transition_accepted" => Ok(HistoryEventKind::TransitionAccepted),
            "triage_accepted" => Ok(HistoryEventKind::TriageAccepted),
            "triage_declined" => Ok(HistoryEventKind::TriageDeclined),
            "triage_duplicated" => Ok(HistoryEventKind::TriageDuplicated),
            "triage_deferred" => Ok(HistoryEventKind::TriageDeferred),
            "archived" => Ok(HistoryEventKind::Archived),
            "restored" => Ok(HistoryEventKind::Restored),
            "health_updated" => Ok(HistoryEventKind::HealthUpdated),
            "health_overridden" => Ok(HistoryEventKind::HealthOverridden),
            "project_associated" => Ok(HistoryEventKind::ProjectAssociated),
            "project_dissociated" => Ok(HistoryEventKind::ProjectDissociated),
            "epic_referenced" => Ok(HistoryEventKind::EpicReferenced),
            "epic_dereferenced" => Ok(HistoryEventKind::EpicDereferenced),
            "cycle_closed" => Ok(HistoryEventKind::CycleClosed),
            "cycle_extended" => Ok(HistoryEventKind::CycleExtended),
            "cycle_skipped" => Ok(HistoryEventKind::CycleSkipped),
            "cycle_paused" => Ok(HistoryEventKind::CyclePaused),
            "cycle_resumed" => Ok(HistoryEventKind::CycleResumed),
            "cycle_adjusted" => Ok(HistoryEventKind::CycleAdjusted),
            "cycle_reopened" => Ok(HistoryEventKind::CycleReopened),
            "cycle_capacity_edited" => Ok(HistoryEventKind::CycleCapacityEdited),
            "time_entry_created" => Ok(HistoryEventKind::TimeEntryCreated),
            "time_entry_updated" => Ok(HistoryEventKind::TimeEntryUpdated),
            "time_entry_deleted" => Ok(HistoryEventKind::TimeEntryDeleted),
            "estimate_changed" => Ok(HistoryEventKind::EstimateChanged),
            "cycle_membership_changed" => Ok(HistoryEventKind::CycleMembershipChanged),
            other => Err(TixError::Parse(format!(
                "unknown History event kind `{other}`"
            ))),
        }
    }
}

impl HistoryEventKind {
    /// The model kind for a hierarchy event.
    ///
    /// Vocabulary translation, not a rule: the service decides *which* transition
    /// happened, and this maps that decision onto the log's spelling. It lives on
    /// the type that owns the log rather than at each call site, because three
    /// callers need it — the storage write path, the `--parent` edit flag, and MCP's
    /// `update_issue` in WP07 — and a mapping repeated three times is one that will
    /// be completed three times and fixed once.
    pub fn from_parent(kind: crate::hierarchy::ParentEventKind) -> Self {
        match kind {
            crate::hierarchy::ParentEventKind::ParentSet => HistoryEventKind::ParentSet,
            crate::hierarchy::ParentEventKind::ParentChanged => HistoryEventKind::ParentChanged,
            crate::hierarchy::ParentEventKind::ParentCleared => HistoryEventKind::ParentCleared,
        }
    }

    /// The model kind for a project association event (WP03).
    ///
    /// The same vocabulary translation as [`Self::from_parent`]: the project
    /// service decides *which* mutation happened by returning a
    /// [`crate::projects::ProjectEventKind`], and this maps that decision onto the
    /// log's spelling. It lives on the type that owns the log because more than one
    /// caller needs it — the storage write path, and the CLI/TUI/MCP surfaces that
    /// follow — and a mapping repeated per call site is one that will be completed
    /// per call site and fixed once.
    #[must_use]
    pub fn from_project(kind: crate::projects::ProjectEventKind) -> Self {
        match kind {
            crate::projects::ProjectEventKind::ProjectAssociated => {
                HistoryEventKind::ProjectAssociated
            }
            crate::projects::ProjectEventKind::ProjectDissociated => {
                HistoryEventKind::ProjectDissociated
            }
        }
    }

    /// The model kind for an epic reference event (WP03).
    ///
    /// The same vocabulary translation as [`Self::from_project`]: the epic service
    /// decides *which* mutation happened by returning a
    /// [`crate::epics::EpicEventKind`], and this maps that decision onto the log's
    /// spelling. It lives on the type that owns the log because more than one caller
    /// needs it — the storage write path, and the CLI/TUI/MCP surfaces that follow —
    /// and a mapping repeated per call site is one that will be completed per call
    /// site and fixed once.
    #[must_use]
    pub fn from_epic(kind: crate::epics::EpicEventKind) -> Self {
        match kind {
            crate::epics::EpicEventKind::EpicReferenced => HistoryEventKind::EpicReferenced,
            crate::epics::EpicEventKind::EpicDereferenced => HistoryEventKind::EpicDereferenced,
        }
    }
}

/// The auditable record of one **accepted** status transition (`data-model.md`
/// §5, WP03 T012).
///
/// ## Why this is not a `HistoryEventKind` alone
///
/// A [`HistoryEvent`] has exactly four fields — timestamp, actor, kind, detail —
/// and the on-disk line format is fixed at four by the U+2014 split in
/// [`HistoryEvent::parse`]. `data-model.md` §5 wants seven. The three surplus
/// fields therefore live in `detail`, and this struct is what converts between
/// the two: [`Self::to_event`] and [`Self::from_event`] are the only places that
/// encoding is written or read.
///
/// ## The `detail` grammar
///
/// ```text
/// detail := head [ "; override: " reason ]
/// head   := from " -> " to " (" from_category " -> " to_category ")"
/// ```
///
/// e.g. `todo -> in progress (unstarted -> active)`, or
/// `done -> in progress (completed -> active); override: mis-filed`.
///
/// **It is a grammar, not prose**, and that is a load-bearing choice rather than a
/// tidiness one. WP06's `lint_direct_edits` has to compare a file's *current*
/// `status` against the column its last accepted transition landed in; recovering
/// that column out of free-form English is guesswork, and a heuristic that
/// misreads it produces a lint result nobody can trust. A fixed grammar makes the
/// comparison exact, and makes "this detail is not a transition record"
/// detectable rather than a guess.
///
/// The parse is deliberately anchored rather than free-floating: the override is
/// split off at the first `") ; override: "`, and the categories are taken from
/// between the last `" ("` and the closing `")"`, so a **reason** may contain the
/// bare `"-> "` and the bare `"; override: "` without disturbing the fields. That
/// anchoring is the whole reason the marker includes the paren — see
/// [`OVERRIDE_MARKER`].
///
/// ## Known limit: a column name containing `" -> "`
///
/// The two column names are separated by the first `" -> "`, and nothing escapes
/// it, so a column literally named `a -> b` would render as
/// `a -> b -> in progress (unstarted -> active)` and parse back with `from == "a"`.
/// The categories still parse correctly, and the *categories* are what an audit
/// reader wants, but a WP06 that recovers `to` from a file would recover `b`.
///
/// This is inherent to a delimiter-based grammar, not a bug in this
/// implementation: any unescaped separator has a name it cannot represent, and
/// escaping would put backslashes into a line a human reads. A board column named
/// with an embedded arrow is not a realistic configuration, so the limit is
/// documented and pinned by a test rather than designed around. WP06 reads `to`
/// from these records, so it inherits the assumption and should not be surprised
/// by it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionDecision {
    /// When the transition was accepted, RFC 3339 — the same shape and clock as
    /// every other History entry.
    pub timestamp: String,
    /// Who performed it.
    ///
    /// A plain `String`, carried through to [`HistoryEvent::actor`] untouched, so
    /// identity handling is the History log's existing one: a bare handle or a full
    /// `Name <email>`, with a legacy `@alice` tolerated on read. This struct
    /// re-implements none of that and cannot drift from it.
    pub actor: String,
    /// The column the issue was in, as stored.
    pub from: String,
    /// The column it was moved to, as stored.
    pub to: String,
    /// The category `from` resolved to, recorded for auditability.
    ///
    /// **Derived, never stored on the issue and never re-derived on read** — that
    /// is the point. If a board's `category_map` is later edited, the historical
    /// record still says what the category *was* when the move was accepted, which
    /// is the only way the audit trail stays true.
    pub from_category: String,
    /// The category `to` resolved to, recorded for the same reason.
    pub to_category: String,
    /// Why a policy rule was overridden, when one was.
    ///
    /// Required to be `Some` for an override to exist at all: the service refuses a
    /// bare "I did it anyway" (see `TransitionOverride`), so this is never `Some`
    /// with an empty or blank reason.
    pub override_reason: Option<String>,
}

/// The marker separating the transition record from its override reason.
///
/// **Includes the closing paren**, and that is load-bearing rather than
/// cosmetic. The obvious marker is `"; override: "`, split with `rsplit_once` so a
/// reason containing the marker survives — and it does not: the *last* occurrence
/// of a bare `"; override: "` inside a reason like `typo; override: actually…` is
/// the one that splits, which leaves the head ending in `; override: typo` and no
/// closing paren, so the parse fails outright. WP03's first version did exactly
/// that and its own test caught it.
///
/// Anchoring the marker to the `)` that closes the head makes the split
/// **unambiguous in both directions**: the head is the only `)` followed by the
/// marker, so `split_once` at the *first* occurrence always takes the right one.
/// A reason may therefore contain the bare marker, a bare `")"`, and even the full
/// anchored marker, and still round-trip.
///
/// That last case is worth spelling out because WP03's first two attempts both got
/// it wrong in opposite directions. `rsplit_once` on the *bare* marker took the
/// last occurrence, so a reason containing `"; override: "` truncated and the parse
/// failed outright. `rsplit_once` on the *anchored* marker would be no better: for
/// a reason containing `"); override: "` the last occurrence is the one inside the
/// reason. `split_once` on the anchored marker is the only combination of the two
/// that is correct, and `t012_a_reason_containing_the_anchored_marker_survives`
/// exists to keep it that way.
const OVERRIDE_MARKER: &str = "); override: ";
/// The marker opening the bracketed category pair.
const CATEGORY_OPEN: &str = " (";
/// The arrow between two names in the `detail` grammar.
const DETAIL_ARROW: &str = " -> ";

impl TransitionDecision {
    /// Build a decision from an accepted transition.
    pub fn new(
        timestamp: impl Into<String>,
        actor: impl Into<String>,
        from: impl Into<String>,
        to: impl Into<String>,
        from_category: impl Into<String>,
        to_category: impl Into<String>,
        override_reason: Option<String>,
    ) -> Self {
        Self {
            timestamp: timestamp.into(),
            actor: actor.into(),
            from: from.into(),
            to: to.into(),
            from_category: from_category.into(),
            to_category: to_category.into(),
            override_reason,
        }
    }

    /// Render to the single `detail` string the History line carries.
    pub fn detail(&self) -> String {
        let mut out = format!(
            "{from}{arrow}{to} ({fc}{arrow}{tc})",
            from = self.from,
            to = self.to,
            fc = self.from_category,
            tc = self.to_category,
            arrow = DETAIL_ARROW,
        );
        // A blank reason renders as no marker at all rather than as an empty field,
        // so `from_event` can never come back with `Some("")` — the same reasoning
        // that makes a blank actor render as an empty field rather than being
        // dropped, applied in the other direction.
        if let Some(reason) = self.override_reason.as_deref().map(str::trim) {
            if !reason.is_empty() {
                // The head already ends in the `)` the marker expects, so the
                // marker supplies the semicolon and the space only. Writing the
                // marker as a whole and *also* leaving the head's `)` is what
                // produced `...active)); override:` on the first pass.
                out.push_str(OVERRIDE_MARKER.trim_start_matches(')'));
                out.push_str(reason);
            }
        }
        out
    }

    /// Recover a decision from a History entry.
    ///
    /// `Err` when `event` is not a `transition_accepted` entry or its `detail` does
    /// not match the grammar — never a partially-filled struct. A caller can
    /// therefore treat a successful parse as "this file records a transition to
    /// `to`", which is exactly the question WP06 asks.
    pub fn from_event(event: &HistoryEvent) -> Result<Self> {
        if event.kind != HistoryEventKind::TransitionAccepted {
            return Err(TixError::Parse(format!(
                "History entry is a `{}`, not a `transition_accepted`",
                event.kind
            )));
        }
        let malformed =
            |what: &str| TixError::Parse(format!("transition record {what}: `{}`", event.detail));
        // The reason is split off at the FIRST anchored marker: the head is the
        // only `)` followed by `; override: `, so a reason containing the bare
        // marker survives. See `OVERRIDE_MARKER`.
        let (head, override_reason) = match event.detail.split_once(OVERRIDE_MARKER) {
            Some((head, reason)) => (head, Some(reason.trim().to_string())),
            None => (event.detail.as_str(), None),
        };
        // The marker *includes* the head's closing paren, so put it back and let
        // the grammar below see one shape whether or not a reason was present. The
        // alternative — two separate shapes to parse — is how the two halves of a
        // grammar drift apart.
        let head = match &override_reason {
            Some(_) => format!("{head})"),
            None => head.to_string(),
        };
        let head = head.as_str();
        let (from, rest) = head
            .split_once(DETAIL_ARROW)
            .ok_or_else(|| malformed("has no `from -> to`"))?;
        let rest = rest
            .strip_suffix(')')
            .ok_or_else(|| malformed("has no closing `)` after the categories"))?;
        let (to, categories) = rest
            .split_once(CATEGORY_OPEN)
            .ok_or_else(|| malformed("has no ` (` before the categories"))?;
        let (from_category, to_category) = categories
            .split_once(DETAIL_ARROW)
            .ok_or_else(|| malformed("has no `from_category -> to_category`"))?;
        for (name, value) in [
            ("from", from),
            ("to", to),
            ("from_category", from_category),
            ("to_category", to_category),
        ] {
            if value.trim().is_empty() {
                return Err(malformed(name));
            }
        }
        Ok(Self {
            timestamp: event.timestamp.clone(),
            actor: event.actor.clone(),
            from: from.to_string(),
            to: to.to_string(),
            from_category: from_category.to_string(),
            to_category: to_category.to_string(),
            override_reason,
        })
    }

    /// The History entry to append for this decision.
    pub fn to_event(&self) -> HistoryEvent {
        HistoryEvent::new(
            self.timestamp.clone(),
            self.actor.clone(),
            HistoryEventKind::TransitionAccepted,
            self.detail(),
        )
    }

    /// Whether this decision is a same-column no-op record.
    ///
    /// The seam never appends one — idempotency is decided by
    /// `TransitionOutcome::Accepted { changed: false }` — but a **hand-edited** file
    /// can contain one, and WP06's `lint_direct_edits` needs to tell that apart
    /// from a real move rather than reading it as "status became todo".
    pub fn is_no_op(&self) -> bool {
        self.from == self.to
    }
}

/// One recorded mutation, and one line of the `## History` section.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HistoryEvent {
    /// When the mutation happened, RFC 3339.
    pub timestamp: String,
    /// Who performed it. Handled like [`Issue::assignee`]: a bare handle or a
    /// full identity, with a legacy `@alice` tolerated on read.
    pub actor: String,
    /// What kind of mutation this was.
    pub kind: HistoryEventKind,
    /// The field-aware description shown in detail views.
    pub detail: String,
}

impl HistoryEvent {
    /// Build an event.
    pub fn new(
        timestamp: impl Into<String>,
        actor: impl Into<String>,
        kind: HistoryEventKind,
        detail: impl Into<String>,
    ) -> Self {
        Self {
            timestamp: timestamp.into(),
            actor: actor.into(),
            kind,
            detail: detail.into(),
        }
    }

    /// The one-line form written to the file:
    /// `- <timestamp> — <actor> — <kind> — <detail>`.
    ///
    /// Four fields, not the three an earlier draft of `data-model.md` §8
    /// specified: a three-field form cannot carry `actor`, so the struct field
    /// would not survive a round trip and the audit trail would silently lose
    /// who performed each mutation. `data-model.md` §8 is corrected to match on
    /// the base and mission branches — it is a protected path, so the fix is not
    /// in this lane. **Read §8 there, not this comment**, if the two ever
    /// disagree.
    ///
    /// A blank actor renders as an empty field rather than being dropped, so
    /// the field count stays fixed and parsing never has to guess.
    fn render(&self) -> String {
        format!(
            "- {t} {h} {a} {h} {k} {h} {d}",
            t = self.timestamp.trim(),
            h = HISTORY_SEP,
            a = self.actor.trim(),
            k = self.kind.as_str(),
            d = self.detail
        )
    }

    /// Parse one rendered list item.
    ///
    /// The four fields are split on the **first three** separators only, so a
    /// detail or actor containing an em dash survives intact.
    fn parse(line: &str) -> Result<Self> {
        let item = line
            .trim()
            .strip_prefix("- ")
            .ok_or_else(|| TixError::Parse(format!("History entry is not a list item: {line}")))?;
        // Split on the first three separators only, so a detail containing an
        // em dash survives intact. Fields are read **positionally** rather than
        // as "the next non-empty value": the actor may legitimately be blank,
        // which is exactly what `render` writes when no identity was recorded,
        // so demanding a non-empty value there would make the writer's own
        // output unparseable.
        let parts: Vec<&str> = item.splitn(4, HISTORY_SEP).collect();
        let missing =
            |what: &str| TixError::Parse(format!("History entry is missing `{what}`: {line}"));
        if parts.len() < 3 {
            return Err(missing("a field separator"));
        }
        let timestamp = parts[0].trim();
        if timestamp.is_empty() {
            return Err(missing("timestamp"));
        }
        let actor = parts[1].trim().to_string();
        let kind_text = parts[2].trim();
        if kind_text.is_empty() {
            return Err(missing("kind"));
        }
        let kind = kind_text.parse::<HistoryEventKind>()?;
        let detail = parts.get(3).copied().unwrap_or_default().trim().to_string();
        Ok(Self {
            timestamp: timestamp.to_string(),
            actor,
            kind,
            detail,
        })
    }
}

/// Whether a line is a **recognised** History entry attempt.
/// Whether a line is **shaped like a markdown list item**, regardless of whether
/// it is a valid entry.
///
/// Used to decide where an unrecognised line belongs: a list item inside a
/// History section is far more likely a hand-edited entry than prose, and the two
/// are not told apart by anything else, because the section has no terminator.
///
/// All four common markers count, not just `- `. This is not a widening of the
/// entry grammar — recognition still requires U+2014, so nothing here can be read
/// as a relationship. With `- ` alone, an entry written
/// `* 2026-01-01T00:00:00Z — a — kind — d` was treated as prose, so the section
/// ended, the heading was deleted, and the next append was rendered above it.
fn is_list_item(item: &str) -> bool {
    for marker in ["- ", "* ", "+ "] {
        if item.starts_with(marker) {
            return true;
        }
    }
    // An ordered marker: digits then `.` or `)` then a space. Bounded to two
    // digits, or `2026. Q1 goals` reads as an ordered-list item and a paragraph
    // of ordinary body prose gets retained in the audit log.
    let Some(dot) = item.find(['.', ')']) else {
        return false;
    };
    dot > 0
        && dot <= 2
        && item[..dot].bytes().all(|b| b.is_ascii_digit())
        && item[dot + 1..].starts_with(' ')
}

/// Whether a line is a **recognised** History entry attempt.
///
/// Recognition requires the U+2014 separator, and nothing else. That is
/// deliberately stricter than "looks like" one: a looser test here is not a
/// nicety, it decides whether a line is *moved into the audit log* or left in
/// the body. A timestamp-shaped heuristic accepted a body to-do item
/// (`- 2026-02-02 review the migration`) as an entry attempt, which emptied
/// `body` and made `tix lint` blame the author — the original M3 defect arriving
/// through a different door, while the documentation claimed the opposite.
///
/// A line that is genuinely an entry but was typed with ASCII hyphens is
/// therefore *not* recognised, and never becomes an event. It may still be
/// *retained* in the section; see [`looks_like_an_unrecognised_entry`].
pub fn looks_like_history_entry(line: &str) -> bool {
    let item = line.trim();
    let Some(rest) = item.strip_prefix("- ") else {
        return false;
    };
    rest.contains(HISTORY_SEP)
}

/// Whether a line looks like a History entry that was **not** recognised — an
/// entry hand-typed with ASCII hyphens instead of U+2014.
///
/// This is the shape test behind two decisions, and they use it differently:
///
/// - `parse_front` asks whether an ambiguous line is a hand-edited *entry* rather
///   than body prose. Being wrong in that direction costs the author's bytes,
///   because a demoted line is body text and a later `tix edit --body` destroys
///   it with no trace.
/// - `tix lint` asks whether to *report* a line, where a false positive costs a
///   user-visible diagnostic on every run and a false negative costs a silent
///   typo.
///
/// A mistyped entry has the whole shape of one: a date, then three further
/// hyphen-separated fields — `<timestamp> - <actor> - <kind> - <detail>`. Both
/// halves are required. An earlier version accepted any 10-character run of
/// digits, dashes and punctuation, which flagged `- 10:00-11:00 sync with infra`,
/// `- 1234567890 is the upstream ticket`, `+49-30-12345678` and `1.2.3.4.5.6`; a
/// later one required only three fields, which flagged `- 2026-01-01 - Bob -
/// Done`. Four fields is what the format actually specifies, so that is what is
/// required.
pub fn looks_like_an_unrecognised_entry(line: &str) -> bool {
    let Some(rest) = strip_list_marker(line) else {
        return false;
    };
    if rest.contains(HISTORY_SEP) {
        return false; // genuinely recognised; not this function's business
    }
    entry_shaped_by_ascii_hyphens(rest, STRICT_TAIL_FIELDS)
}

/// Tail fields required to call a line a mistyped entry when **reporting** it.
///
/// Four fields in total, because that is the form carrying a detail; the shorter
/// three-field form is indistinguishable from a dated changelog line
/// (`- 2026-01-01 - Bob - Done`), and `tix lint` exits non-zero on a finding.
const STRICT_TAIL_FIELDS: usize = 3;

/// Tail fields required to call a line an entry **attempt** when deciding whether
/// to retain it.
///
/// Two, i.e. three fields in total, which is the shortest form `HistoryEvent::parse`
/// accepts — `detail` is optional there. A retention test stricter than the
/// recognition path is backwards: a valid three-field entry would be demoted to
/// body text and then destroyed by the next `tix edit --body`, while the
/// malformed four-field one survived. Cycle 6 found that inversion.
const RETENTION_TAIL_FIELDS: usize = 2;

/// Whether a line is an **entry attempt**: a list item whose content is shaped
/// like an entry, under any accepted marker.
///
/// This is the parser's question, and it is deliberately looser than
/// [`looks_like_an_unrecognised_entry`]'s, because the two have opposite costs.
/// Retaining a line that turns out to be prose moves it into the audit log *and
/// says so*; demoting a line that turns out to be an entry puts it in the body,
/// where the next `tix edit --body` deletes it with no trace. Retention is the
/// recoverable direction, so the parser errs towards retaining and the
/// diagnostic errs towards silence.
/// Whether a line introduces the `## History` section, under the same
/// tolerance the parser applies: trailing spaces or tabs are ignored, leading
/// whitespace is not.
///
/// Public so `tix lint` can report a **misplaced** section using the parser's own
/// rule. A second copy of this test could disagree with the parser about which
/// lines are headings, and then lint would report violations that do not exist
/// while missing ones that do.
pub fn is_history_heading(line: &str) -> bool {
    line.trim_end_matches([' ', '\t']) == HISTORY_HEADING
}

fn is_entry_attempt(item: &str) -> bool {
    let Some(rest) = strip_list_marker(item) else {
        return false;
    };
    if rest.contains(HISTORY_SEP) {
        // Correct separators. A `*`- or `1.`-marked entry is not *recognised* —
        // both `looks_like_history_entry` and `HistoryEvent::parse` require the
        // `- ` prefix — but it is unmistakably an entry attempt, and treating it
        // as prose cost a well-formed audit line. Cycle 6 found this.
        return true;
    }
    entry_shaped_by_ascii_hyphens(rest, RETENTION_TAIL_FIELDS)
}

/// Whether `rest` is a plausible entry body whose separators were typed as ASCII
/// hyphens: a date, then at least `min_tail` further hyphen-separated fields.
///
/// The tail splits on hyphens with optional surrounding spaces rather than on the
/// literal `" - "`, because an entry typed with ASCII hyphens is often typed
/// without the spaces too: `- 2026-01-01T00:00:00Z-alice-kind-d`. An earlier
/// version required `" - "` and so missed the case this tool exists to catch,
/// while the recognition path trims after the marker and accepted the same
/// whitespace — the identical line was "not an entry" and never mentioned.
fn entry_shaped_by_ascii_hyphens(rest: &str, min_tail: usize) -> bool {
    let Some(tail) = strip_leading_timestamp(rest) else {
        return false;
    };
    let parts: Vec<&str> = tail
        .split('-')
        .map(str::trim)
        .filter(|p| !p.is_empty())
        .collect();
    if parts.len() < min_tail {
        return false;
    }
    // The field right after the timestamp is an actor or a kind, and neither is a
    // date. Rejecting a numeric one is what keeps a date *range* out:
    // `- 2026-01-01..2026-01-05 was the freeze` otherwise splits into three
    // parts and reads as a mistyped entry.
    !starts_like_a_date(parts[0])
}

/// Whether a token opens with a run of four or more digits — a year, a serial
/// number, a date. Used only to reject prose that would otherwise split into
/// enough hyphen-separated fields to look like an entry.
fn starts_like_a_date(token: &str) -> bool {
    let digits = token.bytes().take_while(u8::is_ascii_digit).count();
    digits >= 4
}

/// The text after any accepted list marker, with whatever whitespace a hand put
/// after it removed.
///
/// `HistoryEvent::parse` trims after the prefix too, so this must as well:
/// otherwise `-  2026-…—…` and `-\t2026-…—…` are recognised as real entries while
/// their ASCII-hyphen equivalents are silently unreported.
fn strip_list_marker(line: &str) -> Option<&str> {
    let item = line.trim();
    if is_list_item(item) {
        let space = item.find(char::is_whitespace).unwrap_or(item.len());
        return Some(item[space..].trim_start());
    }
    None
}

/// The remainder of a line whose first field begins with a plausible ISO date, or
/// `None` if it does not.
///
/// A date is the only field shape that separates a mistyped entry from an
/// ordinary dated bullet, and requiring it is what keeps `tix lint` quiet on
/// prose. Plausibility is deliberately not checked: rejecting a hand-typed
/// offset like `+02:00` would create a false negative in the one tool whose job
/// is to catch exactly this mistake, so implausible shapes are reported rather
/// than filtered.
fn strip_leading_timestamp(rest: &str) -> Option<&str> {
    let b = rest.as_bytes();
    if b.len() < 10
        || !b[0..4].iter().all(u8::is_ascii_digit)
        || b[4] != b'-'
        || !b[5..7].iter().all(u8::is_ascii_digit)
        || b[7] != b'-'
        || !b[8..10].iter().all(u8::is_ascii_digit)
    {
        return None;
    }
    let mut i = 10;
    if b.get(i) == Some(&b'T') {
        i += 1;
        while i < b.len() && (b[i].is_ascii_digit() || b[i] == b':' || b[i] == b'.') {
            i += 1;
        }
        match b.get(i) {
            Some(b'Z') => i += 1,
            // A `-` is a zone separator only when digits follow it; otherwise it
            // is the first field separator and the timestamp ended at the time.
            Some(&b'-') => {
                let mut j = i + 1;
                while j < b.len() && b[j].is_ascii_digit() {
                    j += 1;
                }
                if j > i + 1 {
                    i = j;
                }
            }
            Some(&b'+') => {
                i += 1;
                while i < b.len() && (b[i].is_ascii_digit() || b[i] == b':') {
                    i += 1;
                }
            }
            _ => {}
        }
    }
    // \`.\` too: a date *range* continues with \`..\`, and leaving it glued to
    // the next token makes \`- 2026-01-01..2026-01-05 was the freeze\` split into
    // three fields.
    Some(rest[i.min(rest.len())..].trim_start_matches(['-', ' ', '\t', '.']))
}

/// One line of the `## History` section.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HistoryEntry {
    /// A well-formed event.
    Event(HistoryEvent),
    /// A line that could not be parsed, preserved **verbatim**.
    ///
    /// The section is documented as human-editable, so a hand edit will
    /// eventually produce a line this parser cannot read — ASCII hyphens
    /// instead of the U+2014 separators is the obvious one. Such a line is
    /// never dropped, never coerced, and never auto-repaired: it is carried
    /// through a read/write cycle unchanged and reported by `tix lint` as a
    /// `history` finding on that issue only. It must never fail the
    /// parse of the whole file, because one mistyped line in one issue would
    /// otherwise make every issue in the repository unreadable.
    Unparsed(String),
}

/// The append-only event log of an issue (`data-model.md` §8).
///
/// Append-only is a hard guarantee of this type: the only mutating operation
/// is [`History::append`]. There is deliberately no remove, no reorder, no
/// trim, and no compaction — those are out of scope, but the container is
/// shaped so a future retention policy has a seam.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct History {
    /// Every line of the section, in file order, which is append order.
    ///
    /// Held as an ordered list of entries rather than a flat `Vec<HistoryEvent>`
    /// so an **unparseable** line keeps its position and its exact text. That
    /// is what lets the section round-trip byte-stably without ever dropping or
    /// repairing a line a human hand-edited.
    pub entries: Vec<HistoryEntry>,
}

impl History {
    /// An empty log.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append one event. Never rewrites, reorders, or removes an existing line.
    pub fn append(&mut self, event: HistoryEvent) {
        self.entries.push(HistoryEntry::Event(event));
    }

    /// Append with the current UTC timestamp.
    pub fn append_now(&mut self, actor: &str, kind: HistoryEventKind, detail: &str) {
        self.append(HistoryEvent::new(utc_now_rfc3339(), actor, kind, detail));
    }

    /// The parsed events, in file order.
    ///
    /// Unparseable lines are excluded here; see [`History::unparsed`].
    pub fn events(&self) -> Vec<&HistoryEvent> {
        self.entries
            .iter()
            .filter_map(|e| match e {
                HistoryEntry::Event(event) => Some(event),
                HistoryEntry::Unparsed(_) => None,
            })
            .collect()
    }

    /// Lines that could not be parsed, verbatim and in file order.
    ///
    /// Non-empty means the section was hand-edited into a shape this parser
    /// does not accept. `tix lint` reports each as a `history`
    /// finding; nothing else treats it as an error.
    pub fn unparsed(&self) -> Vec<&str> {
        self.entries
            .iter()
            .filter_map(|e| match e {
                HistoryEntry::Event(_) => None,
                HistoryEntry::Unparsed(line) => Some(line.as_str()),
            })
            .collect()
    }

    /// Whether the section has no lines at all.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// How many lines the section holds, parsed or not.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Render the section, including its heading and the blank line after it.
    ///
    /// An empty log renders to the empty string, so the section is *omitted*
    /// from the file entirely rather than written as an empty heading. An
    /// unparseable line is re-emitted exactly as it was read, in place, so a
    /// read/write cycle is byte-stable whether or not the section is clean.
    pub fn render(&self) -> String {
        if self.is_empty() {
            return String::new();
        }
        let mut out = String::from(HISTORY_HEADING);
        out.push_str("\n\n");
        for entry in &self.entries {
            match entry {
                HistoryEntry::Event(event) => {
                    out.push_str(&event.render());
                    out.push('\n');
                }
                HistoryEntry::Unparsed(line) => {
                    out.push_str(line);
                    out.push('\n');
                }
            }
        }
        out.push('\n');
        out
    }

    /// Parse a leading `## History` section, returning the log and whatever body
    /// text followed it.
    ///
    /// Only a section at the *front* of the body is recognised, matching the
    /// position `data-model.md` §8 pins (immediately after the frontmatter). A
    /// `## History` heading appearing later in the prose is left alone as
    /// ordinary body text.
    ///
    /// The section ends at the first line that is neither blank nor a list item,
    /// so a **blank line between entries does not end it** — a blank line inside
    /// a list is the most ordinary thing a human or a Markdown formatter
    /// produces, and terminating there would silently demote audit entries to
    /// body prose and reorder the log. Unparseable list items are kept verbatim
    /// rather than failing the file.
    pub fn parse_front(body: &str) -> (Self, String) {
        let lead = body.len() - body.trim_start_matches('\n').len();
        let trimmed = &body[lead..];
        let Some(rest) = trimmed.strip_prefix(HISTORY_HEADING) else {
            return (History::new(), body.to_string());
        };
        // The heading must be alone on its line — but trailing spaces and tabs on
        // it are still that line. Requiring a bare `\n` meant `## History   ` was
        // not recognised at all, and since the heading is then neither the
        // section nor body, the *first* relationship write rendered a second
        // `## History` above the original. Cycle 6 executed that; it had been
        // filed against #1299 as a CRLF-only consequence, which understated it —
        // a trailing space is a far likelier trigger than CRLF.
        let rest = rest.trim_start_matches([' ', '\t']);
        // #1299: a CRLF file spells the heading's line ending `\r\n`.
        let Some(after_heading) = rest
            .strip_prefix("\r\n")
            .or_else(|| rest.strip_prefix('\n'))
        else {
            return (History::new(), body.to_string());
        };
        let after_heading = after_heading.trim_start_matches(['\r', '\n']);

        let mut history = History::new();
        let mut offset = 0usize;
        // Whether the section carried a list item that was **judged prose and
        // dropped by the `break` below**. That is the #1336 shape — a list line
        // above ordinary prose empties the section and deletes the heading — and
        // it is what the empty-history guard restores. A section of pure prose (a
        // bare `## History` heading above a paragraph) carries no list item, so
        // dropping the derived heading stays correct.
        let mut saw_rejected_list_item = false;
        for line in after_heading.split_inclusive('\n') {
            // `item` is the trimmed form used for *shape* decisions; `raw_line`
            // is what a preserved `Unparsed` entry stores, so a hand edit keeps
            // its own bytes.
            let raw_line = line;
            let item = raw_line.trim();
            if item.is_empty() {
                // A blank line *inside* the section is skipped, not treated as
                // the end of it. It is consumed, so the body that follows does
                // not start with stray blank lines.
                offset += line.len();
                continue;
            }
            if !looks_like_history_entry(item) {
                // The section has no end-of-section delimiter, so this line is
                // ambiguous: either body prose, or a hand-edited line *inside*
                // the section. The two are told apart by what follows.
                //
                // If every remaining non-blank line is entry-shaped, the
                // ambiguous line was a hand edit inside the section, so the
                // section continues and the line is kept verbatim as
                // `Unparsed` — nothing is dropped and the real events after it
                // stay events. If anything after it is not entry-shaped, this
                // is body prose and the section genuinely ends here.
                //
                // The alternative — absorbing any `- ` line — moved body content
                // into the audit log, deleted the blank line separating them on
                // the first write, and then had `tix lint` blaming the author's
                // prose as unparseable entries. Trigger was ordinary:
                // `tix edit --body "- step one\n- step two"`.
                // Collected rather than consumed with `next()` + `all()`: that
                // skips judging the *first* following line, and `all()` over an
                // empty remainder is vacuously true — so a section followed by a
                // single non-entry line was absorbed. Both mistakes are the same
                // one: judging nothing and concluding "all of it is entries".
                let following: Vec<&str> = after_heading[offset + line.len()..]
                    .lines()
                    .filter(|l| !l.trim().is_empty())
                    .collect();
                // Two different questions, and conflating them is what broke this
                // twice.
                //
                // *Does anything after this disqualify it as body prose?* When
                // nothing follows, nothing can — `all()` is then vacuously true
                // and that is the **correct** answer, not a bug. A guard
                // requiring a non-empty remainder (added to stop an earlier
                // vacuous-truth defect) made the last line in a section always
                // terminate it, which deleted the `## History` heading, demoted
                // the author's line into the body, and rendered the next append
                // *above* it — file order stopped being append order, and
                // `tix lint` said nothing because a demoted line is body prose
                // and the unparsed loop no longer sees it.
                //
                // *Is this line shaped like a list item at all?* That still
                // decides, at end of section, whether keeping it is defensible.
                // `- step one` at EOF is far more likely a hand-edited entry than
                // the only body content of an issue, and keeping it *discloses*
                // the problem. A bare paragraph at EOF is prose, full stop, and
                // absorbing it would pollute the audit log.
                // Three inputs, and which ones matter depends on whether
                // anything follows. Cycle 5 found this half-fixed: consulting
                // only `is_list_item`, and only when nothing followed, left the
                // whole defect alive for any ambiguous line with body prose
                // after it.
                //
                // The asymmetry that decides the design: a *demoted* line is body
                // text, and `tix edit --body` replaces the body wholesale — so a
                // hand-edited entry that was demoted is destroyed by an ordinary
                // command, with lint silent. A *retained* line is kept verbatim
                // inside the section and reported. Given the choice, retaining is
                // the recoverable one, so the tie only goes to "this is prose"
                // when the line is not plausibly an entry at all.
                let plausible_entry = is_entry_attempt(item);
                let after_all_entries = following.iter().all(|l| looks_like_history_entry(l));
                let keep = if following.is_empty() {
                    // Nothing after to judge by, so shape alone decides. A bare
                    // paragraph at end of section is prose; anything list-shaped
                    // is kept, because there is no following content that could
                    // have been prose instead.
                    is_list_item(item)
                } else {
                    plausible_entry || after_all_entries
                };
                if !keep {
                    // A list-shaped line is the one case where the `break`
                    // discards something that could have been an audit entry, so
                    // record it for the empty-history guard after the loop.
                    saw_rejected_list_item |= is_list_item(item);
                    break;
                }
                // The **raw** line, not the trimmed one: `Unparsed` promises a
                // hand edit is carried through a read/write cycle unchanged, and
                // trimming silently repaired leading indentation and trailing
                // whitespace — exactly the auto-repair data-model §8 forbids.
                history.entries.push(HistoryEntry::Unparsed(
                    raw_line.trim_end_matches('\n').to_string(),
                ));
                offset += line.len();
                continue;
            }
            match HistoryEvent::parse(item) {
                Ok(event) => history.entries.push(HistoryEntry::Event(event)),
                // Kept verbatim. Diagnosed by `tix lint`, never repaired, never
                // dropped, and never fatal to the file.
                // Raw line, for the same reason as above.
                // Terminator only. `trim_end()` also eats trailing spaces and
                // tabs, which is the auto-repair data-model §8 forbids — and
                // `Err` is the arm a *recognised* entry lands in, so it is the
                // more likely one to carry real trailing whitespace.
                Err(_) => history.entries.push(HistoryEntry::Unparsed(
                    raw_line.trim_end_matches('\n').to_string(),
                )),
            }
            offset += line.len();
        }

        if history.entries.is_empty() && saw_rejected_list_item {
            // Nothing was retained and a list-shaped line was dropped. The
            // heading was consumed above, so the current return
            // (`after_heading[offset..]`) would delete it while leaving every
            // line after it as body prose: `tix view` loses the section and only
            // a later append renders a new heading above the demoted text. That
            // is #1336 — a list-shaped line judged prose empties the whole
            // section and deletes the audit trail with no diagnostic. Return the
            // original body verbatim (heading and all) so the file round-trips.
            //
            // A section of **pure prose** (no list item) is deliberately not
            // restored: the heading is derived from the log, and `storage`'s
            // `t010_an_empty_history_section_is_dropped_not_preserved` pins that
            // a heading with nothing to record is omitted rather than kept as a
            // bare heading. There is no audit entry to lose there.
            return (history, body.to_string());
        }
        (history, after_heading[offset..].to_string())
    }
}

impl Issue {
    /// Parse a full issue file (`frontmatter` + `body`) from its text.
    ///
    /// The first line must be `---`; the closing `---` terminates the
    /// frontmatter. The body after it is preserved verbatim (the single
    /// structural separator blank line is consumed).
    pub fn parse(contents: &str) -> Result<Self> {
        // #1299: a CRLF file must parse. The delimiter scan tolerates a `\r`
        // before each `\n` rather than normalizing the whole file — a blanket
        // CRLF-to-LF rewrite would silently change a user's bytes, so the fix
        // stays in the scan that decides where the frontmatter ends.
        let rest = contents
            .strip_prefix("---\n")
            .or_else(|| contents.strip_prefix("---\r\n"))
            .ok_or_else(|| TixError::Parse("file must start with a `---` delimiter".into()))?;
        let mut current = rest;
        let mut fm_len = 0usize;
        loop {
            let line_end = current.find('\n').map(|i| i + 1).unwrap_or(current.len());
            let line = &current[..line_end];
            let content = line.strip_suffix('\n').unwrap_or(line);
            let content = content.strip_suffix('\r').unwrap_or(content);
            if content == "---" {
                break;
            }
            fm_len += line_end;
            current = &current[line_end..];
            if current.is_empty() {
                return Err(TixError::Parse(
                    "frontmatter is not terminated by a closing `---`".into(),
                ));
            }
        }
        let frontmatter = &rest[..fm_len];
        let body_raw = &rest[fm_len..];
        // #1299: the closing delimiter is CRLF too when the file is CRLF.
        let mut body = body_raw
            .strip_prefix("---\n")
            .or_else(|| body_raw.strip_prefix("---\r\n"))
            .unwrap_or(body_raw);
        if let Some(after) = body
            .strip_prefix("\r\n")
            .or_else(|| body.strip_prefix('\n'))
        {
            body = after;
        }
        let mut issue: Issue =
            serde_yaml::from_str(frontmatter).map_err(|e| TixError::Parse(e.to_string()))?;
        // A legacy `links:` key is recorded, never read. The typed model does
        // not migrate it and does not reinterpret it as typed edges; the
        // service reports it as a `retired_links_key` validation result (C-001).
        // `relationships` stays as serde left it — empty.
        issue.has_retired_links_key = frontmatter_has_retired_links_key(frontmatter);
        // Unknown top-level keys are captured so the next write can put them back
        // (#1361). `links` is excluded on purpose — see [`capture_extra_frontmatter`].
        issue.extra_frontmatter = capture_extra_frontmatter(frontmatter);
        let (history, remaining_body) = History::parse_front(body);
        issue.history = history;
        issue.body = remaining_body;
        Ok(issue)
    }

    /// Serialize just the frontmatter YAML (no delimiters), with `None`
    /// fields omitted except `created`/`updated` which are always present.
    pub fn frontmatter(&self) -> String {
        let fm =
            serde_yaml::to_string(self).expect("Issue frontmatter serialization is infallible");
        let mut fm = fm.trim_end_matches('\n').to_string();
        // Unknown keys are appended after the known ones, in `BTreeMap` order, so
        // the render is deterministic. A `HashMap` would reshuffle them on every
        // write and produce a diff in a file that had not changed (#1361).
        //
        // They go last rather than back in their original position because the
        // positions of the *known* keys move as optional fields come and go;
        // re-inserting at the original index would be a guess. `tix` has no
        // opinion about these keys, so where they sit carries no meaning.
        for (key, block) in &self.extra_frontmatter {
            fm.push('\n');
            fm.push_str(block);
            let _ = key;
        }
        fm.push('\n');
        fm
    }

    /// Render the full issue file: `---`, frontmatter, closing `---`,
    /// blank separator and the raw body.
    pub fn to_file_contents(&self) -> String {
        // Frontmatter, then the History section (omitted when empty), then the
        // issue's own body — the order `data-model.md` §8 pins.
        let history = self.history.render();
        let mut out = format!("---\n{}---\n\n", self.frontmatter());
        out.push_str(&history);
        out.push_str(&self.body);
        out
    }

    /// A borrowed [`IssueView`] of this issue, for the relationship service.
    ///
    /// Keeps the service off the full `Issue` surface: it needs only the
    /// number, title, status, relationships, and whether the legacy `links:`
    /// key is still present.
    pub fn issue_view(&self) -> IssueView<'_> {
        IssueView::new(
            self.number,
            &self.title,
            self.status.display(),
            &self.relationships,
        )
        .with_retired_links_key(self.has_retired_links_key)
        .with_parent(self.parent)
    }

    /// The filename stem: `{created}-{id}-{slug}` when the issue has an id, or
    /// the legacy `{created}-{slug}` when it does not.
    ///
    /// The date leads so a lexicographic directory listing is creation order;
    /// the id follows so the name is globally unique across branches (#1587). A
    /// legacy issue keeps the date-leading name it was written with, because
    /// renaming it would be a migration this feature deliberately does not do.
    pub fn filename_stem(&self) -> String {
        match &self.id {
            Some(id) => format!("{}-{id}-{}", self.created, slugify(&self.title)),
            None => format!("{}-{}", self.created, slugify(&self.title)),
        }
    }

    /// Record a mutation by stamping today's date into `updated`.
    pub fn bump_updated(&mut self) {
        self.updated = today();
    }

    /// Set `start_date`/`due_date` together after atomic validation (FR-007):
    /// both must parse as calendar dates and `due_date >= start_date` when
    /// both are present (delegates to [`validate_issue_dates`]).
    pub fn set_dates(
        &mut self,
        start_date: Option<String>,
        due_date: Option<String>,
    ) -> Result<()> {
        validate_issue_dates(start_date.as_deref(), due_date.as_deref())?;
        self.start_date = start_date;
        self.due_date = due_date;
        Ok(())
    }

    /// The byte offset of the first top-level `## Comments` line in `body`,
    /// if any (C-001, `contracts/comments-format.md` rule 6).
    ///
    /// A line counts as the boundary only when it is *not* inside a fenced
    /// code block, so a literal `## Comments` in prose (or a code block) is
    /// never mistaken for the real section head.
    fn comments_boundary(body: &str) -> Option<usize> {
        let mut in_fence = false;
        let mut offset = 0usize;
        for raw in body.split_inclusive('\n') {
            let line = raw.strip_suffix('\n').unwrap_or(raw);
            if line.starts_with("```") || line.starts_with("~~~") {
                in_fence = !in_fence;
            } else if !in_fence && line == "## Comments" {
                return Some(offset);
            }
            offset += raw.len();
        }
        None
    }

    /// The description: everything above the first top-level `## Comments`
    /// heading, trimmed of trailing whitespace. With no section, the whole
    /// body is the description.
    pub fn description(&self) -> &str {
        match Self::comments_boundary(&self.body) {
            Some(idx) => self.body[..idx].trim_end(),
            None => self.body.trim_end(),
        }
    }

    /// The comments parsed from the `## Comments` section, in file order
    /// (NFR-005). With no section — or a section with no `###` heads —
    /// returns an empty vec.
    pub fn comments(&self) -> Vec<Comment> {
        let Some(boundary) = Self::comments_boundary(&self.body) else {
            return Vec::new();
        };
        let section = &self.body[boundary..];
        let mut comments = Vec::new();
        let mut offset = 0usize;
        for raw in section.split_inclusive('\n') {
            let line = raw.strip_suffix('\n').unwrap_or(raw);
            if let Some(after) = line.strip_prefix("### ") {
                let (author, date) = parse_comment_head(after);
                let start = offset + raw.len();
                let mut text = String::new();
                for next in section[start..].split_inclusive('\n') {
                    if next.strip_suffix('\n').unwrap_or(next).starts_with("### ") {
                        break;
                    }
                    text.push_str(next);
                }
                comments.push(Comment {
                    author,
                    date,
                    text: text.trim_end_matches('\n').to_string(),
                });
            }
            offset += raw.len();
        }
        comments
    }

    /// Append a comment to the `## Comments` section.
    ///
    /// Whitespace-only text is discarded and the body is left untouched
    /// (FR-004 case 4). Otherwise the section is created if absent and the
    /// comment block is appended after the last existing comment. The
    /// description and any existing comments are never rewritten.
    pub fn add_comment(&mut self, author: &str, text: &str) {
        if text.trim().is_empty() {
            return;
        }
        if Self::comments_boundary(&self.body).is_none() {
            if !self.body.trim().is_empty() {
                if !self.body.ends_with('\n') {
                    self.body.push('\n');
                }
                self.body.push('\n');
            }
            self.body.push_str("## Comments\n");
        }
        if !self.body.is_empty() && !self.body.ends_with('\n') {
            self.body.push('\n');
        }
        if !self.body.ends_with("\n\n") {
            self.body.push('\n');
        }
        self.body
            .push_str(&format!("### {author} ({})\n\n{text}\n", today()));
        self.bump_updated();
    }
}

// ---------------------------------------------------------------------------
// The hierarchy service's view of an `Issue`
// ---------------------------------------------------------------------------

/// Read in place, rather than through a borrowed projection.
///
/// Implemented here because `hierarchy` cannot import `model` without a cycle, and
/// because it is `Issue` — not [`IssueView`] — that every store-level caller already
/// holds. Without this each of them builds a `Vec<IssueView>` first, which is a
/// projection nobody asked for and one more place for two services to disagree about
/// the same snapshot.
impl crate::hierarchy::HierarchyNode for Issue {
    fn number(&self) -> u32 {
        self.number
    }
    fn title(&self) -> &str {
        &self.title
    }
    fn status(&self) -> &str {
        self.status.display()
    }
    fn parent_number(&self) -> Option<u32> {
        self.parent
    }
}

// ---------------------------------------------------------------------------
// The project service's view of an `Issue`
// ---------------------------------------------------------------------------

/// Read in place, for the same reason as [`crate::hierarchy::HierarchyNode`]:
/// `projects` cannot import `model` without a cycle, and `Issue` is what every
/// store-level caller already holds. Implementing it here rather than building a
/// projection keeps one snapshot shared by the service that decides and the storage
/// layer that writes.
///
/// `project_ids` borrows the stored list; an absent field is the empty slice, so the
/// service sees "no associations" without a second representation.
impl crate::projects::ProjectNode for Issue {
    fn number(&self) -> u32 {
        self.number
    }
    fn title(&self) -> &str {
        &self.title
    }
    fn status(&self) -> &str {
        self.status.display()
    }
    fn project_ids(&self) -> &[String] {
        self.projects.as_deref().unwrap_or(&[])
    }
}

// ---------------------------------------------------------------------------
// The epic service's view of an `Issue`
// ---------------------------------------------------------------------------

/// Read in place, for the same reason as [`crate::projects::ProjectNode`]:
/// `epics` cannot import `model` without a cycle, and `Issue` is what every
/// store-level caller already holds. Implementing it here rather than building a
/// projection keeps one snapshot shared by the service that decides and the storage
/// layer that writes.
///
/// `epic_ids` borrows the stored list; an absent field is the empty slice, so the
/// service sees "no references" without a second representation and never panics
/// on a legacy file.
impl crate::epics::EpicNode for Issue {
    fn number(&self) -> u32 {
        self.number
    }
    fn title(&self) -> &str {
        &self.title
    }
    fn status(&self) -> &str {
        self.status.display()
    }
    fn epic_ids(&self) -> &[String] {
        self.epics.as_deref().unwrap_or(&[])
    }
}

#[cfg(test)]
mod tests {
    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(7), "the parent number 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(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),
            ("!!str 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(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(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(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"
        );
    }
}