tix-tracker 0.12.0

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

/// The no-clobber layer, tested directly.
///
/// `write_new_issue_file`'s **probe** is the common path and is covered end to
/// end by `two_creates_with_the_same_title_both_survive` in `tests/cli.rs`.
/// The probe cannot see a name another process takes between the probe and the
/// write, which is why the final create is exclusive. This is the guarantee that
/// closes that window, so it is asserted on the primitive rather than through a
/// race that would be flaky to provoke.
///
/// If the exclusive path were replaced by a `rename` — the obvious "simplify
/// this" edit — the planted file below would be silently destroyed, which is
/// precisely the data loss `write_new_issue_file` exists to prevent.
#[test]
fn write_file_new_refuses_an_existing_target() {
    let dir = TempDir::new().unwrap();
    let target = dir.path().join("issue.md");
    write_file_new(dir.path(), &target, b"first").unwrap();
    assert_eq!(fs::read_to_string(&target).unwrap(), "first");

    let err = write_file_new(dir.path(), &target, b"second").unwrap_err();
    let TixError::Io(io_err) = err else {
        panic!("expected an I/O error, so the caller can retry on a name collision")
    };
    assert_eq!(
        io_err.kind(),
        std::io::ErrorKind::AlreadyExists,
        "the error must be AlreadyExists, so the caller can retry on a name \\
         collision rather than treating it as a hard failure"
    );
    assert_eq!(
        fs::read_to_string(&target).unwrap(),
        "first",
        "the existing file must be byte-identical — not truncated, not replaced"
    );
}

/// The retry loop turns an `AlreadyExists` into the next free name.
#[test]
fn a_clobbered_name_is_retried_rather_than_failing_or_overwriting() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    let store = Store::open(&crate::config::Config {
        issues_dir: dir.to_path_buf(),
        ..Default::default()
    })
    .unwrap();

    // The probe looks at `<issues_dir>/<segment>/<stem>.md`, so the plants have
    // to sit in the segment directory — that is where the collision is.
    let segment_dir = dir.join("seg");
    fs::create_dir_all(&segment_dir).unwrap();

    // Two plants on the exact names the probe would try first, so the retry has
    // to walk past both to reach the third.
    for name in ["2026-01-01-race.md", "2026-01-01-race-2.md"] {
        fs::write(segment_dir.join(name), "planted").unwrap();
    }

    let (filename, path) = store
        .write_new_issue_file("seg", "2026-01-01-race", b"mine")
        .unwrap();
    assert_eq!(filename, "seg/2026-01-01-race-3.md");
    assert_eq!(fs::read_to_string(&path).unwrap(), "mine");
    assert_eq!(
        fs::read_to_string(segment_dir.join("2026-01-01-race.md")).unwrap(),
        "planted"
    );
    assert_eq!(
        fs::read_to_string(segment_dir.join("2026-01-01-race-2.md")).unwrap(),
        "planted"
    );
}

/// No temp files are left behind on either the success or the collision path.
///
/// A leftover `.tix-tmp-*` in `docs/issues/<segment>/` would be picked up by the
/// next `tix list` as a malformed issue, and the exclusive path has an extra
/// step (`hard_link` then `remove_file`) where a leak is easy to introduce.
#[test]
fn no_temp_files_are_left_behind_on_success_or_collision() {
    let dir = TempDir::new().unwrap();
    let target = dir.path().join("issue.md");
    write_file_new(dir.path(), &target, b"first").unwrap();
    let _ = write_file_new(dir.path(), &target, b"second");
    let leftovers: Vec<String> = fs::read_dir(dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().to_string())
        .filter(|n| n.starts_with(".tix-tmp-"))
        .collect();
    assert!(
        leftovers.is_empty(),
        "temp files must not survive, found {leftovers:?}"
    );
}

fn make_store() -> (tempfile::TempDir, Store) {
    let tmp = tempfile::TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let mut config = Config {
        issues_dir: dir.clone(),
        ..Config::default()
    };
    // Storage unit tests predate configurable layout and assert the legacy
    // one-segment paths; pin it and disable move-on-change so they stay about
    // grouping, not layout. Both the default template and auto-migration are
    // covered by dedicated tests.
    config.layout.directory = "{assignee}".to_string();
    config.layout.move_on_change = false;
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let store = Store {
        issues_dir: dir,
        config,
    };
    (tmp, store)
}

fn write_issue(store: &Store, name: &str, contents: &str) {
    fs::write(store.issues_dir.join(name), contents).unwrap();
}

fn sample_frontmatter(number: u32, title: &str, status: &str) -> String {
    format!(
        "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody text."
    )
}

// ------------------------------------------------------------------
// Issue #1492 — archived issues (dot-prefixed filename, in place)
// ------------------------------------------------------------------

/// The default walk must skip a dot-prefixed file **without opening it**, so
/// an archived file with unparseable frontmatter cannot break `list()`. That
/// an unparseable one is *only* reachable through `list_all()` is the cheapest
/// honest proof the skip happens before the read.
#[test]
fn list_never_opens_an_archived_file_but_list_all_does() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-active.md",
        &sample_frontmatter(1, "Active", "todo"),
    );
    fs::write(
        store.issues_dir.join("alice/.2026-01-02-broken.md"),
        "this file has no frontmatter at all\n",
    )
    .unwrap();

    let active = store
        .list()
        .expect("the default walk must not read the archived file");
    assert_eq!(active.len(), 1);
    assert_eq!(active[0].number, 1);
    assert!(!active[0].archived);

    let all = store.list_all();
    assert!(
        matches!(all, Err(TixError::Parse(_))),
        "list_all() reads it, so the broken file is only invisible to list(): {all:?}"
    );
}

#[test]
fn archive_renames_in_place_and_restore_is_the_inverse() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(5, "X", "todo"),
    );

    let archived = store.archive("5").unwrap();
    assert_eq!(archived.filename, "alice/.2026-01-01-x.md");
    assert!(archived.archived);
    assert!(store.issues_dir.join("alice/.2026-01-01-x.md").is_file());
    assert!(!store.issues_dir.join("alice/2026-01-01-x.md").exists());
    assert!(
        store.list().unwrap().is_empty(),
        "hidden from the default view"
    );

    let all = store.list_all().unwrap();
    assert_eq!(all.len(), 1);
    assert!(all[0].archived);
    assert_eq!(all[0].number, 5, "the number is untouched");

    // Both selectors still resolve the archived issue.
    assert_eq!(
        store.get(IssueSelector::Number(5)).unwrap().filename,
        "alice/.2026-01-01-x.md"
    );
    assert!(store.get(IssueSelector::Slug(slugify("X"))).is_ok());

    let restored = store.restore("5").unwrap();
    assert_eq!(restored.filename, "alice/2026-01-01-x.md");
    assert!(!restored.archived);
    assert_eq!(store.list().unwrap().len(), 1, "visible again");
}

#[test]
fn archive_appends_one_event_and_leaves_the_frontmatter_untouched() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(5, "X", "todo"),
    );
    let before = store
        .get(IssueSelector::Filename("alice/2026-01-01-x.md".into()))
        .unwrap();

    let archived = store.archive("5").unwrap();
    assert_eq!(archived.history.len(), 1, "exactly one History event");
    assert_eq!(
        archived.history.events()[0].kind,
        HistoryEventKind::Archived
    );

    let after = store.get(IssueSelector::Number(5)).unwrap();
    // Every field a reader cares about survives unchanged. `update` re-renders
    // the frontmatter (quoting and key order normalize, as on every tix write),
    // so the invariant is the *values*, not the bytes.
    assert_eq!(after.number, before.number);
    assert_eq!(after.title, before.title);
    assert_eq!(after.status, before.status);
    assert_eq!(after.labels, before.labels);
    assert_eq!(after.priority, before.priority);
    assert_eq!(after.assignee, before.assignee);
    assert_eq!(after.created, before.created);
    assert_eq!(
        after.updated, before.updated,
        "archiving must not bump `updated`: it is a frontmatter field"
    );
    // The marker is the filename; nothing was written into the frontmatter.
    let raw = read_issue_file(&store, "alice/.2026-01-01-x.md");
    let fm = raw.split("\n---").next().unwrap();
    assert!(
        !fm.contains("archived"),
        "the archived flag must never reach the frontmatter: {fm}"
    );
}

#[test]
fn restore_appends_one_restored_event() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(5, "X", "todo"),
    );
    store.archive("5").unwrap();
    let restored = store.restore("5").unwrap();
    assert_eq!(restored.history.len(), 2, "archive + restore");
    assert_eq!(
        restored.history.events()[1].kind,
        HistoryEventKind::Restored
    );
}

#[test]
fn archiving_the_highest_number_does_not_free_it_for_reuse() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    write_issue(
        &store,
        "alice/2026-01-01-b.md",
        &sample_frontmatter(7, "B", "todo"),
    );

    store.archive("7").unwrap();

    let mut fresh = Issue::parse(&sample_frontmatter(0, "New", "todo")).unwrap();
    store.create(&mut fresh, "body", None).unwrap();
    assert_eq!(
        fresh.number, 8,
        "an archived issue keeps its number: `create` must not reuse #7"
    );
}

#[test]
fn redundant_archive_and_restore_are_refused_by_name() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(5, "X", "todo"),
    );

    let err = store.restore("5").unwrap_err();
    assert!(
        err.to_string().contains("not_archived"),
        "an active issue cannot be restored: {err}"
    );
    assert!(
        store.issues_dir.join("alice/2026-01-01-x.md").is_file(),
        "the refused restore writes nothing"
    );

    store.archive("5").unwrap();
    let err = store.archive("5").unwrap_err();
    assert!(
        err.to_string().contains("already_archived"),
        "an archived issue cannot be re-archived: {err}"
    );
    assert!(
        store.issues_dir.join("alice/.2026-01-01-x.md").is_file(),
        "the refused archive writes nothing"
    );
}

#[test]
fn archive_never_clobbers_an_occupied_target_name() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(5, "X", "todo"),
    );
    // A pre-existing dot-prefixed file would be the target of the rename.
    write_issue(
        &store,
        "alice/.2026-01-01-x.md",
        &sample_frontmatter(6, "Other", "todo"),
    );
    let err = store.archive("5").unwrap_err();
    assert!(err.to_string().contains("already exists"), "got: {err}");
    assert!(store.issues_dir.join("alice/2026-01-01-x.md").is_file());
    assert!(store.issues_dir.join("alice/.2026-01-01-x.md").is_file());
}

#[test]
fn archive_and_restore_a_legacy_flat_file_in_place() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-legacy.md",
        &sample_frontmatter(3, "Legacy", "todo"),
    );

    let archived = store.archive("3").unwrap();
    assert_eq!(archived.filename, ".2026-01-01-legacy.md");
    assert!(store.issues_dir.join(".2026-01-01-legacy.md").is_file());
    assert_eq!(store.list().unwrap(), [] as [crate::model::Issue; 0]);
    assert_eq!(store.list_all().unwrap().len(), 1);

    let restored = store.restore("3").unwrap();
    assert_eq!(restored.filename, "2026-01-01-legacy.md");
    assert!(store.issues_dir.join("2026-01-01-legacy.md").is_file());
}

#[test]
fn list_returns_sorted_by_filename() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-03-01-c.md",
        &sample_frontmatter(3, "C", "todo"),
    );
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    write_issue(
        &store,
        "2026-02-01-b.md",
        &sample_frontmatter(2, "B", "todo"),
    );
    let issues = store.list().unwrap();
    assert_eq!(issues.len(), 3);
    assert_eq!(issues[0].number, 1);
    assert_eq!(issues[1].number, 2);
    assert_eq!(issues[2].number, 3);
    assert_eq!(issues[0].title, "A");
}

// Issue #10 follow-up — the single-file reader behind `Corpus::apply`.

#[test]
fn is_issue_rel_path_matches_what_scan_walks() {
    // `scan` indexes these.
    for path in [
        "a.md",
        "alice/b.md",
        ".hidden.md",
        "alice/.hidden.md",
        "deep/a/b.md",
    ] {
        assert!(
            is_issue_rel_path(Path::new(path)),
            "{path} is an issue file `scan` reads"
        );
    }
    // ...and skips these.
    for path in [
        "notes.txt",
        "alice/notes.txt",
        "alice",
        ".tix-tmp-x/a.md",
        "foo-assets/a.md",
        "alice/foo-assets/a.md",
    ] {
        assert!(
            !is_issue_rel_path(Path::new(path)),
            "{path} is not a path `scan` indexes"
        );
    }
}

#[test]
fn scan_above_the_parallel_threshold_is_sorted_and_complete() {
    // The parallel branch runs only above `PARALLEL_SCAN_THRESHOLD`, so a
    // small fixture never reaches it. This pins that the fan-out keeps every
    // file, in filename order, with the same numbering a serial walk gives.
    let (tmp, store) = make_store();
    let _ = tmp;
    let n = Store::PARALLEL_SCAN_THRESHOLD + 44;
    for i in (1..=n).rev() {
        write_issue(
            &store,
            &format!("2026-01-01-{i:04}.md"),
            &sample_frontmatter(i as u32, &format!("T{i}"), "todo"),
        );
    }
    let issues = store.list().unwrap();
    assert_eq!(
        issues.len(),
        n,
        "every file is read, none dropped or doubled"
    );
    let names: Vec<&str> = issues.iter().map(|i| i.filename.as_str()).collect();
    let mut sorted = names.clone();
    sorted.sort_unstable();
    assert_eq!(names, sorted, "sorted by filename as `scan` promises");
    assert_eq!(issues[0].number, 1, "content came from the first file");
    assert_eq!(issues[n - 1].number, n as u32, "and from the last");
}

#[test]
fn read_issue_at_sets_filename_and_archived_like_scan() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    write_issue(
        &store,
        "alice/.2026-01-02-b.md",
        &sample_frontmatter(2, "B", "todo"),
    );

    let active = store
        .read_issue_at(Path::new("alice/2026-01-01-a.md"))
        .unwrap();
    assert_eq!(active.number, 1);
    assert_eq!(active.filename, "alice/2026-01-01-a.md");
    assert!(!active.archived);

    let archived = store
        .read_issue_at(Path::new("alice/.2026-01-02-b.md"))
        .unwrap();
    assert_eq!(archived.filename, "alice/.2026-01-02-b.md");
    assert!(
        archived.archived,
        "the leading dot marks it archived, as `scan` does"
    );

    // A flat file keeps its bare basename, and a missing one is `NotFound`.
    write_issue(&store, "flat.md", &sample_frontmatter(3, "F", "todo"));
    assert_eq!(
        store.read_issue_at(Path::new("flat.md")).unwrap().filename,
        "flat.md"
    );
    assert!(matches!(
        store.read_issue_at(Path::new("alice/gone.md")),
        Err(TixError::NotFound(_))
    ));
}

#[test]
fn list_ignores_non_md_files() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    write_issue(&store, "readme.txt", "not an issue");
    write_issue(&store, "2026-01-01-sub", "no extension");
    let issues = store.list().unwrap();
    assert_eq!(issues.len(), 1);
}

#[test]
fn list_errors_on_malformed_frontmatter() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(&store, "2026-01-01-bad.md", "no frontmatter here\n");
    let err = store.list().unwrap_err();
    assert!(matches!(err, TixError::Parse(_)), "got {err:?}");
}

#[test]
fn get_by_number() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-x.md",
        &sample_frontmatter(5, "X", "todo"),
    );
    let issue = store.get(IssueSelector::Number(5)).unwrap();
    assert_eq!(issue.title, "X");
}

#[test]
fn get_by_filename() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-y.md",
        &sample_frontmatter(2, "Y", "done"),
    );
    let issue = store
        .get(IssueSelector::Filename("2026-01-01-y.md".into()))
        .unwrap();
    assert_eq!(issue.status.display(), "done");
}

#[test]
fn get_by_slug() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-z.md",
        &sample_frontmatter(3, "Z", "todo"),
    );
    let issue = store.get(IssueSelector::Slug("z".into())).unwrap();
    assert_eq!(issue.number, 3);
}

#[test]
fn get_not_found() {
    let (tmp, store) = make_store();
    let _ = tmp;
    assert!(store.get(IssueSelector::Number(99)).is_err());
}

#[test]
fn create_assigns_number_from_live_issues_and_leaves_config_untouched() {
    let (tmp, store) = make_store();
    let _ = tmp;
    assert_eq!(store.config.state.next_number, 0);
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        title: "First".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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    let path = store.create(&mut issue, "Hello world", None).unwrap();
    assert!(path.exists());
    assert_eq!(
        issue.number, 1,
        "an empty store starts at 1, not 0 — #0 is indistinguishable from a \
         sentinel or a failed read (tix #1376)"
    );
    // Issue #52: create never rewrites tix.toml with a counter.
    let config_path = tmp.path().join("tix.toml");
    let on_disk = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        !on_disk.contains("next_number"),
        "create must not persist an issue-number counter:\n{on_disk}"
    );
    let reloaded = Config::load_with_warning(&config_path, |_| {}).unwrap();
    assert_eq!(reloaded.state.next_number, 0, "state is never written");
}

#[test]
fn create_resolves_max_live_number_plus_one() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(0, "A", "todo"),
    );
    write_issue(
        &store,
        "2026-01-01-b.md",
        &sample_frontmatter(1, "B", "todo"),
    );
    write_issue(
        &store,
        "2026-01-01-c.md",
        &sample_frontmatter(2, "C", "todo"),
    );
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        title: "D".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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    store.create(&mut issue, "", None).unwrap();
    assert_eq!(issue.number, 3);
}

#[test]
fn create_reuses_number_of_deleted_highest_issue() {
    // Issue #52 tradeoff: without a persisted counter the next number is
    // re-derived from the live set, so deleting the highest-numbered
    // issue lets its number be reused by the next create.
    let (_tmp, store) = make_store();
    let mut issue_a = Issue {
        projects: None,
        id: None,
        number: 0,
        title: "A".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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    store.create(&mut issue_a, "", None).unwrap();
    let filename = issue_a.filename.clone();
    assert_eq!(issue_a.number, 1, "the first issue in a fresh store is #1");
    store.delete(&filename).unwrap();
    let mut issue_b = Issue {
        projects: None,
        id: None,
        number: 0,
        title: "B".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-02".into(),
        type_: None,
        updated: "2026-01-02".into(),
        filename: String::new(),
        body: String::new(),
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    store.create(&mut issue_b, "", None).unwrap();
    assert_eq!(
        issue_b.number, 1,
        "an emptied store resumes at the same floor as a fresh one: 1"
    );
}

#[test]
fn create_with_custom_filename_stem() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    let path = store
        .create(&mut issue, "body", Some("custom-stem"))
        .unwrap();
    assert!(path.to_string_lossy().contains("custom-stem.md"));
}

#[test]
fn create_ensures_issues_dir_exists() {
    let tmp = tempfile::TempDir::new().unwrap();
    let dir = tmp.path().join("nested").join("issues");
    let config_path = tmp.path().join("tix.toml");
    let config = Config {
        issues_dir: dir.clone(),
        ..Config::default()
    };
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let store = Store {
        issues_dir: dir,
        config,
    };
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    store.create(&mut issue, "", None).unwrap();
    assert_eq!(issue.number, 1, "the first issue in a fresh store is #1");
}

#[test]
fn update_replaces_content_atomically() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-u.md",
        &sample_frontmatter(1, "U", "todo"),
    );
    let mut issue = store
        .get(IssueSelector::Filename("2026-01-01-u.md".into()))
        .unwrap();
    issue.title = "Updated".into();
    issue.bump_updated();
    store.update("2026-01-01-u.md", &issue).unwrap();
    let reloaded = store
        .get(IssueSelector::Filename("2026-01-01-u.md".into()))
        .unwrap();
    assert_eq!(reloaded.title, "Updated");
}

#[test]
fn update_not_found() {
    let (tmp, store) = make_store();
    let _ = tmp;
    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![],
        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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    assert!(store.update("nope.md", &issue).is_err());
}

#[test]
fn delete_removes_file() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-d.md",
        &sample_frontmatter(1, "D", "todo"),
    );
    assert!(store.issues_dir.join("2026-01-01-d.md").exists());
    store.delete("2026-01-01-d.md").unwrap();
    assert!(!store.issues_dir.join("2026-01-01-d.md").exists());
}

#[test]
fn delete_not_found() {
    let (tmp, store) = make_store();
    let _ = tmp;
    assert!(store.delete("nope.md").is_err());
}

#[test]
fn stray_tmp_file_not_treated_as_issue() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    fs::write(store.issues_dir.join(".tix-tmp-9999-0"), "orphaned data").unwrap();
    let issues = store.list().unwrap();
    assert_eq!(issues.len(), 1);
}

// ------------------------------------------------------------------
// WP03 T015 — the storage seam's contract, as executable evidence
// ------------------------------------------------------------------
//
// Every case asserts the **file bytes**, not just the returned `Result`. A
// refusal that returns an error after having already re-serialised the issue
// would pass an `is_err()` assertion and still have destroyed the audit trail,
// so "did it refuse?" and "did it touch anything?" are separate questions here
// and both are asked.

/// A store whose board **declares a `category_map`**, so category policy —
/// the terminal lock and adjacency — applies.
///
/// The mapping is `todo=unstarted, doing=active, done=completed`, which is
/// forward-moving in the declared vocabulary order. `triage` is added as a
/// `backlog` column so there is a genuine backwards move to be refused.
fn seam_store() -> (tempfile::TempDir, Store) {
    let tmp = tempfile::TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let mut config = Config {
        issues_dir: dir.clone(),
        kanban: crate::config::KanbanSection {
            configurations: indexmap::IndexMap::from([(
                "default".to_string(),
                crate::config::BoardConfiguration {
                    columns: vec![
                        "triage".into(),
                        "todo".into(),
                        "doing".into(),
                        "done".into(),
                    ],
                    done_column: Some("done".to_string()),
                    category_map: indexmap::IndexMap::from([
                        ("triage".to_string(), "backlog".to_string()),
                        ("todo".to_string(), "unstarted".to_string()),
                        ("doing".to_string(), "active".to_string()),
                        ("done".to_string(), "completed".to_string()),
                    ]),
                    ..Default::default()
                },
            )]),
        },
        ..Config::default()
    };
    config.layout.move_on_change = false;
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    (
        tmp,
        Store {
            issues_dir: dir,
            config,
        },
    )
}

/// A seam store holding one issue at `status`, and that file's bytes.
///
/// The fixture carries every key the model always writes, `files` included.
/// That is not tidiness: `t015_no_new_frontmatter_key_was_introduced` compares
/// the key set before and after, and a fixture that omits `files` makes the
/// comparison report the model's own always-written key as a change — so the
/// test would have been measuring the fixture instead of the seam.
fn seam_issue(status: &str) -> (tempfile::TempDir, Store, String) {
    let (tmp, store) = seam_store();
    write_issue(
        &store,
        "2026-01-01-seam.md",
        &format!(
            "---\nnumber: 1\ntitle: \"Seam\"\nstatus: {status}\nlabels: []\n\
             priority: \"medium\"\nfiles: []\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody."
        ),
    );
    let before = read_issue_file(&store, "2026-01-01-seam.md");
    (tmp, store, before)
}

/// Assert a refusal left the file byte-identical.
fn assert_untouched(store: &Store, before: &str, what: &str) {
    let after = read_issue_file(store, "2026-01-01-seam.md");
    assert_eq!(after, before, "{what}: the file must be byte-identical");
}

#[test]
fn t015_accepted_transition_writes_status_bumps_updated_and_appends_one_decision() {
    let (_tmp, store, _before) = seam_issue("todo");
    let outcome = store
        .set_status("2026-01-01-seam.md", StatusChange::to("doing"))
        .unwrap();
    assert!(outcome.written, "an accepted, changing move writes");
    let decision = outcome
        .decision
        .clone()
        .expect("an accepted transition appends exactly one decision");
    assert_eq!(decision.from, "todo");
    assert_eq!(decision.to, "doing");
    assert_eq!(decision.from_category, "unstarted");
    assert_eq!(decision.to_category, "active");
    assert!(
        decision.override_reason.is_none(),
        "no override was supplied"
    );
    assert_eq!(
        outcome.issue.status.display(),
        "doing",
        "Issue.status holds the COLUMN name, never a category (C-001)"
    );
    assert_eq!(outcome.issue.updated, today(), "`updated` is bumped");

    // Re-read from disk: the in-memory record is not evidence of what landed.
    let reloaded = store
        .get(IssueSelector::Filename("2026-01-01-seam.md".into()))
        .unwrap();
    assert_eq!(reloaded.status.display(), "doing");
    let events = reloaded.history.events();
    assert_eq!(
        events.len(),
        1,
        "exactly one History entry, and it is the decision: {events:?}"
    );
    assert_eq!(events[0].kind, HistoryEventKind::TransitionAccepted);
    assert_eq!(
        crate::model::TransitionDecision::from_event(events[0])
            .unwrap()
            .to,
        "doing",
        "and the decision round-trips out of the file with its fields intact"
    );
}

#[test]
fn t015_unknown_column_is_refused_by_name_and_writes_nothing() {
    let (_tmp, store, before) = seam_issue("todo");
    let err = store
        .set_status("2026-01-01-seam.md", StatusChange::to("nope"))
        .unwrap_err();
    assert!(
        matches!(&err, TixError::Workflow(d) if d.kind.as_str() == "unknown_column"),
        "the shared named diagnostic, contract §6: {err:?}"
    );
    assert!(
        err.to_string()
            .contains("valid columns: triage, todo, doing, done"),
        "in BOARD order, not hash order: {err}"
    );
    assert_untouched(&store, &before, "unknown column");
}

#[test]
fn t015_terminal_exit_is_refused_and_writes_nothing() {
    let (_tmp, store, before) = seam_issue("done");
    let err = store
        .set_status("2026-01-01-seam.md", StatusChange::to("todo"))
        .unwrap_err();
    assert!(
        matches!(&err, TixError::Workflow(d) if d.kind.as_str() == "invalid_transition"),
        "{err:?}"
    );
    assert_untouched(&store, &before, "terminal exit without a reason");
}

#[test]
fn t015_adjacency_restricted_backwards_move_is_refused_and_writes_nothing() {
    // `doing` is `active`; `triage` is `backlog`. Forward in the declared
    // vocabulary order, so no terminal lock applies — this is adjacency alone,
    // and it must name the same `invalid_transition` kind.
    let (_tmp, store, before) = seam_issue("doing");
    let err = store
        .set_status("2026-01-01-seam.md", StatusChange::to("triage"))
        .unwrap_err();
    assert!(
        matches!(&err, TixError::Workflow(d) if d.kind.as_str() == "invalid_transition"),
        "{err:?}"
    );
    assert!(
        err.to_string().contains("category policy"),
        "the message names the rule that refused it: {err}"
    );
    assert_untouched(&store, &before, "adjacency refusal");
}

#[test]
fn t015_terminal_exit_with_a_reason_is_accepted_and_the_reason_is_recorded() {
    let (_tmp, store, before) = seam_issue("done");
    let outcome = store
        .set_status(
            "2026-01-01-seam.md",
            StatusChange::to("todo").with_override(Some("reopening: wrong epic")),
        )
        .unwrap();
    assert!(outcome.written);
    let decision = outcome.decision.expect("one decision");
    assert_eq!(
        decision.override_reason.as_deref(),
        Some("reopening: wrong epic"),
        "an override with no recorded reason is not an audit record"
    );
    assert_ne!(
        read_issue_file(&store, "2026-01-01-seam.md"),
        before,
        "sanity: an accepted move must have changed the file at all"
    );
}

#[test]
fn t015_a_blank_reason_is_not_an_override() {
    // The service trims and drops a blank reason, so a whitespace-only string
    // must not unlock a terminal exit. Asserted here as well as in the service
    // because "the seam passes the caller's string through untouched" would
    // satisfy a service-level test and still be wrong at the boundary.
    let (_tmp, store, before) = seam_issue("done");
    let err = store
        .set_status(
            "2026-01-01-seam.md",
            StatusChange::to("todo").with_override(Some("   ")),
        )
        .unwrap_err();
    assert!(
        matches!(&err, TixError::Workflow(_)),
        "a blank reason is not a reason: {err:?}"
    );
    assert_untouched(&store, &before, "blank override reason");
}

#[test]
fn t015_same_column_is_accepted_and_writes_nothing() {
    let (_tmp, store, before) = seam_issue("doing");
    let outcome = store
        .set_status("2026-01-01-seam.md", StatusChange::to("doing"))
        .unwrap();
    assert!(!outcome.written, "a same-column re-apply is a no-op");
    assert!(
        outcome.decision.is_none(),
        "and appends no decision, contract §3.2"
    );
    assert_untouched(&store, &before, "same column");
    // `updated` is not bumped either: a no-op that touched the date would make
    // `tix edit --status <current column>` look like an edit.
    let reloaded = store
        .get(IssueSelector::Filename("2026-01-01-seam.md".into()))
        .unwrap();
    assert_eq!(
        reloaded.updated, "2026-01-01",
        "the fixture's original date"
    );
}

#[test]
fn t015_no_new_frontmatter_key_was_introduced() {
    // C-001. The mission must be byte-compatible on the file surface, so this
    // compares the key set of a file the seam wrote against the key set of the
    // fixture it read. A category key on the issue would break here.
    let (_tmp, store, before) = seam_issue("todo");
    store
        .set_status("2026-01-01-seam.md", StatusChange::to("doing"))
        .unwrap();
    let after = read_issue_file(&store, "2026-01-01-seam.md");
    let keys = |text: &str| -> Vec<String> {
        text.split("---\n")
            .nth(1)
            .unwrap()
            .lines()
            .filter_map(|l| l.split_once(':').map(|(k, _)| k.trim().to_string()))
            .filter(|k| !k.is_empty())
            .collect()
    };
    assert_eq!(
        keys(&after),
        keys(&before),
        "the seam must not add or remove a top-level frontmatter key"
    );
}

#[test]
fn t015_a_hand_edited_inconsistent_file_is_read_and_not_repaired() {
    // C-005. A file whose `status` was hand-edited to a column the policy would
    // never have allowed is *readable* and this path must leave it alone. The
    // diagnosis is WP06's job; storage correcting it would be the escalation
    // the decision `01M3C3XBMTR5WFV7059NXM04AJ` names.
    let (_tmp, store, before) = seam_issue("doing");
    // Simulate the hand edit: `doing` (active) becomes `triage` (backlog),
    // a move adjacency refuses.
    let edited = before.replace("status: doing", "status: triage");
    write_issue(&store, "2026-01-01-seam.md", &edited);
    let after_edit = read_issue_file(&store, "2026-01-01-seam.md");

    let issue = store
        .get(IssueSelector::Filename("2026-01-01-seam.md".into()))
        .unwrap();
    assert_eq!(
        issue.status.display(),
        "triage",
        "a hand-edited status is read, not rejected at load"
    );
    assert_eq!(
        read_issue_file(&store, "2026-01-01-seam.md"),
        after_edit,
        "reading must not repair it"
    );
    // And a legal move away from the hand-edited column proceeds, without the
    // seam trying to reconcile the history of how the file got there.
    store
        .set_status("2026-01-01-seam.md", StatusChange::to("doing"))
        .unwrap();
    let moved = store
        .get(IssueSelector::Filename("2026-01-01-seam.md".into()))
        .unwrap();
    assert_eq!(moved.status.display(), "doing");
    assert_eq!(
        moved.history.events().len(),
        1,
        "only the new decision; nothing was written to explain the old one"
    );
}

#[test]
fn t015_every_rejection_kind_is_one_of_the_contract_vocabulary() {
    // The contract fixes seven names (contract §6). A refusal that invents an
    // eighth is a surface that reports a condition under a name no other
    // surface knows, which is the exact failure the vocabulary exists to stop.
    let allowed = [
        "missing_completion_category",
        "unknown_category",
        "mapping_for_unknown_column",
        "unmapped_column_default",
        "invalid_transition",
        "unknown_column",
        "direct_edit_policy_violation",
    ];
    let cases: Vec<(&str, &str)> = vec![
        ("todo", "nope"),    // unknown_column
        ("done", "todo"),    // invalid_transition (terminal lock)
        ("doing", "triage"), // invalid_transition (adjacency)
    ];
    for (from, to) in cases {
        let (_tmp, store, _before) = seam_issue(from);
        let err = store
            .set_status("2026-01-01-seam.md", StatusChange::to(to))
            .unwrap_err();
        let TixError::Workflow(d) = &err else {
            panic!("{from} -> {to} must refuse through the workflow variant: {err:?}");
        };
        assert!(
            allowed.contains(&d.kind.as_str()),
            "`{}` is not in the contract's vocabulary",
            d.kind.as_str()
        );
    }
}

#[test]
fn t015_a_legacy_board_gains_no_policy_but_keeps_completion() {
    // The opt-in this WP decided: a board with no `category_map` gets the
    // completion definition and the commit-clearing rule, and no transition
    // restriction. Both halves are asserted, because a change that dropped the
    // completion rule along with the policy would otherwise look correct.
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-legacy.md",
        &sample_frontmatter(1, "Legacy", "done"),
    );
    let moved = store
        .set_status("2026-01-01-legacy.md", StatusChange::to("todo"))
        .unwrap();
    assert!(moved.written, "a legacy board imposes no policy");
    assert_eq!(moved.issue.status.display(), "todo");

    // And completion still resolves through the reconciliation, not the string
    // "done": this issue is no longer complete, and an untouched `done` one is.
    let resolution =
        crate::workflow::resolution(&store.config, store.config.default_config(), "default");
    assert!(
        !resolution.explicit_policy,
        "precondition: this board declared no category_map"
    );
    assert!(
        resolution.has_completion(),
        "but it still has a done column"
    );
    assert!(
        !crate::workflow::is_completed(&moved.issue, &resolution),
        "and `todo` is not complete"
    );
}

#[test]
fn t015_a_mapped_board_keeps_the_commit_coupling() {
    // The commit rule moved from `mv.rs` into the seam, so it is pinned here
    // rather than only in the command layer: reaching completion records the
    // commit, leaving it clears the one that was recorded.
    let (_tmp, store, _before) = seam_issue("doing");
    store
        .set_status(
            "2026-01-01-seam.md",
            StatusChange::to("done").with_commit(Some("abc123")),
        )
        .unwrap();
    let at_done = store
        .get(IssueSelector::Filename("2026-01-01-seam.md".into()))
        .unwrap();
    assert_eq!(at_done.commit.as_deref(), Some("abc123"));

    store
        .set_status(
            "2026-01-01-seam.md",
            StatusChange::to("todo").with_override(Some("not actually finished")),
        )
        .unwrap();
    let off_done = store
        .get(IssueSelector::Filename("2026-01-01-seam.md".into()))
        .unwrap();
    assert_eq!(
        off_done.commit, None,
        "leaving completion clears the recorded commit"
    );
}

#[test]
fn t015_a_decision_round_trips_through_a_file_unchanged() {
    // T012's round trip, end to end rather than in memory: the rendered line
    // must parse back to the same fields, or WP06 cannot read a file's last
    // accepted column out of it.
    let (_tmp, store, _before) = seam_issue("todo");
    store
        .set_status("2026-01-01-seam.md", StatusChange::to("doing"))
        .unwrap();
    let first = store
        .get(IssueSelector::Filename("2026-01-01-seam.md".into()))
        .unwrap();
    let text = read_issue_file(&store, "2026-01-01-seam.md");
    // Parse the file back from its own bytes — not from the in-memory issue.
    let parsed = Issue::parse(&text).unwrap();
    let events = parsed.history.events();
    let decision = crate::model::TransitionDecision::from_event(events[0]).unwrap();
    assert_eq!(decision.to, "doing");
    assert_eq!(decision.from_category, "unstarted");
    assert_eq!(decision.to_category, "active");
    // And re-serialising the parsed file reproduces it byte for byte, so the
    // grammar is not lossy in a way only a rewrite would reveal.
    assert_eq!(
        parsed.to_file_contents(),
        text,
        "a parsed decision must re-render to the same bytes"
    );
    assert_eq!(parsed.history.events().len(), first.history.events().len());
}

#[test]
fn t015_two_transitions_append_two_decisions_in_order() {
    let (_tmp, store, _before) = seam_issue("triage");
    for to in ["todo", "doing"] {
        store
            .set_status("2026-01-01-seam.md", StatusChange::to(to))
            .unwrap();
    }
    let after = store
        .get(IssueSelector::Filename("2026-01-01-seam.md".into()))
        .unwrap();
    let events = after.history.events();
    assert_eq!(events.len(), 2, "one per accepted transition");
    let tos: Vec<String> = events
        .iter()
        .map(|e| crate::model::TransitionDecision::from_event(e).unwrap().to)
        .collect();
    assert_eq!(tos, vec!["todo", "doing"], "append order, not sorted");
}

#[test]
fn set_status_changes_status_and_bumps_updated() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-s.md",
        &sample_frontmatter(1, "S", "todo"),
    );
    let outcome = store
        .set_status("2026-01-01-s.md", StatusChange::to("in progress"))
        .unwrap();
    let issue = &outcome.issue;
    assert_eq!(issue.status.display(), "in progress");
    assert_eq!(issue.updated, today());
    assert_eq!(issue.title, "S");
    assert_eq!(issue.body, "Body text.");
}

#[test]
fn set_status_preserves_file_path() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-f.md",
        &sample_frontmatter(1, "F", "todo"),
    );
    let _ = store
        .set_status("2026-01-01-f.md", StatusChange::to("done"))
        .unwrap();
    assert!(store.issues_dir.join("2026-01-01-f.md").exists());
}

// ------------------------------------------------------------------
// WP02 T009 — typed relationship writes delegate to the service
// ------------------------------------------------------------------

/// Read an issue file's raw bytes, for the byte-identical assertions.
fn read_issue_file(store: &Store, filename: &str) -> String {
    std::fs::read_to_string(store.issues_dir.join(filename)).unwrap()
}

/// A frontmatter fixture with no relationship data, i.e. what every
/// pre-existing issue file in the repository looks like.
fn bare_frontmatter(number: u32, title: &str) -> String {
    format!(
        "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody text."
    )
}

/// A frontmatter fixture carrying the **retired** `links:` key.
fn legacy_links_frontmatter(number: u32, title: &str, links: &str) -> String {
    format!(
        "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\nlinks: {links}\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody text."
    )
}

/// Two seeded issues, plus the store, for the relationship tests.
fn related_pair() -> (TempDir, Store, Issue, Issue) {
    let (tmp, store) = make_store();
    write_issue(&store, "2026-01-01-a.md", &bare_frontmatter(1, "A"));
    write_issue(&store, "2026-01-01-b.md", &bare_frontmatter(2, "B"));
    let a = store.get(IssueSelector::Number(1)).unwrap();
    let b = store.get(IssueSelector::Number(2)).unwrap();
    (tmp, store, a, b)
}

#[test]
fn t009_link_records_a_single_directed_edge() {
    let (_tmp, store, a, b) = related_pair();
    let outcome = store
        .link(
            &a.number.to_string(),
            &b.number.to_string(),
            RelationKind::Blocks,
        )
        .unwrap();
    assert!(outcome.changed);

    // One edge, stored once, on the blocking side. The old symmetric
    // back-reference on the other issue is gone (C-001).
    let a_after = store.get(IssueSelector::Number(1)).unwrap();
    let b_after = store.get(IssueSelector::Number(2)).unwrap();
    assert_eq!(a_after.relationships.len(), 1);
    assert!(
        b_after.relationships.is_empty(),
        "no back-reference is written for a directed edge"
    );
    assert_eq!(a_after.relationships[0].kind, RelationKind::Blocks);
    assert_eq!(
        (
            a_after.relationships[0].from.as_number(),
            a_after.relationships[0].to.as_number()
        ),
        (Some(1), Some(2))
    );
}

#[test]
fn t009_link_appends_exactly_one_history_event() {
    let (_tmp, store, a, b) = related_pair();
    store
        .link(
            &a.number.to_string(),
            &b.number.to_string(),
            RelationKind::Blocks,
        )
        .unwrap();
    let a_after = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(a_after.history.len(), 1);
    assert_eq!(
        a_after.history.events()[0].kind,
        HistoryEventKind::RelationshipAdded
    );
    // Every event records an actor, or the audit trail is not an audit trail.
    assert_ne!(a_after.history.events()[0].actor, "");
}

#[test]
fn t009_idempotent_reapply_writes_nothing_and_appends_no_second_event() {
    let (_tmp, store, a, b) = related_pair();
    let args = (a.number.to_string(), b.number.to_string());
    store.link(&args.0, &args.1, RelationKind::Blocks).unwrap();
    let first = store.get(IssueSelector::Number(1)).unwrap();
    let bytes_after_first = read_issue_file(&store, &first.filename);

    let second = store.link(&args.0, &args.1, RelationKind::Blocks).unwrap();
    assert!(!second.changed, "re-applying an existing edge is a no-op");
    assert!(second.written.is_none(), "no file is written for a no-op");

    let after = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(after.relationships.len(), 1, "no duplicate edge");
    assert_eq!(after.history.len(), 1, "no second History event");
    assert_eq!(
        read_issue_file(&store, &after.filename),
        bytes_after_first,
        "the file is byte-identical after the no-op"
    );
}

#[test]
fn t009_inverse_spelling_resolves_to_the_same_stored_edge() {
    let (_tmp, store, a, b) = related_pair();
    let args = (a.number.to_string(), b.number.to_string());
    store.link(&args.0, &args.1, RelationKind::Blocks).unwrap();
    // "2 is blocked by 1" is the same edge as "1 blocks 2".
    let again = store
        .link(&args.1, &args.0, RelationKind::BlockedBy)
        .unwrap();
    assert!(!again.changed, "the inverse spelling must not add an edge");
    let after = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(after.relationships.len(), 1);
    assert_eq!(
        after.relationships[0].kind,
        RelationKind::Blocks,
        "the stored kind is always the canonical one"
    );
}

#[test]
fn t009_self_link_is_refused_and_writes_nothing() {
    let (_tmp, store, a, _b) = related_pair();
    let before = read_issue_file(&store, &a.filename);
    let err = store
        .link(
            &a.number.to_string(),
            &a.number.to_string(),
            RelationKind::Blocks,
        )
        .unwrap_err();
    assert!(matches!(err, TixError::Refused(_)));
    assert!(
        err.to_string().contains("self_link"),
        "the diagnostic names the rule: {err}"
    );
    assert_eq!(
        read_issue_file(&store, &a.filename),
        before,
        "SC-005: a rejected mutation leaves the file byte-identical"
    );
}

#[test]
fn t009_cycle_closing_edge_is_refused_and_writes_nothing() {
    let (tmp, store) = make_store();
    write_issue(&store, "2026-01-01-a.md", &bare_frontmatter(1, "A"));
    write_issue(&store, "2026-01-01-b.md", &bare_frontmatter(2, "B"));
    write_issue(&store, "2026-01-01-c.md", &bare_frontmatter(3, "C"));
    let _ = tmp;
    store.link("1", "2", RelationKind::Blocks).unwrap();
    store.link("2", "3", RelationKind::Blocks).unwrap();
    let c_before = read_issue_file(&store, "2026-01-01-c.md");

    let err = store.link("3", "1", RelationKind::Blocks).unwrap_err();
    assert!(err.to_string().contains("cycle"), "{err}");
    assert_eq!(
        read_issue_file(&store, "2026-01-01-c.md"),
        c_before,
        "SC-005: both files of a rejected two-issue mutation are unchanged"
    );
}

#[test]
fn t009_unlink_removes_the_edge_and_is_idempotent() {
    let (_tmp, store, a, b) = related_pair();
    let args = (a.number.to_string(), b.number.to_string());
    store.link(&args.0, &args.1, RelationKind::Blocks).unwrap();

    let removed = store
        .unlink(&args.0, &args.1, RelationKind::Blocks)
        .unwrap();
    assert!(removed.changed);
    let after = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(
        after.relationships,
        [] as [crate::relationships::Relationship; 0]
    );
    assert_eq!(after.history.len(), 2, "added then removed");

    // Removing again is a no-op, not a second History entry.
    let again = store
        .unlink(&args.0, &args.1, RelationKind::Blocks)
        .unwrap();
    assert!(!again.changed);
    let after2 = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(after2.history.len(), 2, "no third History event");
}

#[test]
fn t009_unlink_of_a_never_linked_pair_is_a_noop() {
    let (_tmp, store, a, b) = related_pair();
    let outcome = store
        .unlink(
            &a.number.to_string(),
            &b.number.to_string(),
            RelationKind::Blocks,
        )
        .unwrap();
    assert!(!outcome.changed);
    assert!(outcome.written.is_none());
    let after = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(
        after.relationships,
        [] as [crate::relationships::Relationship; 0]
    );
    assert!(after.history.is_empty(), "a no-op appends nothing");
}

#[test]
fn t009_set_relationships_replaces_the_set_and_keeps_surviving_ids() {
    let (_tmp, store, _a, _b) = related_pair();
    store.link("1", "2", RelationKind::Blocks).unwrap();
    let before = store.get(IssueSelector::Number(1)).unwrap();
    let survivor_id = before.relationships[0].id.clone();

    // Replace the set with a different target; the old edge goes, recorded.
    let updated = store
        .set_relationships(&before.filename, &[(2, RelationKind::Blocks)])
        .unwrap();
    assert_eq!(updated.relationships.len(), 1);
    assert_eq!(
        updated.relationships[0].id, survivor_id,
        "a surviving relationship keeps its stable id"
    );
}

#[test]
fn t009_set_relationships_rejects_unknown_target_and_self() {
    let (_tmp, store, a, _b) = related_pair();
    assert!(
        store
            .set_relationships(&a.filename, &[(404, RelationKind::Blocks)])
            .is_err(),
        "an unknown target is refused"
    );
    assert!(
        store
            .set_relationships(&a.filename, &[(1, RelationKind::Blocks)])
            .is_err(),
        "a self-link is refused"
    );
}

// ------------------------------------------------------------------
// WP02 review round 1 — F1, F4, F5, F13: canonical storage lookups
// ------------------------------------------------------------------

/// Seed an issue, optionally with raw extra frontmatter.
fn seeded(store: &Store, number: u32, title: &str, extra: &str) {
    let slug = title.to_lowercase();
    write_issue(
        store,
        &format!("2026-01-01-{slug}.md"),
        &format!(
            "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\n{extra}files: []\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody.\n"
        ),
    );
}

#[test]
fn f1_set_relationships_refuses_a_reciprocal_pair_the_service_rejects() {
    // F1. `set_relationships` used to re-implement existence and the
    // self-link rule locally and skip the rest, so with `1 blocks 2` on disk
    // it stored `2 blocks 1` — a reciprocal pair that `link` rejects one
    // line earlier and that contract §3 rules 3 and 4 require be refused.
    // Latent only because `--links` hard-codes `related`; user-reachable the
    // moment WP03 wires `--type`.
    let (_tmp, store) = make_store();
    seeded(&store, 1, "A", "");
    seeded(&store, 2, "B", "");
    store.link("1", "2", RelationKind::Blocks).unwrap();

    let err = store
        .set_relationships("2026-01-01-b.md", &[(1, RelationKind::Blocks)])
        .unwrap_err();
    assert!(
        err.to_string().contains("cycle"),
        "the service's verdict is what refuses it: {err}"
    );
    let two = store.get(IssueSelector::Number(2)).unwrap();
    assert!(
        two.relationships.is_empty(),
        "SC-005: a refused mutation writes nothing"
    );
}

#[test]
fn f4_a_hand_ordered_related_row_is_removable() {
    // F4. A hand-authored `related` row in the non-canonical endpoint order.
    // Removals used to be keyed by where the row *should* live while rows
    // were found where they *were* stored, so this row matched no file and
    // no code path could delete it.
    let (_tmp, store) = make_store();
    seeded(&store, 2, "B", "");
    seeded(
        &store,
        5,
        "E",
        "relationships:\n- id: rel_handauthored\n  from: 5\n  to: 2\n  kind: related\n  display: \"related #2 B\"\n",
    );
    let out = store.unlink("5", "2", RelationKind::Related).unwrap();
    assert!(out.changed, "the row is found and removed");
    assert_eq!(
        store.get(IssueSelector::Number(5)).unwrap().relationships,
        [] as [crate::relationships::Relationship; 0]
    );
}

#[test]
fn f5_a_persisted_blocked_by_row_is_removable() {
    // F5. `blocked_by` is the input-only spelling and must never be
    // persisted, but the format is human-editable so a hand edit can put it
    // there. `unlink` compared authored fields while `link` canonicalized,
    // so the two disagreed and the row was un-removable — leaving a
    // permanently invalid row plus a `tix lint` cycle finding with no way to
    // clear it.
    let (_tmp, store) = make_store();
    seeded(&store, 1, "A", "");
    seeded(
        &store,
        2,
        "B",
        "relationships:\n- id: rel_bb\n  from: 2\n  to: 1\n  kind: blocked_by\n  display: \"blocks #1 A\"\n",
    );
    let out = store.unlink("2", "1", RelationKind::BlockedBy).unwrap();
    assert!(out.changed, "the row is found and removed");
    assert_eq!(
        store.get(IssueSelector::Number(2)).unwrap().relationships,
        [] as [crate::relationships::Relationship; 0]
    );
}

#[test]
fn f13_a_dangling_edge_is_removable() {
    // F13. A dangling edge is a diagnosed, expected condition, so the one
    // operation that can clean it up must still work. `unlink` resolved
    // both endpoints first, so deleting the target made the edge
    // permanently unfixable through the tool.
    let (_tmp, store) = make_store();
    seeded(&store, 1, "A", "");
    seeded(&store, 2, "B", "");
    store.link("1", "2", RelationKind::Blocks).unwrap();
    std::fs::remove_file(store.issues_dir.join("2026-01-01-b.md")).unwrap();

    let out = store.unlink("1", "2", RelationKind::Blocks).unwrap();
    assert!(out.changed, "a dangling edge is still removable");
    let one = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(
        one.relationships,
        [] as [crate::relationships::Relationship; 0]
    );
    assert_eq!(one.history.len(), 2, "and the removal is recorded");
}

#[test]
fn m10_one_unlink_of_a_duplicated_edge_appends_one_event() {
    // M10. The same canonical `related` edge hand-authored into **both**
    // endpoints — the redundancy the data model says is kept so no stored id
    // silently stops resolving. One `unlink` is one accepted mutation, so it
    // appends one History event, not one per file written. The previous
    // implementation computed the summary per file, and the comment directly
    // above it claimed the opposite.
    let (_tmp, store) = make_store();
    // A redundant pair is one row in **each** endpoint's file — the two
    // spellings of a single association. My first version of this fixture
    // put both rows in one file, which tested a different thing and then
    // asserted an event count for a file that was never written.
    seeded(
        &store,
        1,
        "A",
        "relationships:\n- id: rel_dup_12\n  from: 1\n  to: 2\n  kind: related\n  display: \"related #2 B\"\n",
    );
    seeded(
        &store,
        2,
        "B",
        "relationships:\n- id: rel_dup_21\n  from: 2\n  to: 1\n  kind: related\n  display: \"related #1 A\"\n",
    );

    let outcome = store.unlink("1", "2", RelationKind::Related).unwrap();
    assert!(outcome.changed, "both redundant rows are removed");
    let mut summaries = Vec::new();
    for number in [1u32, 2] {
        let issue = store.get(IssueSelector::Number(number)).unwrap();
        assert!(
            issue.relationships.is_empty(),
            "issue #{number} keeps no edge"
        );
        assert_eq!(
            issue.history.len(),
            1,
            "issue #{number} records exactly one event, got {:?}",
            issue.history.events()
        );
        let event = &issue.history.events()[0];
        assert!(
            event.detail.contains("removed 2 relationships"),
            "and the event says both spellings went: {}",
            event.detail
        );
        summaries.push(event.detail.clone());
    }
    // The point of the fix: one mutation, one wording. The previous version
    // computed the summary per file, so each file described only its own row
    // and the two events disagreed about what had happened.
    assert_eq!(
        summaries[0], summaries[1],
        "both files record the same single event, not two differing ones"
    );
}

#[test]
fn m11_unlink_reports_the_row_it_removed_not_an_empty_placeholder() {
    // M11. The post-removal re-scan could never match — every matching row is
    // gone by then — so a successful unlink always reported a relationship
    // with an empty id, which is not addressable by
    // `edit_relation`/`remove_relation`. `link`'s no-op path returned a real
    // row; this brings the two into line.
    let (_tmp, store, a, b) = related_pair();
    let args = (a.number.to_string(), b.number.to_string());
    store.link(&args.0, &args.1, RelationKind::Blocks).unwrap();
    let before = store.get(IssueSelector::Number(1)).unwrap();
    let real_id = before.relationships[0].id.clone();

    let outcome = store
        .unlink(&args.0, &args.1, RelationKind::Blocks)
        .unwrap();
    assert!(outcome.changed);
    assert_eq!(
        outcome.relationship.id, real_id,
        "the reported row is the one that was actually removed"
    );
    assert!(!outcome.relationship.id.is_empty(), "so it is addressable");
    assert_eq!(
        outcome.relationship.display,
        before.relationships[0].display
    );
}

#[test]
fn m15_the_history_detail_names_the_relationship_id() {
    // M15. `display` already begins with the kind, so naming the kind again
    // produced `created blocks: blocks #2 B`. The id is the stable handle and
    // is what data-model §8's example shows.
    let (_tmp, store, a, b) = related_pair();
    let args = (a.number.to_string(), b.number.to_string());
    store.link(&args.0, &args.1, RelationKind::Blocks).unwrap();
    let one = store.get(IssueSelector::Number(1)).unwrap();
    let id = one.relationships[0].id.clone();

    let detail = &one.history.events()[0].detail;
    assert!(
        detail.starts_with(&format!("created {id}:")),
        "the detail names the stable id: {detail}"
    );
    assert!(
        !detail.contains(&format!("created {}:", RelationKind::Blocks)),
        "and does not stutter the kind, which `display` already carries: {detail}"
    );
}

#[test]
fn f17_all_diagnostics_are_reported_not_just_the_first() {
    // F17 / M4. The previous version of this test built exactly **one**
    // diagnostic and asserted only that the kind prefix was not doubled —
    // so it never exercised the multi-diagnostic path the fix exists for.
    // Replacing the join with `errors.iter().take(1)` left it green.
    //
    // `1 blocks 2` plus `2 duplicates 1` makes the same pair carry two
    // distinct rule violations at once.
    // The corrupt state is hand-authored, because the write path refuses to
    // create it — which is the point. A file written before these rules
    // existed, or edited by hand, can hold several violations at once, and
    // `validate_snapshot` is the surface that must report all of them.
    let (_tmp, store) = make_store();
    seeded(
        &store,
        1,
        "A",
        "relationships:\n- id: rel_b12\n  from: 1\n  to: 2\n  kind: blocks\n  display: blocks\n- id: rel_d12\n  from: 1\n  to: 2\n  kind: duplicates\n  display: dup\n",
    );
    seeded(
        &store,
        2,
        "B",
        "relationships:\n- id: rel_b21\n  from: 2\n  to: 1\n  kind: blocks\n  display: blocks\n",
    );

    let issues = store.list().unwrap();
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    let verdict = RelationshipGraph::new(&views, "done").validate_snapshot();
    assert!(
        verdict.errors.len() >= 2,
        "the fixture must really produce several diagnostics, got {:?}",
        verdict.errors
    );

    let rendered = relationship_error(&verdict.errors).to_string();
    for kind in ["conflicting_edge", "cycle"] {
        assert!(
            rendered.contains(kind),
            "every diagnostic must be reported; {kind} missing from: {rendered}"
        );
    }
    assert!(
        !rendered.contains("conflicting_edge: conflicting_edge")
            && !rendered.contains("cycle: cycle:"),
        "no doubled kind prefix: {rendered}"
    );
    // M5, tested at the seam. Whether the *service* emits a duplicate
    // self-link diagnostic depends on which rules fire, and that has not
    // been reproducible from either the library or the binary — so this
    // asserts the property where it is decided: `relationship_error` must
    // never render the same (kind, message) twice, whatever it is handed.
    let dup = vec![
        Diagnostic::new(
            DiagnosticKind::SelfLink,
            "to",
            "#1 cannot block itself: a self-link is not a valid relationship",
        ),
        Diagnostic::new(
            DiagnosticKind::SelfLink,
            "to",
            "#1 cannot block itself: a self-link is not a valid relationship",
        ),
        Diagnostic::new(DiagnosticKind::Cycle, "to", "cycle: 1 -> 1 -> #1"),
    ];
    let rendered = relationship_error(&dup).to_string();
    assert_eq!(
        rendered.matches("cannot block itself").count(),
        1,
        "an identical diagnostic renders once, not twice: {rendered}"
    );
    assert!(
        rendered.contains("cycle"),
        "a distinct diagnostic is still reported: {rendered}"
    );
    assert!(
        !rendered.contains("self_link: self_link") && !rendered.contains("cycle: cycle:"),
        "and no kind is prefixed twice: {rendered}"
    );
}

#[test]
fn t009_clearing_a_set_removes_a_related_edge_owned_by_another_file() {
    // Regression, found in final review. A `related` edge is stored once, in
    // the lower-numbered issue's frontmatter, so #5's own file is empty even
    // though #5 *is* related to #3. Clearing #5's set must still remove the
    // association, or `tix edit 5 --links ""` silently does nothing.
    let (_tmp, store) = make_store();
    write_issue(&store, "2026-01-01-a.md", &bare_frontmatter(3, "A"));
    write_issue(&store, "2026-01-01-b.md", &bare_frontmatter(5, "B"));

    store.link("5", "3", RelationKind::Related).unwrap();
    let three = store.get(IssueSelector::Number(3)).unwrap();
    let five = store.get(IssueSelector::Number(5)).unwrap();
    assert_eq!(
        three.relationships.len(),
        1,
        "the edge is stored in the lower-numbered issue's file"
    );
    assert!(
        five.relationships.is_empty(),
        "and #5's own file holds none"
    );

    store.set_relationships(&five.filename, &[]).unwrap();

    let three_after = store.get(IssueSelector::Number(3)).unwrap();
    let five_after = store.get(IssueSelector::Number(5)).unwrap();
    assert!(
        three_after.relationships.is_empty(),
        "the association is gone from the file that actually stored it"
    );
    assert_eq!(
        five_after.relationships,
        [] as [crate::relationships::Relationship; 0]
    );
}

#[test]
fn t009_clearing_a_set_does_not_remove_an_inbound_directional_edge() {
    // The other half of the ownership rule. If #3 blocks #5, that edge is
    // #3's declaration; #5 clearing its own relationship set must not
    // rewrite #3's dependency graph. Only the non-directional case is
    // shared, because only there does the association belong to both ends.
    let (_tmp, store) = make_store();
    write_issue(&store, "2026-01-01-a.md", &bare_frontmatter(3, "A"));
    write_issue(&store, "2026-01-01-b.md", &bare_frontmatter(5, "B"));

    store.link("3", "5", RelationKind::Blocks).unwrap();
    let five = store.get(IssueSelector::Number(5)).unwrap();

    store.set_relationships(&five.filename, &[]).unwrap();

    let three_after = store.get(IssueSelector::Number(3)).unwrap();
    assert!(
        three_after
            .relationships
            .iter()
            .any(|r| r.to == 5 && r.kind == RelationKind::Blocks),
        "#3's declaration that it blocks #5 survives: a blocked issue \
         cannot unilaterally clear the blocker's graph"
    );
}

/// The path of a committed relationship fixture.
fn relationship_fixture(name: &str) -> String {
    format!(
        "{}/tests/fixtures/relationships/{name}",
        env!("CARGO_MANIFEST_DIR")
    )
}

#[test]
fn t010_typed_fixture_round_trips_byte_stable_including_history() {
    // NFR-003, model-level half: a typed fixture survives read -> write ->
    // read unchanged, `## History` region included.
    let original = std::fs::read_to_string(relationship_fixture("typed-relationships.md")).unwrap();
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(issue.relationships.len(), 2);
    assert_eq!(issue.history.len(), 2);
    let rendered = issue.to_file_contents();
    assert_eq!(
        rendered, original,
        "a typed fixture must not churn on a read/write round trip"
    );
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered
    );
    // The stable ids and the section position both survive.
    assert_eq!(issue.relationships[0].id, "rel_01JQ8Z4W2M6N7P9R3S5T7V9X1");
    assert!(
        rendered.find("## History").unwrap() < rendered.find("Prose that follows").unwrap(),
        "History sits between the frontmatter and the body"
    );
}

#[test]
fn t010_issue_with_no_relationship_data_is_untouched() {
    let original =
        std::fs::read_to_string(relationship_fixture("no-relationship-data.md")).unwrap();
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(
        issue.relationships,
        [] as [crate::relationships::Relationship; 0]
    );
    assert!(issue.history.is_empty());
    assert!(!issue.has_retired_links_key);
    let rendered = issue.to_file_contents();
    assert_eq!(
        rendered, original,
        "an issue with no relationship data must not churn"
    );
    assert!(!rendered.contains("relationships:"));
    assert!(!rendered.contains("## History"));
}

#[test]
fn t010_an_empty_history_section_is_dropped_not_preserved() {
    // A hand-left `## History` heading with no entries parses to an empty
    // log. The section is derived from the log, so an empty one has no
    // representation on disk and is omitted on write — diagnosed, never
    // silently filled in, and never kept as a bare heading.
    let original = std::fs::read_to_string(relationship_fixture("history-empty.md")).unwrap();
    assert!(
        original.contains("## History"),
        "the fixture must actually carry the empty heading"
    );
    let issue = Issue::parse(&original).unwrap();
    assert!(
        issue.history.is_empty(),
        "a heading with no entries parses to an empty log"
    );
    assert!(
        issue
            .body
            .contains("An issue whose History section is present but empty."),
        "the prose after the heading is body, not a dropped event: {:?}",
        issue.body
    );
    let rendered = issue.to_file_contents();
    assert!(
        !rendered.contains("## History"),
        "the empty section is omitted rather than kept as a bare heading"
    );
    assert!(rendered.contains("An issue whose History section is present but empty."));
}

#[test]
fn t010_issue_with_no_history_section_is_untouched() {
    let original = std::fs::read_to_string(relationship_fixture("history-absent.md")).unwrap();
    let issue = Issue::parse(&original).unwrap();
    assert!(issue.history.is_empty());
    let rendered = issue.to_file_contents();
    assert_eq!(
        rendered, original,
        "a file written before History existed must not gain an empty section"
    );
}

#[test]
fn f2_one_bad_history_line_does_not_make_the_store_unreadable() {
    // Store-level consequence of the model-level guarantee. Before the parse
    // became non-fatal, `Store::list` propagated the error, so a single
    // mistyped line in one issue broke `list`, `get`, `view`, `board`,
    // `status`, `lint`, `export`, `link`, `unlink` and `set_relationships`
    // for *every* issue — including `get` on a completely unrelated,
    // perfectly valid one. There is also no recovery through the tool,
    // because every command that could rewrite the file was among the
    // failures.
    let (_tmp, store) = make_store();
    write_issue(&store, "2026-01-01-a.md", &bare_frontmatter(1, "A"));
    write_issue(
        &store,
        "2026-01-01-c.md",
        "---\nnumber: 3\ntitle: \"C\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\n## History\n\n- 2026-01-01T00:00:00Z - alice - relationship_added - ascii hyphens\n",
    );

    let all = store.list().expect("the store must remain listable");
    assert_eq!(all.len(), 2, "both issues load");
    assert_eq!(
        store
            .get(IssueSelector::Number(1))
            .expect("an unrelated, valid issue must stay readable")
            .title,
        "A"
    );
    // And the damaged line is still reachable for diagnosis, which is the
    // whole point of the non-fatal parse. An ASCII-hyphen line is not
    // *recognised*, so no event is fabricated from it, but it is retained in
    // the section verbatim and reported rather than demoted into the body
    // (see the F1 trade in `parse_front`).
    let three = store.get(IssueSelector::Number(3)).unwrap();
    assert!(three.history.events().is_empty(), "no event is fabricated");
    assert_eq!(
        three.history.unparsed().len(),
        1,
        "the line is preserved for diagnosis: {:?}",
        three.history.unparsed()
    );
    assert!(
        !three.body.contains("ascii hyphens"),
        "and is not demoted into the body: {:?}",
        three.body
    );
}

/// Seed an issue into its own assignee segment, so a write can be failed
/// for one owner and not another.
#[cfg(unix)]
fn seeded_in_segment(store: &Store, number: u32, title: &str, segment: &str) {
    let dir = store.issues_dir.join(segment);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join(format!("2026-01-01-{}.md", title.to_lowercase())),
        format!(
            "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\nfiles: []\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody.\n"
        ),
    )
    .unwrap();
}

#[cfg(unix)]
#[test]
fn f6_a_mid_sequence_write_failure_rolls_every_file_back() {
    use std::os::unix::fs::PermissionsExt;
    // F6 / anti-pattern 7. This can write N files, because an edge is stored
    // in its canonical source's file, so a failure partway through used to
    // leave the store half-mutated while the command reported failure.
    //
    // `atomic_write` renames a temp file, which needs write permission on
    // the *directory*, so the injection makes one owner's segment
    // read-only. The owners are 1, 2 and 3 and are written in ascending
    // order, so #1 and #2 are committed before #3 fails.
    let (tmp, store) = make_store();
    let _ = tmp;
    seeded_in_segment(&store, 1, "A", "alice");
    seeded_in_segment(&store, 2, "B", "bob");
    seeded_in_segment(&store, 3, "C", "carol");
    seeded_in_segment(&store, 5, "E", "erin");

    let paths: Vec<std::path::PathBuf> = [
        "alice/2026-01-01-a.md",
        "bob/2026-01-01-b.md",
        "carol/2026-01-01-c.md",
    ]
    .iter()
    .map(|p| store.issues_dir.join(p))
    .collect();
    let before: Vec<String> = paths
        .iter()
        .map(|p| std::fs::read_to_string(p).unwrap())
        .collect();

    // Order-normalization puts target 5's edge on the lower number, so the
    // owners really are 1, 2 and 3 and #3 is written last.
    let carol = store.issues_dir.join("carol");
    let mut perms = std::fs::metadata(&carol).unwrap().permissions();
    perms.set_mode(0o555);
    std::fs::set_permissions(&carol, perms).unwrap();

    let result = store.set_relationships(
        "carol/2026-01-01-c.md",
        &[
            (1, RelationKind::Related),
            (2, RelationKind::Related),
            (5, RelationKind::Related),
        ],
    );

    let mut perms = std::fs::metadata(&carol).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&carol, perms).unwrap();

    assert!(result.is_err(), "the blocked write must fail");
    for (path, previous) in paths.iter().zip(before.iter()) {
        assert_eq!(
            std::fs::read_to_string(path).unwrap(),
            *previous,
            "{} was left mutated by a failed mutation",
            path.display()
        );
    }
}

#[cfg(unix)]
#[test]
fn f6b_the_updated_bump_is_itself_rollback_covered() {
    // The `updated` bump on the named issue (F16) is a real write, and it
    // used to sit *after* the rollback check — so a failure there returned an
    // error with the relationship writes already committed and nothing left
    // to restore. That is the same class of defect F6 was about, reintroduced
    // by the F16 fix.
    //
    // Order matters here: the relationship write lands in the *other*
    // endpoint's segment, and the bump targets the named issue's own
    // segment, so blocking the named segment fails the second write.
    use std::os::unix::fs::PermissionsExt;

    let (tmp, store) = make_store();
    let _ = tmp;
    seeded_in_segment(&store, 1, "A", "alice");
    seeded_in_segment(&store, 3, "C", "carol");

    let alice = store.issues_dir.join("alice/2026-01-01-a.md");
    let before = std::fs::read_to_string(&alice).unwrap();

    let carol = store.issues_dir.join("carol");
    let mut perms = std::fs::metadata(&carol).unwrap().permissions();
    perms.set_mode(0o555);
    std::fs::set_permissions(&carol, perms).unwrap();

    let result = store.set_relationships("carol/2026-01-01-c.md", &[(1, RelationKind::Related)]);

    let mut perms = std::fs::metadata(&carol).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&carol, perms).unwrap();

    assert!(result.is_err(), "the blocked bump must fail the call");
    assert_eq!(
        std::fs::read_to_string(&alice).unwrap(),
        before,
        "the relationship write that succeeded earlier must be rolled back \
         when the subsequent `updated` bump fails"
    );
}

#[test]
fn f9_relationships_for_reports_both_endpoints_of_a_one_sided_edge() {
    // F9. An edge is stored once, in its canonical source's file, so the
    // issue's own `relationships` field is a *partial* view. Reading it made
    // a related issue look unrelated — a user-visible regression against the
    // retired symmetric model, which mirrored the link on both sides by
    // construction.
    let (_tmp, store) = make_store();
    seeded(&store, 1, "A", "");
    seeded(&store, 2, "B", "");
    store.link("2", "1", RelationKind::Related).unwrap();

    // The edge is stored once, in the lower-numbered issue's file.
    let one = store.get(IssueSelector::Number(1)).unwrap();
    let two = store.get(IssueSelector::Number(2)).unwrap();
    assert_eq!(one.relationships.len(), 1, "precondition: #1 stores it");
    assert!(
        two.relationships.is_empty(),
        "precondition: #2's own field is the partial view that caused F9"
    );

    // The service-backed accessor is what a read surface must use, and it
    // answers for both endpoints.
    for number in [1u32, 2] {
        let resolved = store.relationships_for(number).unwrap();
        assert_eq!(
            resolved.len(),
            1,
            "issue #{number} must see the relationship that touches it"
        );
        assert_eq!(resolved[0].kind, RelationKind::Related);
    }
}

#[test]
fn f7_writing_an_issue_with_the_retired_key_discloses_that_it_is_removed() {
    // F7 / M6. The previous version of this test asserted only the
    // *consequence* — the key is gone from the file — which was already true
    // before the fix, so removing the disclosure entirely left it green.
    // It never checked the thing its name promised.
    let (tmp, store) = make_store();
    let _ = tmp;
    let _ = take_disclosures();
    // **Populated**, not `[]`. The disclosure fires because the key's value is
    // no longer readable, and an empty value has nothing to lose — reporting
    // the key's mere presence made `tix lint` reject every issue file this
    // repository has ever written, since they all carry a `links: []`.
    write_issue(
        &store,
        "2026-01-01-legacy.md",
        &legacy_links_frontmatter(1, "Legacy", "['7']"),
    );
    let issue = store.get(IssueSelector::Number(1)).unwrap();
    assert!(
        issue.has_retired_links_key,
        "precondition: the key is present"
    );

    store.update(&issue.filename, &issue).unwrap();

    // The disclosure, which is the whole point of the fix.
    let disclosures = take_disclosures();
    assert_eq!(
        disclosures.len(),
        1,
        "the write must disclose that it dropped the key: {disclosures:?}"
    );
    let line = &disclosures[0];
    assert!(
        line.contains("`links:`"),
        "it names what was removed: {line}"
    );
    // The action leads, so it is the part that survives truncation in the
    // TUI's one-row status area. Cycle 6 measured the previous wording being
    // cut off at 80, 100 and 120 columns.
    assert!(
        line.starts_with("remove `links:` by hand"),
        "and leads with what to do about it: {line}"
    );
    assert!(
        line.contains(&issue.filename),
        "and which file it was removed from: {line}"
    );
    assert!(
        line.contains("C-001"),
        "and that no migration was applied, so the user is not left \
         wondering where their data went: {line}"
    );

    // The consequence the disclosure is about.
    let after = read_issue_file(&store, &issue.filename);
    assert!(
        !after.contains("links:"),
        "the key is not re-emitted (C-001: no migration)"
    );
    // And a re-read no longer reports it, which is precisely why the
    // disclosure matters: the diagnostic is self-erasing without it.
    let reread = store.get(IssueSelector::Number(1)).unwrap();
    assert!(!reread.has_retired_links_key);
    assert!(
        take_disclosures().is_empty(),
        "and it is disclosed once, not on every read"
    );
}

#[test]
fn f7b_writing_an_issue_without_the_retired_key_is_silent() {
    // The disclosure is scoped to the condition that triggers it, so the
    // ordinary path stays quiet and this queue cannot become noise.
    let (tmp, store) = make_store();
    let _ = tmp;
    let _ = take_disclosures();
    write_issue(&store, "2026-01-01-plain.md", &bare_frontmatter(1, "Plain"));
    let issue = store.get(IssueSelector::Number(1)).unwrap();
    assert!(!issue.has_retired_links_key);
    store.update(&issue.filename, &issue).unwrap();
    assert!(
        take_disclosures().is_empty(),
        "an ordinary write discloses nothing"
    );
}

#[test]
fn t010_legacy_fixture_reports_the_retired_key_and_yields_no_edges() {
    // C-001, the compatibility/error matrix in one place: tolerant read,
    // explicit diagnostic, and zero reinterpretation.
    let original = std::fs::read_to_string(relationship_fixture("legacy-links-key.md")).unwrap();
    let issue = Issue::parse(&original).unwrap();
    assert!(issue.has_retired_links_key, "the retired key is reported");
    assert!(
        issue.relationships.is_empty(),
        "C-001: legacy values are never reinterpreted as typed edges"
    );
    assert!(
        issue.history.is_empty(),
        "a legacy file gains no History section from parsing"
    );
    // The diagnostic names the field and is located in the file, per the
    // validation contract. Exercised through the real `tix lint` path so
    // the test covers the code that actually ships.
    let (_tmp, store) = make_store();
    write_issue(&store, "2026-01-01-legacy.md", &original);
    let findings = crate::commands::lint::collect(&store.config, &store).unwrap();
    let retired: Vec<_> = findings
        .iter()
        .filter(|f| f.kind == "retired_links_key")
        .collect();
    assert_eq!(
        retired.len(),
        1,
        "one finding for the retired key: {findings:?}"
    );
    assert_eq!(retired[0].value, "links", "the finding names the field");
    assert!(
        retired[0].message.contains("retired"),
        "the message says why: {}",
        retired[0].message
    );
    assert!(
        retired[0].line > 0,
        "the finding points into the frontmatter"
    );
    // No code path converts the legacy value into a typed edge.
    let rewritten = issue.to_file_contents();
    assert!(!rewritten.contains("kind: related"));
    assert!(!rewritten.contains("kind: blocks"));
    assert!(!rewritten.contains("links:"));
}

#[test]
fn c001_a_legacy_links_key_is_reported_and_yields_no_typed_edges() {
    let (tmp, store) = make_store();
    write_issue(
        &store,
        "2026-01-01-legacy.md",
        &legacy_links_frontmatter(1, "Legacy", "[\"12\", \"47\"]"),
    );
    let _ = tmp;
    let issue = store.get(IssueSelector::Number(1)).unwrap();
    assert!(
        issue.has_retired_links_key,
        "the retired key is recorded as a validation result"
    );
    assert!(
        issue.relationships.is_empty(),
        "C-001: legacy values are never read as typed edges"
    );
}

#[test]
fn c001_there_is_no_migration_path_from_the_retired_key() {
    // This test used to say "writing the issue back is the only way a
    // migration could occur" and then never write it back, so its
    // load-bearing assertion was on an in-memory flag after a pure string
    // render — which cannot change it. The actual write-back is where the
    // key disappears, so the test as written masked the very thing it
    // appeared to guard.
    //
    // It now performs the write and asserts on the resulting bytes.
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-legacy.md",
        &legacy_links_frontmatter(1, "Legacy", "[\"12\", \"47\"]"),
    );
    let issue = store.get(IssueSelector::Number(1)).unwrap();
    assert!(
        issue.has_retired_links_key,
        "precondition: the key is present"
    );
    assert!(
        issue.relationships.is_empty(),
        "C-001: legacy values are never read as typed edges"
    );

    store.update(&issue.filename, &issue).unwrap();
    let written = read_issue_file(&store, &issue.filename);

    // No migration: not one legacy value became a typed edge, under any kind.
    //
    // The re-read matters, and this test has already fallen into the trap
    // once: asserting on `issue.to_file_contents()` instead of the written
    // file cannot fail, because `Issue::parse` never populates
    // `relationships`, so the in-memory render is clean whatever the *writer*
    // does. Reading the file back off disk is the only form of this check
    // that the write-back actually has to satisfy.
    let reparsed = store.get(IssueSelector::Number(1)).unwrap();
    assert!(
        reparsed.relationships.is_empty(),
        "the file on disk parses to zero typed edges, not just the in-memory copy"
    );
    for kind in ["blocks", "blocked_by", "duplicates", "related"] {
        assert!(
            !written.contains(&format!("kind: {kind}")),
            "a legacy link became a `{kind}` edge:\n{written}"
        );
    }
    assert!(
        !written.contains("kind:"),
        "no typed edge was written at all"
    );
    // The retired key is not re-emitted, and the write did not manufacture
    // a History entry for something the user did not do.
    assert!(!written.contains("links:"), "the key is not re-emitted");
    let reread = store.get(IssueSelector::Number(1)).unwrap();
    assert!(
        reread.history.is_empty(),
        "a format change is not a relationship mutation, so it records no event"
    );
}

#[test]
fn f15_the_idempotent_no_op_reports_the_real_addressable_row() {
    // F15. The no-op path returned a synthetic `Relationship` with an empty
    // id and display. The contract defines the output as the accepted
    // relationship, and an empty id is not addressable by
    // `edit_relation`/`remove_relation`, so a caller that persisted it would
    // store a dangling reference.
    let (_tmp, store, a, b) = related_pair();
    let args = (a.number.to_string(), b.number.to_string());
    let first = store.link(&args.0, &args.1, RelationKind::Blocks).unwrap();
    let second = store.link(&args.0, &args.1, RelationKind::Blocks).unwrap();

    assert!(first.changed);
    assert!(!second.changed, "the second apply is a no-op");
    assert_eq!(
        second.relationship.id, first.relationship.id,
        "the no-op reports the real, addressable row"
    );
    assert!(
        !second.relationship.id.is_empty(),
        "an empty id is not addressable"
    );
    assert_eq!(second.relationship.display, first.relationship.display);
}

#[test]
fn f16_clearing_a_set_bumps_updated_on_the_named_issue() {
    // F16. The named issue's own frontmatter can be untouched while its
    // relationship set changed, because an order-normalized `related` edge
    // lives in the other endpoint's file. That left `tix edit <n> --links ""`
    // looking like it had done nothing to the issue it named.
    let (_tmp, store, _a, _b) = related_pair();
    store.link("2", "1", RelationKind::Related).unwrap();
    let before = store.get(IssueSelector::Number(2)).unwrap();
    let updated_before = before.updated.clone();

    store.set_relationships(&before.filename, &[]).unwrap();

    let after = store.get(IssueSelector::Number(2)).unwrap();
    assert_ne!(
        after.updated, updated_before,
        "the named issue's relationship set changed, so `updated` must move"
    );
}

#[test]
fn c002_an_issue_with_no_relationship_data_round_trips_unchanged() {
    let (tmp, store) = make_store();
    let _ = tmp;
    // A pre-existing issue file: no relationship data, no History. This is
    // the shape every file in the repository has today, and reading then
    // writing it must not churn it (the WP's "existing files must not be
    // rewritten" guard).
    write_issue(&store, "2026-01-01-plain.md", &bare_frontmatter(1, "Plain"));
    let issue = store.get(IssueSelector::Number(1)).unwrap();
    let first = issue.to_file_contents();
    assert!(
        !first.contains("relationships:"),
        "the empty typed field is omitted, not written as `[]`"
    );
    assert!(
        !first.contains("## History"),
        "an empty History section is omitted entirely"
    );
    // Byte-stable through read -> write -> read, and no unrelated
    // frontmatter key is added, removed, or reordered.
    let reparsed = Issue::parse(&first).unwrap();
    let second = reparsed.to_file_contents();
    assert_eq!(second, first);
}

#[test]
fn c002_history_section_round_trips_byte_stable() {
    let (tmp, store) = make_store();
    write_issue(&store, "2026-01-01-h.md", &bare_frontmatter(1, "H"));
    let _ = tmp;
    let mut issue = store.get(IssueSelector::Number(1)).unwrap();
    issue.history.append_now(
        "alice",
        HistoryEventKind::RelationshipAdded,
        "created blocks: blocks #2 B",
    );
    issue.history.append_now(
        "bob",
        HistoryEventKind::BlockedMoveAcknowledged,
        "acknowledged 1 open blocker",
    );
    let first = issue.to_file_contents();
    assert!(first.contains("## History"), "{first}");

    // Read -> write -> read must be byte-stable.
    let reparsed = Issue::parse(&first).unwrap();
    assert_eq!(reparsed.to_file_contents(), first);
    assert_eq!(reparsed.history.len(), 2);
    assert_eq!(reparsed.history.events()[0].actor, "alice");
    assert_eq!(
        reparsed.history.events()[1].kind,
        HistoryEventKind::BlockedMoveAcknowledged
    );
    assert!(
        !reparsed.body.contains("History"),
        "the section is stripped from the body: {:?}",
        reparsed.body
    );
}

#[test]
fn f1_a_hand_edit_last_in_the_section_stays_in_it() {
    // Cycle-4 F1. The disambiguation rule carried a `!following.is_empty()`
    // guard, added to stop an earlier vacuous-truth defect. It over-corrected:
    // a hand-edited line that is the **last** line of the section has nothing
    // after it, so the guard forced the section to terminate there. Through
    // the real binary that meant `tix move 1 "in progress"` silently
    //
    //   - deleted the `## History` heading,
    //   - demoted the author's line into the issue body, and
    //   - rendered the *next* appended event above it, so file order stopped
    //     being append order,
    //
    // and `tix lint` reported nothing, because a demoted line is body prose
    // and the unparsed loop no longer sees it. Three explicit data-model §8
    // invariants at once.
    //
    // The distinguishing question is not "is there anything after this?" but
    // "is this shaped like a list item?". Nothing-following cannot disqualify
    // a line; a bare paragraph at EOF is still plainly prose.
    let (tmp, store) = make_store();
    let _ = tmp;
    let original = "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} prior\n  - my hand edit\n";
    write_issue(&store, "2026-01-01-a.md", original);

    // Read precondition: the hand edit is inside the section, and the section
    // holds the prior event.
    let before = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(
        before.history.events().len(),
        1,
        "precondition: the real event parsed"
    );
    assert_eq!(
        before.history.unparsed(),
        vec!["  - my hand edit"],
        "precondition: the hand edit is inside the section"
    );
    assert_eq!(before.body, "", "precondition: body is empty");

    // An ordinary command that has nothing to do with relationships.
    let mut moved = before.clone();
    moved.status = crate::model::Status::new("in progress");
    store.update(&moved.filename, &moved).unwrap();

    let after = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(
        after.history.unparsed(),
        vec!["  - my hand edit"],
        "the hand edit is still in the audit log, not demoted to the body"
    );
    assert_eq!(
        after.history.events().len(),
        1,
        "and the real event survived"
    );
    assert_eq!(after.body, "", "nothing leaked into the body");

    // The heading is still there, and the next append goes *after* what was
    // already in the file.
    store
        .link("1", "2", RelationKind::Related)
        .ok()
        .or_else(|| {
            write_issue(&store, "2026-01-01-b.md", &bare_frontmatter(2, "B"));
            store.link("1", "2", RelationKind::Related).ok()
        });
    let linked = store.get(IssueSelector::Number(1)).unwrap();
    let rendered = linked.to_file_contents();
    assert!(
        rendered.contains("## History"),
        "the heading survived an unrelated write: {rendered}"
    );
    let hand = rendered
        .find("my hand edit")
        .expect("the hand edit is present");
    let newest = rendered
        .find("relationship_added")
        .expect("the new event is present");
    assert!(
        newest < hand,
        "the new event is appended AFTER the pre-existing content, so file \
         order is still append order: {rendered}"
    );
}

#[test]
fn f1_but_a_bare_paragraph_at_end_of_section_is_still_prose() {
    // The other half of F1's rule, and the reason the fix is not simply
    // "vacuous truth is fine". A non-list line at EOF is body prose: keeping
    // it would put ordinary prose into the append-only audit log, which is
    // the defect cycle 3 found (N1) travelling in the opposite direction.
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-a.md",
        "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} prior\n\njust a closing paragraph\n",
    );
    let issue = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(issue.history.events().len(), 1, "the real event parsed");
    assert!(
        issue.history.unparsed().is_empty(),
        "the paragraph is not in the audit log: {:?}",
        issue.history.unparsed()
    );
    assert!(
        issue.body.contains("just a closing paragraph"),
        "it is body prose: {:?}",
        issue.body
    );
}

#[test]
fn f1_a_hand_edit_survives_body_prose_and_a_later_body_replacement() {
    // Cycle-5 Blocker 1. Cycle 4's F1 fix consulted `is_list_item` *only*
    // when nothing followed the ambiguous line, so the whole defect survived
    // for any hand-edited entry with body prose after it. The existing F1
    // tests could not see it because every one of their fixtures asserts
    // `before.body == ""` — the empty body was precisely what hid it.
    //
    // The consequence was data loss, not just reordering. A demoted line is
    // body text, and `tix edit --body` replaces the body wholesale, so:
    //
    //   ## History / - <event> / - 2026-02-02T00:00:00Z - bob \
    //     - relationship_removed - I removed this by hand / (blank) / Notes.
    //
    // then `tix edit 1 --body='Completely new body text.'` destroyed the
    // hand-edited append-only audit entry, and lint was silent.
    let (_tmp, store) = make_store();
    write_issue(&store, "2026-01-01-b.md", &bare_frontmatter(2, "B"));
    let hand = "- 2026-02-02T00:00:00Z - bob - relationship_removed - by hand";
    write_issue(
        &store,
        "2026-01-01-a.md",
        &format!(
            "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} prior\n{hand}\n\nSome body prose.\n"
        ),
    );

    let before = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(before.history.events().len(), 1, "the real event parsed");
    assert_eq!(
        before.history.unparsed(),
        vec![hand],
        "the hand-edited entry is retained even though body prose follows"
    );
    assert!(
        before.body.contains("Some body prose."),
        "and the prose is still body text: {:?}",
        before.body
    );

    // An ordinary unrelated write must not relocate it.
    let mut moved = before.clone();
    moved.status = crate::model::Status::new("in progress");
    store.update(&moved.filename, &moved).unwrap();
    assert_eq!(
        store
            .get(IssueSelector::Number(1))
            .unwrap()
            .history
            .unparsed(),
        vec![hand],
        "a `tix move` keeps it in the audit log"
    );

    // And replacing the body — the operation that used to destroy it — must
    // not either.
    let mut replaced = store.get(IssueSelector::Number(1)).unwrap();
    replaced.body = "Completely new body text.".to_string();
    store.update(&replaced.filename, &replaced).unwrap();
    let after = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(
        after.history.unparsed(),
        vec![hand],
        "the hand-edited entry survives a wholesale body replacement"
    );
    assert_eq!(after.body, "Completely new body text.");

    // And the next append still goes after what the file already held.
    store.link("1", "2", RelationKind::Related).unwrap();
    let rendered = store
        .get(IssueSelector::Number(1))
        .unwrap()
        .to_file_contents();
    assert!(
        rendered.contains("## History"),
        "the heading survived: {rendered}"
    );
    let hand_at = rendered.find("by hand").expect("the hand edit is present");
    let new_at = rendered
        .find("created rel_")
        .expect("the new event is present");
    assert!(
        new_at > hand_at,
        "the new event is appended AFTER the pre-existing content, so file \
         order is still append order: {rendered}"
    );
}

#[test]
fn f1_a_well_formed_star_marked_entry_is_retained_with_body_prose_after_it() {
    // Cycle-6 F1. A *correctly formatted* entry written with a `*` marker was
    // demoted to the body and then destroyed by `tix edit --body`, with lint
    // silent. The cause was a collapsed predicate: `looks_like_history_entry`
    // and `HistoryEvent::parse` both require the `- ` prefix, so a `*`-marked
    // em-dash line was not *recognised*; and the retention test asked
    // "does it look like a *misspelled* entry?", which explicitly excludes
    // anything containing U+2014. So a well-formed line matched neither.
    // Retention now asks its own question — is this an entry attempt under any
    // marker?
    let (_tmp, store) = make_store();
    write_issue(&store, "2026-01-01-b.md", &bare_frontmatter(2, "B"));
    let hand = "* 2026-02-02T00:00:00Z \u{2014} bob \u{2014} relationship_removed \u{2014} by hand";
    write_issue(
        &store,
        "2026-01-01-a.md",
        &format!(
            "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} prior\n{hand}\n\nSome body prose.\n"
        ),
    );

    let before = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(before.history.events().len(), 1, "the real event parsed");
    assert_eq!(
        before.history.unparsed(),
        vec![hand],
        "a well-formed `*` entry is retained even with body prose after it"
    );
    assert!(
        before.body.contains("Some body prose."),
        "and the prose is still body text: {:?}",
        before.body
    );

    // The destructive sequence, which is the whole point.
    let mut replaced = before.clone();
    replaced.body = "Completely new body text.".to_string();
    store.update(&replaced.filename, &replaced).unwrap();
    assert_eq!(
        store
            .get(IssueSelector::Number(1))
            .unwrap()
            .history
            .unparsed(),
        vec![hand],
        "it survives a wholesale body replacement"
    );

    store.link("1", "2", RelationKind::Related).unwrap();
    let rendered = store
        .get(IssueSelector::Number(1))
        .unwrap()
        .to_file_contents();
    assert_eq!(
        rendered.matches("## History").count(),
        1,
        "still exactly one section: {rendered}"
    );
    let hand_at = rendered.find("by hand").expect("the hand edit is present");
    let new_at = rendered
        .find("created rel_")
        .expect("the new event is present");
    assert!(
        new_at > hand_at,
        "appended after, so order is append order: {rendered}"
    );
}

#[test]
fn f1_a_three_field_ascii_hyphen_entry_is_retained_with_body_prose_after_it() {
    // Cycle-6 F2. `HistoryEvent::parse` accepts three total fields with
    // `detail` optional, so `- <ts> - <actor> - <kind>` is a valid entry whose
    // only defect is the separator. The retention test required four, so that
    // line was demoted and then destroyed while the malformed four-field one
    // survived — the recoverable direction was the one that lost.
    let (_tmp, store) = make_store();
    let hand = "- 2026-02-02T00:00:00Z - bob - relationship_removed";
    write_issue(
        &store,
        "2026-01-01-a.md",
        &format!(
            "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} prior\n{hand}\n\nSome body prose.\n"
        ),
    );

    // Precondition: the em-dash twin really is a valid event, so the
    // three-field form is in fact part of the format.
    let twin = Issue::parse(
        "---\nnumber: 2\ntitle: \"T\"\nstatus: todo\n---\n\n## History\n\n- 2026-02-02T00:00:00Z \u{2014} bob \u{2014} relationship_removed\n",
    )
    .unwrap();
    assert_eq!(
        twin.history.events().len(),
        1,
        "three fields with em-dashes is a valid event, detail optional"
    );

    let before = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(
        before.history.unparsed(),
        vec![hand],
        "so its ASCII-hyphen twin is retained, not demoted"
    );
    let mut replaced = before.clone();
    replaced.body = "Completely new body text.".to_string();
    store.update(&replaced.filename, &replaced).unwrap();
    assert_eq!(
        store
            .get(IssueSelector::Number(1))
            .unwrap()
            .history
            .unparsed(),
        vec![hand],
        "and survives a body replacement"
    );
}

#[test]
fn f1_a_heading_with_trailing_spaces_is_still_the_heading() {
    // Cycle-6 F3(c). `## History   ` was not recognised, and since the
    // heading is then neither the section nor body, the first relationship
    // write rendered a **second** `## History` above the original. That was
    // filed on #1299 as a CRLF-only consequence, which understated it: a
    // trailing space is a far likelier trigger than CRLF.
    let (_tmp, store) = make_store();
    write_issue(&store, "2026-01-01-b.md", &bare_frontmatter(2, "B"));
    for (label, heading) in [
        ("plain", "## History"),
        ("trailing spaces", "## History   "),
    ] {
        write_issue(
            &store,
            "2026-01-01-a.md",
            &format!(
                "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n{heading}\n\n- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} prior\n"
            ),
        );
        let before = store.get(IssueSelector::Number(1)).unwrap();
        assert_eq!(
            before.history.events().len(),
            1,
            "{label}: the section is recognised"
        );
        store.link("1", "2", RelationKind::Related).unwrap();
        let rendered = store
            .get(IssueSelector::Number(1))
            .unwrap()
            .to_file_contents();
        assert_eq!(
            rendered.matches("## History").count(),
            1,
            "{label}: exactly one section after a write, got {rendered}"
        );
        assert!(
            !rendered.lines().any(|l| l != l.trim_end()),
            "{label}: no line keeps trailing whitespace, so the heading is \
             normalised: {rendered}"
        );
    }
}

#[test]
fn set_status_discloses_the_retired_key_rather_than_dropping_it_silently() {
    // Cycle-6 F4. Routing `set_status` through `update` is what makes it
    // disclose, and the behavioural difference is real — reverted to a direct
    // `atomic_write`, the key is still removed but nothing is disclosed, which
    // is silent data loss. Reverting also left the **entire suite green**,
    // because no test exercised it. That is the sixth time this package has
    // produced a correct fix with no regression protection, so this pins it.
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "2026-01-01-a.md",
        "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nlinks:\n- \"2\"\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
    );
    let before = store.get(IssueSelector::Number(1)).unwrap();
    assert!(
        before.has_retired_links_key,
        "precondition: the file carries the retired key"
    );
    let _ = crate::storage::take_disclosures();

    store
        .set_status("2026-01-01-a.md", StatusChange::to("in progress"))
        .unwrap();

    let disclosures = crate::storage::take_disclosures();
    assert_eq!(
        disclosures.len(),
        1,
        "set_status must disclose the removal, got {disclosures:?}"
    );
    assert!(
        disclosures[0].contains("links:") && disclosures[0].contains("a.md"),
        "naming the field and the file: {disclosures:?}"
    );
    assert!(
        !store
            .get(IssueSelector::Number(1))
            .unwrap()
            .has_retired_links_key,
        "and the key is gone, as C-001 intends"
    );
}

#[test]
fn f1_but_ordinary_prose_bullets_still_end_the_section() {
    // The other direction, and the reason the retention rule is not simply
    // "keep every list item". N1's original trigger: several body bullets in
    // a row. Neither is entry-shaped, so neither is plausibly a hand-edited
    // entry, and the section ends where it should.
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "2026-01-01-a.md",
        concat!(
            "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\n",
            "created: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n",
            "- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} prior\n\n",
            "- step one\n- step two\n",
        ),
    );
    let issue = store.get(IssueSelector::Number(1)).unwrap();
    assert_eq!(
        issue.history.events().len(),
        1,
        "the real event is an event"
    );
    assert!(
        issue.history.unparsed().is_empty(),
        "ordinary bullets are not retained: {:?}",
        issue.history.unparsed()
    );
    assert!(
        issue.body.contains("step one") && issue.body.contains("step two"),
        "they stay body text: {:?}",
        issue.body
    );
}

#[test]
fn a_year_is_not_an_ordered_list_marker() {
    // Cycle-5 Minor 7. `is_list_item` accepted any run of digits before `.`,
    // so `2026. Q1 goals` counted as a list item and a paragraph of ordinary
    // body prose was retained in the append-only audit log.
    for prose in [
        "2026. Q1 goals",
        "2026. roadmap review",
        "007. padded",
        "99999999999999999999. big",
    ] {
        assert!(
            !crate::model::looks_like_an_unrecognised_entry(prose)
                && Issue::parse(&format!(
                    "---\nnumber: 1\ntitle: T\nstatus: todo\n---\n\n## History\n\n{prose}\n"
                ))
                .unwrap()
                .history
                .is_empty(),
            "{prose:?} must be body prose, not a retained entry"
        );
    }
}

#[test]
fn f2_a_recognised_entry_with_a_bad_kind_keeps_its_trailing_whitespace() {
    // Cycle-4 F2. The `Err` arm — a *recognised* entry whose kind is unknown —
    // used `trim_end()`, which also eats trailing spaces and tabs. That is
    // the auto-repair data-model §8 forbids, and it contradicts §8's
    // "preserved byte-for-byte, including its own indentation and trailing
    // whitespace". The sibling ambiguous arm was already correct, so the two
    // disagreed about what "verbatim" means.
    let line = "  - 2026-01-01T00:00:00Z \u{2014} alice \u{2014} bogus_kind \u{2014} d   ";
    let raw = format!(
        "---\nnumber: 1\ntitle: \"A\"\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n{line}\n"
    );
    let issue = Issue::parse(&raw).unwrap();
    assert!(issue.history.events().is_empty(), "no event was fabricated");
    assert_eq!(
        issue.history.unparsed(),
        vec![line],
        "kept byte-for-byte, trailing spaces included"
    );

    // And a real write must not repair it either.
    let rendered = issue.to_file_contents();
    assert!(
        rendered.contains(&format!("{line}\n")),
        "re-emitted exactly, so an unrelated `tix edit` does not rewrite the \
         author's audit log: {rendered}"
    );
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered,
        "and the file is byte-stable from here"
    );
}

#[test]
fn c002_history_is_append_only() {
    let (tmp, store) = make_store();
    write_issue(&store, "2026-01-01-h.md", &bare_frontmatter(1, "H"));
    let _ = tmp;
    let mut issue = store.get(IssueSelector::Number(1)).unwrap();
    issue
        .history
        .append_now("alice", HistoryEventKind::RelationshipAdded, "first");
    let after_first = issue.history.clone();
    issue
        .history
        .append_now("alice", HistoryEventKind::RelationshipRemoved, "second");

    assert_eq!(issue.history.len(), 2, "appending never replaces");
    assert_eq!(
        &issue.history.events()[..1],
        after_first.events(),
        "the earlier entry is untouched and still first"
    );
}

#[test]
fn c002_an_unknown_history_kind_is_kept_verbatim_not_coerced() {
    // The old version of this test asserted `contains("bogus_kind")` against
    // an error message that *echoes the offending line*, so it passed for any
    // input mentioning the word. It also fed ASCII hyphens, so
    // `splitn(4, U+2014)` never split and the real failure was a missing
    // field — the kind was never checked at all. Neither defect is a
    // hypothetical: the assertion was satisfied by the echo.
    //
    // Fixed on both counts. The line uses real em dashes, so the parser
    // genuinely reaches the kind field, and the assertion is on the parsed
    // outcome rather than on a substring of an error string.
    let line = "- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} bogus_kind \u{2014} something";
    let raw =
        format!("---\nnumber: 1\ntitle: \"H\"\nstatus: \"todo\"\n---\n\n## History\n\n{line}\n");
    let issue = Issue::parse(&raw).expect("an unknown kind must not fail the parse");

    assert!(
        issue.history.events().is_empty(),
        "no event was fabricated for an unknown kind"
    );
    assert_eq!(
        issue.history.unparsed(),
        vec![line],
        "the line is kept verbatim: not dropped, not repaired"
    );
    // Idempotence, not equality with the hand-written input: that input
    // omits keys serde always emits, so only the rendered form is a
    // meaningful byte-stability assertion.
    let rendered = issue.to_file_contents();
    assert!(rendered.contains(line), "the line survives the write");
    assert_eq!(
        Issue::parse(&rendered).unwrap().to_file_contents(),
        rendered,
        "and the file round-trips byte-identically"
    );
}

#[test]
fn list_mixes_grouped_and_flat_issues_sorted_by_relative_filename() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    fs::create_dir_all(store.issues_dir.join("bob")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    write_issue(
        &store,
        "bob/2026-05-10-b.md",
        &sample_frontmatter(2, "B", "todo"),
    );
    write_issue(
        &store,
        "2026-02-01-c.md",
        &sample_frontmatter(3, "C", "todo"),
    );
    let issues = store.list().unwrap();
    let filenames: Vec<&str> = issues.iter().map(|i| i.filename.as_str()).collect();
    assert_eq!(issues.len(), 3);
    assert_eq!(
        filenames,
        vec![
            "2026-02-01-c.md",
            "alice/2026-01-01-a.md",
            "bob/2026-05-10-b.md"
        ],
        "deterministic sort by relative filename"
    );
}

#[test]
fn list_sorts_chronologically_within_a_group() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-03-01-c.md",
        &sample_frontmatter(3, "C", "todo"),
    );
    write_issue(
        &store,
        "alice/2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    write_issue(
        &store,
        "alice/2026-02-01-b.md",
        &sample_frontmatter(2, "B", "todo"),
    );
    let issues = store.list().unwrap();
    let numbers: Vec<u32> = issues.iter().map(|i| i.number).collect();
    assert_eq!(numbers, vec![1, 2, 3]);
}

#[test]
fn list_ignores_non_md_files_in_segments() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    fs::write(store.issues_dir.join("alice/notes.txt"), "not an issue").unwrap();
    fs::write(store.issues_dir.join("alice/.tix-tmp-123-456"), "orphan").unwrap();
    let issues = store.list().unwrap();
    assert_eq!(issues.len(), 1);
    assert_eq!(issues[0].filename, "alice/2026-01-01-a.md");
}

#[test]
fn list_skips_temp_marker_directories() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join(".tix-tmp-999-0")).unwrap();
    write_issue(
        &store,
        ".tix-tmp-999-0/2026-01-01-junk.md",
        &sample_frontmatter(9, "J", "todo"),
    );
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    let issues = store.list().unwrap();
    assert_eq!(issues.len(), 1);
    assert_eq!(issues[0].filename, "2026-01-01-a.md");
}

#[test]
fn list_parse_error_carries_grouped_relative_path() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    fs::write(
        store.issues_dir.join("alice/2026-01-01-bad.md"),
        "no frontmatter here\n",
    )
    .unwrap();
    let err = store.list().unwrap_err();
    assert!(
        matches!(&err, TixError::Parse(m) if m.starts_with("alice/2026-01-01-bad.md:")),
        "parse error must carry the relative path, got {err:?}"
    );
}

// ------------------------------------------------------------------
// T007 — grouped create writes into the assignee segment (FR-029/30)
// ------------------------------------------------------------------

#[test]
fn create_uses_the_default_layout_template() {
    // The documented default: `{assignee}/{type}/{status}` for the directory,
    // `{date}-{id}-{slug}.md` for the filename. With no `type:` attribute the
    // type component falls back to `default`. The id is pinned here so the
    // path is deterministic; a real create generates a random one.
    let tmp = tempfile::TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let store = Store {
        issues_dir: dir,
        config: Config::default(),
    };
    let mut issue = Issue {
        projects: None,
        id: Some("A1B2C3D4".into()),
        number: 0,
        title: "Round trip".into(),
        status: Status::new("todo"),
        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![],
        parent: None,
        series: None,
        health: None,
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        entered_at: None,
        source: 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(),
        archived: false,
    };
    store.create(&mut issue, "", None).unwrap();
    assert_eq!(
        issue.filename,
        "alice/default/todo/2026-01-01-A1B2C3D4-round-trip.md"
    );
    assert!(
        store
            .issues_dir
            .join("alice/default/todo/2026-01-01-A1B2C3D4-round-trip.md")
            .is_file()
    );
}

#[test]
fn create_assigns_a_valid_id_and_leads_the_filename_with_it() {
    let (tmp, store) = make_store();
    let _ = tmp;
    // Two creates with the same title and day: before ids these shared a
    // stem and only the `-2` fallback kept them apart; the id now makes the
    // names distinct at the source.
    let mut a = crate::model::Issue::parse(
        "---\nnumber: 0\ntitle: Same title\nstatus: todo\nlabels: []\npriority: medium\n\
         created: 2026-01-01\nupdated: 2026-01-01\n---\n\n",
    )
    .unwrap();
    let mut b = a.clone();
    store.create(&mut a, "", None).unwrap();
    store.create(&mut b, "", None).unwrap();

    let id_a = a.id.clone().expect("an id is assigned at create");
    let id_b = b.id.clone().expect("an id is assigned at create");
    assert!(crate::id::is_issue_id(&id_a), "shaped id: {id_a}");
    assert_ne!(id_a, id_b, "two creates must not share an id");
    assert!(
        a.filename.contains(&id_a),
        "filename must carry the id: {}",
        a.filename
    );
    assert!(
        a.to_file_contents().contains(&format!("id: {id_a}\n")),
        "the id must reach the frontmatter"
    );
}

#[test]
fn slug_from_stem_skips_the_id_and_date_prefixes() {
    // Legacy name: date prefix stripped.
    assert_eq!(slug_from_stem("2026-01-01-fix-login"), "fix-login");
    // New-schema name: date then id stripped.
    assert_eq!(slug_from_stem("2026-01-01-A1B2C3D4-fix-login"), "fix-login");
    // The earlier new-schema order (id then date) is still handled.
    assert_eq!(slug_from_stem("A1B2C3D4-2026-01-01-fix-login"), "fix-login");
    // No recognisable prefix: used verbatim.
    assert_eq!(slug_from_stem("no-prefix"), "no-prefix");
}

#[test]
fn update_always_reconciles_the_file_location() {
    // Unconditional auto-migration: a write moves the file to the directory
    // `[layout]` renders, even from a legacy/mismatched path.
    let tmp = tempfile::TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let store = Store {
        issues_dir: dir,
        config: Config::default(),
    };
    let mut issue = Issue {
        projects: None,
        id: Some("A1B2C3D4".into()),
        number: 0,
        type_: None,
        title: "Round trip".into(),
        status: Status::new("todo"),
        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![],
        parent: None,
        series: None,
        health: None,
        files: vec![],
        cycles: None,
        milestones: None,
        reviewer: None,
        start_date: None,
        due_date: None,
        entered_at: None,
        source: None,
        created: "2026-01-01".into(),
        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(),
        archived: false,
    };
    store.create(&mut issue, "", None).unwrap();
    let old = issue.filename.clone();

    // A status change relocates the laid-out file into the new status dir.
    issue.status = Status::new("done");
    issue.filename = store.update(&old, &issue).unwrap();
    assert_eq!(
        issue.filename,
        "alice/default/done/2026-01-01-A1B2C3D4-round-trip.md"
    );
    assert!(!store.issues_dir.join(&old).exists());

    // A mismatched (legacy flat) file is left for `tix layout migrate`.
    let flat = "2026-01-01-legacy.md";
    fs::write(
        store.issues_dir.join(flat),
        "---\nnumber: 9\ntitle: L\nstatus: todo\nlabels: []\npriority: medium\n\
         files: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nbody\n",
    )
    .unwrap();
    let mut legacy = store
        .get(IssueSelector::Filename(flat.to_string()))
        .unwrap();
    legacy.status = Status::new("done");
    let after = store.update(flat, &legacy).unwrap();
    assert_eq!(after, "unassigned/default/done/2026-01-01-legacy.md");
    assert!(!store.issues_dir.join(flat).exists(), "migrated, not left");
    assert!(store.issues_dir.join(&after).is_file());
}

#[test]
fn create_writes_into_assignee_segment_and_records_relative_filename() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    let path = store
        .create(&mut issue, "body", Some("custom-stem"))
        .unwrap();
    let rel = "herbert-maschke/custom-stem.md";
    assert_eq!(issue.filename, rel);
    assert_eq!(path, store.issues_dir.join(rel));
    assert!(store.issues_dir.join("herbert-maschke").is_dir());
    assert!(store.issues_dir.join(rel).is_file());
}

#[test]
fn create_without_assignee_writes_unassigned_segment() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    let path = store.create(&mut issue, "", Some("stem")).unwrap();
    assert_eq!(issue.filename, "unassigned/stem.md");
    assert!(store.issues_dir.join("unassigned").is_dir());
    assert!(store.issues_dir.join("unassigned/stem.md").is_file());
    assert_eq!(path, store.issues_dir.join("unassigned/stem.md"));
}

#[test]
fn create_with_at_handle_derives_bare_segment() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    store.create(&mut issue, "", Some("stem")).unwrap();
    assert_eq!(issue.filename, "alice/stem.md");
    assert!(store.issues_dir.join("alice/stem.md").is_file());
}

// ------------------------------------------------------------------
// T008 — reassign(): move-on-reassign (FR-031), never overwrites
// ------------------------------------------------------------------

#[test]
fn reassign_moves_file_between_segments() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(1, "X", "todo"),
    );
    let new_path = store
        .reassign("alice/2026-01-01-x.md", Some("@bob"))
        .unwrap();
    assert_eq!(new_path, PathBuf::from("bob/2026-01-01-x.md"));
    assert!(store.issues_dir.join("bob/2026-01-01-x.md").is_file());
    assert!(!store.issues_dir.join("alice/2026-01-01-x.md").exists());
}

#[test]
fn reassign_into_occupied_segment_picks_deterministic_suffix() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    fs::create_dir_all(store.issues_dir.join("bob")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(1, "X", "todo"),
    );
    write_issue(
        &store,
        "bob/2026-01-01-x.md",
        &sample_frontmatter(2, "X", "todo"),
    );
    let new_path = store
        .reassign("alice/2026-01-01-x.md", Some("@bob"))
        .unwrap();
    assert_eq!(new_path, PathBuf::from("bob/2026-01-01-x-1.md"));
    assert!(store.issues_dir.join("bob/2026-01-01-x.md").is_file());
    assert!(store.issues_dir.join("bob/2026-01-01-x-1.md").is_file());
    assert!(!store.issues_dir.join("alice/2026-01-01-x.md").exists());
}

#[test]
fn reassign_legacy_flat_file_into_segment() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-y.md",
        &sample_frontmatter(1, "Y", "todo"),
    );
    let new_path = store.reassign("2026-01-01-y.md", Some("alice")).unwrap();
    assert_eq!(new_path, PathBuf::from("alice/2026-01-01-y.md"));
    assert!(store.issues_dir.join("alice/2026-01-01-y.md").is_file());
    assert!(!store.issues_dir.join("2026-01-01-y.md").exists());
}

#[test]
fn reassign_to_none_uses_unassigned_fallback() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-z.md",
        &sample_frontmatter(1, "Z", "todo"),
    );
    let new_path = store.reassign("alice/2026-01-01-z.md", None).unwrap();
    assert_eq!(new_path, PathBuf::from("unassigned/2026-01-01-z.md"));
    assert!(
        store
            .issues_dir
            .join("unassigned/2026-01-01-z.md")
            .is_file()
    );
    assert!(!store.issues_dir.join("alice/2026-01-01-z.md").exists());
}

#[test]
fn reassign_keeps_number_and_created_stable() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        title: "Stable".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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    store.create(&mut issue, "body", None).unwrap();
    let number = issue.number;
    let created = issue.created.clone();
    let before = issue.filename.clone();
    let new_path = store.reassign(&before, Some("@bob")).unwrap();
    let rescan = store.list().unwrap();
    let moved = rescan
        .iter()
        .find(|i| i.filename == new_path)
        .expect("moved file must be listed at its new relative path");
    assert_eq!(moved.number, number);
    assert_eq!(moved.created, created);
    assert_eq!(moved.title, "Stable");
}

#[test]
fn reassign_equal_segment_is_noop() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(1, "X", "todo"),
    );
    let new_path = store
        .reassign("alice/2026-01-01-x.md", Some("alice"))
        .unwrap();
    assert_eq!(new_path, PathBuf::from("alice/2026-01-01-x.md"));
    assert!(store.issues_dir.join("alice/2026-01-01-x.md").is_file());
}

#[test]
fn reassign_missing_file_is_not_found() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let err = store.reassign("nope.md", Some("alice")).unwrap_err();
    assert!(matches!(err, TixError::NotFound(_)));
}

// ------------------------------------------------------------------
// T009 — validate_filename relaxation + relative-path ops (C-008/C-010)
// ------------------------------------------------------------------

#[test]
fn validate_filename_allows_flat_and_single_segment_prefix() {
    validate_filename("2026-01-01-x.md").unwrap();
    validate_filename("alice/2026-01-01-x.md").unwrap();
}

#[test]
fn validate_filename_allows_deeper_segments() {
    // Configurable layout: depth is unbounded, so a nested path is valid.
    validate_filename("alice/bug/in-progress/2026-01-01-x.md").unwrap();
}

#[test]
fn validate_filename_refuses_leading_and_trailing_slash_and_absolute() {
    let err = validate_filename("/alice/2026-01-01-x.md").unwrap_err();
    assert!(matches!(err, TixError::InvalidInput(_)));
    let err = validate_filename("/etc/passwd").unwrap_err();
    assert!(matches!(err, TixError::InvalidInput(_)));
    let err = validate_filename("alice/").unwrap_err();
    assert!(matches!(err, TixError::InvalidInput(_)));
}

#[test]
fn path_traversal_with_segment_dotdot_refused() {
    let err = validate_filename("alice/../../x.md").unwrap_err();
    assert!(matches!(err, TixError::InvalidInput(_)));
    let err = validate_filename("alice/../x.md").unwrap_err();
    assert!(matches!(err, TixError::InvalidInput(_)));
}

#[test]
fn get_update_delete_set_status_work_on_grouped_relative_paths() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-g.md",
        &sample_frontmatter(7, "G", "todo"),
    );
    let got = store
        .get(IssueSelector::Filename("alice/2026-01-01-g.md".into()))
        .unwrap();
    assert_eq!(got.number, 7);
    let done = store
        .set_status("alice/2026-01-01-g.md", StatusChange::to("done"))
        .unwrap();
    assert_eq!(done.issue.status.display(), "done");
    assert!(store.issues_dir.join("alice/2026-01-01-g.md").is_file());
    let mut edited = store
        .get(IssueSelector::Filename("alice/2026-01-01-g.md".into()))
        .unwrap();
    edited.title = "Updated".into();
    store.update("alice/2026-01-01-g.md", &edited).unwrap();
    let reloaded = store
        .get(IssueSelector::Filename("alice/2026-01-01-g.md".into()))
        .unwrap();
    assert_eq!(reloaded.title, "Updated");
    store.delete("alice/2026-01-01-g.md").unwrap();
    assert!(!store.issues_dir.join("alice/2026-01-01-g.md").exists());
}

// ------------------------------------------------------------------
// T010 — grouped round-trip sweep
// ------------------------------------------------------------------

#[test]
fn grouped_round_trip_create_list_get_update_delete() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let mut issue = Issue {
        projects: None,
        id: Some("A1B2C3D4".into()),
        number: 0,
        title: "Round trip".into(),
        status: Status::default(),
        labels: vec!["bug".into()],
        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![],
        parent: None,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    store.create(&mut issue, "initial body", None).unwrap();
    let rel = issue.filename.clone();
    assert_eq!(rel, "herbert-maschke/2026-01-01-A1B2C3D4-round-trip.md");

    let listed = store.list().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].filename, rel);
    assert_eq!(listed[0].number, issue.number);

    let got = store.get(IssueSelector::Filename(rel.clone())).unwrap();
    let mut edited = got.clone();
    edited.title = "Renamed".into();
    store.update(&rel, &edited).unwrap();
    let reloaded = store.get(IssueSelector::Filename(rel.clone())).unwrap();
    assert_eq!(reloaded.title, "Renamed");

    store.delete(&rel).unwrap();
    assert!(!store.issues_dir.join(&rel).exists());
    assert_eq!(store.list().unwrap(), [] as [crate::model::Issue; 0]);
}

#[test]
fn legacy_flat_file_edit_and_status_still_work_after_layout_flip() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write_issue(
        &store,
        "2026-01-01-legacy.md",
        &sample_frontmatter(5, "Legacy", "todo"),
    );
    let listed = store.list().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].filename, "2026-01-01-legacy.md");
    let mutated = store
        .set_status("2026-01-01-legacy.md", StatusChange::to("in progress"))
        .unwrap();
    assert_eq!(mutated.issue.status.display(), "in progress");
    assert!(store.issues_dir.join("2026-01-01-legacy.md").is_file());
}

// ------------------------------------------------------------------
// T004 — add_asset(): copy + link insert (FR-006, NFR-004)
// ------------------------------------------------------------------

fn write_asset_source(tmp: &tempfile::TempDir, name: &str, contents: &[u8]) -> PathBuf {
    let path = tmp.path().join(name);
    fs::write(&path, contents).unwrap();
    path
}

fn write_issue_with_basic_body(store: &Store, name: &str, number: u32) {
    write_issue(
        store,
        name,
        &sample_frontmatter(number, "Asset host", "todo"),
    );
}

#[test]
fn add_asset_image_inserts_image_link_and_writes_file() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    let src = write_asset_source(&tmp, "diagram.png", b"PNGDATA");
    let added = store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    assert_eq!(added.written_name, "diagram.png");
    assert_eq!(added.link, "![diagram](fix-login-bug-assets/diagram.png)");
    assert!(
        store
            .issues_dir
            .join("alice/fix-login-bug-assets/diagram.png")
            .is_file()
    );
}

#[test]
fn add_asset_non_image_inserts_generic_markdown_link() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    let src = write_asset_source(&tmp, "report.pdf", b"%PDF");
    let added = store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    assert_eq!(added.link, "[report](fix-login-bug-assets/report.pdf)");
    assert!(
        store
            .issues_dir
            .join("alice/fix-login-bug-assets/report.pdf")
            .is_file()
    );
}

#[test]
fn add_asset_collision_resolves_with_numeric_suffix_and_link_points_at_it() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    let src = write_asset_source(&tmp, "x.png", b"first");
    let first = store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    assert_eq!(first.written_name, "x.png");
    let again = store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    assert_eq!(again.written_name, "x-1.png");
    assert_eq!(again.link, "![x-1](fix-login-bug-assets/x-1.png)");
    assert!(
        store
            .issues_dir
            .join("alice/fix-login-bug-assets/x.png")
            .is_file()
    );
    assert!(
        store
            .issues_dir
            .join("alice/fix-login-bug-assets/x-1.png")
            .is_file()
    );
}

#[test]
fn add_asset_appends_single_link_and_preserves_description() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-fix-login-bug.md",
        "---\nnumber: 1\ntitle: \"H\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nTitle line.\n\n## Comments\n\n### alice (2026-01-01)\n\nExisting comment.\n",
    );
    let src = write_asset_source(&tmp, "diagram.svg", b"<svg/>");
    store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    let reloaded = store
        .get(crate::storage::IssueSelector::Filename(
            "alice/2026-01-01-fix-login-bug.md".into(),
        ))
        .unwrap();
    // Description (above the `## Comments` boundary) untouched.
    assert_eq!(reloaded.description(), "Title line.");
    // Exactly one link line, appended after the comments section.
    let link_count = reloaded.body.matches("![diagram]").count();
    assert_eq!(link_count, 1);
    assert!(
        reloaded
            .body
            .ends_with("fix-login-bug-assets/diagram.svg)\n")
    );
}

#[test]
fn add_asset_missing_issue_is_not_found() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let src = write_asset_source(&tmp, "x.png", b"x");
    let err = store.add_asset("missing.md", &src).unwrap_err();
    assert!(matches!(err, TixError::NotFound(_)));
}

#[test]
fn add_asset_legacy_flat_file_uses_stem_assets_under_issues_dir() {
    let (tmp, store) = make_store();
    write_issue_with_basic_body(&store, "2026-01-01-legacy.md", 1);
    let src = write_asset_source(&tmp, "x.png", b"x");
    let added = store.add_asset("2026-01-01-legacy.md", &src).unwrap();
    assert_eq!(added.link, "![x](legacy-assets/x.png)");
    assert!(store.issues_dir.join("legacy-assets/x.png").is_file());
}

// ------------------------------------------------------------------
// T005 — reassign() moves the assets dir (FR-007)
// ------------------------------------------------------------------

#[test]
fn reassign_moves_asset_dir_with_the_file() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    let src = write_asset_source(&tmp, "diagram.png", b"PNGDATA");
    store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    let new_path = store
        .reassign("alice/2026-01-01-fix-login-bug.md", Some("@bob"))
        .unwrap();
    assert_eq!(new_path, PathBuf::from("bob/2026-01-01-fix-login-bug.md"));
    assert!(
        store
            .issues_dir
            .join("bob/fix-login-bug-assets/diagram.png")
            .is_file()
    );
    assert!(!store.issues_dir.join("alice/fix-login-bug-assets").exists());
}

#[test]
fn reassign_without_asset_dir_behaves_as_before() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-plain.md", 1);
    let new_path = store
        .reassign("alice/2026-01-01-plain.md", Some("@bob"))
        .unwrap();
    assert_eq!(new_path, PathBuf::from("bob/2026-01-01-plain.md"));
    assert!(store.issues_dir.join("bob/2026-01-01-plain.md").is_file());
    assert!(!store.issues_dir.join("bob/plain-assets").exists());
}

#[test]
fn reassign_into_segment_with_same_named_asset_dir_uses_suffix_no_loss() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    fs::create_dir_all(store.issues_dir.join("bob")).unwrap();
    // Both segments already hold a same-named asset dir.
    let existing = store.issues_dir.join("bob/fix-login-bug-assets");
    fs::create_dir_all(&existing).unwrap();
    fs::write(existing.join("keep.txt"), "precious").unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    let src = write_asset_source(&tmp, "diagram.png", b"PNGDATA");
    store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    let new_path = store
        .reassign("alice/2026-01-01-fix-login-bug.md", Some("@bob"))
        .unwrap();
    assert_eq!(new_path, PathBuf::from("bob/2026-01-01-fix-login-bug.md"));
    // Pre-existing target assets untouched, moved dir suffixed.
    assert!(existing.join("keep.txt").is_file());
    assert!(
        store
            .issues_dir
            .join("bob/fix-login-bug-assets-1/diagram.png")
            .is_file()
    );
    assert!(!store.issues_dir.join("alice/fix-login-bug-assets").exists());
}

#[test]
fn reassign_preserves_markdown_link_resolution_in_new_segment() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    let src = write_asset_source(&tmp, "diagram.png", b"PNGDATA");
    store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    store
        .reassign("alice/2026-01-01-fix-login-bug.md", Some("@bob"))
        .unwrap();
    // The asset dir kept its base name, so the relative link
    // `fix-login-bug-assets/diagram.png` resolves in the new segment.
    assert!(
        store
            .issues_dir
            .join("bob/fix-login-bug-assets/diagram.png")
            .is_file()
    );
}

// ------------------------------------------------------------------
// T006 — delete() removes the assets dir (FR-008) + sweep
// ------------------------------------------------------------------

#[test]
fn delete_removes_asset_dir_no_orphans() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    let src = write_asset_source(&tmp, "x.png", b"x");
    store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    store.delete("alice/2026-01-01-fix-login-bug.md").unwrap();
    assert!(
        !store
            .issues_dir
            .join("alice/2026-01-01-fix-login-bug.md")
            .exists()
    );
    assert!(!store.issues_dir.join("alice/fix-login-bug-assets").exists());
}

#[test]
fn delete_without_asset_dir_still_deletes_file() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-plain.md", 1);
    store.delete("alice/2026-01-01-plain.md").unwrap();
    assert!(!store.issues_dir.join("alice/2026-01-01-plain.md").exists());
}

#[test]
fn list_ignores_asset_directories() {
    let (tmp, store) = make_store();
    write_issue_with_basic_body(&store, "2026-01-01-legacy.md", 1);
    let src = write_asset_source(&tmp, "x.png", b"x");
    store.add_asset("2026-01-01-legacy.md", &src).unwrap();
    // Legacy flat file → `legacy-assets/` sits directly under issues_dir,
    // where the `-assets` guard in `list()` must skip it.
    let issues = store.list().unwrap();
    assert_eq!(issues.len(), 1);
    assert_eq!(issues[0].filename, "2026-01-01-legacy.md");
}

#[test]
fn list_ignores_nested_asset_directories_under_segment() {
    let (tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    let src = write_asset_source(&tmp, "x.png", b"x");
    store
        .add_asset("alice/2026-01-01-fix-login-bug.md", &src)
        .unwrap();
    let issues = store.list().unwrap();
    assert_eq!(issues.len(), 1);
    assert_eq!(issues[0].filename, "alice/2026-01-01-fix-login-bug.md");
}

#[test]
fn asset_dir_with_formless_md_child_is_not_scanned_as_segment() {
    let (tmp, store) = make_store();
    let _ = tmp;
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue_with_basic_body(&store, "alice/2026-01-01-fix-login-bug.md", 1);
    // A `.md` straggler inside an `-assets` dir must never surface as an
    // issue segment (guard in `list()` for `<slug>-assets/`).
    let assets_dir = store.issues_dir.join("alice/fix-login-bug-assets");
    fs::create_dir_all(&assets_dir).unwrap();
    fs::write(assets_dir.join("notes.md"), "no frontmatter").unwrap();
    let issues = store.list().unwrap();
    assert_eq!(issues.len(), 1);
    assert_eq!(issues[0].filename, "alice/2026-01-01-fix-login-bug.md");
}

// -----------------------------------------------------------------------
// WP02 / T008 — hierarchy writes
// -----------------------------------------------------------------------
//
// 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), SC-004 (a rejected
// change writes nothing).
//
// These tests assert the *write* behaviour only. Every rule lives in
// `crate::hierarchy`; the last test below is the guard against one of them
// being copied in here.

/// Three seeded issues, for the hierarchy write tests.
fn hierarchy_trio() -> (TempDir, Store) {
    let (tmp, store) = make_store();
    for (n, title) in [(1, "A"), (2, "B"), (3, "C")] {
        write_issue(
            &store,
            &format!("2026-01-01-{}.md", title.to_lowercase()),
            &bare_frontmatter(n, title),
        );
    }
    (tmp, store)
}

/// A store over one checked-in hierarchy fixture, by file name.
///
/// `tests/fixtures/hierarchy/` rather than a string built inline, because the
/// interesting cases are exactly the states the command layer refuses to
/// create: a self-parent, a dangling reference. Those can only be reached by
/// writing the file, which is the point of the fixtures.
fn store_from_hierarchy_fixture(name: &str) -> (TempDir, Store) {
    let (tmp, store) = make_store();
    write_issue(
        &store,
        name,
        &std::fs::read_to_string(format!(
            "{}/tests/fixtures/hierarchy/{name}",
            env!("CARGO_MANIFEST_DIR")
        ))
        .unwrap(),
    );
    (tmp, store)
}

fn bytes_of(store: &Store, number: u32) -> String {
    let issue = store.get(IssueSelector::Number(number)).unwrap();
    read_issue_file(store, &issue.filename)
}

#[test]
fn t008_set_writes_the_field_and_exactly_one_history_event() {
    let (_tmp, store) = hierarchy_trio();
    let outcome = store.set_parent("2", "1").unwrap();
    assert!(outcome.changed);
    assert_eq!(outcome.parent, Some(1));

    let child = store.get(IssueSelector::Number(2)).unwrap();
    assert_eq!(
        child.parent,
        Some(crate::id::IssueRef::Number(1)),
        "the legacy numeric alias is readable"
    );
    assert_eq!(child.history.len(), 1, "C-004: exactly one event");
    let event = &child.history.events()[0];
    assert_eq!(event.kind, HistoryEventKind::ParentSet);
    assert!(
        !event.actor.is_empty(),
        "an event without an actor is not an audit record"
    );
    // The detail names both sides, read from the *previous* value.
    assert_eq!(event.detail, "parent none -> #1", "got: {}", event.detail);
}

#[test]
fn t008_change_repoints_and_records_parent_changed() {
    let (_tmp, store) = hierarchy_trio();
    store.set_parent("3", "1").unwrap();
    let outcome = store.change_parent("3", "2").unwrap();
    assert!(outcome.changed);
    assert_eq!(outcome.parent, Some(2));

    let child = store.get(IssueSelector::Number(3)).unwrap();
    assert_eq!(child.parent, Some(crate::id::IssueRef::Number(2)));
    assert_eq!(child.history.len(), 2, "one event per accepted change");
    let events = child.history.events();
    let last = events.last().unwrap();
    assert_eq!(last.kind, HistoryEventKind::ParentChanged);
    // Regression: the detail used to be built after the assignment, so a
    // repoint recorded `parent #1 -> #1` and named neither side.
    assert_eq!(last.detail, "parent #1 -> #2", "got: {}", last.detail);
}

#[test]
fn t008_clear_removes_the_field_and_records_parent_cleared() {
    let (_tmp, store) = hierarchy_trio();
    store.set_parent("2", "1").unwrap();
    let outcome = store.clear_parent("2").unwrap();
    assert!(outcome.changed);
    assert_eq!(outcome.parent, None);

    let child = store.get(IssueSelector::Number(2)).unwrap();
    assert_eq!(child.parent, None);
    assert_eq!(child.history.len(), 2);
    let events = child.history.events();
    let last = events.last().unwrap();
    assert_eq!(last.kind, HistoryEventKind::ParentCleared);
    assert_eq!(last.detail, "parent #1 -> none", "got: {}", last.detail);
}

#[test]
fn t008_reapplying_the_same_parent_is_a_no_op_with_no_second_event() {
    let (_tmp, store) = hierarchy_trio();
    store.set_parent("2", "1").unwrap();
    let after_first = bytes_of(&store, 2);

    let second = store.set_parent("2", "1").unwrap();
    assert!(!second.changed, "an unchanged parent is not a change");
    assert!(second.event.is_none(), "a no-op records nothing (C-004)");
    assert_eq!(
        bytes_of(&store, 2),
        after_first,
        "a no-op must not rewrite the file at all"
    );
}

#[test]
fn t008_clearing_a_child_with_no_parent_is_a_no_op() {
    let (_tmp, store) = hierarchy_trio();
    let before = bytes_of(&store, 2);
    let outcome = store.clear_parent("2").unwrap();
    assert!(!outcome.changed);
    assert!(outcome.event.is_none());
    assert_eq!(bytes_of(&store, 2), before);
}

#[test]
fn t008_sc004_a_rejected_cycle_leaves_every_file_byte_identical() {
    // 1 -> 2 -> 3, then ask 1 to become a child of 3: that closes the loop.
    let (_tmp, store) = hierarchy_trio();
    store.set_parent("2", "1").unwrap();
    store.set_parent("3", "2").unwrap();
    let before: Vec<String> = (1..=3).map(|n| bytes_of(&store, n)).collect();

    let err = store
        .set_parent("1", "3")
        .expect_err("1 -> 2 -> 3 -> 1 is a cycle and must be refused");
    let msg = err.to_string();
    assert!(
        msg.contains("cycle"),
        "the diagnostic must name the rule: {msg}"
    );

    // SC-004: nothing written, nothing appended, on *any* file.
    for n in 1..=3 {
        assert_eq!(
            bytes_of(&store, n),
            before[(n - 1) as usize],
            "issue {n} must be byte-identical after a rejected cycle"
        );
    }
}

#[test]
fn t008_a_self_parent_is_rejected_and_writes_nothing() {
    let (_tmp, store) = hierarchy_trio();
    let before = bytes_of(&store, 2);
    let err = store
        .set_parent("2", "2")
        .expect_err("an issue cannot be its own parent");
    assert!(err.to_string().contains("self_parent"), "got: {err}");
    assert_eq!(bytes_of(&store, 2), before);
}

#[test]
fn t008_a_self_parent_already_on_disk_is_still_refused() {
    // The laundering case, through the file path rather than the service.
    //
    // A child that *already* records itself as its own parent looks like a
    // redundant request, and a no-op check placed before validation accepted it
    // as one — while the identical request against any other child was refused.
    // Only a fixture in that state can catch it: the test above seeds a
    // parentless child, so the guard never fired.
    let (_tmp, store) = store_from_hierarchy_fixture("self-parent.md");
    let before = bytes_of(&store, 7);
    let err = store
        .set_parent("7", "7")
        .expect_err("a stored self-parent must still be refused on a re-set");
    assert!(
        err.to_string().contains("self_parent"),
        "refused for the wrong reason: {err}"
    );
    assert_eq!(
        bytes_of(&store, 7),
        before,
        "and the refused write must leave the file byte-identical"
    );
    // `change_parent` shares the path and must refuse identically.
    assert!(store.change_parent("7", "7").is_err());
    // The fixture really is in the state under test.
    assert_eq!(
        store.get(IssueSelector::Number(7)).unwrap().parent,
        Some(crate::id::IssueRef::Number(7))
    );
}

#[test]
fn t008_c003_setting_a_child_writes_nothing_to_the_parents_file() {
    // Child membership is derived by inverting the child's pointer; the
    // parent file must not learn about it at all.
    let (_tmp, store) = hierarchy_trio();
    let parent_before = bytes_of(&store, 1);
    store.set_parent("2", "1").unwrap();
    store.set_parent("3", "1").unwrap();
    assert_eq!(
        bytes_of(&store, 1),
        parent_before,
        "the parent's file must be untouched by its children appearing"
    );
    assert!(
        !parent_before.contains("parent:"),
        "the parent is a top of the hierarchy and has no parent itself"
    );
}

#[test]
fn t008_a_legacy_file_without_the_field_is_unchanged_by_a_no_op_write() {
    // The file-format contract, seen through the write path.
    let (_tmp, store) = hierarchy_trio();
    let before = bytes_of(&store, 2);
    assert!(!before.contains("parent:"), "the fixture must be legacy");

    store.clear_parent("2").unwrap();
    assert_eq!(bytes_of(&store, 2), before, "a no-op must not add the key");
}

#[test]
fn t008_an_unresolvable_selector_is_refused_before_any_write() {
    let (_tmp, store) = hierarchy_trio();
    let before = bytes_of(&store, 2);
    assert!(store.set_parent("2", "no such issue").is_err());
    assert!(store.change_parent("2", "999").is_err());
    assert_eq!(bytes_of(&store, 2), before);
}

#[test]
fn t008_t008_contains_no_hierarchy_rule_of_its_own() {
    // T008's own note: "Storage must contain no hierarchy *rules*. If a check
    // appears here that also exists in the service, that is a defect."
    //
    // Asserted behaviourally rather than by reading the source: a storage
    // rejection must be **exactly** what the service says for the same
    // snapshot. If someone re-implemented a rule here, the two would drift and
    // this comparison would stop holding.
    //
    // Compared against the service *type's own* rendering, reached through the
    // `From<HierarchyError> for TixError` conversion the call site uses. An
    // earlier version of this test compared storage against a private
    // `hierarchy_error` helper — both sides went through the same function, so
    // it certified only that the helper was called, and it could not detect the
    // duplication it was meant to police (a second renderer that had drifted
    // from the first).
    let (_tmp, store) = hierarchy_trio();
    store.set_parent("2", "1").unwrap();
    store.set_parent("3", "2").unwrap();

    let issues = store.list().unwrap();
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    let index = HierarchyIndex::build(&views);
    let service = hierarchy::set_parent(&index, 1, 3).expect_err("the service refuses this too");
    let storage = store.set_parent("1", "3").expect_err("and so does storage");

    assert_eq!(
        storage.to_string(),
        TixError::from(service).to_string(),
        "storage must surface the service's diagnosis verbatim, not its own"
    );
    // And the rendering is the shared one, not a lookalike: the kind is
    // prefixed exactly once and no diagnostic is dropped.
    let text = storage.to_string();
    assert!(
        text.contains("cycle:") && !text.contains("cycle: cycle:"),
        "a lookalike renderer or a doubled prefix: {text}"
    );
    assert!(
        text.starts_with("error[E-tix-hierarchy]: "),
        "a hierarchy refusal carries the shared rustc-style header: {text}"
    );
}

#[test]
fn t008_a_no_op_reports_no_written_issue_but_still_reports_the_current_parent() {
    // Pins the `ParentOutcome` contract, which its own doc comment used to
    // contradict: `written` is `None` for a no-op (matching
    // `RelationshipOutcome`), and the real state comes from `parent`.
    let (_tmp, store) = hierarchy_trio();
    store.set_parent("2", "1").unwrap();
    let again = store.set_parent("2", "1").unwrap();
    assert!(!again.changed);
    assert!(
        again.written.is_none(),
        "a no-op wrote nothing, so there is no written issue to hand back"
    );
    assert!(
        again.event.is_none(),
        "and no event, or a retry would pad the audit trail"
    );
    assert_eq!(
        again.parent,
        Some(1),
        "but the resulting state is still reported, so a caller need not re-read"
    );
}

// -----------------------------------------------------------------------
// tix #1541 — the command-level write transaction
// -----------------------------------------------------------------------

/// A failed transaction restores the bytes of **every** file it wrote, not
/// only the last. The intermediate write is the one a naive "undo the last
/// step" rollback would leave behind.
#[test]
fn a_failed_transaction_restores_every_file_it_touched() {
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    write_issue(
        &store,
        "2026-01-01-b.md",
        &sample_frontmatter(2, "B", "todo"),
    );
    let before_a = read_issue_file(&store, "2026-01-01-a.md");
    let before_b = read_issue_file(&store, "2026-01-01-b.md");

    let mut a = store.get(IssueSelector::Number(1)).unwrap();
    a.title = "Changed".into();
    let mut b = store.get(IssueSelector::Number(2)).unwrap();
    b.title = "Also changed".into();

    let err = store
        .transaction(|| {
            store.update("2026-01-01-a.md", &a)?;
            store.update("2026-01-01-b.md", &b)?;
            Err::<(), _>(TixError::InvalidInput("boom".into()))
        })
        .unwrap_err();

    assert!(err.to_string().contains("boom"), "got: {err}");
    assert_eq!(
        read_issue_file(&store, "2026-01-01-a.md"),
        before_a,
        "the first write must be undone too, not only the last"
    );
    assert_eq!(read_issue_file(&store, "2026-01-01-b.md"), before_b);
    assert_eq!(store.get(IssueSelector::Number(1)).unwrap().title, "A");
    assert_eq!(store.get(IssueSelector::Number(2)).unwrap().title, "B");
}

/// A transaction that returns `Ok` keeps its writes — the journal is taken
/// and discarded, never applied.
#[test]
fn a_committed_transaction_keeps_its_writes() {
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    let mut a = store.get(IssueSelector::Number(1)).unwrap();
    a.title = "Changed".into();

    store
        .transaction(|| {
            store.update("2026-01-01-a.md", &a)?;
            Ok(())
        })
        .unwrap();

    assert_eq!(
        store.get(IssueSelector::Number(1)).unwrap().title,
        "Changed"
    );
}

/// The window in #1302 was between two steps that touch *different paths*: a
/// reassign moves the file, then the content is written at the new path. A
/// rollback must undo both — move the file back **and** restore its bytes —
/// which only works if the journal records the pre-image of the original path
/// before the move and replays in reverse.
#[test]
fn a_failed_transaction_undoes_a_reassign_move_and_its_content_write() {
    let (_tmp, store) = make_store();
    fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
    write_issue(
        &store,
        "alice/2026-01-01-x.md",
        &sample_frontmatter(5, "X", "todo"),
    );
    let before = read_issue_file(&store, "alice/2026-01-01-x.md");

    let mut edited = store.get(IssueSelector::Number(5)).unwrap();
    edited.title = "Edited".into();

    let err = store
        .transaction(|| {
            let moved = store.reassign("alice/2026-01-01-x.md", Some("@bob"))?;
            store.update(&moved.to_string_lossy(), &edited)?;
            Err::<(), _>(TixError::InvalidInput("boom".into()))
        })
        .unwrap_err();

    assert!(err.to_string().contains("boom"));
    assert!(
        store.issues_dir.join("alice/2026-01-01-x.md").is_file(),
        "the moved file must be back under its original segment"
    );
    assert!(
        !store.issues_dir.join("bob/2026-01-01-x.md").exists(),
        "the moved copy must not survive the rollback"
    );
    assert_eq!(read_issue_file(&store, "alice/2026-01-01-x.md"), before);
}

/// A `delete` inside a failing transaction is undone, so the file is not lost.
#[test]
fn a_failed_transaction_restores_a_deleted_file() {
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    let before = read_issue_file(&store, "2026-01-01-a.md");

    let _ = store
        .transaction(|| {
            store.delete("2026-01-01-a.md")?;
            Err::<(), _>(TixError::InvalidInput("boom".into()))
        })
        .unwrap_err();

    assert!(store.issues_dir.join("2026-01-01-a.md").is_file());
    assert_eq!(read_issue_file(&store, "2026-01-01-a.md"), before);
}

/// A nested transaction joins the outer one: an inner failure rolls back the
/// work the outer transaction did *before* the inner call, because the outer
/// call owns the single journal. Without this a command that wraps another
/// transactional command would silently lose atomicity.
#[test]
fn a_nested_transaction_joins_the_outer_one() {
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    let before = read_issue_file(&store, "2026-01-01-a.md");
    let mut a = store.get(IssueSelector::Number(1)).unwrap();
    a.title = "Outer".into();
    let mut a2 = a.clone();
    a2.title = "Inner".into();

    let err = store
        .transaction(|| {
            store.update("2026-01-01-a.md", &a)?;
            // The inner call must NOT commit or clear the outer journal.
            store.transaction(|| {
                store.update("2026-01-01-a.md", &a2)?;
                Err::<(), _>(TixError::InvalidInput("inner boom".into()))
            })?;
            Ok(())
        })
        .unwrap_err();

    assert!(err.to_string().contains("inner boom"));
    assert_eq!(
        read_issue_file(&store, "2026-01-01-a.md"),
        before,
        "the outer write must also be undone, so the whole unit is atomic"
    );
}

/// Outside a transaction nothing is journaled: a write that is not wrapped
/// takes effect and stays.
#[test]
fn a_write_outside_a_transaction_is_not_journaled() {
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    let mut a = store.get(IssueSelector::Number(1)).unwrap();
    a.title = "Plain".into();
    store.update("2026-01-01-a.md", &a).unwrap();
    assert_eq!(store.get(IssueSelector::Number(1)).unwrap().title, "Plain");
}

// ------------------------------------------------------------------
// WP03 — project association writes (mission first-class-projects-01M3BYBW)
// ------------------------------------------------------------------

/// A store whose **persisted** registry declares project `p-1`, holding issue #1.
///
/// `p-1` is written to `tix.toml`, unlike the in-memory fixtures elsewhere, so
/// the negative assertion below compares a real registry file before and after.
fn project_store() -> (TempDir, Store) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let mut config = Config {
        issues_dir: dir.clone(),
        ..Config::default()
    };
    config.layout.directory = "{assignee}".to_string();
    config.layout.move_on_change = false;
    config.projects.insert(
        "p-1".to_string(),
        ProjectConfiguration {
            name: "One".into(),
            ..ProjectConfiguration::default()
        },
    );
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let store = Store {
        issues_dir: dir,
        config,
    };
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    (tmp, store)
}

/// The issue as written to disk, not as it was held in memory.
fn reloaded(store: &Store, filename: &str) -> Issue {
    store
        .get(IssueSelector::Filename(filename.to_string()))
        .unwrap()
}

/// A fixture from `tests/fixtures/projects/`, read from the crate root so the
/// path is independent of the test's working directory.
fn project_fixture(name: &str) -> String {
    let path = format!(
        "{}/tests/fixtures/projects/{name}",
        env!("CARGO_MANIFEST_DIR")
    );
    fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading fixture {name}: {e}"))
}

/// Every fixture, sorted, so a new one is picked up without editing a list.
fn all_project_fixtures() -> Vec<String> {
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/projects");
    let mut names: Vec<String> = fs::read_dir(&dir)
        .unwrap()
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .filter(|name| name.ends_with(".md"))
        .collect();
    names.sort();
    names
}

#[test]
fn t013_an_accepted_association_writes_the_list_and_exactly_one_history_entry() {
    let (_tmp, store) = project_store();
    let before = read_issue_file(&store, "2026-01-01-a.md");
    let outcome = store.associate("1", "p-1").unwrap();

    assert!(outcome.changed, "an accepted, changing association writes");
    assert!(outcome.written.is_some());
    assert_eq!(outcome.project_ids, vec!["p-1".to_string()]);
    let event = outcome
        .event
        .clone()
        .expect("an accepted change is audited");
    assert_eq!(event.detail, "project `p-1` associated");

    // Re-read from disk: the in-memory record is not evidence of what landed.
    let after = reloaded(&store, "2026-01-01-a.md");
    assert_eq!(after.projects, Some(vec!["p-1".to_string()]));
    let events = after.history.events();
    assert_eq!(events.len(), 1, "exactly one History entry: {events:?}");
    assert_eq!(events[0].kind, HistoryEventKind::ProjectAssociated);
    assert_eq!(events[0].detail, "project `p-1` associated");
    assert_ne!(
        read_issue_file(&store, "2026-01-01-a.md"),
        before,
        "an accepted change is written"
    );
}

#[test]
fn t013_a_refused_association_writes_nothing_and_appends_nothing() {
    let (_tmp, store) = project_store();
    let before = read_issue_file(&store, "2026-01-01-a.md");

    let err = store.associate("1", "p-unknown").unwrap_err();
    assert!(
        matches!(err, TixError::InvalidInput(_)),
        "an unknown project is a user input refusal, got {err:?}"
    );
    assert_eq!(
        read_issue_file(&store, "2026-01-01-a.md"),
        before,
        "a refusal must leave the file byte-identical"
    );
    assert!(
        reloaded(&store, "2026-01-01-a.md").history.is_empty(),
        "a refusal must append nothing"
    );

    // An unknown issue selector is refused too, and also writes nothing.
    let err = store.associate("999", "p-1").unwrap_err();
    assert!(matches!(err, TixError::NotFound(_)), "got {err:?}");
    assert_eq!(read_issue_file(&store, "2026-01-01-a.md"), before);
}

#[test]
fn t013_a_refusal_reports_the_service_wording_not_a_storage_copy() {
    // Cross-checker (8): storage holds no project rule, so a refusal must be the
    // service's own diagnostic. A second wording here would be a second rule.
    let (_tmp, store) = project_store();
    let err = store.associate("1", "p-unknown").unwrap_err();
    assert!(
        err.to_string()
            .contains(&crate::projects::unknown_project_reason("p-unknown")),
        "the refusal must come from the service, got: {err}"
    );
}

#[test]
fn t013_re_associating_is_idempotent_no_second_entry_and_no_second_event() {
    let (_tmp, store) = project_store();
    store.associate("1", "p-1").unwrap();
    let after_first = read_issue_file(&store, "2026-01-01-a.md");

    let second = store.associate("1", "p-1").unwrap();
    assert!(!second.changed, "the idempotent re-apply changes nothing");
    assert!(second.written.is_none(), "and writes no file");
    assert!(second.event.is_none(), "and appends no event");
    assert_eq!(second.project_ids, vec!["p-1".to_string()]);
    assert_eq!(
        read_issue_file(&store, "2026-01-01-a.md"),
        after_first,
        "the file is byte-identical after a repeated association"
    );

    let after = reloaded(&store, "2026-01-01-a.md");
    assert_eq!(after.history.events().len(), 1, "no second History event");
    assert_eq!(
        after.projects,
        Some(vec!["p-1".to_string()]),
        "and no duplicate entry: (issue, project_id) is unique"
    );
}

#[test]
fn t013_dissociate_drops_only_the_association_and_records_one_event() {
    let (_tmp, store) = project_store();
    store.associate("1", "p-1").unwrap();

    let outcome = store.dissociate("1", "p-1").unwrap();
    assert!(outcome.changed);
    assert_eq!(outcome.project_ids, [] as [std::string::String; 0]);
    let event = outcome
        .event
        .clone()
        .expect("an accepted change is audited");
    assert_eq!(event.detail, "project `p-1` dissociated");

    let after = reloaded(&store, "2026-01-01-a.md");
    assert_eq!(after.projects, None, "the association is dropped");
    assert!(
        !read_issue_file(&store, "2026-01-01-a.md").contains("projects:"),
        "an empty list is written as an absent key"
    );
    let events = after.history.events();
    assert_eq!(events.len(), 2, "associate + dissociate = two entries");
    assert_eq!(events[1].kind, HistoryEventKind::ProjectDissociated);

    // Dissociating an absent association is an idempotent no-op.
    let again = store.dissociate("1", "p-1").unwrap();
    assert!(!again.changed);
    assert!(again.event.is_none());
    assert_eq!(
        reloaded(&store, "2026-01-01-a.md").history.events().len(),
        2,
        "no third History event"
    );
}

#[test]
fn t013_bulk_associate_writes_each_affected_file_independently() {
    let (_tmp, store) = project_store();
    write_issue(
        &store,
        "2026-01-01-b.md",
        &sample_frontmatter(2, "B", "todo"),
    );

    let outcomes = store
        .bulk_associate(
            "p-1",
            &["1".to_string(), "999".to_string(), "2".to_string()],
        )
        .unwrap();

    assert_eq!(outcomes.len(), 3, "one entry per selector, in input order");
    assert_eq!(outcomes[0].selector, "1");
    assert!(outcomes[0].outcome.as_ref().unwrap().changed);
    assert!(
        outcomes[1].outcome.is_err(),
        "a bad selector is its own error, not a failure of the run"
    );
    assert!(outcomes[2].outcome.as_ref().unwrap().changed);

    for filename in ["2026-01-01-a.md", "2026-01-01-b.md"] {
        let issue = reloaded(&store, filename);
        assert_eq!(issue.projects, Some(vec!["p-1".to_string()]));
        assert_eq!(issue.history.events().len(), 1, "{filename}");
    }

    // An unknown project refuses the entry without writing the file.
    write_issue(
        &store,
        "2026-01-01-c.md",
        &sample_frontmatter(3, "C", "todo"),
    );
    let before = read_issue_file(&store, "2026-01-01-c.md");
    let refused = store
        .bulk_associate("p-unknown", &["3".to_string()])
        .unwrap();
    assert!(refused[0].outcome.is_err());
    assert_eq!(read_issue_file(&store, "2026-01-01-c.md"), before);
}

#[test]
fn t013_bulk_associate_is_idempotent_across_two_selectors_for_one_issue() {
    // Regression: the same issue named by number and by filename. Applying both
    // against one immutable read made the second miss the first write and append
    // a second `project_associated` event; the working copy means the second
    // selector sees the association and reports the service's no-op.
    let (_tmp, store) = project_store();
    let outcomes = store
        .bulk_associate("p-1", &["1".to_string(), "2026-01-01-a.md".to_string()])
        .unwrap();
    assert_eq!(outcomes.len(), 2, "one entry per selector, in input order");

    let first = outcomes[0].outcome.as_ref().unwrap();
    assert!(first.changed, "the first selector writes");
    assert!(first.written.is_some());
    assert!(first.event.is_some(), "and appends its one event");

    let second = outcomes[1].outcome.as_ref().unwrap();
    assert!(
        !second.changed,
        "the repeated selector is the idempotent no-op"
    );
    assert!(second.written.is_none(), "and writes nothing a second time");
    assert!(second.event.is_none(), "and appends no second event");
    assert_eq!(
        second.project_ids,
        vec!["p-1".to_string()],
        "and still reports the current list"
    );

    let after = reloaded(&store, "2026-01-01-a.md");
    assert_eq!(after.projects, Some(vec!["p-1".to_string()]));
    assert_eq!(
        after.history.events().len(),
        1,
        "exactly one History entry across both selectors"
    );
}

#[test]
fn t014_nfr_002_every_project_fixture_round_trips_with_no_key_added_removed_or_reordered() {
    let names = all_project_fixtures();
    for required in [
        "no-associations.md",
        "one-association.md",
        "several-associations.md",
        "missing-reference.md",
        "legacy-no-key.md",
    ] {
        assert!(
            names.iter().any(|name| name == required),
            "the fixture set must cover every shape T014 names; {required} is missing from {names:?}"
        );
    }
    for name in names {
        let original = project_fixture(&name);
        let issue = Issue::parse(&original).expect("fixture parses");
        assert_eq!(
            issue.to_file_contents(),
            original,
            "{name} must round-trip byte-identically"
        );
        assert_eq!(
            Issue::parse(&issue.to_file_contents())
                .unwrap()
                .to_file_contents(),
            original,
            "{name} must be byte-stable once re-read"
        );
    }
}

#[test]
fn t014_nfr_002_a_legacy_fixture_gains_no_projects_key() {
    let original = project_fixture("legacy-no-key.md");
    assert!(!original.contains("projects:"));
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(issue.projects, None);
    assert_eq!(
        issue.to_file_contents(),
        original,
        "a pre-project file must not gain a key"
    );
}

#[test]
fn t014_c_003_a_multi_membership_fixture_is_byte_stable_and_ordered() {
    let original = project_fixture("several-associations.md");
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(
        issue.projects,
        Some(vec![
            "p-platform".to_string(),
            "p-docs".to_string(),
            "p-infra".to_string()
        ]),
        "declaration order is preserved (NFR-002)"
    );
    assert_eq!(issue.to_file_contents(), original);
}

#[test]
fn t014_c_005_a_missing_reference_round_trips_through_a_store_unchanged() {
    // The registry declares no projects, so `p-deleted` cannot resolve. A loader
    // that "helpfully" dropped an unknown id would fail here and nowhere else.
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "missing-reference.md",
        &project_fixture("missing-reference.md"),
    );
    assert!(
        store.config.projects.is_empty(),
        "the reference is missing by construction"
    );

    let issue = store.get(IssueSelector::Number(4)).unwrap();
    assert_eq!(issue.projects, Some(vec!["p-deleted".to_string()]));

    // Save the issue unchanged, then re-read: the id is still there.
    store.update(&issue.filename, &issue).unwrap();
    assert_eq!(
        read_issue_file(&store, "missing-reference.md"),
        project_fixture("missing-reference.md"),
        "saving a missing reference must not drop or rewrite it"
    );
    let reloaded_issue = store.get(IssueSelector::Number(4)).unwrap();
    assert_eq!(reloaded_issue.projects, Some(vec!["p-deleted".to_string()]));
}

#[test]
fn t014_c_003_associating_an_issue_writes_no_member_list_to_the_registry() {
    let (tmp, store) = project_store();
    let config_path = tmp.path().join("tix.toml");
    let before = fs::read_to_string(&config_path).unwrap();
    assert!(
        before.contains("[projects.p-1]"),
        "the record is persisted before the association: {before}"
    );

    store.associate("1", "p-1").unwrap();

    let after = fs::read_to_string(&config_path).unwrap();
    assert_eq!(
        after, before,
        "the project's registry record must not grow a member list"
    );
    assert!(
        !after.contains("members"),
        "membership is derived, never stored on the project:\n{after}"
    );
}

// ------------------------------------------------------------------
// WP03 — epic reference writes (mission epics-work-items-01M3BYW4)
// ------------------------------------------------------------------

/// A store whose **persisted** registry declares epic `e-7c4a91`, holding
/// issue #1.
///
/// The epic is written to `tix.toml`, unlike the in-memory fixtures elsewhere,
/// so the negative assertion below compares a real registry file before and
/// after.
fn epic_store() -> (TempDir, Store) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let mut config = Config {
        issues_dir: dir.clone(),
        ..Config::default()
    };
    config.layout.directory = "{assignee}".to_string();
    config.layout.move_on_change = false;
    config.epics.insert(
        "e-7c4a91".to_string(),
        EpicConfiguration {
            name: "One".into(),
            ..EpicConfiguration::default()
        },
    );
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let store = Store {
        issues_dir: dir,
        config,
    };
    write_issue(
        &store,
        "2026-01-01-a.md",
        &sample_frontmatter(1, "A", "todo"),
    );
    (tmp, store)
}

/// A fixture from `tests/fixtures/epics/`, read from the crate root so the path
/// is independent of the test's working directory.
fn epic_fixture(name: &str) -> String {
    let path = format!("{}/tests/fixtures/epics/{name}", env!("CARGO_MANIFEST_DIR"));
    fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading fixture {name}: {e}"))
}

/// Every fixture, sorted, so a new one is picked up without editing a list.
fn all_epic_fixtures() -> Vec<String> {
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/epics");
    let mut names: Vec<String> = fs::read_dir(&dir)
        .unwrap()
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .filter(|name| name.ends_with(".md"))
        .collect();
    names.sort();
    names
}

#[test]
fn t015_an_accepted_reference_writes_the_list_and_exactly_one_history_entry() {
    let (_tmp, store) = epic_store();
    let before = read_issue_file(&store, "2026-01-01-a.md");
    let outcome = store.reference_epic("1", "e-7c4a91").unwrap();

    assert!(outcome.changed, "an accepted, changing reference writes");
    assert!(outcome.written.is_some());
    assert_eq!(outcome.epic_ids, vec!["e-7c4a91".to_string()]);
    let event = outcome
        .event
        .clone()
        .expect("an accepted change is audited");
    assert_eq!(event.detail, "epic `e-7c4a91` referenced");

    // Re-read from disk: the in-memory record is not evidence of what landed.
    let after = reloaded(&store, "2026-01-01-a.md");
    assert_eq!(after.epics, Some(vec!["e-7c4a91".to_string()]));
    let events = after.history.events();
    assert_eq!(events.len(), 1, "exactly one History entry: {events:?}");
    assert_eq!(events[0].kind, HistoryEventKind::EpicReferenced);
    assert_eq!(events[0].detail, "epic `e-7c4a91` referenced");
    assert_ne!(
        read_issue_file(&store, "2026-01-01-a.md"),
        before,
        "an accepted change is written"
    );
}

#[test]
fn t015_a_refused_reference_writes_nothing_and_appends_nothing() {
    let (_tmp, store) = epic_store();
    let before = read_issue_file(&store, "2026-01-01-a.md");

    let err = store.reference_epic("1", "e-unknown").unwrap_err();
    assert!(
        matches!(err, TixError::InvalidInput(_)),
        "an unknown epic is a user input refusal, got {err:?}"
    );
    assert_eq!(
        read_issue_file(&store, "2026-01-01-a.md"),
        before,
        "a refusal must leave the file byte-identical"
    );
    assert!(
        reloaded(&store, "2026-01-01-a.md").history.is_empty(),
        "a refusal must append nothing"
    );

    // An unknown issue selector is refused too, and also writes nothing.
    let err = store.reference_epic("999", "e-7c4a91").unwrap_err();
    assert!(matches!(err, TixError::NotFound(_)), "got {err:?}");
    assert_eq!(read_issue_file(&store, "2026-01-01-a.md"), before);
}

#[test]
fn t015_a_refusal_reports_the_service_wording_not_a_storage_copy() {
    // Storage holds no epic rule, so a refusal must be the service's own
    // diagnostic. A second wording here would be a second rule.
    let (_tmp, store) = epic_store();
    let err = store.reference_epic("1", "e-unknown").unwrap_err();
    assert!(
        err.to_string()
            .contains(&crate::epics::unknown_epic_reason("e-unknown")),
        "the refusal must come from the service, got: {err}"
    );
}

#[test]
fn t015_re_referencing_is_idempotent_no_second_entry_and_no_second_event() {
    let (_tmp, store) = epic_store();
    store.reference_epic("1", "e-7c4a91").unwrap();
    let after_first = read_issue_file(&store, "2026-01-01-a.md");

    let second = store.reference_epic("1", "e-7c4a91").unwrap();
    assert!(!second.changed, "the idempotent re-apply changes nothing");
    assert!(second.written.is_none(), "and writes no file");
    assert!(second.event.is_none(), "and appends no event");
    assert_eq!(second.epic_ids, vec!["e-7c4a91".to_string()]);
    assert_eq!(
        read_issue_file(&store, "2026-01-01-a.md"),
        after_first,
        "the file is byte-identical after a repeated reference"
    );

    let after = reloaded(&store, "2026-01-01-a.md");
    assert_eq!(after.history.events().len(), 1, "no second History event");
    assert_eq!(
        after.epics,
        Some(vec!["e-7c4a91".to_string()]),
        "and no duplicate entry: (issue, epic_id) is unique"
    );
}

#[test]
fn t015_dereference_drops_only_the_reference_and_records_one_event() {
    let (_tmp, store) = epic_store();
    store.reference_epic("1", "e-7c4a91").unwrap();

    let outcome = store.dereference_epic("1", "e-7c4a91").unwrap();
    assert!(outcome.changed);
    assert_eq!(outcome.epic_ids, [] as [std::string::String; 0]);
    let event = outcome
        .event
        .clone()
        .expect("an accepted change is audited");
    assert_eq!(event.detail, "epic `e-7c4a91` dereferenced");

    let after = reloaded(&store, "2026-01-01-a.md");
    assert_eq!(after.epics, None, "the reference is dropped");
    assert!(
        !read_issue_file(&store, "2026-01-01-a.md").contains("epics:"),
        "an empty list is written as an absent key"
    );
    let events = after.history.events();
    assert_eq!(events.len(), 2, "reference + dereference = two entries");
    assert_eq!(events[1].kind, HistoryEventKind::EpicDereferenced);

    // Dereferencing an absent reference is an idempotent no-op.
    let again = store.dereference_epic("1", "e-7c4a91").unwrap();
    assert!(!again.changed);
    assert!(again.event.is_none());
    assert_eq!(
        reloaded(&store, "2026-01-01-a.md").history.events().len(),
        2,
        "no third History event"
    );
}

#[test]
fn t015_dereference_retains_a_missing_reference_and_removes_it_verbatim() {
    // The repair path: a stored id that is no longer a valid shape or no longer
    // in the registry is removed by verbatim comparison, not by resolution.
    let (_tmp, store) = epic_store();
    write_issue(
        &store,
        "2026-01-01-b.md",
        "---\nnumber: 2\ntitle: B\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\nepics:\n- e-deleted\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.",
    );
    let outcome = store.dereference_epic("2", "e-deleted").unwrap();
    assert!(outcome.changed, "a stale reference is removable");
    assert_eq!(outcome.epic_ids, [] as [std::string::String; 0]);
    assert_eq!(reloaded(&store, "2026-01-01-b.md").epics, None);
}

#[test]
fn t015_bulk_reference_writes_each_affected_file_independently() {
    let (_tmp, store) = epic_store();
    write_issue(
        &store,
        "2026-01-01-b.md",
        &sample_frontmatter(2, "B", "todo"),
    );

    let outcomes = store
        .bulk_reference(
            "e-7c4a91",
            &["1".to_string(), "999".to_string(), "2".to_string()],
        )
        .unwrap();

    assert_eq!(outcomes.len(), 3, "one entry per selector, in input order");
    assert_eq!(outcomes[0].selector, "1");
    assert!(outcomes[0].outcome.as_ref().unwrap().changed);
    assert!(
        outcomes[1].outcome.is_err(),
        "a bad selector is its own error, not a failure of the run"
    );
    assert!(outcomes[2].outcome.as_ref().unwrap().changed);

    for filename in ["2026-01-01-a.md", "2026-01-01-b.md"] {
        let issue = reloaded(&store, filename);
        assert_eq!(issue.epics, Some(vec!["e-7c4a91".to_string()]));
        assert_eq!(issue.history.events().len(), 1, "{filename}");
    }

    // An unknown epic refuses the entry without writing the file.
    write_issue(
        &store,
        "2026-01-01-c.md",
        &sample_frontmatter(3, "C", "todo"),
    );
    let before = read_issue_file(&store, "2026-01-01-c.md");
    let refused = store
        .bulk_reference("e-unknown", &["3".to_string()])
        .unwrap();
    assert!(refused[0].outcome.is_err());
    assert_eq!(read_issue_file(&store, "2026-01-01-c.md"), before);
}

#[test]
fn t015_bulk_reference_is_idempotent_across_two_selectors_for_one_issue() {
    // Regression guard, mirrored from the project path: the same issue named by
    // number and by filename must not append a second `epic_referenced` event.
    let (_tmp, store) = epic_store();
    let outcomes = store
        .bulk_reference(
            "e-7c4a91",
            &["1".to_string(), "2026-01-01-a.md".to_string()],
        )
        .unwrap();
    assert_eq!(outcomes.len(), 2, "one entry per selector, in input order");

    let first = outcomes[0].outcome.as_ref().unwrap();
    assert!(first.changed, "the first selector writes");
    assert!(first.written.is_some());
    assert!(first.event.is_some(), "and appends its one event");

    let second = outcomes[1].outcome.as_ref().unwrap();
    assert!(
        !second.changed,
        "the repeated selector is the idempotent no-op"
    );
    assert!(second.written.is_none(), "and writes nothing a second time");
    assert!(second.event.is_none(), "and appends no second event");
    assert_eq!(
        second.epic_ids,
        vec!["e-7c4a91".to_string()],
        "and still reports the current list"
    );

    let after = reloaded(&store, "2026-01-01-a.md");
    assert_eq!(after.epics, Some(vec!["e-7c4a91".to_string()]));
    assert_eq!(
        after.history.events().len(),
        1,
        "exactly one History entry across both selectors"
    );
}

#[test]
fn t016_nfr_002_every_epic_fixture_round_trips_with_no_key_added_removed_or_reordered() {
    let names = all_epic_fixtures();
    for required in [
        "no-references.md",
        "one-reference.md",
        "several-references.md",
        "missing-reference.md",
        "legacy-no-key.md",
        "task-labelled.md",
    ] {
        assert!(
            names.iter().any(|name| name == required),
            "the fixture set must cover every shape T016 names; {required} is missing from {names:?}"
        );
    }
    for name in names {
        let original = epic_fixture(&name);
        let issue = Issue::parse(&original).expect("fixture parses");
        assert_eq!(
            issue.to_file_contents(),
            original,
            "{name} must round-trip byte-identically"
        );
        assert_eq!(
            Issue::parse(&issue.to_file_contents())
                .unwrap()
                .to_file_contents(),
            original,
            "{name} must be byte-stable once re-read"
        );
    }
}

#[test]
fn t016_nfr_002_a_legacy_fixture_gains_no_epics_key() {
    let original = epic_fixture("legacy-no-key.md");
    assert!(!original.contains("epics:"));
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(issue.epics, None);
    assert_eq!(
        issue.to_file_contents(),
        original,
        "a pre-epic file must not gain a key"
    );
}

#[test]
fn t016_c_003_a_multi_reference_fixture_is_byte_stable_and_ordered() {
    let original = epic_fixture("several-references.md");
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(
        issue.epics,
        Some(vec![
            "e-platform".to_string(),
            "e-docs".to_string(),
            "e-infra".to_string()
        ]),
        "declaration order is preserved (NFR-002)"
    );
    assert_eq!(issue.to_file_contents(), original);
}

#[test]
fn t016_c_005_a_missing_reference_round_trips_through_a_store_unchanged() {
    // The registry declares no epics, so `e-deleted` cannot resolve. A loader
    // that "helpfully" dropped an unknown id would fail here and nowhere else.
    let (_tmp, store) = make_store();
    write_issue(
        &store,
        "missing-reference.md",
        &epic_fixture("missing-reference.md"),
    );
    assert!(
        store.config.epics.is_empty(),
        "the reference is missing by construction"
    );

    let issue = store.get(IssueSelector::Number(4)).unwrap();
    assert_eq!(issue.epics, Some(vec!["e-deleted".to_string()]));

    // Save the issue unchanged, then re-read: the id is still there.
    store.update(&issue.filename, &issue).unwrap();
    assert_eq!(
        read_issue_file(&store, "missing-reference.md"),
        epic_fixture("missing-reference.md"),
        "saving a missing reference must not drop or rewrite it"
    );
    let reloaded_issue = store.get(IssueSelector::Number(4)).unwrap();
    assert_eq!(reloaded_issue.epics, Some(vec!["e-deleted".to_string()]));
}

#[test]
fn t016_c_001_a_task_labelled_fixture_round_trips_and_gains_no_task_key() {
    // Tasks are issues (C-001): a `task` label and the Spec Kitty `task`
    // pointer create no new entity and no new key. This field must not have
    // introduced a `task`/`work_item`/`epic_task` key.
    let original = epic_fixture("task-labelled.md");
    let issue = Issue::parse(&original).unwrap();
    assert_eq!(issue.epics, Some(vec!["e-7c4a91".to_string()]));
    assert_eq!(issue.task, Some("WP03".to_string()));

    let rendered = issue.to_file_contents();
    assert_eq!(rendered, original, "the fixture round-trips unchanged");
    assert_eq!(
        rendered.matches("task:").count(),
        1,
        "exactly one `task:` key — the Spec Kitty pointer, never a second:\n{rendered}"
    );
    for forbidden in ["work_item:", "epic_task:"] {
        assert!(
            !rendered.contains(forbidden),
            "`{forbidden}` must not exist (C-001):\n{rendered}"
        );
    }
}

#[test]
fn t016_c_003_referencing_an_issue_writes_no_member_list_to_the_registry() {
    let (tmp, store) = epic_store();
    let config_path = tmp.path().join("tix.toml");
    let before = fs::read_to_string(&config_path).unwrap();
    assert!(
        before.contains("[epics") && before.contains("e-7c4a91"),
        "the record is persisted before the reference: {before}"
    );

    store.reference_epic("1", "e-7c4a91").unwrap();

    let after = fs::read_to_string(&config_path).unwrap();
    assert_eq!(
        after, before,
        "the epic's registry record must not grow a member list"
    );
    assert!(
        !after.contains("members"),
        "membership is derived, never stored on the epic:\n{after}"
    );
}

#[test]
fn every_issue_write_seam_records_the_paths_the_tui_must_refresh() {
    let (_tmp, store) = make_store();
    let mut issue = crate::model::Issue::parse(&sample_frontmatter(1, "A", "todo"))
        .expect("the fixture parses");
    store.create(&mut issue, "Body", None).unwrap();
    let created = issue.filename.clone();
    match take_internal_issue_writes() {
        InternalIssueWrites::Delta(delta) => {
            assert_eq!(delta.changed, vec![std::path::PathBuf::from(&created)]);
            assert_eq!(delta.removed, [] as [std::path::PathBuf; 0]);
        }
        other => panic!("create did not journal one changed path: {other:?}"),
    }

    issue.title = "A edited".into();
    store.update(&created, &issue).unwrap();
    match take_internal_issue_writes() {
        InternalIssueWrites::Delta(delta) => {
            assert_eq!(delta.changed, vec![std::path::PathBuf::from(&created)]);
            assert_eq!(delta.removed, [] as [std::path::PathBuf; 0]);
        }
        other => panic!("update did not journal one changed path: {other:?}"),
    }

    store.delete(&issue.filename).unwrap();
    match take_internal_issue_writes() {
        InternalIssueWrites::Delta(delta) => {
            assert_eq!(delta.changed, [] as [std::path::PathBuf; 0]);
            assert_eq!(
                delta.removed,
                vec![std::path::PathBuf::from(&issue.filename)]
            );
        }
        other => panic!("delete did not journal one removed path: {other:?}"),
    }
}

#[test]
fn the_internal_write_journal_is_bounded_and_falls_back_to_a_rebuild() {
    take_internal_issue_writes();
    for number in 0..=ISSUE_WRITE_JOURNAL_LIMIT {
        journal_issue_change(std::path::Path::new(&format!("{number}.md")), true);
    }
    assert!(matches!(
        take_internal_issue_writes(),
        InternalIssueWrites::Overflow
    ));
    assert!(matches!(
        take_internal_issue_writes(),
        InternalIssueWrites::None
    ));
}