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
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
//! End-to-end CLI contract tests (`contracts/cli.md`), driven through the
//! compiled binary only — never through library calls. Deterministic within
//! run time: filenames are asserted on their slug suffix (the date prefix is
//! dynamic), and every interaction avoids stdin TTYs (`assert_cmd` pipes).

use std::fs;
use std::path::{Path, PathBuf};

use assert_cmd::Command;
use predicates::prelude::*;
use tempfile::TempDir;

fn tix() -> Command {
    Command::cargo_bin("tix").unwrap()
}

/// Run `tix init` in dir and fetch the single issue file created by the next
/// `create`. Returns the issue file path.
///
/// Post-WP02 the layout is assignee-grouped: files live one level deep
/// (`docs/issues/<segment>/<stem>.md`, `unassigned/` for no assignee), with
/// legacy flat files at the top level still supported (C-010). The scan walks
/// exactly that one segment level plus the flat root, so a create landing in
/// `alice/…` and one landing in `unassigned/…` are both found.
fn issue_file(dir: &std::path::Path) -> PathBuf {
    let issues = dir.join("docs").join("issues");
    let mut md: Vec<PathBuf> = Vec::new();
    // Recursive: the configurable layout (`[layout].directory`) may nest to any
    // depth, default `{assignee}/{type}/{status}`.
    walk(&issues, &mut md);
    assert_eq!(
        md.len(),
        1,
        "expected exactly one issue file in {}",
        issues.display()
    );
    md.swap_remove(0)
}

fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
    for entry in fs::read_dir(dir).unwrap() {
        let path = entry.unwrap().path();
        let name = path.file_name().unwrap().to_string_lossy().to_string();
        if path.is_dir() {
            if name.starts_with('.') || name.starts_with(".tix-tmp-") || name.ends_with("-assets") {
                continue;
            }
            walk(&path, out);
        } else if path.extension().is_some_and(|e| e == "md") {
            out.push(path);
        }
    }
}

/// Every `.md` issue file under `dir`, recursively and sorted.
fn issue_files_under(dir: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    walk(dir, &mut out);
    out.sort();
    out
}

/// The relative issue path `tix create` prints on success (`Created <rel>`),
/// e.g. `alice/2026-09-13-fix-login.md` (IC-03).
fn created_relative(out: &[u8]) -> String {
    let stdout = String::from_utf8(out.to_vec()).unwrap();
    stdout
        .lines()
        .map(str::trim)
        .find_map(|l| l.strip_prefix("Created "))
        .unwrap_or_else(|| panic!("no `Created ` line in {stdout:?}"))
        .to_string()
}

/// Run `git` inside `dir` for a hermetic local author identity, and assert it
/// succeeded. Local repo config always beats any global config, so the test
/// is deterministic regardless of the machine's ~/.gitconfig.
fn git(dir: &std::path::Path, args: &[&str]) {
    let status = std::process::Command::new("git")
        .current_dir(dir)
        .args(args)
        .status()
        .expect("`git` must be available to run the CLI tests");
    assert!(status.success(), "git {args:?} failed");
}

#[test]
fn cli_list_columns_selects_order_and_rejects_invalid_values() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Selected title"])
        .assert()
        .success();

    let output = tix()
        .current_dir(dir)
        // `--all`: the default listing is scoped to *your* issues in the board's
        // entry column (#1711), and this test is about `--columns`.
        .args(["list", "--all", "--columns", "title, num"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let output = String::from_utf8(output).unwrap();
    let header = output.lines().next().unwrap();
    assert!(header.starts_with("TITLE"));
    assert!(!header.contains("STATUS"));
    assert!(output.contains("Selected title"));

    tix()
        .current_dir(dir)
        .args(["list", "--all", "--columns", "title, bogus"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown list column"));
}

/// #1584: a relative `issues_dir` in `tix.toml` is resolved against the
/// **project root** — the directory holding `tix.toml` — not the invocation
/// directory. Before this, launching tix from a nested subdirectory read
/// `<subdir>/docs/issues`, found nothing, and silently created an empty tree
/// there. The same `Store::open` backs `tix`, `tix new`, `tix mcp` and
/// `tix render`, so `render` is the headless witness.
#[test]
fn cli_reads_the_same_issues_from_any_subdirectory() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Nested read"])
        .assert()
        .success();

    let nested = dir.join("a").join("b");
    fs::create_dir_all(&nested).unwrap();

    // Positive control: from the root the card is on the board.
    tix()
        .current_dir(dir)
        .arg("render")
        .assert()
        .success()
        .stdout(predicate::str::contains("Nested read"));
    // And from a nested subdirectory it must be the same board, not an empty one.
    tix()
        .current_dir(&nested)
        .arg("render")
        .assert()
        .success()
        .stdout(predicate::str::contains("Nested read"));
    // No spurious `docs/issues` tree was created under the subdirectory.
    assert!(
        !nested.join("docs").exists(),
        "the store must resolve to the project root, not create a tree under cwd"
    );
}

#[test]
// One narrative on purpose: the value of this test is that create → list → view →
// move → render runs as a single sequence against the real binary, so splitting it
// to satisfy a line count would remove what it checks.
#[allow(clippy::too_many_lines)]
fn cli_happy_path_end_to_end() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    // init
    tix()
        .current_dir(dir)
        .arg("init")
        .assert()
        .success()
        .stdout(predicate::str::contains("Created"));
    assert!(dir.join("tix.toml").is_file());

    // create
    tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Fix login bug"])
        .args(["--body", "Users can't log in"])
        .args(["--priority", "high"])
        .args(["--labels", "bug, auth"])
        .args(["--assignee", "@alice"])
        .args(["--estimate", "2"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Created "));
    let file = issue_file(dir);
    let filename = file.file_name().unwrap().to_string_lossy().to_string();
    assert!(
        filename.ends_with("-fix-login-bug.md"),
        "expected slug filename, got {filename}"
    );

    // list: header row first, issue row present.
    //
    // `--all`, because the default listing is scoped to your issues in the board's
    // entry column (#1711) and this issue is assigned `@alice` in the inbox column.
    let out = tix()
        .current_dir(dir)
        .args(["list", "--all"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let list = String::from_utf8(out).unwrap();
    let first = list.lines().next().unwrap();
    assert!(
        first.contains("NUM") && first.contains("ID") && first.contains("TITLE"),
        "header row must be first: {list}"
    );
    assert!(
        list.lines().any(|l| l.contains("Fix login bug")),
        "issue row missing: {list}"
    );

    // list --status filter (nothing is done yet → header only)
    let out = tix()
        .current_dir(dir)
        .args(["list", "--status", "done"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert_eq!(String::from_utf8(out).unwrap().lines().count(), 1);

    // view by number: frontmatter + verbatim body, nothing else on stdout
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(
            predicate::str::starts_with("---\n").and(
                predicate::str::contains("number: 1")
                    .and(predicate::str::contains("title: Fix login bug"))
                    .and(predicate::str::contains("status: triage"))
                    .and(predicate::str::contains("priority: high"))
                    .and(predicate::str::contains("labels:"))
                    .and(predicate::str::contains("assignee:"))
                    .and(predicate::str::contains("@alice"))
                    .and(predicate::str::contains("estimate:"))
                    .and(predicate::str::contains("Users can't log in")),
            ),
        );

    // status board summary: header row, per-column counts, Total row
    let out = tix()
        .current_dir(dir)
        .arg("status")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let status = String::from_utf8(out).unwrap();
    let header = status.lines().next().unwrap();
    assert!(
        header.contains("COLUMN") && header.contains("COUNT"),
        "status header first: {status}"
    );
    assert!(
        status
            .lines()
            .any(|l| l.trim().starts_with("triage") && l.contains('1')),
        "triage count missing (create lands in the board's first column): {status}"
    );
    assert!(
        status
            .lines()
            .any(|l| l.trim().starts_with("Total") && l.contains('1')),
        "total row missing: {status}"
    );

    // move into done with --commit: hash recorded in frontmatter
    tix()
        .current_dir(dir)
        .args(["move", "1", "done"])
        .arg("--commit")
        .arg("abc123")
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("status: done").and(predicate::str::contains("abc123")));

    // move out of done: the starter board maps `done` to `completed`, so this is a
    // terminal transition and needs a reason — refused without one, then applied.
    tix()
        .current_dir(dir)
        .args(["move", "1", "in progress"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("invalid_transition"));
    tix()
        .current_dir(dir)
        .args(["move", "1", "in progress", "--reason", "reopened"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("status: in progress")
                .and(predicate::str::contains("abc123").not()),
        );

    // move into done without --commit on a pipe: hard error with guidance
    tix()
        .current_dir(dir)
        .args(["move", "1", "done"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("--commit"));

    // move to an unknown column: error listing the valid columns
    tix()
        .current_dir(dir)
        .args(["move", "1", "bogus"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("valid columns"));

    // edit: invalid priority rejected, valid flags merged
    tix()
        .current_dir(dir)
        .args(["edit", "1"])
        .args(["--priority", "bogus"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("invalid priority"));
    tix()
        .current_dir(dir)
        .args(["edit", "1"])
        .args(["--priority", "medium"])
        .args(["--title", "Fix login bug v2"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("priority: medium")
                .and(predicate::str::contains("Fix login bug v2")),
        );

    // edit --commit set and clear
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--commit", "abc123"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("abc123"));
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--commit", "clear"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("abc123").not());

    // delete --yes, then leftover scans
    tix()
        .current_dir(dir)
        .args(["delete", "1"])
        .arg("--yes")
        .assert()
        .success()
        .stdout(predicate::str::contains("Deleted "));
    assert!(!file.exists());
    let out = tix()
        .current_dir(dir)
        .arg("list")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert_eq!(String::from_utf8(out).unwrap().lines().count(), 1);

    // viewing a deleted issue → exit 2 (target-not-found)
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("not found"));
}

#[test]
fn list_group_cycle_shows_progress_rollups() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();

    tix()
        .current_dir(dir)
        .args(["cycle", "create", "--name", "Alpha"])
        .assert()
        .success();

    tix()
        .current_dir(dir)
        .args(["cycle", "create", "--name", "Beta"])
        .assert()
        .success();

    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "A",
            "--cycles",
            "Alpha",
            "--due-date",
            "2000-01-01",
        ])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "B",
            "--status",
            "done",
            "--cycles",
            "Alpha",
            "--due-date",
            "2999-01-01",
        ])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "C",
            "--cycles",
            "Beta",
            "--due-date",
            "2999-01-01",
        ])
        .assert()
        .success();

    let out = tix()
        .current_dir(dir)
        // `--all`: the default listing is scoped to your issues in the board's entry
        // column (#1711); this test is about the group rollup.
        .args(["list", "--all", "--filter", "group:cycle sort:cycle"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    assert!(
        text.contains("-- cycle: Alpha (1/2 done, 50%) --"),
        "missing Alpha rollup:\n{text}"
    );
    assert!(
        text.contains("-- cycle: Beta (0/1 done, 0%) --"),
        "missing Beta rollup:\n{text}"
    );
}

#[test]
fn cycle_create_warns_on_stderr_about_an_overlapping_window() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();

    tix()
        .current_dir(dir)
        .args([
            "cycle",
            "create",
            "--name",
            "October",
            "--start-date",
            "2026-10-01",
            "--due-date",
            "2026-10-31",
        ])
        .assert()
        .success();

    // The second window intersects `October`; it is still created, and the
    // overlap is named on stderr so a script's stdout stays clean.
    tix()
        .current_dir(dir)
        .args([
            "cycle",
            "create",
            "--name",
            "Late October",
            "--start-date",
            "2026-10-20",
            "--due-date",
            "2026-11-10",
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "warning[W-tix-cycle]: cycle `Late October` overlaps existing cycle(s): October",
        ));

    // The cycle exists and keeps its window despite the warning.
    let out = tix()
        .current_dir(dir)
        .args(["cycle", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    assert!(
        text.contains("Late October\t\t2026-10-20\t2026-11-10\t0"),
        "the warned cycle is still created:\n{text}"
    );
}

#[test]
fn status_filter_overdue_reports_overdue_row_and_group_rollup() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();

    tix()
        .current_dir(dir)
        .args(["cycle", "create", "--name", "Alpha"])
        .assert()
        .success();

    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "A",
            "--cycles",
            "Alpha",
            "--due-date",
            "2000-01-01",
        ])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "B",
            "--status",
            "done",
            "--cycles",
            "Alpha",
            "--due-date",
            "2999-01-01",
        ])
        .assert()
        .success();

    let out = tix()
        .current_dir(dir)
        .args(["status", "--filter", "group:cycle overdue"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    assert!(text.contains("Overdue"), "missing Overdue row:\n{text}");
    // WP04 T019: the label is `complete`, not `done`. The figure comes from the
    // service's category decision, so the word must not name a column — on a board
    // whose completion column is `shipped`, "0/1 done" describes a column the board
    // does not have. This is a user-visible output change and the old assertion is
    // corrected here rather than worked around.
    assert!(
        text.contains("cycle Alpha: 0/1 complete (0%)"),
        "missing cycle group rollup:\n{text}"
    );
}

#[test]
fn list_and_status_filters_do_not_persist_derived_fields() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["cycle", "create", "--name", "Alpha"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Derived check A",
            "--cycles",
            "Alpha",
            "--due-date",
            "2000-01-01",
        ])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Derived check B",
            "--status",
            "done",
            "--cycles",
            "Alpha",
            "--due-date",
            "2999-01-01",
        ])
        .assert()
        .success();

    let issues_dir = dir.join("docs").join("issues");
    let before: Vec<(PathBuf, String)> = issue_files_under(&issues_dir)
        .into_iter()
        .map(|p| {
            let text = fs::read_to_string(&p).unwrap();
            (p, text)
        })
        .collect();

    tix()
        .current_dir(dir)
        .args(["list", "--filter", "group:cycle overdue sort:cycle"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "status",
            "--filter",
            "group:cycle overdue",
            "--sort",
            "cycle",
        ])
        .assert()
        .success();

    for (path, original) in before {
        let now = fs::read_to_string(&path).unwrap();
        assert_eq!(
            original, now,
            "derived list/status output must not mutate issue file {path:?}"
        );
    }
}

#[test]
fn export_ics_to_stdout_emits_calendar_with_cycle_and_issue_events() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args([
            "cycle",
            "create",
            "--name",
            "Release",
            "--start-date",
            "2026-09-01",
            "--due-date",
            "2026-09-10",
        ])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Ship, now",
            "--cycles",
            "Release",
            "--start-date",
            "2026-09-03",
            "--due-date",
            "2026-09-05",
        ])
        .assert()
        .success();

    let out = tix()
        .current_dir(dir)
        .args(["export", "--target", "ics", "--cycle", "Release"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    assert!(text.contains("BEGIN:VCALENDAR\r\n"));
    assert!(text.contains("PRODID:-//tix//tix-tracker//EN\r\n"));
    assert!(text.contains("UID:cycle-release-2026-09-01-2026-09-10@tix\r\n"));
    assert!(text.contains("UID:issue-1-Release@tix\r\n"));
    assert!(text.contains("SUMMARY:[triage] Ship\\, now\r\n"));
}

#[test]
fn export_ics_output_writes_file_and_prints_path() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args([
            "cycle",
            "create",
            "--name",
            "Release",
            "--start-date",
            "2026-09-01",
            "--due-date",
            "2026-09-10",
        ])
        .assert()
        .success();

    let out_path = dir.join("out").join("calendar.ics");
    let out_path_s = out_path.to_string_lossy().to_string();
    tix()
        .current_dir(dir)
        .args([
            "export",
            "--target",
            "ics",
            "--cycle",
            "Release",
            "--output",
            &out_path_s,
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(&out_path_s));

    let contents = fs::read_to_string(&out_path).unwrap();
    assert!(contents.contains("BEGIN:VCALENDAR\r\n"));
    assert!(contents.contains("UID:cycle-release-2026-09-01-2026-09-10@tix\r\n"));
}

#[test]
fn export_ics_unknown_cycle_fails_nonzero() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["export", "--target", "ics", "--cycle", "Nope"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("cycle `Nope`"));
}

#[test]
fn export_ics_requires_cycle_argument() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["export", "--target", "ics"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("missing --cycle"));
}

#[test]
fn export_ics_is_deterministic_across_runs_and_orders_events() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();

    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args([
            "cycle",
            "create",
            "--name",
            "Release",
            "--start-date",
            "2026-09-01",
            "--due-date",
            "2026-09-10",
        ])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Issue B",
            "--cycles",
            "Release",
            "--start-date",
            "2026-09-03",
            "--due-date",
            "2026-09-05",
        ])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Issue A",
            "--cycles",
            "Release",
            "--start-date",
            "2026-09-02",
            "--due-date",
            "2026-09-04",
        ])
        .assert()
        .success();

    let first = tix()
        .current_dir(dir)
        .args(["export", "--target", "ics", "--cycle", "Release"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let second = tix()
        .current_dir(dir)
        .args(["export", "--target", "ics", "--cycle", "Release"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert_eq!(first, second, "ICS export must be byte-stable");

    let text = String::from_utf8(first).unwrap();
    let cycle_uid = "UID:cycle-release-2026-09-01-2026-09-10@tix\r\n";
    let issue1_uid = "UID:issue-1-Release@tix\r\n";
    let issue2_uid = "UID:issue-2-Release@tix\r\n";
    let cycle_pos = text.find(cycle_uid).expect("cycle uid present");
    let issue1_pos = text.find(issue1_uid).expect("issue 1 uid present");
    let issue2_pos = text.find(issue2_uid).expect("issue 2 uid present");
    assert!(
        cycle_pos < issue1_pos && issue1_pos < issue2_pos,
        "unexpected event order:\n{text}"
    );
}

#[test]
fn init_refuses_overwrite() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("init")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("refusing to overwrite"));
    // existing config preserved
    let toml = fs::read_to_string(dir.join("tix.toml")).unwrap();
    assert!(toml.contains("issues_dir"));
}

#[test]
fn missing_config_notice_on_stderr_but_subcommand_succeeds() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix()
        .current_dir(dir)
        .arg("list")
        .assert()
        .success()
        .code(0)
        .stdout(predicate::str::contains("NUM"))
        .stderr(predicate::str::contains(
            "no tix.toml found (run 'tix init' to create one)",
        ));
}

#[test]
fn no_argv_without_config_is_contract_error() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix()
        .current_dir(dir)
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "no tix.toml found — run \"tix init\" first",
        ));
}

#[test]
fn create_without_title_on_pipe_is_usage_error() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("create")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("--title"));
}

#[cfg(unix)]
#[test]
fn edit_invokes_real_editor_on_copy_and_commits_changes() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Editor target"])
        .args(["--priority", "high"])
        .assert()
        .success();

    let editor = dir.join("editor.sh");
    fs::write(
        &editor,
        "#!/bin/sh\nsed -i 's/priority: high/priority: low/' \"$1\"\n",
    )
    .unwrap();
    fs::set_permissions(&editor, fs::Permissions::from_mode(0o755)).unwrap();

    tix()
        .current_dir(dir)
        .args(["edit", "1"])
        .env("EDITOR", editor.to_str().unwrap())
        .assert()
        .success();

    // The editor flip persisted to the issue file on disk (not just the copy)
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("priority: low"));
}

#[test]
fn view_by_slug_prefix_and_title_fragment_resolve() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Refactor auth module"])
        .assert()
        .success();
    let file = issue_file(dir);
    let stem = file.file_stem().unwrap().to_string_lossy().to_string();
    // slug prefix (without the dynamic date prefix)
    tix()
        .current_dir(dir)
        .arg("view")
        .arg("refactor-auth")
        .assert()
        .success()
        .stdout(predicate::str::contains("title: Refactor auth module"));
    // unique title fragment
    tix()
        .current_dir(dir)
        .arg("view")
        .arg("auth")
        .assert()
        .success()
        .stdout(predicate::str::contains("title: Refactor auth module"));
    let _ = stem;
}

// -----------------------------------------------------------------------
// T011 — create defaults the assignee from the git identity (FR-028)
// -----------------------------------------------------------------------

/// create without `--assignee` in a *git-less* repo (global config
/// neutralized) never errors and lands in `unassigned/` (FR-028 fallback).
#[test]
fn create_without_assignee_without_git_identity_lands_in_unassigned() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    // Neutralize system + global git config so no identity can resolve —
    // the create must still succeed and fall back to `unassigned/`.
    let out = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "No git task"])
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&out);
    assert!(
        rel.starts_with("unassigned/"),
        "expected unassigned/<stem>.md relative path, got {rel}"
    );
    assert!(
        rel.ends_with("-no-git-task.md"),
        "expected slug stem, got {rel}"
    );
    assert!(
        dir.join("docs").join("issues").join(&rel).is_file(),
        "file must exist at docs/issues/{rel}"
    );
}

/// Two creates with the same title on the same day do **not** destroy each other.
///
/// The stem is `{created}-{slugified title}` inside the assignee segment, so it is
/// a function of the creation date, the title, and the segment — three things
/// routinely identical across two issues. `create` built that path and handed it
/// to `atomic_write`, which `rename`s over the target. The second create therefore
/// replaced the first file outright, and **both commands reported success**:
///
/// ```text
/// $ tix create --title "Same title" --priority high   # -> priority: high
/// $ tix create --title "Same title" --priority low    # -> priority: low
/// $ ls docs/issues/*/
/// 2026-09-28-same-title.md            # one file
/// $ tix list
/// 1    Same title  todo  low          # issue #0 is gone
/// ```
///
/// No concurrency required. Losing a whole issue to a second create with the same
/// title is the worst data-loss path in the tool.
///
/// Both layers are exercised: the deterministic collision is handled by probing for
/// a free name (`-2`, `-3`, …), and the final create is `O_EXCL` via `hard_link`, so
/// a collision that appears *between* the probe and the write cannot clobber either.
/// The third assertion below is what distinguishes the two: it checks the surviving
/// files kept their **own** priority, so the first file is genuinely intact rather
/// than absent.
#[test]
fn two_creates_with_the_same_title_both_survive() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    for priority in ["high", "low", "medium"] {
        tix()
            .current_dir(dir)
            .args(["create", "--title", "Same title", "--priority", priority])
            .assert()
            .success();
    }

    let files: Vec<PathBuf> = issue_files_under(&dir.join("docs").join("issues"))
        .into_iter()
        .filter(|p| {
            p.to_string_lossy().contains("herbert-maschke")
                && p.extension().is_some_and(|x| x == "md")
        })
        .collect();
    assert_eq!(
        files.len(),
        3,
        "three creates must leave three files, found {:?}",
        files
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
    );

    // Each file kept **its own** priority: the first was not merely replaced, and
    // the second and third did not inherit the first's contents.
    let mut priorities: Vec<String> = files
        .iter()
        .map(|p| {
            let text = fs::read_to_string(p).unwrap();
            text.lines()
                .find_map(|l| l.strip_prefix("priority:"))
                .unwrap_or("<none>")
                .trim()
                .to_string()
        })
        .collect();
    priorities.sort();
    assert_eq!(
        priorities,
        ["high", "low", "medium"],
        "all three priorities must survive, found {priorities:?}"
    );

    // And the board agrees: three distinct issues, not one.
    let listed = tix()
        .current_dir(dir)
        .args(["list", "--all"])
        .assert()
        .success();
    let out = String::from_utf8_lossy(&listed.get_output().stdout).to_string();
    for number in 1..4 {
        assert!(
            out.contains(&format!("{number} ")),
            "issue #{number} must exist on the board:\n{out}"
        );
    }
}

/// 24 concurrent `tix create` runs produce 24 files with 24 **distinct** numbers.
///
/// #1352, part 2. This needs **real subprocesses**: `Store` is `&self` with no
/// interior mutability, the TUI is a single event loop, and `src/mcp/mod.rs`
/// handles one message to completion before reading the next, so there is no
/// intra-process race to provoke and an in-process test would be unfalsifiable by
/// construction. Two processes — an agent's `tix mcp` and a human's `tix` — is
/// the real scenario, and it is also why this looked rare enough to live with.
///
/// `resolve_next_number` reads the directory, takes `max`, and adds one. That is a
/// *hint*, not an allocation: nothing serialised read-then-write, so processes
/// arriving together all got the same answer and all proceeded. Measured before
/// the fix:
///
/// ```text
/// files: 24   distinct numbers: 8
///   5 × number: 7    4 × number: 4    4 × number: 6    3 × number: 3
/// ```
///
/// 16 of 24 issues shared a number, after which every number-addressed command —
/// `tix view 0`, `tix move 0`, `tix edit 0`, `tix link 0 X`, `tix delete 0` —
/// silently addressed an arbitrary one of several issues.
///
/// The claim ledger (`NumberClaim`) reserves each number with an `O_EXCL` marker
/// *before* the frontmatter is serialised, so the `number:` in the file is the
/// claimed one.
#[test]
fn concurrent_creates_get_distinct_numbers() {
    const N: usize = 24;
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    // Spawned together, not awaited in sequence — the whole point is that they
    // overlap. `assert_cmd::Command` is a wrapper, so the raw `std::process::Command`
    // is used here to get `spawn` with the output detached.
    let bin = assert_cmd::cargo::cargo_bin("tix");
    let mut children: Vec<std::process::Child> = (1..=N)
        .map(|i| {
            std::process::Command::new(&bin)
                .current_dir(dir)
                .args(["create", "--title", &format!("Concurrent {i}")])
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
                .unwrap()
        })
        .collect();
    for child in children.iter_mut() {
        child.wait().unwrap();
    }

    // 24 files.
    let segment = dir.join("docs").join("issues").join("herbert-maschke");
    let files: Vec<PathBuf> = issue_files_under(&segment)
        .into_iter()
        .filter(|p| p.extension().is_some_and(|x| x == "md"))
        .collect();
    assert_eq!(files.len(), N, "every create must land its own file");

    // 24 distinct numbers — the assertion this whole fix exists for.
    let mut numbers: Vec<u32> = files
        .iter()
        .map(|p| {
            let text = fs::read_to_string(p).unwrap();
            text.lines()
                .find_map(|l| l.strip_prefix("number:"))
                .unwrap_or_else(|| panic!("no number: in {}", p.display()))
                .trim()
                .parse()
                .unwrap()
        })
        .collect();
    numbers.sort_unstable();
    let distinct = {
        let mut d = numbers.clone();
        d.dedup();
        d
    };
    assert_eq!(
        distinct.len(),
        N,
        "every issue must have its own number, found {numbers:?}"
    );

    // **The number in the file must be the number that was claimed.** A claim
    // ledger that reserved numbers but let the pre-claim number reach the bytes
    // would show 24 valid claims alongside 8 distinct `number:` values, and every
    // assertion above would pass except this one. So the ledger is cross-checked
    // against the files: the set of claims must equal the set of numbers on disk.
    let claim_dir = dir.join("docs").join(".tix-numbers");
    let claim_entries = fs::read_dir(&claim_dir).unwrap_or_else(|e| {
        panic!(
            "the claim ledger must exist at {} — if it is missing, the number was \
             never reserved and nothing was serialised: {e}",
            claim_dir.display()
        )
    });
    let claims: Vec<u32> = claim_entries
        .filter_map(|e| e.ok())
        .filter_map(|e| e.path().file_stem()?.to_str()?.parse::<u32>().ok())
        .collect();
    assert_eq!(
        claims.len(),
        N,
        "one claim per created issue, found {}",
        claims.len()
    );
    let mut sorted_claims = claims;
    sorted_claims.sort_unstable();
    assert_eq!(
        sorted_claims, numbers,
        "the claim ledger and the numbers on disk must agree"
    );

    // And the numbers address distinct issues end to end — the user-visible
    // consequence. Launch order does not determine number order, so the titles are
    // compared as a *set*: the point is that `tix view N` is a bijection onto the
    // 24 issues, not that number N is the Nth title launched.
    let mut seen: Vec<String> = Vec::new();
    for number in &numbers {
        let out = tix()
            .current_dir(dir)
            .args(["view", &number.to_string()])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let text = String::from_utf8_lossy(&out).to_string();
        let title = text
            .lines()
            .find_map(|l| l.strip_prefix("title:"))
            .unwrap_or_else(|| panic!("no title for #{number}:\n{text}"))
            .trim()
            .to_string();
        assert!(
            title.starts_with("Concurrent "),
            "#{number} must address a Concurrent issue, got {title:?}"
        );
        seen.push(title);
    }
    seen.sort();
    seen.dedup();
    assert_eq!(
        seen.len(),
        N,
        "each number must address a different issue, found {seen:?}"
    );

    // The ledger lives **beside** `docs/issues/`, not inside it. `docs/issues/` is
    // the committed source of truth that people hand-edit, script against, and glob,
    // so an internal directory there would change what every one of those consumers
    // sees. Asserted here because the only symptom of getting it wrong is somebody
    // else's `read_dir` counting two directories instead of one.
    let issues_entries: Vec<String> = fs::read_dir(dir.join("docs").join("issues"))
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().to_string())
        .filter(|n| n != "herbert-maschke")
        .collect();
    assert!(
        issues_entries.is_empty(),
        "docs/issues/ must contain only assignee segments, also found {issues_entries:?}"
    );
}

/// create without `--assignee` inside a configured git repo defaults the
/// assignee to the full git identity and lands in its derived segment (FR-028).
#[test]
fn create_without_assignee_defaults_to_git_identity_segment() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    git(dir, &["init", "-q"]);
    git(dir, &["config", "user.name", "Herb Mason"]);
    git(dir, &["config", "user.email", "herb@example.com"]);

    tix().current_dir(dir).arg("init").assert().success();
    let out = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Git task"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&out);
    assert!(
        rel.starts_with("herb-mason/"),
        "expected identity segment, got {rel}"
    );
    assert!(
        dir.join("docs").join("issues").join(&rel).is_file(),
        "file must exist at docs/issues/{rel}"
    );

    // The full identity is stored verbatim in the frontmatter — never
    // @-prefixed (the raw view contract stays byte-true).
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("assignee:")
                .and(predicate::str::contains("Herb Mason <herb@example.com>"))
                .and(predicate::str::contains("@Herb").not()),
        );
}

// -----------------------------------------------------------------------
// T012 — edit --assignee physically moves the file (FR-031)
// -----------------------------------------------------------------------

/// `tix edit <n> --assignee <other>` migrates the file into the new assignee
/// segment: old relative path gone, new one present, `number` unchanged.
#[test]
fn edit_assignee_moves_file_and_keeps_number() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let created = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Reassign me"])
        .args(["--assignee", "@alice"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&created);
    assert!(
        rel.starts_with("alice/"),
        "explicit --assignee must win, got {rel}"
    );
    let issues = dir.join("docs").join("issues");
    assert!(issues.join(&rel).is_file(), "{rel} must exist before edit");

    // edit: alice -> bob (bare handle, no @)
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--assignee", "bob"])
        .assert()
        .success();
    assert!(
        !issues.join(&rel).exists(),
        "old path {rel} must be gone after reassign"
    );
    let new_rel = rel.replacen("alice/", "bob/", 1);
    assert!(
        issues.join(&new_rel).is_file(),
        "new path {new_rel} must exist after reassign"
    );
    // number stable; new assignee persisted
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("number: 1")
                .and(predicate::str::contains("assignee:"))
                .and(predicate::str::contains("bob")),
        );
}

/// `tix edit <n> --assignee ""` clears the assignee and moves the file to
/// `unassigned/` (FR-031).
#[test]
fn edit_assignee_empty_moves_to_unassigned() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let created = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Clear me"])
        .args(["--assignee", "alice"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&created);
    let issues = dir.join("docs").join("issues");
    assert!(issues.join(&rel).is_file());

    tix()
        .current_dir(dir)
        .args(["edit", "1", "--assignee", ""])
        .assert()
        .success();
    assert!(
        !issues.join(&rel).exists(),
        "old path {rel} must be gone after clearing the assignee"
    );
    let new_rel = rel.replacen("alice/", "unassigned/", 1);
    assert!(
        issues.join(&new_rel).is_file(),
        "new path {new_rel} must exist under unassigned/"
    );
    // assignee cleared from the frontmatter (omitted when None)
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("number: 1").and(predicate::str::contains("assignee").not()),
        );
}

// -----------------------------------------------------------------------
// WP04 — `tix search` (FR-012, contract cli.md §search) and `tix lint`
// (FR-015..FR-018, contract cli.md §lint)
// -----------------------------------------------------------------------

/// Write a synthetic issue file into the store with full frontmatter control.
///
/// Returns the issues dir. The store layout accepts both flat legacy files
/// (C-010) and `segment/` grouped files; these helpers write flat files so
/// the search/lint corpus shape is fully deterministic.
fn with_store() -> (TempDir, std::path::PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    // These tests write bare/legacy fixtures; keep them about their own concern
    // rather than auto-migration (covered by dedicated tests).
    let cfg = dir.join("tix.toml");
    let mut text = std::fs::read_to_string(&cfg).unwrap();
    text.push_str("\n[layout]\nmove_on_change = false\n");
    std::fs::write(&cfg, text).unwrap();
    let issues = dir.join("docs").join("issues");
    std::fs::create_dir_all(&issues).unwrap();
    (tmp, issues)
}

fn write_frontmatter(path: &std::path::Path, fm: &str) {
    let contents = format!("---\n{fm}\n---\n\nbody text\n");
    std::fs::write(path, contents).unwrap();
}

/// Default valid frontmatter key/value pairs; individual tests override.
const GOOD_FM: &[&str] = &[
    "number: '1'",
    "title: \"Synthetic issue\"",
    "labels: []",
    "status: \"todo\"",
    "priority: \"medium\"",
    "created: \"2026-01-01\"",
    "updated: \"2026-01-01\"",
];

fn fm_line(number: u32, title: &str, extra: &[(&str, &str)]) -> Vec<String> {
    let mut parts: Vec<String> = vec![format!("number: {number}"), format!("title: \"{title}\"")];
    for line in GOOD_FM {
        if line.starts_with("number:") || line.starts_with("title:") {
            continue;
        }
        parts.push(line.to_string());
    }
    for (key, val) in extra {
        let rendered = if val.starts_with('[') || val.starts_with('{') || *val == "null" {
            format!("{key}: {val}")
        } else {
            format!("{key}: '{val}'")
        };
        if let Some(slot) = parts.iter_mut().find(|l| l.starts_with(&format!("{key}:"))) {
            *slot = rendered;
        } else {
            parts.push(rendered);
        }
    }
    parts
}

#[test]
fn search_matches_assignee_field() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-alice-task.md"),
        &fm_line(1, "Config work", &[("assignee", "@alice")]).join("\n"),
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "alice"])
        .assert()
        .success()
        .code(0)
        .stdout(
            predicate::str::contains("#1 Config work — todo (2026-01-01-alice-task.md)")
                .and(predicate::str::contains("@alice")),
        );
}

#[test]
fn search_matches_comment_text_only() {
    let (_tmp, issues) = with_store();
    let contents = format!(
        "---\n{}\n---\n\nbody\n\n## Comments\n\n### alice (2026-01-03)\n\nNeed a hotfix for the timeout.\n",
        fm_line(1, "Timeout investigation", &[]).join("\n")
    );
    std::fs::write(issues.join("2026-01-01-timeout.md"), contents).unwrap();
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "hotfix"])
        .assert()
        .success()
        .code(0)
        .stdout(
            predicate::str::contains("#1 Timeout investigation — todo (2026-01-01-timeout.md)")
                .and(predicate::str::contains("hotfix for the timeout")),
        );
}

#[test]
fn search_matches_frontmatter_label() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-02-bug-repro.md"),
        &fm_line(1, "Repro steps", &[("labels", "[bug]")]).join("\n"),
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "bug"])
        .assert()
        .success()
        .stdout(predicate::str::contains("#1 Repro steps"));
}

#[test]
fn search_is_case_insensitive() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-case-test.md"),
        &fm_line(1, "Login flow", &[]).join("\n"),
    );
    let out = tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "LOGIN"])
        .assert()
        .success()
        .code(0)
        .get_output()
        .stdout
        .clone();
    assert!(String::from_utf8(out).unwrap().contains("#1 Login flow"));
}

#[test]
fn search_orders_hits_by_number() {
    let (_tmp, issues) = with_store();
    // Written out of numeric order on purpose; results must be #1, #2, #3.
    // All three share a label so the query matches every issue.
    let shared = [("labels", "[shared-word]")];
    write_frontmatter(
        &issues.join("2026-01-01-c.md"),
        &fm_line(3, "Third", &shared).join("\n"),
    );
    write_frontmatter(
        &issues.join("2026-01-02-a.md"),
        &fm_line(1, "First", &shared).join("\n"),
    );
    write_frontmatter(
        &issues.join("2026-01-03-b.md"),
        &fm_line(2, "Second", &shared).join("\n"),
    );
    let out = tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "shared-word"])
        .assert()
        .success()
        .code(0)
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    let idx1 = stdout.find("#1 First").expect("hit #1 missing");
    let idx2 = stdout.find("#2 Second").expect("hit #2 missing");
    let idx3 = stdout.find("#3 Third").expect("hit #3 missing");
    assert!(idx1 < idx2 && idx2 < idx3, "hits not ordered: {stdout}");
}

#[test]
fn search_zero_matches_prints_message_and_exits_zero() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-foo.md"),
        &fm_line(1, "Foo", &[]).join("\n"),
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "zzz-nothing"])
        .assert()
        .success()
        .code(0)
        .stdout("No issues found.\n");
}

#[test]
fn search_empty_query_is_usage_error_exit_2() {
    let (_tmp, issues) = with_store();
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", ""])
        .assert()
        .failure()
        .code(2);
}

#[test]
fn search_store_io_failure_exits_1() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    // Replace the issues store with a plain file: `Store::open` sees the
    // path exists, so `list` hits `read_dir` on a file (ENOTDIR), a real
    // I/O error that search must surface with exit 1 (contract cli.md §search).
    std::fs::create_dir_all(dir.join("docs")).unwrap();
    std::fs::write(dir.join("docs/issues"), "not a directory").unwrap();
    let assert = tix()
        .current_dir(dir)
        .args(["search", "anything"])
        .assert()
        .failure()
        .code(1);
    assert!(
        !assert.get_output().stderr.is_empty(),
        "io failure must surface on stderr"
    );
}

#[test]
fn lint_flags_bad_status_with_valid_columns() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Bad status", &[("status", "donex")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-bad-status.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("2026-01-01-bad-status.md"))
                .and(predicate::str::contains("donex"))
                .and(predicate::str::contains(
                    "valid options: triage, todo, in progress, in review, done, wontfix",
                )),
        );
}

/// #1361: an unknown top-level frontmatter key survives an unrelated edit.
///
/// Before this, `Issue` deserialised a fixed set of keys and `frontmatter()`
/// re-emitted exactly those, so a key `tix` did not recognise was **deleted** by the
/// next unrelated write — silently, because `tix lint` had no unknown-key rule at
/// all. Two issues' worth of data, gone, after a linter certified the file valid.
///
/// The key is captured as its **raw source block**, not a parsed value, so it comes
/// back byte-identically. Re-serialising a parsed value would re-quote and re-indent
/// it, and every write would produce a spurious diff in a file that had not changed
/// — which for a "preserve the user's data" feature would be a new bug.
#[test]
fn an_unknown_top_level_frontmatter_key_survives_an_unrelated_edit() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    // Keep auto-migration out of this test: it asserts the file path is stable.
    let cfg = dir.join("tix.toml");
    let mut text = std::fs::read_to_string(&cfg).unwrap();
    text.push_str("\n[layout]\nmove_on_change = false\n");
    std::fs::write(&cfg, text).unwrap();
    let segment = dir.join("docs").join("issues").join("herbert-maschke");
    std::fs::create_dir_all(&segment).unwrap();
    let path = segment.join("2026-01-01-extras.md");
    std::fs::write(
        &path,
        "---\n\
         number: 1\n\
         title: Has extras\n\
         status: todo\n\
         labels: []\n\
         priority: medium\n\
         assignee: Herbert Maschke <thyseus@pm.me>\n\
         files: []\n\
         created: 2026-01-01\n\
         updated: 2026-01-01\n\
         custom_field: keep me\n\
         list_of_things:\n\
         - one\n\
         - two\n\
         nested:\n\
         \x20 a: 1\n\
         \x20 b: two\n\
         ---\n\n\
         body text\n",
    )
    .unwrap();

    tix()
        .current_dir(dir)
        .args(["edit", "1", "--priority", "high"])
        .assert()
        .success();

    let after = std::fs::read_to_string(&path).unwrap();
    // A scalar, a block sequence, and a nested mapping — all three shapes.
    for expected in [
        "custom_field: keep me",
        "list_of_things:\n- one\n- two",
        // The two-space indent of the nested block is part of the captured bytes.
        "nested:\n  a: 1\n  b: two",
    ] {
        assert!(
            after.contains(expected),
            "the unknown key must survive byte-identically, expected {expected:?} in:\n{after}"
        );
    }
    assert!(
        after.contains("priority: high"),
        "and the edit itself must have applied: {after}"
    );

    // **Second pass**: the round trip is stable, so a file that has not changed
    // produces no diff. A splice that re-ordered or re-quoted on the way out would
    // show up here as a difference between the first write and the second.
    let once = after.clone();
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--priority", "high"])
        .assert()
        .success();
    assert_eq!(
        std::fs::read_to_string(&path).unwrap(),
        once,
        "a second unrelated write must produce no diff"
    );
}

/// #1361: an unknown key **warns**, and `tix lint` still exits 0.
///
/// The exit code is the design. The file parses, the key is preserved on write, and
/// nothing is broken — so failing a build over it would report a non-problem as a
/// broken file. The warning exists because an unrecognised key is usually a *typo*:
/// `titel:` round-trips and is never read by anything, which is the failure mode
/// this whole change trades silent deletion for.
///
/// The diagnostic is rendered as `W-`, not `E-`, for the same reason: an `E-` in red
/// reads as "this file is broken" at a glance, and the output has to agree with the
/// exit code.
#[test]
fn an_unknown_top_level_key_warns_without_failing_the_lint() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Typo", &[("titel", "probably a typo")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-typo.md"), &fm);

    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .success()
        .code(0)
        .stderr(
            predicate::str::contains("warning[W-tix-lint]")
                .and(predicate::str::contains(
                    "unknown top-level frontmatter key `titel`",
                ))
                .and(predicate::str::contains("[custom_attributes]"))
                .and(predicate::str::contains("probably a typo")),
        )
        .stdout(predicate::str::contains("Lint OK with 2 warnings"));
}

/// #1361: a key declared in `[custom_attributes]` does not warn.
///
/// The escape hatch. A project that genuinely uses a key declares it once and stops
/// being told about it, which is what makes the warning safe to ship: the remedy is
/// always available and is never urgent.
#[test]
fn a_declared_custom_attribute_does_not_warn() {
    let (tmp, issues) = with_store();
    let fm = fm_line(1, "Declared", &[("build_id", "ci-4471")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-declared.md"), &fm);

    // The declaration must be a **top-level** table: appended at the end of the
    // file it lands inside whatever table came last, and every key after it is then
    // read as part of this section.
    let config = tmp.path().join("tix.toml");
    let mut text = std::fs::read_to_string(&config).unwrap();
    let at = text
        .find("\n[")
        .expect("tix.toml must have at least one table");
    text.insert_str(at, "\n[custom_attributes]\nkeys = [\"build_id\"]\n");
    std::fs::write(&config, text).unwrap();

    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .success()
        .code(0)
        // WP06: the store is still OK; the board's safe-default reliance is
        // the only finding, and that is a warning. The property this test checks is
        // that declaring the key suppressed the *frontmatter* warning, below.
        .stdout(predicate::str::contains("Lint OK"))
        .stderr(predicate::str::contains("build_id").not());
    drop(tmp);
}

/// #1361: the **positive control**. A file with only known keys is silent.
///
/// Without this the warning is untested noise — a rule that fires on everything is
/// indistinguishable from no rule, and a reader has no way to tell whether the
/// suppression above works or the check simply never fires.
#[test]
fn a_file_with_only_known_keys_lints_silently() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Clean", &[]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-clean.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .success()
        .code(0)
        // WP06: "silently" now means "no *frontmatter* diagnostic", not "no output at
        // all" — the board's safe-default reliance is reported and is not a
        // frontmatter problem. The control this test exists for is the absence of
        // the unknown-key warning, asserted below.
        .stdout(predicate::str::contains("Lint OK"))
        .stderr(predicate::str::contains("unknown top-level frontmatter key").not());
}

/// #1361: a real error alongside a warning still exits 1.
///
/// The severity split must not turn the exit code into "any finding at all". If it
/// did, the warning would be fatal in everything but name, and the message telling
/// users to declare the key would be advice that breaks their build.
#[test]
fn an_error_alongside_a_warning_still_fails_the_lint() {
    let (_tmp, issues) = with_store();
    // A genuine error alongside the warning, so the exit code is 1 either way — the
    // assertion is that BOTH render, under their own ids.
    let fm = fm_line(
        1,
        "Both",
        &[("titel", "probably a typo"), ("status", "nonsense")],
    )
    .join("\n");
    write_frontmatter(&issues.join("2026-01-01-both.md"), &fm);

    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("warning[W-tix-lint]")),
        );
}

/// #1361 + C-001: the retired `links:` key is still dropped, and still reported by
/// **its own** finding rather than by the new unknown-key warning.
///
/// This is the interaction that needed deciding. `links` is a key `tix` recognises
/// but no longer reads, so capturing it as an "extra" would round-trip it and
/// quietly undo the typed-relationship migration: the data would come back, and the
/// model would still not understand it. It is excluded from the capture, and warning
/// about it here as well would report one problem twice.
#[test]
fn the_retired_links_key_is_still_dropped_and_reported_once() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Retired", &[("links", "\n- 2")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-retired.md"), &fm);

    let out = tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .get_output()
        .stderr
        .clone();
    let err = String::from_utf8_lossy(&out).to_string();
    assert!(
        err.contains("retired") || err.contains("links"),
        "the retired key must still be reported by its own finding:\n{err}"
    );
    assert!(
        !err.contains("unknown top-level frontmatter key `links`"),
        "and must NOT also be reported as an unknown key — one problem, one finding:\n{err}"
    );

    // And a write still drops it rather than round-tripping it.
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["edit", "1", "--priority", "high"])
        .assert()
        .success();
    let after = std::fs::read_to_string(issues.join("2026-01-01-retired.md")).unwrap();
    assert!(
        !after.contains("\nlinks:"),
        "the retired key must still be dropped on write:\n{after}"
    );
}

#[test]
fn lint_flags_unknown_priority() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Urgent", &[("priority", "urgent")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-urgent.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("priority"))
                .and(predicate::str::contains("urgent"))
                .and(predicate::str::contains("low, medium, high")),
        );
}

#[test]
fn lint_flags_malformed_created_date() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Date issue", &[("created", "2026-13-99")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-date.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("created"))
                .and(predicate::str::contains("2026-13-99"))
                .and(predicate::str::contains("YYYY-MM-DD")),
        );
}

#[test]
fn lint_flags_an_unreadable_estimate() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Estimate", &[("estimate", "a couple of days")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-estimate.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("estimate"))
                .and(predicate::str::contains("a couple of days")),
        );
}

#[test]
fn lint_accepts_durations_ranges_and_annotations() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Estimate", &[("estimate", "~300 LOC, 0.5-1 day")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-estimate.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .success()
        .stdout(predicate::str::contains("Lint OK"));
}

#[test]
fn lint_flags_non_integer_number() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-bad-number.md"),
        "number: 'abc'\ntitle: \"Bad number\"",
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("error[E-tix-lint]"));
}

/// #1361 **reverses** this test's old policy, so the reversal is recorded here
/// rather than left as a silent edit.
///
/// It used to be `lint_ignores_unknown_keys`, and it asserted
/// `stderr(predicate::str::is_empty())` — the charter's stated rule that unknown
/// frontmatter keys are *never* flagged. That rule was reasonable for flagging and
/// catastrophic for the other half: nothing warned about the **loss** either, so a
/// custom key was deleted by the next unrelated write with the linter certifying the
/// file valid.
///
/// The new rule is narrower in the way that matters. The key is **preserved** on
/// write, so the file is genuinely fine, and the finding is a warning that does not
/// set the exit code. What it buys is that `titel:` — which round-trips silently and
/// is read by nothing — now says so, while `build_id:` can be declared once in
/// `[custom_attributes]` and never mentioned again.
///
/// The exit code stays 0 here, and that is the assertion worth keeping: an
/// unrecognised key must not break a build.
#[test]
fn lint_warns_about_an_unknown_key_but_still_succeeds() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Custom", &[("custom_key", "custom_value")]).join("\n");
    write_frontmatter(&issues.join("2026-01-03-clean.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .success()
        .code(0)
        .stdout(predicate::str::contains(
            "Lint OK with 2 warnings: 1 issues checked.",
        ))
        .stderr(predicate::str::contains("warning[W-tix-lint]"));
}

#[test]
fn lint_clean_store_summary() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-a.md"),
        &fm_line(1, "A", &[]).join("\n"),
    );
    write_frontmatter(
        &issues.join("2026-01-02-b.md"),
        &fm_line(2, "B", &[]).join("\n"),
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .success()
        .code(0)
        // WP06: the store is still OK; the safe-default warning is the only finding.
        .stdout(predicate::str::contains("Lint OK"))
        .stdout(predicate::str::contains("2 issues checked."));
}

#[test]
fn lint_missing_frontmatter_diagnostic_no_crash() {
    let (_tmp, issues) = with_store();
    std::fs::write(issues.join("2026-01-01-naked.md"), "no frontmatter here\n").unwrap();
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("2026-01-01-naked.md")),
        );
}

#[test]
fn lint_unparsable_yaml_diagnostic_no_crash() {
    let (_tmp, issues) = with_store();
    write_frontmatter(&issues.join("2026-01-01-broken.md"), "number 0x\n");
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("2026-01-01-broken.md")),
        );
}

#[test]
fn lint_non_utf8_diagnostic_no_crash() {
    let (_tmp, issues) = with_store();
    std::fs::write(issues.join("2026-01-01-binary.md"), b"\xff\xfe\x00\x01\xff").unwrap();
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("error[E-tix-lint]"));
}
#[test]
fn edit_assignee_same_segment_is_noop_success() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let created = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Stay put"])
        .args(["--assignee", "alice"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&created);
    let issues = dir.join("docs").join("issues");

    tix()
        .current_dir(dir)
        .args(["edit", "1", "--assignee", "@alice"])
        .assert()
        .success();
    assert!(
        issues.join(&rel).is_file(),
        "file must stay at {rel} when the segment is unchanged"
    );
}

/// `git rev-parse HEAD` inside `dir`.
fn head_of(dir: &std::path::Path) -> String {
    let out = std::process::Command::new("git")
        .current_dir(dir)
        .args(["rev-parse", "HEAD"])
        .output()
        .expect("`git` must be available to run the CLI tests");
    assert!(out.status.success(), "git rev-parse HEAD failed");
    String::from_utf8(out.stdout).unwrap().trim().to_string()
}

/// A local repo with an identity, so commits are hermetic regardless of the
/// machine's `~/.gitconfig`.
fn init_repo(dir: &std::path::Path) {
    git(dir, &["init"]);
    git(dir, &["config", "user.email", "test@example.com"]);
    git(dir, &["config", "user.name", "Test"]);
}

#[test]
fn move_into_done_auto_captures_head() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Ship it"])
        .assert()
        .success();

    init_repo(dir);
    git(dir, &["add", "-A"]);
    git(dir, &["commit", "-m", "work"]);
    let head = head_of(dir);

    // No `--commit` on a pipe: HEAD is captured automatically (no prompt/error).
    tix()
        .current_dir(dir)
        .args(["move", "1", "done"])
        .assert()
        .success();

    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("status: done").and(predicate::str::contains(&head)));
}

#[test]
fn move_batch_previews_without_yes_and_writes_nothing() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    for title in ["Alpha", "Beta"] {
        tix()
            .current_dir(dir)
            .args(["create", "--title", title, "--status", "todo"])
            .assert()
            .success();
    }

    tix()
        .current_dir(dir)
        .args(["move", "1,2", "in progress"])
        .assert()
        .failure()
        .code(1)
        .stdout(
            predicate::str::contains("would move 2 issue(s) to in progress")
                .and(predicate::str::contains("re-run with --yes")),
        );

    // Nothing was written: both are still in the entry column.
    for number in ["1", "2"] {
        tix()
            .current_dir(dir)
            .args(["view", number])
            .assert()
            .success()
            .stdout(predicate::str::contains("status: todo"));
    }
}

#[test]
fn move_batch_applies_every_selected_issue() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    for title in ["Alpha", "Beta"] {
        tix()
            .current_dir(dir)
            .args(["create", "--title", title])
            .assert()
            .success();
    }

    tix()
        .current_dir(dir)
        .args(["move", "1,2", "in progress", "--yes"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("#1 moved to in progress")
                .and(predicate::str::contains("#2 moved to in progress"))
                .and(predicate::str::contains("2 moved, 0 refused")),
        );

    for number in ["1", "2"] {
        tix()
            .current_dir(dir)
            .args(["view", number])
            .assert()
            .success()
            .stdout(predicate::str::contains("status: in progress"));
    }
}

#[test]
fn move_batch_filter_dry_run_lists_the_filtered_set_and_writes_nothing() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Alpha", "--status", "todo"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Beta", "--status", "todo"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Gamma", "--status", "in progress"])
        .assert()
        .success();

    tix()
        .current_dir(dir)
        .args(["move", "--filter", "status:todo", "done", "--dry-run"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("selection: 2 issues")
                .and(predicate::str::contains("#1 Alpha"))
                .and(predicate::str::contains("#2 Beta"))
                .and(predicate::str::contains("dry run: nothing written")),
        );

    // Gamma was outside the filter and nobody moved.
    tix()
        .current_dir(dir)
        .args(["view", "3"])
        .assert()
        .success()
        .stdout(predicate::str::contains("status: in progress"));

    // One selector with `--dry-run` is a preview too, never a write.
    tix()
        .current_dir(dir)
        .args(["move", "1", "done", "--dry-run"])
        .assert()
        .success()
        .stdout(predicate::str::contains("would move 1 issue(s) to done"));
    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("status: todo"));
}

#[test]
fn move_batch_partial_refusal_exits_nonzero_and_applies_the_rest() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Done one"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["move", "1", "done", "--commit", "abc123"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Todo one"])
        .assert()
        .success();

    // #1 leaves a terminal category without a reason and is refused; #2 is an
    // ordinary move and is applied. The batch reports both and exits non-zero.
    tix()
        .current_dir(dir)
        .args(["move", "1,2", "in progress", "--yes"])
        .assert()
        .failure()
        .code(1)
        .stdout(
            predicate::str::contains("#1 refused:")
                .and(predicate::str::contains("1 moved, 1 refused")),
        );

    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("status: done"));
    tix()
        .current_dir(dir)
        .args(["view", "2"])
        .assert()
        .success()
        .stdout(predicate::str::contains("status: in progress"));
}

#[test]
fn move_batch_terminal_exit_reason_is_recorded_on_every_item() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    for title in ["Alpha", "Beta"] {
        tix()
            .current_dir(dir)
            .args(["create", "--title", title])
            .assert()
            .success();
        tix()
            .current_dir(dir)
            .args(["move", title, "done", "--commit", "abc123"])
            .assert()
            .success();
    }

    tix()
        .current_dir(dir)
        .args([
            "move",
            "1,2",
            "in progress",
            "--yes",
            "--reason",
            "reopened",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("2 moved, 0 refused"));

    for number in ["1", "2"] {
        tix()
            .current_dir(dir)
            .args(["view", number])
            .assert()
            .success()
            .stdout(
                predicate::str::contains("status: in progress")
                    .and(predicate::str::contains("reopened")),
            );
    }
}

#[test]
fn edit_commit_auto_resolves_the_closing_commit() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Close me"])
        .assert()
        .success();

    init_repo(dir);
    git(dir, &["add", "-A"]);
    git(dir, &["commit", "-m", "work"]);

    // Close the ticket with a placeholder, then commit the closure: the
    // resulting commit is the one that last touched the issue file.
    tix()
        .current_dir(dir)
        .args(["move", "1", "done", "--commit", "placeholder"])
        .assert()
        .success();
    git(dir, &["add", "-A"]);
    git(dir, &["commit", "-m", "close ticket"]);
    let closing = head_of(dir);

    // Back-fill the real closing commit from history.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--commit", "auto"])
        .assert()
        .success();

    tix()
        .current_dir(dir)
        .args(["view", "1"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains(format!("commit: {closing}"))
                .and(predicate::str::contains("placeholder").not()),
        );
}

// ---------------------------------------------------------------------------
// WP03 — typed relationships through the real binary (T011–T015)
// ---------------------------------------------------------------------------
//
// Every assertion here runs the compiled `tix`, never the library. That is the
// whole point of this section: the unit tests in `src/commands/link.rs` can
// prove the service was asked the right question, but only a subprocess can
// prove the **flag** was required, the **exit code** was non-zero, the
// **diagnostic** reached stderr, and the **bytes on disk** did not move.
//
// The no-partial-write assertions snapshot every issue file and compare
// byte-for-byte. An exit code is not evidence that nothing was written, and a
// re-read through the same parser that might have dropped a line proves nothing
// either.

/// A repository with `n` issues, created through the real binary.
///
/// The titles are distinct so a title-fragment selector never resolves
/// ambiguously, and each carries its number in the title so the tests can find
/// the right file.
fn repo_with_issues(count: usize) -> (TempDir, std::path::PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    tix().current_dir(&dir).arg("init").assert().success();
    for i in 0..count {
        tix()
            .current_dir(&dir)
            .args(["create", "--title", &format!("Issue {i}")])
            .assert()
            .success();
    }
    (tmp, dir)
}

/// Nine issues titled with words, so a rendered relationship row's target name is
/// unambiguous. `repo_with_issues` titles them `Issue N`, whose last token is
/// just the number — and a row naming "#2  2" cannot distinguish the right title
/// from the wrong one.
fn repo_with_named_issues(count: usize) -> (TempDir, std::path::PathBuf) {
    let names = [
        "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India",
    ];
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    tix().current_dir(&dir).arg("init").assert().success();
    for name in names.iter().take(count) {
        tix()
            .current_dir(&dir)
            .args(["create", "--title", &format!("Issue {name}")])
            .assert()
            .success();
    }
    (tmp, dir)
}

/// Every issue file's relative path paired with its exact bytes.
///
/// Sorted, so a comparison is order-independent and cannot pass because of
/// directory iteration order.
fn issue_snapshot(dir: &std::path::Path) -> Vec<(String, Vec<u8>)> {
    let issues = dir.join("docs").join("issues");
    let mut out: Vec<(String, Vec<u8>)> = Vec::new();
    let mut stack = vec![issues.clone()];
    while let Some(current) = stack.pop() {
        if !current.is_dir() {
            continue;
        }
        for entry in fs::read_dir(&current).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else if path.extension().is_some_and(|e| e == "md") {
                let rel = path
                    .strip_prefix(&issues)
                    .unwrap()
                    .to_string_lossy()
                    .to_string();
                out.push((rel, fs::read(&path).unwrap()));
            }
        }
    }
    out.sort();
    out
}

/// The relationship id `tix link list` printed on the line naming `needle`.
///
/// Extracted from real stdout rather than computed, so the id the test then
/// feeds back to `tix link edit`/`remove` is the id the tool actually
/// advertised. A hardcoded id would pass whether or not the tool prints usable
/// ones.
fn id_from_list(stdout: &str, needle: &str) -> String {
    stdout
        .lines()
        .find(|l| l.contains(needle))
        .and_then(|l| l.rsplit_once('['))
        .map(|(_, rest)| rest.trim_end_matches(']').to_string())
        .unwrap_or_else(|| panic!("no relationship line mentioning {needle:?} in:\n{stdout}"))
}

// ---- T011: typed creation, required --type -----------------------------

#[test]
fn wp03_link_requires_type_and_names_the_flag() {
    let (_tmp, dir) = repo_with_issues(2);
    let before = issue_snapshot(&dir);

    let assert = tix()
        .current_dir(&dir)
        .args(["link", "1", "2"])
        .assert()
        .failure();
    let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.contains("--type"),
        "the rejection must name the missing flag, got: {stderr}"
    );
    for spelling in ["blocks", "blocked_by", "duplicates", "related"] {
        assert!(
            stderr.contains(spelling),
            "the rejection must list `{spelling}`, got: {stderr}"
        );
    }
    // The breaking change, as an observable: the old untyped form is refused,
    // not silently upgraded to `related`.
    assert_eq!(
        issue_snapshot(&dir),
        before,
        "a rejected link must leave every file byte-identical"
    );
}

#[test]
fn wp03_link_rejects_an_unknown_kind() {
    let (_tmp, dir) = repo_with_issues(2);
    let before = issue_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "depends-on"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown_kind"))
        .stderr(predicate::str::contains("depends-on"));
    assert_eq!(issue_snapshot(&dir), before, "no file may change");
}

#[test]
fn wp03_link_rejects_an_empty_type_rather_than_defaulting() {
    // The dangerous case: an empty value reaching the parser. Treating it as
    // "no flag given" and then defaulting would recreate the untype
    // relationship the breaking change removed.
    let (_tmp, dir) = repo_with_issues(2);
    let before = issue_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", ""])
        .assert()
        .failure()
        .stderr(predicate::str::contains("--type"));
    assert_eq!(issue_snapshot(&dir), before, "no file may change");
}

#[test]
fn wp03_the_retired_untype_spellings_are_gone() {
    // C-001 removes the old symmetric surface. A flag that is merely unused
    // still works, and still creates an untype relationship, so its absence has
    // to be pinned rather than assumed.
    let (_tmp, dir) = repo_with_issues(2);
    let before = issue_snapshot(&dir);

    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Fresh", "--links", "0"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("--links"));
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--links", "2"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("--links"));
    tix()
        .current_dir(&dir)
        .args(["unlink", "1", "2"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("--type"));

    assert_eq!(
        issue_snapshot(&dir),
        before,
        "no retired spelling may write anything"
    );
}

/// `tix link list` shows the target's **whole** title, not its last word.
///
/// #1346. `display_target` recovered the title from the `display` field with
/// `rel.display.rfind(' ')`, justified in a comment by "the title may itself contain
/// spaces, so the split is from the right". That is backwards: splitting from the
/// right of `"blocks #1 Second one"` yields `"one"`.
///
///     $ tix create --title "Second one"
///     $ tix link 0 1 --type blocks
///     $ tix link list
///       #0 --blocks--> #1  one  [rel_01M3KY5M2P4ZES4MT3E6KVE8NH]
///
/// `one` is not anybody's title, and it reads as a plausible one — so the edge
/// appears to point at an issue it does not. Single-word titles render correctly,
/// which is why it survived: every existing fixture used one word.
///
/// The title is everything after the **known** prefix (`<kind> #<number> `), so it
/// is a `strip_prefix` rather than a search for a delimiter.
#[test]
fn link_list_renders_a_multi_word_target_title_in_full() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    for title in [
        "First issue here",
        "Second one",
        "A very long multi word title indeed",
    ] {
        tix()
            .current_dir(dir)
            .args(["create", "--title", title])
            .assert()
            .success();
    }
    tix()
        .current_dir(dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["link", "1", "3", "--type", "blocks"])
        .assert()
        .success();

    let out = tix()
        .current_dir(dir)
        .args(["link", "list", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let out = String::from_utf8(out).unwrap();

    // Every word of every title, not just the last.
    for title in ["Second one", "A very long multi word title indeed"] {
        assert!(
            out.contains(title),
            "`tix link list` must show the whole title {title:?}:\n{out}"
        );
    }
    // And specifically not the fragment the old code produced.
    assert!(
        !out.contains("#1  one "),
        "the title must not be truncated to its last word:\n{out}"
    );

    // **Positive control**: a single-word title still renders, so the assertion
    // above is not satisfied by an empty column. `First issue here` is the source,
    // and it is reachable through `tix chain`, which carries the title separately —
    // checked here so both paths are covered by one fixture.
    let chain = tix()
        .current_dir(dir)
        .args(["chain", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert!(
        String::from_utf8(chain)
            .unwrap()
            .contains("First issue here"),
        "the chain line must also show the whole title"
    );
}

#[test]
fn wp03_link_creates_a_typed_edge_and_lists_it_deterministically() {
    let (_tmp, dir) = repo_with_issues(3);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success()
        .stdout(predicate::str::contains("blocks"));
    tix()
        .current_dir(&dir)
        .args(["link", "1", "3", "--type", "duplicates"])
        .assert()
        .success();

    // Ordering is `(kind, target)`, so `blocks` precedes `duplicates`.
    let first = tix()
        .current_dir(&dir)
        .args(["link", "list", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let first = String::from_utf8(first).unwrap();
    let second = tix()
        .current_dir(&dir)
        .args(["link", "list", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert_eq!(
        first,
        String::from_utf8(second).unwrap(),
        "listing must be byte-comparable across runs"
    );
    let blocks_at = first.find("blocks").unwrap();
    let dupes_at = first.find("duplicates").unwrap();
    assert!(
        blocks_at < dupes_at,
        "ordered by (kind, target), got:\n{first}"
    );
}

#[test]
fn wp03_blocked_by_stores_the_canonical_blocks_edge() {
    let (_tmp, dir) = repo_with_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocked_by"])
        .assert()
        .success();
    let out = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let out = String::from_utf8(out).unwrap();
    assert!(out.contains("blocks"), "the stored form is `blocks`: {out}");
    assert!(
        !out.contains("blocked_by"),
        "`blocked_by` is an input spelling and is never persisted: {out}"
    );
    // And the documented filter spelling finds the same edge.
    tix()
        .current_dir(&dir)
        .args(["link", "list", "--kind", "blocked_by"])
        .assert()
        .success()
        .stdout(predicate::str::contains("blocks").and(predicate::str::contains("rel_")));
    tix()
        .current_dir(&dir)
        .args(["link", "list", "--kind", "related"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No related relationships"));
}

#[test]
fn wp03_a_reciprocal_pair_is_rejected_as_a_cycle() {
    // The `blocks` cycle case, now reachable from the CLI. Before WP03 the bare
    // `tix link` recorded `related`, which is order-normalized, so a reciprocal
    // "link" was a no-op rather than a cycle and the case was undemonstrable
    // from the command line.
    let (_tmp, dir) = repo_with_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    let before = issue_snapshot(&dir);

    tix()
        .current_dir(&dir)
        .args(["link", "2", "1", "--type", "blocks"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cycle"));
    assert_eq!(
        issue_snapshot(&dir),
        before,
        "a cycle-closing edge must change nothing (SC-005)"
    );
}

#[test]
fn wp03_a_self_link_and_a_missing_target_are_both_refused() {
    let (_tmp, dir) = repo_with_issues(2);
    let before = issue_snapshot(&dir);

    tix()
        .current_dir(&dir)
        .args(["link", "1", "1", "--type", "blocks"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("self"));
    tix()
        .current_dir(&dir)
        .args(["link", "1", "4243", "--type", "blocks"])
        .assert()
        .failure();

    assert_eq!(issue_snapshot(&dir), before, "no file may change");
}

// ---- T012: edit / remove / idempotency --------------------------------

#[test]
fn wp03_link_edit_keeps_the_id_and_retargets() {
    let (_tmp, dir) = repo_with_issues(3);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    let listed = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let id = id_from_list(&String::from_utf8(listed).unwrap(), "#1 --blocks--> #2");

    tix()
        .current_dir(&dir)
        .args(["link", "edit", &id, "--to", "3"])
        .assert()
        .success();

    let after = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let after = String::from_utf8(after).unwrap();
    assert!(
        after.contains(&"#1 --blocks--> #3".to_string()),
        "the retarget took effect and the id survived: {after}"
    );
    assert!(after.contains(&id), "the same id is still listed: {after}");
}

#[test]
fn wp03_link_remove_is_idempotent_and_writes_nothing_the_second_time() {
    let (_tmp, dir) = repo_with_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    let listed = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let id = id_from_list(&String::from_utf8(listed).unwrap(), "#1 --blocks--> #2");

    tix()
        .current_dir(&dir)
        .args(["link", "remove", &id])
        .assert()
        .success()
        .stdout(predicate::str::contains("Removed"));
    let after_first = issue_snapshot(&dir);

    // The second remove must not write a byte. "Prints a friendly message" and
    // "appends no History entry" are different claims, and only the snapshot
    // tells them apart.
    tix()
        .current_dir(&dir)
        .args(["link", "remove", &id])
        .assert()
        .success()
        .stdout(predicate::str::contains("no change"));
    assert_eq!(
        issue_snapshot(&dir),
        after_first,
        "a repeated remove must not write a file or append History"
    );
}

#[test]
fn wp03_removing_an_absent_id_is_a_no_op_not_an_error() {
    let (_tmp, dir) = repo_with_issues(1);
    let before = issue_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["link", "remove", "rel_does_not_exist"])
        .assert()
        .success()
        .stdout(predicate::str::contains("no change"));
    assert_eq!(issue_snapshot(&dir), before, "nothing may be written");
}

#[test]
fn wp03_a_rejected_edit_changes_nothing() {
    let (_tmp, dir) = repo_with_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    let listed = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let id = id_from_list(&String::from_utf8(listed).unwrap(), "#1 --blocks--> #2");
    let before = issue_snapshot(&dir);

    // Retarget onto the source: a self-link, refused by the service.
    tix()
        .current_dir(&dir)
        .args(["link", "edit", &id, "--to", "1"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("self"));
    assert_eq!(issue_snapshot(&dir), before, "no file may change (SC-005)");
}

#[test]
fn wp03_unlink_with_type_removes_the_same_edge_as_link_remove() {
    let (_tmp, dir) = repo_with_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "related"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["unlink", "1", "2", "--type", "related"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Unlinked"));
    tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No relationships"));
}

#[test]
fn wp03_reapplying_the_same_create_is_idempotent() {
    // T015 step 5: one edge and no second History entry. The `History` heading
    // count is the observable for the second half.
    let (_tmp, dir) = repo_with_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    let after_first = tix()
        .current_dir(&dir)
        .args(["view", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let after_first = String::from_utf8(after_first).unwrap();
    let events_first = after_first.matches("relationship_added").count();

    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success()
        .stdout(predicate::str::contains("no change"));

    let after_second = tix()
        .current_dir(&dir)
        .args(["view", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let after_second = String::from_utf8(after_second).unwrap();
    assert_eq!(
        after_second.matches("relationship_added").count(),
        events_first,
        "a re-applied create appends no second History event:\n{after_second}"
    );

    let listed = tix()
        .current_dir(&dir)
        .args(["link", "list", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let listed = String::from_utf8(listed).unwrap();
    assert_eq!(
        listed.lines().filter(|l| l.contains("rel_")).count(),
        1,
        "one edge, not two:\n{listed}"
    );
}

// ---- T013: chain ------------------------------------------------------

#[test]
fn wp03_chain_prints_a_three_node_chain_in_order() {
    let (_tmp, dir) = repo_with_issues(3);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["link", "2", "3", "--type", "blocks"])
        .assert()
        .success();

    let out = tix()
        .current_dir(&dir)
        .args(["chain", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let out = String::from_utf8(out).unwrap();
    let at = |n: &str| {
        out.find(n)
            .unwrap_or_else(|| panic!("{n} missing from:\n{out}"))
    };
    assert!(at("#1") < at("#2"), "order 1 then 2:\n{out}");
    assert!(at("#2") < at("#3"), "order 2 then 3:\n{out}");
    assert!(out.contains("Issue 0"), "display names appear:\n{out}");
    assert!(
        !out.contains("truncated"),
        "a three-node chain is not truncated:\n{out}"
    );
}

#[test]
fn wp03_chain_names_the_empty_case() {
    let (_tmp, dir) = repo_with_issues(2);
    // #0 is blocked *by* #1; it holds nothing up, so it has no chain.
    tix()
        .current_dir(&dir)
        .args(["link", "2", "1", "--type", "blocks"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["chain", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No dependency chain"));
}

#[test]
fn wp03_chain_with_an_unresolvable_selector_exits_two() {
    let (_tmp, dir) = repo_with_issues(1);
    tix()
        .current_dir(&dir)
        .args(["chain", "1000"])
        .assert()
        .code(2);
}

// ---- T014: list and detail -------------------------------------------

#[test]
fn wp03_list_show_relationships_adds_blocked_and_relations_columns() {
    let (_tmp, dir) = repo_with_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "2", "1", "--type", "blocks"])
        .assert()
        .success();

    // The default listing is unchanged, which is what keeps the presentation
    // difference documented rather than surprising. `--all` so the control is the
    // whole board: the default *scope* (#1711) would otherwise empty it and make the
    // assertion below true for the wrong reason.
    let plain = tix()
        .current_dir(&dir)
        .args(["list", "--all"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let plain = String::from_utf8(plain).unwrap();
    assert!(
        !plain.contains("BLOCKED"),
        "the default listing gains no column:\n{plain}"
    );

    let shown = tix()
        .current_dir(&dir)
        // `--all`: the default listing is scoped to your issues in the board's entry
        // column (#1711). This test is about the relationship columns.
        .args(["list", "--all", "--show", "relationships"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let shown = String::from_utf8(shown).unwrap();
    let header = shown.lines().next().unwrap();
    assert!(header.contains("BLOCKED"), "header: {header}");
    assert!(header.contains("RELATIONS"), "header: {header}");
    assert!(
        shown.contains("Blocked by #2"),
        "the blocked reason comes from the service:\n{shown}"
    );
    assert!(
        shown.contains("blocks -> #1"),
        "the relationship is shown on the blocked side too:\n{shown}"
    );
}

#[test]
fn wp03_a_related_only_issue_is_not_shown_as_blocked() {
    let (_tmp, dir) = repo_with_issues(2);
    // Typed as `1 related 0`, deliberately not in canonical order.
    tix()
        .current_dir(&dir)
        .args(["link", "2", "1", "--type", "related"])
        .assert()
        .success();
    let shown = tix()
        .current_dir(&dir)
        // `--all`: the default listing is scoped to your issues in the board's entry
        // column (#1711). This test is about the relationship columns.
        .args(["list", "--all", "--show", "relationships"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let shown = String::from_utf8(shown).unwrap();
    assert!(
        !shown.contains("Blocked by"),
        "`related` must not imply blocked — the distinction is the point:\n{shown}"
    );

    // `related` is order-normalized by canonical id, so **both** endpoints render
    // the same stored orientation. The chosen number can differ by run because ids
    // are random; equality of the two rows is the invariant.
    let rows: Vec<&str> = shown
        .lines()
        .skip(1)
        .filter(|line| line.contains("related -> #"))
        .collect();
    assert_eq!(
        rows.len(),
        2,
        "both endpoints show the canonical orientation:\n{shown}"
    );
    let target = rows[0].split("related -> ").nth(1).unwrap();
    assert_eq!(
        rows[1].split("related -> ").nth(1).unwrap(),
        target,
        "both rows must render the one stored orientation:\n{shown}"
    );
}

#[test]
fn wp03_view_show_relationships_appends_the_derived_block() {
    let (_tmp, dir) = repo_with_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "2", "1", "--type", "blocks"])
        .assert()
        .success();

    // Without the flag, `tix view` is the file and nothing else.
    let plain = tix()
        .current_dir(&dir)
        .args(["view", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let plain = String::from_utf8(plain).unwrap();
    assert!(
        !plain.contains("## Relationships"),
        "the default detail output is unchanged:\n{plain}"
    );

    let shown = tix()
        .current_dir(&dir)
        .args(["view", "1", "--show", "relationships"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let shown = String::from_utf8(shown).unwrap();
    for section in ["## Relationships", "## Dependency chain", "## Blocked"] {
        assert!(shown.contains(section), "missing {section} in:\n{shown}");
    }
    assert!(shown.contains("Blocked by #2"), "reason:\n{shown}");
}

#[test]
fn wp03_an_unknown_show_value_is_rejected() {
    let (_tmp, dir) = repo_with_issues(1);
    tix()
        .current_dir(&dir)
        .args(["list", "--show", "relatinships"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown --show value"));
    tix()
        .current_dir(&dir)
        .args(["view", "1", "--show", "relatinships"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown --show value"));
}

// ---- the two-issue no-partial-write guarantee (T015 step 4) -----------

#[test]
fn wp03_a_two_issue_mutation_is_all_or_nothing() {
    // The strongest form of SC-005. A command that would touch two files and
    // fails on the second must leave **both** byte-identical, which a
    // single-file check would not catch.
    let (_tmp, dir) = repo_with_issues(3);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    let before = issue_snapshot(&dir);
    assert!(before.len() >= 3, "precondition: three files on disk");

    // Each of these is refused before any write.
    tix()
        .current_dir(&dir)
        .args(["link", "2", "1", "--type", "blocks"])
        .assert()
        .failure();
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["link", "3", "1", "--type", "blocks"])
        .assert()
        .success();

    // Now the strong case: a retarget whose *second* endpoint is invalid. The
    // service validates before the first write, so the already-valid first half
    // must also be rolled back.
    let mid = issue_snapshot(&dir);
    let listed = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let id = id_from_list(&String::from_utf8(listed).unwrap(), "#1 --blocks--> #2");
    tix()
        .current_dir(&dir)
        .args(["link", "edit", &id, "--to", "1", "--type", "related"])
        .assert()
        .failure();
    assert_eq!(
        issue_snapshot(&dir),
        mid,
        "a rejected two-half mutation must leave both files byte-identical"
    );
}

#[test]
fn wp03_relationship_commands_are_tty_free() {
    // T015 step 6. `assert_cmd` already pipes stdin, so a command that demanded
    // a TTY would fail here rather than hang; this asserts the contract
    // explicitly and gives the failure a name.
    let (_tmp, dir) = repo_with_issues(2);
    for args in [
        vec!["link", "1", "2", "--type", "blocks"],
        vec!["link", "list"],
        vec!["chain", "1"],
        vec!["list", "--show", "relationships"],
        vec!["view", "2", "--show", "relationships"],
    ] {
        tix().current_dir(&dir).args(&args).assert().success();
    }
}

/// A relationship re-kind that moves the canonical `from` is the case the
/// existing `wp03_link_edit_keeps_the_id_and_retargets` never reaches: it
/// retargets `blocks -> blocks`, where the owner cannot change.
///
/// A re-kind *can* change the owner, because `related` is order-normalised and
/// `blocked_by` swaps the endpoints. The edit removed the row from its old owner
/// and re-added it only when the file it removed from was also the new one — so
/// when ownership moved, the row was deleted and nothing was ever written to the
/// new owner. The call reported success, exit 0, and the relationship was gone.
#[test]
fn wp03_a_rekind_that_moves_the_canonical_owner_keeps_the_relationship() {
    for (from, to, kind, rekind) in [
        // duplicates 3->1 is directional and stays as authored; re-kinding to
        // `blocked_by` normalizes into `1 blocks 3`, so the owner moves 3 -> 1.
        ("3", "1", "duplicates", "blocked_by"),
        // duplicates 3->1 re-kinded to `related` normalizes to `(1, 3)`.
        ("3", "1", "duplicates", "related"),
        // `related 6 related 9` is already stored canonically as `(6, 9)`, so
        // re-kinding it to `related` is the identity edit and is correctly
        // refused. Moving the owner needs a *target* below the current one:
        // retargeting to #3 makes the canonical pair `(3, 6)`.
        ("6", "9", "related", "retarget"),
    ] {
        let (_tmp, dir) = repo_with_named_issues(9);
        tix()
            .current_dir(&dir)
            .args(["link", from, to, "--type", kind])
            .assert()
            .success();
        let listed = tix()
            .current_dir(&dir)
            .args(["link", "list"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let id = id_from_list(&String::from_utf8(listed).unwrap(), &format!("--{kind}-->"));

        let edit = if rekind == "retarget" {
            tix()
                .current_dir(&dir)
                .args(["link", "edit", &id, "--to", "3"])
                .assert()
                .success()
        } else {
            tix()
                .current_dir(&dir)
                .args(["link", "edit", &id, "--type", rekind])
                .assert()
                .success()
        };
        let text = String::from_utf8(edit.get_output().stdout.clone()).unwrap();
        assert!(
            text.starts_with("Relinked"),
            "{from} {kind} {to} -> {rekind}: {text}"
        );

        // The edge must be *findable* afterwards. Reporting success while the
        // relationship is gone is the whole failure, so the assertion is on the
        // store, never on the message.
        let after = tix()
            .current_dir(&dir)
            .args(["link", "list"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let after = String::from_utf8(after).unwrap();
        assert!(
            after.contains(&id),
            "{from} {kind} {to} -> {rekind}: the relationship vanished.\nlist said: {after}"
        );

        // And exactly one `relationship_retargeted` event, on the **new** owner.
        //
        // Counted across every issue file rather than at two hardcoded numbers:
        // the new owner differs per case (#0 for a `blocked_by` re-kind, #2 for a
        // `related` retarget), and a check that only looked at two of them would
        // have passed with the event recorded on neither.
        let events: Vec<String> = issue_files_under(&dir.join("docs").join("issues"))
            .into_iter()
            .filter(|p| {
                std::fs::read_to_string(p)
                    .unwrap()
                    .contains("relationship_retargeted")
            })
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert_eq!(
            events.len(),
            1,
            "{from} {kind} {to} -> {rekind}: exactly one retarget event, on the new owner, got {events:?}"
        );
    }
}

/// The stored display name must describe the edge it is stored on.
///
/// A `2 duplicates 0` edge re-kinded to `blocked_by` is stored as `0 blocks 2`,
/// so the canonical target is #2. Deriving the display from the *authored*
/// target produced `blocks #2 Issue A` — right endpoints, wrong issue, and a row
/// that lies about what it names.
#[test]
fn wp03_a_rekind_names_the_canonical_target_in_its_display_and_history() {
    let (_tmp, dir) = repo_with_named_issues(3);
    tix()
        .current_dir(&dir)
        .args(["link", "3", "1", "--type", "duplicates"])
        .assert()
        .success();
    let listed = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let id = id_from_list(&String::from_utf8(listed).unwrap(), "--duplicates--> #1");

    tix()
        .current_dir(&dir)
        .args(["link", "edit", &id, "--type", "blocked_by"])
        .assert()
        .success();

    let listed = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let listed = String::from_utf8(listed).unwrap();
    let row = listed
        .lines()
        .find(|l| l.contains("#1 --blocks--> #3"))
        .unwrap_or_else(|| panic!("no blocks edge after the re-kind:\n{listed}"));
    // `tix link list` renders the target's title, so the row itself proves the
    // display names #2 rather than #0.
    assert!(
        row.ends_with(" Charlie  [") || row.contains(" Charlie "),
        "the row must name #2's title, got {row:?}"
    );
    assert!(
        !row.contains(" Alpha "),
        "and must not name #0's title, got {row:?}"
    );

    // The History detail is built from the same display, so it must agree.
    let view = tix()
        .current_dir(&dir)
        .args(["view", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let view = String::from_utf8(view).unwrap();
    let event = view
        .lines()
        .find(|l| l.contains("relationship_retargeted"))
        .unwrap_or_else(|| panic!("no retarget event:\n{view}"));
    assert!(
        event.contains("blocks #3 Issue Charlie"),
        "the event must name the canonical target, got {event:?}"
    );
    assert!(
        !event.contains("blocks #2 Issue Alpha"),
        "and must not name the authored target, got {event:?}"
    );
}

/// Only `blocks` can close a cycle.
///
/// The reachability search runs over the `blocks` adjacency, so asking it about a
/// `related` or `duplicates` edge is asking a question about an edge that is not
/// in that graph. It found a `blocks` path between the two endpoints and reported
/// a cycle for an edge that closes none — which also made a legitimate re-kind
/// unreachable, since `2 blocks 0` plus "re-kind to `related`" was refused.
#[test]
fn wp03_only_blocks_edges_are_subject_to_cycle_rejection() {
    let (_tmp, dir) = repo_with_named_issues(3);
    tix()
        .current_dir(&dir)
        .args(["link", "3", "1", "--type", "blocks"])
        .assert()
        .success();

    // `related` between the two endpoints of a `blocks` path: not a cycle.
    tix()
        .current_dir(&dir)
        .args(["link", "1", "3", "--type", "related"])
        .assert()
        .success()
        .stdout(predicate::str::contains("linked").or(predicate::str::contains("Linked")));

    // And a genuine `blocks` cycle is still refused, with the cycle named.
    tix()
        .current_dir(&dir)
        .args(["link", "1", "3", "--type", "blocks"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cycle"));
}

/// A re-kind that turns a `blocks` edge into a `related` one is reachable again.
///
/// This is the practical consequence of scoping cycle detection to `blocks`: with
/// the rule as it was, the only way to reach this state was the edit path that
/// destroyed the relationship, so the two defects compounded.
#[test]
fn wp03_a_blocks_edge_can_be_rekinds_as_related() {
    let (_tmp, dir) = repo_with_named_issues(3);
    tix()
        .current_dir(&dir)
        .args(["link", "3", "1", "--type", "blocks"])
        .assert()
        .success();
    let listed = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let id = id_from_list(&String::from_utf8(listed).unwrap(), "--blocks--> #1");

    tix()
        .current_dir(&dir)
        .args(["link", "edit", &id, "--type", "related"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Relinked"));

    let after = tix()
        .current_dir(&dir)
        .args(["link", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let after = String::from_utf8(after).unwrap();
    assert!(
        after.contains("--related-->"),
        "the re-kinded edge must be stored: {after}"
    );
    assert!(
        !after.contains("--blocks-->"),
        "and must no longer be a `blocks` edge: {after}"
    );
}

/// `--status` is a move, so it answers to the same blocked-move policy as
/// `tix move`.
///
/// The guard used to be a suggestion with a second door beside it: `tix move <n>
/// done` warned and refused, while `tix edit <n> --status done` put the same issue
/// into the same column silently, recorded nothing, and exited 0.
#[test]
fn wp04_edit_status_cannot_move_a_blocked_issue_into_completion() {
    let (_tmp, dir) = repo_with_named_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    let before = issue_snapshot(&dir);

    // Both surfaces, one decision.
    let move_err = tix()
        .current_dir(&dir)
        .args(["move", "2", "done"])
        .assert()
        .failure()
        .get_output()
        .stderr
        .clone();
    let edit_err = tix()
        .current_dir(&dir)
        .args(["edit", "2", "--status", "done"])
        .assert()
        .failure()
        .get_output()
        .stderr
        .clone();
    let move_err = String::from_utf8_lossy(&move_err).to_string();
    let edit_err = String::from_utf8_lossy(&edit_err).to_string();

    // The same diagnostic kind, and the same reason.
    for (label, text) in [("move", &move_err), ("edit", &edit_err)] {
        assert!(text.contains("blocked:"), "{label}: {text}");
        assert!(text.contains("#1"), "{label} must name the blocker: {text}");
    }
    // And the edit names the route that does work.
    assert!(
        edit_err.contains("tix move"),
        "the refusal must say how to proceed: {edit_err}"
    );

    // Nothing written, and no acknowledgement recorded for a move that did not
    // happen.
    assert_eq!(
        issue_snapshot(&dir),
        before,
        "a refused edit writes nothing"
    );
    let view = tix()
        .current_dir(&dir)
        .args(["view", "2"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let view = String::from_utf8(view).unwrap();
    assert!(
        !view.contains("blocked_move_acknowledged"),
        "a refused move must not record an acknowledgement:\n{view}"
    );
    assert!(
        view.contains("status: triage"),
        "the status must be unchanged:\n{view}"
    );
}

/// The refusal is specific to the completion column, and to blocked issues.
#[test]
fn wp04_edit_status_still_allows_ordinary_columns_and_unblocked_issues() {
    let (_tmp, dir) = repo_with_named_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();

    // A blocked issue moving to an ordinary column: blockers do not block
    // ordinary progress.
    tix()
        .current_dir(&dir)
        .args(["edit", "2", "--status", "in progress"])
        .assert()
        .success();

    // The blocker itself is unblocked, so it reaches the completion column.
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--status", "done"])
        .assert()
        .success();
    let view = tix()
        .current_dir(&dir)
        .args(["view", "1"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert!(String::from_utf8(view).unwrap().contains("status: done"));
}

/// A rejected `--show` must produce **no output at all**.
///
/// `tix view 0 --show bogus` used to print the whole issue file and *then* exit
/// non-zero, so a consumer that redirects stdout got a file that looks complete
/// alongside a status code that says it failed, and no way to tell which to
/// believe. The contract is that stdout stays clean for the parseability case
/// (`src/cli.rs`: "Human-readable errors go to stderr; stdout stays clean").
#[test]
fn wp04_a_rejected_show_value_writes_nothing_to_stdout() {
    let (_tmp, dir) = repo_with_named_issues(1);
    let out = tix()
        .current_dir(&dir)
        .args(["view", "1", "--show", "bogus"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    assert!(
        out.is_empty(),
        "a rejected invocation must print nothing, got {} bytes: {:?}",
        out.len(),
        String::from_utf8_lossy(&out)
    );
}

/// The blocked-move History entry names the blockers exactly once.
///
/// `blocked_note` prepends `blocked: ` for the CLI warning, the TUI prompt and the
/// detail view. The History line is not one of those surfaces, and reusing the
/// wrapper produced `moved to done: blocked: Blocked by #0 Issue A` — the prefix
/// twice, in the one record an audit trail keeps.
#[test]
fn wp04_the_acknowledgement_event_names_the_blockers_once() {
    let (_tmp, dir) = repo_with_named_issues(2);
    tix()
        .current_dir(&dir)
        .args(["link", "1", "2", "--type", "blocks"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["move", "2", "done", "--yes", "--commit", "abc123"])
        .assert()
        .success();

    let view = tix()
        .current_dir(&dir)
        .args(["view", "2"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let view = String::from_utf8(view).unwrap();
    let event = view
        .lines()
        .find(|l| l.contains("blocked_move_acknowledged"))
        .unwrap_or_else(|| panic!("no acknowledgement event:\n{view}"));
    assert!(
        event.contains("Blocked by #1"),
        "the event must name the blocker: {event:?}"
    );
    // Zero, not one: the History line is not a surface, so it carries the bare
    // service reason and no `blocked: ` wrapper at all. The wrapper belongs to the
    // CLI warning, the TUI prompt and the detail view.
    assert_eq!(
        event.matches("blocked:").count(),
        0,
        "the record carries the reason, not the surface wrapper: {event:?}"
    );
    assert!(
        !event.contains("blocked: Blocked by"),
        "no doubled prefix: {event:?}"
    );
}

// ---------------------------------------------------------------------------
// WP03 / T014 — the hierarchy through the real binary
// ---------------------------------------------------------------------------
//
// Directory snapshots before and after are the only honest proof that a rejected
// command wrote nothing (SC-004). Exit codes alone cannot tell a correct refusal
// from the wrong one, and a `tix edit` that half-applied before failing still
// exits non-zero.
//
// Note on numbering: `Store::resolve_next_number` returns 0 for an empty
// directory, so the first issue in a fresh repo is `#0` (tix #1376). These tests
// read the numbers back from `tix list` rather than assuming a sequence, so they
// will keep passing if that is ever changed to start at 1.

/// Every issue file's bytes, as one sorted list — the "nothing was written" check.
fn hierarchy_snapshot(dir: &Path) -> Vec<(PathBuf, Vec<u8>)> {
    let root = dir.join("docs").join("issues");
    let mut stack = vec![root];
    let mut out = Vec::new();
    while let Some(cur) = stack.pop() {
        for entry in fs::read_dir(&cur).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else {
                out.push((path.clone(), fs::read(&path).unwrap()));
            }
        }
    }
    out.sort();
    out
}

/// A repo with one issue, and its number as `tix` reports it.
fn hierarchy_repo(count: usize) -> (TempDir, PathBuf, u32) {
    let names = ["Epic", "Alpha", "Bravo", "Charlie"];
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    tix().current_dir(&dir).arg("init").assert().success();
    // Disable auto-migration so parent/child edits keep files where fixtures put them.
    let cfg = dir.join("tix.toml");
    let mut text = std::fs::read_to_string(&cfg).unwrap();
    text.push_str("\n[layout]\nmove_on_change = false\n");
    std::fs::write(&cfg, text).unwrap();
    for name in names.iter().take(count) {
        tix()
            .current_dir(&dir)
            .args(["create", "--title", name])
            .assert()
            .success();
    }
    let out = tix()
        .current_dir(&dir)
        // `--all`: the default listing is scoped to your issues in the board's entry
        // column (#1711), and this helper only needs the number a create produced.
        .args(["list", "--all"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let first = String::from_utf8(out).unwrap();
    let number: u32 = first
        .lines()
        .nth(1)
        .and_then(|l| l.split_whitespace().next())
        .and_then(|n| n.parse().ok())
        .expect("`tix list` must report a first row with a number");
    (tmp, dir, number)
}

/// The parsed canonical `parent` value of the issue titled `title`, or `None`.
fn parent_of_title(dir: &Path, title: &str) -> Option<String> {
    let path = issue_file_named(dir, title);
    let text = fs::read_to_string(path).unwrap();
    text.lines()
        .find_map(|l| l.strip_prefix("parent: "))
        .map(|value| value.trim().to_string())
}

/// The canonical issue `id` of the issue titled `title`.
fn id_of_title(dir: &Path, title: &str) -> String {
    let path = issue_file_named(dir, title);
    let text = fs::read_to_string(path).unwrap();
    text.lines()
        .find_map(|line| line.strip_prefix("id: "))
        .map(str::trim)
        .filter(|id| tix::id::is_issue_id(id))
        .map(str::to_string)
        .unwrap_or_else(|| panic!("issue {title:?} has no canonical id"))
}

/// The `## History` event lines of the issue titled `title`.
fn history_of_title(dir: &Path, title: &str) -> Vec<String> {
    let text = fs::read_to_string(issue_file_named(dir, title)).unwrap();
    text.lines()
        .skip_while(|l| *l != "## History")
        .filter(|l| l.starts_with("- "))
        .map(|l| {
            // The timestamp and actor vary per run; the kind and detail do not.
            let parts: Vec<&str> = l.trim_start_matches("- ").split(" \u{2014} ").collect();
            format!(
                "{} | {}",
                parts.get(2).copied().unwrap_or("?"),
                parts.get(3).copied().unwrap_or("?")
            )
        })
        .collect()
}

fn issue_file_named(dir: &Path, title: &str) -> PathBuf {
    let slug = title.to_lowercase().replace(' ', "-");
    let issues = dir.join("docs").join("issues");
    for child in issue_files_under(&issues) {
        if child
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.contains(&slug))
        {
            return child;
        }
    }
    panic!("no issue file matching {title:?} under {issues:?}");
}

#[test]
fn t014_create_with_a_parent_writes_the_field_and_one_history_entry() {
    let (_tmp, dir, epic) = hierarchy_repo(1);
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Alpha", "--parent", &epic.to_string()])
        .assert()
        .success();

    assert_eq!(
        parent_of_title(&dir, "Alpha"),
        Some(id_of_title(&dir, "Epic")),
        "the parent is stored as the parent's canonical id"
    );
    let events = history_of_title(&dir, "Alpha");
    assert_eq!(events.len(), 1, "exactly one entry: {events:?}");
    assert!(
        events[0].starts_with("parent_set"),
        "the kind must name the transition: {events:?}"
    );
    assert!(
        events[0].contains(&format!("#{epic}")),
        "the entry must name the parent: {events:?}"
    );
}

#[test]
fn t014_edit_changes_then_clears_the_parent() {
    let (_tmp, dir, epic) = hierarchy_repo(3);
    let alpha = epic + 1;
    let bravo = epic + 2;
    tix()
        .current_dir(&dir)
        .args(["edit", &alpha.to_string(), "--parent", &epic.to_string()])
        .assert()
        .success();
    let epic_id = id_of_title(&dir, "Epic");
    let bravo_id = id_of_title(&dir, "Bravo");
    assert_eq!(parent_of_title(&dir, "Alpha"), Some(epic_id));

    tix()
        .current_dir(&dir)
        .args(["edit", &alpha.to_string(), "--parent", &bravo.to_string()])
        .assert()
        .success();
    assert_eq!(parent_of_title(&dir, "Alpha"), Some(bravo_id));

    let events = history_of_title(&dir, "Alpha");
    assert_eq!(events.len(), 2, "one entry per accepted change: {events:?}");
    assert!(events[0].starts_with("parent_set"), "{events:?}");
    assert!(
        events[1].starts_with("parent_changed"),
        "a repoint is a change, not a second set: {events:?}"
    );

    tix()
        .current_dir(&dir)
        .args(["edit", &alpha.to_string(), "--parent", ""])
        .assert()
        .success();
    assert_eq!(
        parent_of_title(&dir, "Alpha"),
        None,
        "`--parent \"\"` clears"
    );
    let events = history_of_title(&dir, "Alpha");
    assert_eq!(events.len(), 3, "{events:?}");
    assert!(events[2].starts_with("parent_cleared"), "{events:?}");
}

#[test]
fn t014_parent_reports_the_hierarchy() {
    // Only the parent is seeded. The first version seeded three issues *and* then
    // created two children also titled `Alpha` and `Bravo`, so the two sets
    // collided on the date-prefixed slug and the numbers in the report did not
    // match the ones the test had computed.
    let (_tmp, dir, epic) = hierarchy_repo(1);
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Alpha", "--parent", &epic.to_string()])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Bravo", "--parent", &epic.to_string()])
        .assert()
        .success();
    let alpha = epic + 1;

    let show = tix()
        .current_dir(&dir)
        .args(["parent", "show", &epic.to_string()])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let show = String::from_utf8(show).unwrap();
    assert!(show.contains("parent: none"), "{show}");
    assert!(show.contains("children: 2"), "{show}");
    assert!(show.contains("completed: 0/2"), "{show}");
    // Ordered by issue number.
    let alpha_at = show.find(&format!("#{alpha} Alpha")).unwrap();
    let bravo = alpha + 1;
    let bravo_at = show.find(&format!("#{bravo} Bravo")).unwrap();
    assert!(alpha_at < bravo_at, "children must be ordered:\n{show}");

    let children = tix()
        .current_dir(&dir)
        .args(["parent", "children", &epic.to_string()])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let children = String::from_utf8(children).unwrap();
    assert!(children.contains("2 children"), "{children}");

    let list = tix()
        .current_dir(&dir)
        .arg("parent")
        .arg("list")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let list = String::from_utf8(list).unwrap();
    assert!(list.contains("Epic"), "{list}");
    assert!(
        !list.contains("Alpha") && !list.contains("Bravo"),
        "leaves are not parents: {list}"
    );
}

#[test]
fn t014_a_rejected_change_leaves_every_file_byte_identical() {
    // The three refusals, each asserting **why** it was refused and that the whole
    // directory is unchanged. An exit code alone cannot tell a correct refusal
    // from the wrong one — the same lesson that made
    // `sc005_a_rejected_mutation_leaves_every_byte_unchanged` assert phrases.
    let (_tmp, dir, epic) = hierarchy_repo(3);
    let alpha = epic + 1;
    let bravo = epic + 2;
    tix()
        .current_dir(&dir)
        .args(["edit", &alpha.to_string(), "--parent", &epic.to_string()])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["edit", &bravo.to_string(), "--parent", &alpha.to_string()])
        .assert()
        .success();
    let before = hierarchy_snapshot(&dir);

    // `String`s bound first: a `&String` inside a `Vec<&str>` borrows a temporary
    // that dies at the end of the statement.
    let alpha_s = alpha.to_string();
    let bravo_s = bravo.to_string();
    let epic_s = epic.to_string();
    let cases: Vec<(Vec<&str>, &str)> = vec![
        // Self-parent: the issue's own number.
        (
            vec!["edit", alpha_s.as_str(), "--parent", alpha_s.as_str()],
            "self_parent",
        ),
        // Unknown parent.
        (vec!["edit", alpha_s.as_str(), "--parent", "99999"], "99999"),
        // Cycle: epic -> alpha -> bravo, so epic under bravo closes the loop.
        (
            vec!["edit", epic_s.as_str(), "--parent", bravo_s.as_str()],
            "cycle",
        ),
    ];
    for (args, expected) in cases {
        tix()
            .current_dir(&dir)
            .args(&args)
            .assert()
            .failure()
            .stderr(predicate::str::contains(expected));
        assert_eq!(
            hierarchy_snapshot(&dir),
            before,
            "a rejected change must leave every file byte-identical; failed for {args:?}"
        );
    }
}

#[test]
fn t014_create_with_a_bad_parent_creates_no_file() {
    let (_tmp, dir, _) = hierarchy_repo(1);
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Orphan", "--parent", "99999"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("99999"));
    assert_eq!(
        hierarchy_snapshot(&dir),
        before,
        "a refused create must leave the directory byte-identical"
    );
}

#[test]
fn t014_clearing_an_issue_with_no_parent_is_a_no_op() {
    let (_tmp, dir, _) = hierarchy_repo(2);
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--parent", ""])
        .assert()
        .success();
    assert_eq!(
        hierarchy_snapshot(&dir),
        before,
        "a no-op must not write, append, or move a date"
    );
}

#[test]
fn t014_a_legacy_file_with_no_parent_key_is_accepted_and_left_byte_identical() {
    // A file written before the field existed: it must parse, and nothing about
    // reading it may change it.
    let (_tmp, dir, _) = hierarchy_repo(1);
    let legacy = dir
        .join("docs")
        .join("issues")
        .join("unassigned")
        .join("2026-01-01-legacy.md");
    fs::create_dir_all(legacy.parent().unwrap()).unwrap();
    let contents = "---\nnumber: 90\ntitle: Legacy issue\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody text.\n";
    fs::write(&legacy, contents).unwrap();

    // Reading it through a hierarchy report must not rewrite it.
    tix()
        .current_dir(&dir)
        .args(["parent", "show", "90"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["parent", "children", "90"])
        .assert()
        .success();
    assert_eq!(
        fs::read_to_string(&legacy).unwrap(),
        contents,
        "a legacy file must survive the hierarchy surfaces byte-identically"
    );

    // And a no-op edit leaves it alone.
    tix()
        .current_dir(&dir)
        .args(["edit", "90", "--parent", ""])
        .assert()
        .success();
    assert_eq!(fs::read_to_string(&legacy).unwrap(), contents);
}

// ---------------------------------------------------------------------------
// WP04 T020 — the workflow surface, through the real binary
// ---------------------------------------------------------------------------
//
// Every rejection in this section asserts **byte-identity of the whole fixture
// directory**, not a non-zero exit code. An exit code is evidence that the command
// reported failure; it is not evidence that nothing was written. A path that
// validates, refuses, and has already re-serialised the issue on its way out
// satisfies `assert().failure()` perfectly and still destroys the audit trail.
//
// `hierarchy_snapshot` is reused for this: it reads every file under
// `docs/issues` into `(path, bytes)`, which is exactly the property "nothing was
// written, including no History entry".

/// A repo whose board **declares a `category_map`**, so transition policy applies.
///
/// `triage=backlog, wip=active, review=active, shipped=completed,
/// abandoned=canceled` — which gives a forward move (`triage`→`wip`), a backwards
/// move refused by adjacency (`wip`→`triage`), a terminal exit (`shipped`→`wip`),
/// and a second terminal category that is **not** complete (`abandoned`).
fn workflow_repo() -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    fs::create_dir_all(dir.join("docs").join("issues")).unwrap();
    fs::write(
        dir.join("tix.toml"),
        "issues_dir = \"docs/issues\"\n\n\
         [kanban.default]\n\
         columns = [\"triage\", \"wip\", \"review\", \"shipped\", \"abandoned\"]\n\
         done_column = \"shipped\"\n\n\
         [kanban.default.category_map]\n\
         triage = \"backlog\"\n\
         wip = \"active\"\n\
         review = \"active\"\n\
         shipped = \"completed\"\n\
         abandoned = \"canceled\"\n",
    )
    .unwrap();
    for title in ["Alpha", "Bravo"] {
        tix()
            .current_dir(&dir)
            .args(["create", "--title", title])
            .assert()
            .success();
    }
    (tmp, dir)
}

/// A repo on a **legacy** board — the four columns and no `category_map` at all.
///
/// Written by hand rather than by `tix init`: init now writes a fully mapped,
/// triage-ready board, so a test that wants the *unmapped* path has to ask for one.
/// This is the board every repository had before the category vocabulary existed.
/// Completion detection must work here (the `done_column` resolves to `completed`) and
/// no transition policy may apply, which is the opt-in WP03 settled.
fn legacy_board_repo() -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    fs::create_dir_all(dir.join("docs").join("issues")).unwrap();
    fs::write(
        dir.join("tix.toml"),
        "issues_dir = \"docs/issues\"\n\n\
         [kanban.default]\n\
         columns = [\"todo\", \"in progress\", \"in review\", \"done\"]\n\
         done_column = \"done\"\n",
    )
    .unwrap();
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Alpha"])
        .assert()
        .success();
    (tmp, dir)
}

#[test]
fn t020_workflow_categories_prints_the_vocabulary_in_order() {
    let (_tmp, dir) = legacy_board_repo();
    let out = tix()
        .current_dir(&dir)
        .args(["workflow", "categories"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    for key in ["backlog", "unstarted", "active", "completed", "canceled"] {
        assert!(text.contains(key), "`{key}` must be listed: {text}");
    }
    // Order is the *declared* order, which is what adjacency is evaluated against.
    let order_line = text
        .lines()
        .find(|l| l.starts_with("Order:"))
        .expect("the declared order must be printed");
    let listed: Vec<&str> = order_line
        .trim_start_matches("Order: ")
        .split(" -> ")
        .collect();
    assert_eq!(
        listed.first().copied(),
        Some("backlog"),
        "the order line is the adjacency order: {order_line}"
    );
    assert!(
        listed.iter().position(|c| *c == "completed")
            < listed.iter().position(|c| *c == "canceled"),
        "and it matches the vocabulary: {order_line}"
    );
    // Both terminal categories are marked, and `active` is not.
    let completed_row = text
        .lines()
        .find(|l| l.starts_with("completed"))
        .expect("a row per category");
    assert!(
        completed_row.trim_end().ends_with("yes"),
        "completed is terminal: {completed_row}"
    );
    let active_row = text
        .lines()
        .find(|l| l.starts_with("active "))
        .expect("a row per category");
    assert!(
        !active_row.contains("yes"),
        "active is not terminal: {active_row}"
    );
}

#[test]
fn t020_workflow_show_reports_the_source_of_each_resolution() {
    // A board with explicit mappings: every column says `category_map`.
    let (_tmp, dir) = workflow_repo();
    let out = tix()
        .current_dir(&dir)
        .args(["workflow", "show"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    assert!(
        text.contains("Category policy: declared"),
        "a board with a map has opted into policy: {text}"
    );
    for column in ["triage", "wip", "review", "shipped", "abandoned"] {
        assert!(text.contains(column), "{column} must be listed: {text}");
    }
    assert!(
        text.contains("category_map"),
        "and its source must be named: {text}"
    );
    assert!(
        !text.contains("safe default"),
        "nothing on a fully-mapped board relied on the default: {text}"
    );

    // A board with no map at all: the safe default is named for every column, and
    // the opt-in is reported as *not* declared.
    let (_tmp2, dir2) = legacy_board_repo();
    let out2 = tix()
        .current_dir(&dir2)
        .args(["workflow", "show"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text2 = String::from_utf8(out2).unwrap();
    assert!(
        text2.contains("Category policy: not declared"),
        "a board with no map has no transition policy: {text2}"
    );
    assert!(
        text2.contains("safe default"),
        "and the default is reported rather than silent: {text2}"
    );
    // The board's completion column resolves to `completed` even with no map —
    // that reconciliation is what makes completion work everywhere.
    let done_row = text2
        .lines()
        .find(|l| l.starts_with("done"))
        .expect("the completion column must be listed");
    assert!(
        done_row.contains("completed"),
        "the done_column resolves to completed via the legacy rule: {done_row}"
    );
    assert!(
        done_row.contains("safe default"),
        "and via the default, which is why it is not listed as a finding: {done_row}"
    );
}

#[test]
fn t020_workflow_show_on_an_unconfigured_board_is_not_an_error() {
    // NFR-003: a board with no configuration reports the vocabulary and the
    // inherited default rather than failing. `tix init` always writes a board, so
    // the fixture is a config with an empty `[kanban]` section.
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    fs::create_dir_all(dir.join("docs").join("issues")).unwrap();
    fs::write(dir.join("tix.toml"), "issues_dir = \"docs/issues\"\n").unwrap();
    tix()
        .current_dir(&dir)
        .args(["workflow", "show"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["workflow", "categories"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["workflow", "transitions"])
        .assert()
        .success();
}

#[test]
fn t020_workflow_show_names_an_unknown_board_and_lists_the_real_ones() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["workflow", "show", "nope"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("nope"))
        .stderr(predicates::str::contains("default"));
}

#[test]
fn t020_workflow_transitions_reports_the_effective_policy() {
    // A mapped board: the lock and adjacency apply.
    let (_tmp, dir) = workflow_repo();
    let text = String::from_utf8(
        tix()
            .current_dir(&dir)
            .args(["workflow", "transitions"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(text.contains("Terminal lock: on"), "{text}");
    assert!(text.contains("Applies: yes"), "{text}");
    assert!(text.contains("Category adjacency: on"), "{text}");
    assert!(
        text.contains("--reason"),
        "the escape hatch is spelled, not just described: {text}"
    );

    // An unmapped board: configured on, but not applicable, and saying so is the
    // whole value of this command.
    let (_tmp2, dir2) = legacy_board_repo();
    let text2 = String::from_utf8(
        tix()
            .current_dir(&dir2)
            .args(["workflow", "transitions"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(text2.contains("Terminal lock: on"), "{text2}");
    assert!(
        text2.contains("Applies: no"),
        "on but inapplicable must not read as enforced: {text2}"
    );
}

#[test]
fn t020_a_compatible_move_is_accepted_and_recorded() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "wip"])
        .assert()
        .success()
        .stdout(predicates::str::contains("In progress"));
    let events = history_of_title(&dir, "Alpha");
    assert_eq!(
        events,
        vec!["transition_accepted | triage -> wip (backlog -> active)".to_string()],
        "exactly one decision, naming both columns and both categories: {events:?}"
    );
    let text = fs::read_to_string(issue_file_named(&dir, "Alpha")).unwrap();
    assert!(text.contains("status: wip"), "{text}");
}

#[test]
fn t020_an_unknown_column_is_rejected_and_writes_nothing() {
    let (_tmp, dir) = workflow_repo();
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["move", "1", "nonsense"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("unknown_column"))
        // The valid-column list is what lets a user recover, and it must be in
        // board order — a `HashMap` order would differ between runs.
        .stderr(predicates::str::contains(
            "valid columns: triage, wip, review, shipped, abandoned",
        ));
    assert_eq!(
        hierarchy_snapshot(&dir),
        before,
        "a rejected move must not touch a single byte"
    );
}

#[test]
fn t020_a_backwards_move_is_rejected_and_writes_nothing() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "wip"])
        .assert()
        .success();
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["move", "1", "triage"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("invalid_transition"))
        .stderr(predicates::str::contains("category policy"));
    assert_eq!(hierarchy_snapshot(&dir), before);
}

#[test]
fn t020_a_terminal_exit_is_refused_without_a_reason_and_writes_nothing() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc1234"])
        .assert()
        .success();
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["move", "1", "wip"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("invalid_transition"))
        // The refusal must name the spelling of the override, or the user has the
        // rule and no route.
        .stderr(predicates::str::contains("--reason"));
    assert_eq!(
        hierarchy_snapshot(&dir),
        before,
        "and the recorded commit is still there, untouched"
    );
}

#[test]
fn t020_a_terminal_exit_with_a_reason_is_accepted_and_the_reason_is_recorded() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc1234"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args([
            "move",
            "1",
            "wip",
            "--reason",
            "reopening: shipped by mistake",
        ])
        .assert()
        .success();
    let events = history_of_title(&dir, "Alpha");
    assert_eq!(events.len(), 2, "{events:?}");
    assert!(
        events[1].contains("override: reopening: shipped by mistake"),
        "the reason is in the audit trail, or the override is unexplained: {events:?}"
    );
    // Leaving completion clears the commit the completion recorded.
    let text = fs::read_to_string(issue_file_named(&dir, "Alpha")).unwrap();
    assert!(
        !text.contains("commit:"),
        "leaving completion clears it: {text}"
    );
}

#[test]
fn t020_a_blank_reason_is_not_a_reason() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc1234"])
        .assert()
        .success();
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["move", "1", "wip", "--reason", "   "])
        .assert()
        .failure()
        .stderr(predicates::str::contains("invalid_transition"));
    assert_eq!(hierarchy_snapshot(&dir), before);
}

#[test]
fn t020_a_same_column_move_is_inert() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "triage"])
        .assert()
        .success();
    let before = hierarchy_snapshot(&dir);
    // `create` leaves the issue in `triage`, so this is already a no-op column.
    tix()
        .current_dir(&dir)
        .args(["move", "1", "triage"])
        .assert()
        .success();
    assert_eq!(
        hierarchy_snapshot(&dir),
        before,
        "a same-column move writes nothing: not the file, not a decision, not the date"
    );
    assert_eq!(
        history_of_title(&dir, "Alpha"),
        Vec::<String>::new(),
        "and appends no decision"
    );
}

#[test]
fn t020_edit_status_is_not_a_bypass_of_the_same_rules() {
    // The CLI half of research R8. The payloads are identical to the `tix mv` cases
    // above on purpose: parity means the same input produces the same outcome, so a
    // test that used different payloads would prove nothing about parity.
    let (_tmp, dir) = workflow_repo();

    // Accepted, identically.
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--status", "wip"])
        .assert()
        .success();
    assert_eq!(
        history_of_title(&dir, "Alpha"),
        vec!["transition_accepted | triage -> wip (backlog -> active)".to_string()],
        "the same decision `tix mv` would have recorded"
    );

    // Rejected, identically, and byte-identically.
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--status", "triage"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("invalid_transition"));
    assert_eq!(hierarchy_snapshot(&dir), before);
}

#[test]
fn t020_edit_status_cannot_skip_the_override_requirement() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--status", "shipped"])
        .assert()
        .success();
    let before = hierarchy_snapshot(&dir);
    // No reason, and `--yes` deliberately does not exist on `edit`: acknowledging
    // blockers is `tix move --yes`, and a second spelling would give the audit
    // trail two ways to record one decision.
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--status", "wip"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("invalid_transition"));
    assert_eq!(hierarchy_snapshot(&dir), before);

    // With a reason it works, and records it.
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--status", "wip", "--reason", "reopening"])
        .assert()
        .success();
    let events = history_of_title(&dir, "Alpha");
    assert!(
        events.last().unwrap().contains("override: reopening"),
        "{events:?}"
    );
}

#[test]
fn t020_an_unrelated_edit_does_not_clear_the_status() {
    // The regression that WP04's own first attempt introduced: `--status` was
    // withheld from the merge with an expression that turned an **absent** flag
    // into `Some("")`, so `tix edit 1 --title X` wiped the status of every issue
    // edited for any other reason. Found by an existing byte-snapshot test, and
    // pinned here through the real binary because the failure was silent and total.
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "wip"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--title", "Renamed"])
        .assert()
        .success();
    // Looked up by the *file's* slug, not the new title: `tix edit --title` does
    // not rename the file, so `issue_file_named(.., "Renamed")` would look for a
    // file that does not exist and report the fixture as missing rather than as a
    // failed assertion.
    let text = fs::read_to_string(issue_file_named(&dir, "Alpha")).unwrap();
    assert!(
        text.contains("title: Renamed"),
        "the title did change: {text}"
    );
    assert!(
        text.contains("status: wip"),
        "an unrelated edit must leave the column alone: {text}"
    );
}

#[test]
fn t020_status_clearing_is_a_field_write_not_a_transition() {
    // `--status ""` follows the clearing convention every other field has. There is
    // no target column to judge, so it is not a transition and no decision is
    // recorded — confirmed here rather than assumed (T017 step 3).
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--status", ""])
        .assert()
        .success();
    let text = fs::read_to_string(issue_file_named(&dir, "Alpha")).unwrap();
    assert!(
        text.contains("status: ''") || text.contains("status: \"\""),
        "the field is cleared: {text}"
    );
    assert_eq!(
        history_of_title(&dir, "Alpha"),
        Vec::<String>::new(),
        "and a clearing is not a transition, so it records no decision"
    );
}

#[test]
fn t020_a_custom_completion_column_reports_the_same_completion_as_a_board_named_done() {
    // T019 step 5: the intake's first reporting scenario. A board whose completion
    // column is `shipped` must report the same figures as one whose is `done`, and
    // must not be reporting them by matching the string `done`.
    let (_tmp, mapped) = workflow_repo();
    tix()
        .current_dir(&mapped)
        .args(["move", "1", "shipped", "--commit", "abc"])
        .assert()
        .success();

    let (_tmp2, legacy) = legacy_board_repo();
    tix()
        .current_dir(&legacy)
        .args(["move", "1", "done", "--commit", "abc"])
        .assert()
        .success();

    let mapped_overdue = tix()
        .current_dir(&mapped)
        .args(["status", "--filter", "overdue"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let legacy_overdue = tix()
        .current_dir(&legacy)
        .args(["status", "--filter", "overdue"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    // Both boards hold one complete issue and one not, so the figures must match
    // even though the column names do not appear in either output.
    // The **figures**, not the line counts. The two boards have different column
    // counts, so their tables are different lengths by construction and comparing
    // line counts would be comparing the fixture rather than the reporting. An
    // earlier version of this assertion did exactly that and passed for the wrong
    // reason.
    let figure = |text: &str, label: &str| -> String {
        text.lines()
            .find(|l| l.trim_start().starts_with(label))
            .unwrap_or_else(|| panic!("no `{label}` row in:\n{text}"))
            .split_whitespace()
            .last()
            .unwrap_or("")
            .to_string()
    };
    let mapped_text = String::from_utf8(mapped_overdue).unwrap();
    let legacy_text = String::from_utf8(legacy_overdue).unwrap();
    assert_eq!(
        figure(&mapped_text, "Total"),
        figure(&legacy_text, "Total"),
        "a custom completion column reports the same total"
    );
    assert_eq!(
        figure(&mapped_text, "Overdue"),
        figure(&legacy_text, "Overdue"),
        "and the same overdue figure, which is the completion decision in use:\n{mapped_text}\n---\n{legacy_text}"
    );
    // And the label is `complete`, not `done` — the word no longer names a column.
    assert!(
        !mapped_text.contains(" done"),
        "reporting must not name a completion column: {mapped_text}"
    );
}

#[test]
fn t020_a_canceled_issue_is_not_complete() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "2", "abandoned"])
        .assert()
        .success();
    let text = String::from_utf8(
        tix()
            .current_dir(&dir)
            // `--all`: the default listing is scoped to your issues in the board's
            // entry column (#1711); these tests observe one issue's category.
            .args(["list", "--all", "--show", "category"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(text.contains("Canceled"), "the category is shown: {text}");

    // `canceled` is terminal but **not complete** (contract §4), so it must still
    // count as overdue. Two issues with the same past due date, one canceled and one
    // completed: the completion figure differs by exactly one.
    //
    // An earlier version of this test filtered on `status:abandoned`, which is not a
    // filter token `tix status` understands — the filter matched nothing and the
    // assertion was really about an empty table.
    let overdue = |dir: &Path| -> String {
        let out = tix()
            .current_dir(dir)
            .args(["status", "--filter", "overdue"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let text = String::from_utf8(out).unwrap();
        text.lines()
            .find(|l| l.trim_start().starts_with("Overdue"))
            .unwrap_or_else(|| panic!("no Overdue row in:\n{text}"))
            .split_whitespace()
            .last()
            .unwrap_or("")
            .to_string()
    };
    tix()
        .current_dir(&dir)
        .args(["edit", "2", "--due-date", "2000-01-01"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--due-date", "2000-01-01"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc"])
        .assert()
        .success();
    assert_eq!(
        overdue(&dir),
        "1",
        "the canceled issue is still overdue and the completed one is not, so exactly \
         one is counted: a terminal category is not a completion"
    );
}

#[test]
fn t020_list_show_category_labels_match_the_service() {
    // T019 step 6: the label must be the service's `label()`, so the values WP08
    // asserts in the detail view also hold in list output. Pinned by name here
    // because the alternative is two surfaces inventing their own spelling.
    let (_tmp, dir) = workflow_repo();
    let text = String::from_utf8(
        tix()
            .current_dir(&dir)
            // `--all`: the default listing is scoped to your issues in the board's
            // entry column (#1711); these tests observe one issue's category.
            .args(["list", "--all", "--show", "category"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(text.contains("CATEGORY"), "the column is named: {text}");
    assert!(text.contains("Backlog"), "`triage` is `backlog`: {text}");
    // An issue in a column the board does not configure is reported, not an error.
    let path = issue_file_named(&dir, "Alpha");
    let text_on_disk = fs::read_to_string(&path).unwrap();
    fs::write(
        &path,
        text_on_disk.replace("status: triage", "status: not-a-column"),
    )
    .unwrap();
    let text2 = String::from_utf8(
        tix()
            .current_dir(&dir)
            // `--all`: the default listing is scoped to your issues in the board's
            // entry column (#1711); these tests observe one issue's category.
            .args(["list", "--all", "--show", "category"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        text2.contains("(unmapped)"),
        "an unconfigured column is reported as such, not defaulted: {text2}"
    );
}

#[test]
fn t020_a_legacy_board_gains_no_transition_policy() {
    // The opt-in WP03 decided, through the real binary. `tix init` writes a board
    // with no `category_map`, and on that board moving out of `done` must still
    // work — it did before this mission, and a user must not find that it stopped.
    let (_tmp, dir) = legacy_board_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "done", "--commit", "abc"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "in progress"])
        .assert()
        .success();
    let text = fs::read_to_string(issue_file_named(&dir, "Alpha")).unwrap();
    assert!(
        text.contains("status: in progress"),
        "a board with no category_map has no policy to override: {text}"
    );
}

#[test]
fn t020_workflow_show_for_a_board_with_no_completion_column_is_reported() {
    // Contract §4: a board with nothing mapped to `completed` is a configuration
    // error to report, never a board where nothing completes. Surfaced by name.
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    fs::create_dir_all(dir.join("docs").join("issues")).unwrap();
    // The first version of this fixture set `done_column = "done"` on a board
    // whose columns are `a` and `b`, and config load rejected it — so the test
    // failed at the *fixture* and never reached the command. Omitting `done_column`
    // does not help either: the deserializer defaults it to `"done"`, which is
    // still not a column.
    //
    // A board that is valid *and* has no completion is therefore one whose
    // `done_column` is a real column that the `category_map` deliberately does not
    // point at `completed`. That is a configuration a user can genuinely write by
    // accident, which makes it the right fixture for this diagnostic.
    fs::write(
        dir.join("tix.toml"),
        "issues_dir = \"docs/issues\"\n\n\
         [kanban.default]\n\
         columns = [\"a\", \"b\"]\n\
         done_column = \"b\"\n\n\
         [kanban.default.category_map]\n\
         a = \"backlog\"\n\
         b = \"active\"\n",
    )
    .unwrap();
    // Contract §4 calls this a **configuration error**, and WP01 makes it fatal at
    // load rather than a warning. So the assertion is on the refusal, and it is
    // stronger than the one this test started with: the board cannot be opened by
    // *any* command, so nothing can silently treat it as "nothing completes".
    //
    // The first version asserted that `tix workflow show` *printed* the diagnostic
    // in its Diagnostics block. It cannot: config load refuses first. Asserting the
    // success it never reached is what made this test look like a real failure for a
    // while.
    tix()
        .current_dir(&dir)
        .args(["workflow", "show"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("missing_completion_category"))
        .stderr(predicates::str::contains("maps no column to `completed`"))
        // Every command is equally unable to open it.
        .stderr(predicates::str::contains("config error"));
    tix()
        .current_dir(&dir)
        .args(["list"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("missing_completion_category"));
}

#[test]
fn t020_the_commit_prompt_follows_the_service_not_the_done_column_name() {
    // T016 step 8's last case, and the direct evidence that the prompt trigger and
    // the reporting agree through the service.
    //
    // This board maps `shipped` to `completed` while keeping `done_column = "done"`.
    // The service calls `shipped` complete; the old trigger asked whether the column
    // *equalled* `done_column`. One of the two was a lie, and which one depended on
    // the board's configuration.
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    fs::create_dir_all(dir.join("docs").join("issues")).unwrap();
    fs::write(
        dir.join("tix.toml"),
        "issues_dir = \"docs/issues\"\n\n\
         [kanban.default]\n\
         columns = [\"todo\", \"shipped\", \"done\"]\n\
         done_column = \"done\"\n\n\
         [kanban.default.category_map]\n\
         todo = \"unstarted\"\n\
         shipped = \"completed\"\n\
         done = \"active\"\n",
    )
    .unwrap();
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Alpha"])
        .assert()
        .success();

    // Moving to `shipped` reaches completion, so the commit is recorded — even
    // though `shipped` is not the `done_column`.
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc1234"])
        .assert()
        .success();
    let text = fs::read_to_string(issue_file_named(&dir, "Alpha")).unwrap();
    assert!(
        text.contains("commit: abc1234"),
        "the service's completion decision is what records the commit: {text}"
    );
    assert!(
        text.contains("shipped -> shipped") || text.contains("todo -> shipped"),
        "and the decision names the columns: {text}"
    );
}

#[test]
fn t020_a_rejected_status_leaves_the_other_edit_fields_unwritten() {
    // The observable difference between judging a transition in `edit::apply` and
    // leaving it to the seam.
    //
    // `tix edit --status` is the *only* mutation in the program that writes some
    // fields and then applies a transition, so it is the only place where "the
    // refusal wrote nothing" and "the refusal left the file byte-identical" are
    // different claims. Without the pre-write judgement, the title would be saved
    // and the status refused — a partial edit reported as a failure.
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "wip"])
        .assert()
        .success();
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--title", "Renamed", "--status", "triage"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("invalid_transition"));
    assert_eq!(
        hierarchy_snapshot(&dir),
        before,
        "a refused transition must not commit the fields edited alongside it"
    );
}

#[test]
fn t020_list_overdue_uses_completion_rather_than_a_column_name() {
    // The `list` half of C-004. `tix status --filter overdue` and `tix list`'s
    // OVERDUE column are two surfaces rendering the same fact; this pins the second.
    //
    // Two issues, same past due date, one in the completion column and one not. The
    // board's completion column is `shipped`, so a comparison against the literal
    // `done` would count both.
    let (_tmp, dir) = workflow_repo();
    for (selector, title) in [("1", "Alpha"), ("2", "Bravo")] {
        tix()
            .current_dir(&dir)
            .args(["edit", selector, "--due-date", "2000-01-01"])
            .assert()
            .success();
        let _ = title;
    }
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc"])
        .assert()
        .success();
    let out = String::from_utf8(
        tix()
            .current_dir(&dir)
            .args(["list", "--columns", "num,title,overdue"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    let overdue_rows: Vec<&str> = out.lines().skip(1).filter(|l| l.contains("yes")).collect();
    assert_eq!(
        overdue_rows.len(),
        1,
        "exactly the incomplete issue is overdue, so completion is a category \\
         decision and not a column comparison:\n{out}"
    );
    assert!(
        overdue_rows[0].contains("Bravo"),
        "and it is the one still in a non-completion column:\n{out}"
    );
}

#[test]
fn t020_workflow_show_reports_the_non_fatal_diagnostics() {
    // `validate_config`'s fatal kinds are refused at config load, so the only
    // findings `tix workflow show` can actually print are the report-only ones. This
    // pins that the block is wired to the service rather than to a hardcoded empty
    // list — an earlier version of the verification reverted the call and this test
    // did not notice, because nothing was asserting the block was reachable.
    let (_tmp, dir) = legacy_board_repo();
    let text = String::from_utf8(
        tix()
            .current_dir(&dir)
            .args(["workflow", "show"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        text.contains("unmapped_column_default"),
        "a board relying on the safe default is reported by name:\n{text}"
    );
    assert!(
        text.contains("Diagnostics:"),
        "under a heading, so it is not mistaken for part of the table:\n{text}"
    );
    // And the completion column — also resolved by the default — is not reported as
    // a finding, because that reconciliation is working as intended.
    assert_eq!(
        text.matches("unmapped_column_default").count(),
        // `tix init` writes todo / in progress / in review / done: three columns
        // besides the completion one.
        3,
        "the completion column is not a finding:\n{text}"
    );
}

/// A board whose `done_column` is **not** the completion column.
///
/// `done_column = "done"` while `category_map` puts `completed` on `shipped` and
/// `active` on `done`. Any reporting that compares a column *name* against
/// `done_column` answers a different question from one that asks the service, and on
/// this board the two answers are opposites. It is the fixture that makes C-004
/// observable rather than a matter of taste.
fn split_completion_repo() -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    fs::create_dir_all(dir.join("docs").join("issues")).unwrap();
    fs::write(
        dir.join("tix.toml"),
        "issues_dir = \"docs/issues\"\n\n\
         [kanban.default]\n\
         columns = [\"todo\", \"shipped\", \"done\"]\n\
         done_column = \"done\"\n\n\
         [kanban.default.category_map]\n\
         todo = \"unstarted\"\n\
         shipped = \"completed\"\n\
         done = \"active\"\n",
    )
    .unwrap();
    for title in ["Alpha", "Bravo"] {
        tix()
            .current_dir(&dir)
            .args(["create", "--title", title])
            .assert()
            .success();
    }
    (tmp, dir)
}

#[test]
fn t020_reaching_completion_without_a_commit_is_refused() {
    // The commit-prompt **trigger**, as distinct from the recording of the commit.
    // The prompt only fires when no `--commit` was given, and in a piped (non-TTY)
    // test that means a refusal naming `--commit` — so supplying `--commit` in a
    // test cannot observe the trigger at all. An earlier version of the verification
    // supplied one, and reverting the trigger left the suite green.
    let (_tmp, dir) = split_completion_repo();
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("requires a commit hash"));
    assert_eq!(
        hierarchy_snapshot(&dir),
        before,
        "`shipped` is the service's completion column, so the prompt fires and the \\
         move is refused for want of a hash"
    );

    // The contrast: `done` is the configured `done_column` but **not** complete, so
    // no commit is demanded. A trigger that asked the wrong question would demand one
    // here and not there — the two failures together pin which question is being
    // asked.
    tix()
        .current_dir(&dir)
        .args(["move", "1", "done"])
        .assert()
        .success();
}

#[test]
fn t020_overdue_uses_completion_on_a_board_whose_done_column_is_not_complete() {
    // The `tix status` Overdue row, on the board where a column-name comparison and
    // a category decision disagree.
    //
    // `Alpha` moves to `shipped`, which is `completed` — so it is not overdue however
    // old its due date. `Bravo` stays in `todo`, which is not. Under a comparison
    // against `done_column` (which is `done`) both would count as overdue.
    let (_tmp, dir) = split_completion_repo();
    for selector in ["1", "2"] {
        tix()
            .current_dir(&dir)
            .args(["edit", selector, "--due-date", "2000-01-01"])
            .assert()
            .success();
    }
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc"])
        .assert()
        .success();
    let out = String::from_utf8(
        tix()
            .current_dir(&dir)
            .args(["status", "--filter", "overdue"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    let overdue = out
        .lines()
        .find(|l| l.trim_start().starts_with("Overdue"))
        .unwrap_or_else(|| panic!("no Overdue row in:\n{out}"))
        .split_whitespace()
        .last()
        .unwrap_or("")
        .to_string();
    assert_eq!(
        overdue, "1",
        "only the issue outside the completion category is overdue:\n{out}"
    );
}

#[test]
fn t025_create_rejects_a_column_the_board_does_not_configure() {
    // WP05 found this by typing a status into the TUI's free-text form: the create
    // succeeded and wrote a column the board does not have, so every
    // category-derived surface then reported the issue as `(unmapped)` and no
    // transition could ever move it anywhere.
    //
    // It was recorded as WP04's "create = column check only" decision and the check
    // itself was never implemented — a recorded decision is not an implemented one.
    let (_tmp, dir) = workflow_repo();
    let before = hierarchy_snapshot(&dir);
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Nowhere", "--status", "nonsense"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("unknown_column"))
        .stderr(predicates::str::contains(
            "valid columns: triage, wip, review, shipped, abandoned",
        ));
    assert_eq!(
        hierarchy_snapshot(&dir),
        before,
        "a refused create writes nothing"
    );

    // And a terminal column is **legal** on create: there is no `from` to judge, so
    // the terminal lock has nothing to say. A triaged backlog item arrives that way.
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Dropped", "--status", "abandoned"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Finished", "--status", "shipped"])
        .assert()
        .success();
}

#[test]
fn t025_a_created_issue_reports_its_category() {
    // The end of the chain the check protects: an issue created into a real column
    // resolves to a category, so `--show category` names it.
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["create", "--title", "Dropped", "--status", "abandoned"])
        .assert()
        .success();
    let out = String::from_utf8(
        tix()
            .current_dir(&dir)
            // `--all`: the default listing is scoped to your issues in the board's
            // entry column (#1711); these tests observe one issue's category.
            .args(["list", "--all", "--show", "category"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        out.contains("Canceled"),
        "and `canceled` is not complete: {out}"
    );
    assert!(
        out.contains("Backlog"),
        "and the untouched issues are still `backlog`: {out}"
    );
}

// ---------------------------------------------------------------------------
// WP08 T037 — the category is the same on every path that shows it
// ---------------------------------------------------------------------------

/// The `tix list --show category` **row** for one issue.
///
/// Returning the row rather than a parsed cell is deliberate. A category label can
/// contain a space — `Not started` does — so "the last whitespace-separated token"
/// yields `started`, which is how the first version of this helper read
/// `Not started` and then failed against a surface that was **correct**. Callers
/// assert with [`assert_row_cell_is`], which compares the whole trailing cell and so
/// has no parser to be wrong about.
fn list_row(dir: &std::path::Path, number: u32) -> String {
    let out = tix()
        .current_dir(dir)
        // `--all`: the default listing is scoped to your issues in the board's entry
        // column (#1711). This helper is about the CATEGORY cell of a named issue, so
        // the scope would only decide whether the row exists at all.
        .args(["list", "--all", "--show", "category"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    // The number column is bare (`1`, not `#1`). The header check is here so that a
    // format change reports "unexpected table header" rather than "no row", which
    // would send the reader looking for a missing issue.
    assert!(text.contains("NUM"), "unexpected table header in:\n{text}");
    text.lines()
        .find(|l| {
            l.split_whitespace()
                .next()
                .is_some_and(|first| first == number.to_string())
        })
        .unwrap_or_else(|| panic!("no row for #{number} in:\n{text}"))
        .trim_end()
        .to_string()
}

/// The trailing cell of a table row — the `CATEGORY` column, which is the last one
/// when `--show category` is the only addition.
///
/// Split on the two-space column separator rather than on whitespace, which is what
/// makes a label containing a space recoverable.
fn last_cell(row: &str) -> &str {
    row.rsplit_once("  ")
        .map(|(_, cell)| cell.trim())
        .expect("a row with at least two cells")
}

/// Assert the row's trailing cell is exactly `cell`.
#[track_caller]
fn assert_row_cell_is(row: &str, cell: &str, context: &str) {
    assert_eq!(
        last_cell(row),
        cell,
        "{context}: the row's trailing cell\n  row: {row:?}"
    );
}

/// The `category: <key> (<label>)` line from `tix show`.
fn show_category_line(dir: &std::path::Path, selector: &str) -> String {
    let out = tix()
        .current_dir(dir)
        .args(["show", selector])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        text.contains("## Workflow"),
        "no workflow block in:\n{text}"
    );
    text.lines()
        .find(|l| l.starts_with("- category: "))
        .unwrap_or_else(|| panic!("no category line in:\n{text}"))
        .trim_start_matches("- category: ")
        .to_string()
}

#[test]
fn t037_the_category_label_is_identical_on_every_path() {
    // T037 step 1, the mechanism that would catch a reworded label before a user
    // does. Three paths that could each own a string: the detail block (T036), the
    // list column (WP04, which this WP does not own), and the service's `label()`.
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc1234"])
        .assert()
        .success();
    tix()
        .current_dir(&dir)
        .args(["move", "2", "wip"])
        .assert()
        .success();
    // Two categories, not one. A loop over a single tuple is not a loop — clippy
    // said so — and one case would have covered half the vocabulary.
    //
    // The `canceled` category and the one label with a **space** in it
    // (`Not started`) are the other two tests' subjects: `canceled` is terminal and
    // not complete, and the spaced label is what a whitespace-splitting cell reader
    // gets wrong. This test is the cross-path *equality* mechanism, and it needs two
    // distinct labels to be evidence rather than a restatement of the service.
    // `Config::load` takes a **project root** and joins `tix.toml` onto it. Passing
    // the file path instead makes it look for `<file>/tix.toml`, find nothing, and
    // return `Config::default()` — silently, with no error. The symptom was a
    // resolution over the *default* board's columns (`todo, in progress, in review,
    // done`) while the CLI halves of the same test read the fixture's five, so the
    // cross-path comparison was comparing two different boards. The columns are
    // printed in the failure message below, which is what made it legible.
    let mut config = tix::config::Config::load(&dir).unwrap();
    // `issues_dir` is **relative**, and `Store` resolves it against the *process*
    // cwd — so loading the temp repo's `tix.toml` from a test that never changed
    // directory yields a store over **this repository's** issues, not the fixture's.
    // The first version of this test did exactly that, and the service leg reported
    // `Done` for an issue the CLI had just moved to `wip`: two paths, two different
    // stores, and the cross-path comparison silently comparing across repositories.
    // The absolute path removes the question.
    config.issues_dir = dir.join("docs").join("issues");
    let store = tix::storage::Store::open(&config).unwrap();
    assert_eq!(
        store.list().unwrap().len(),
        2,
        "the fixture's two issues, not this repository's"
    );
    for (number, key, label) in [(1u32, "completed", "Done"), (2u32, "active", "In progress")] {
        let shown = show_category_line(&dir, &number.to_string());
        assert_eq!(
            shown,
            format!("{key} ({label})"),
            "`tix show` for #{number}"
        );
        assert_eq!(
            last_cell(&list_row(&dir, number)),
            label,
            "`tix list --show category` for #{number}"
        );
        // And the service, through the same `label()` the two surfaces call. A
        // third path that could own a string, and the one the other two are
        // supposed to be thin wrappers over.
        let (_, resolution) = tix::workflow::active_resolution(&config);
        let issue = store
            .get(tix::storage::IssueSelector::Number(number))
            .unwrap();
        let from_service = tix::workflow::category_of(&issue, &resolution).unwrap_or_else(|| {
            panic!(
                "no category for #{number}: status {:?}, board {:?}, columns {:?}",
                issue.status.display(),
                resolution.board,
                resolution.columns().collect::<Vec<_>>()
            )
        });
        assert_eq!(
            from_service.label(),
            label,
            "the service's `label()` for #{number}"
        );
        assert_eq!(from_service.key(), key, "and its key for #{number}");
    }
}

#[test]
fn t037_a_canceled_issue_is_never_reported_complete_on_any_path() {
    // T037 step 2.
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "abandoned", "--yes"])
        .assert()
        .success();
    assert_eq!(
        show_category_line(&dir, "1"),
        "canceled (Canceled)",
        "`tix show` must not read a canceled issue as done"
    );
    assert_row_cell_is(&list_row(&dir, 1), "Canceled", "a canceled row");
    let out = tix().current_dir(&dir).args(["status"]).output().unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        !text.contains("1/1 done") && !text.contains("1/1 complete"),
        "the board summary must not count a canceled issue as complete:\n{text}"
    );
}

#[test]
fn t037_an_unmapped_column_reports_the_safe_default_label_on_all_three_paths() {
    // T037 step 3. A **configured but unmapped** column, because an unconfigured
    // column is `(unmapped)` and that case is pinned in `view.rs`.
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--status", "review"])
        .assert()
        .success();
    // `review` **is** mapped to `active` on `workflow_repo`; strip the mapping and
    // the column falls to the safe default.
    let toml = dir.join("tix.toml");
    let stripped = fs::read_to_string(&toml)
        .unwrap()
        .replace("review = \"active\"\n", "");
    fs::write(&toml, stripped).unwrap();
    assert_eq!(
        show_category_line(&dir, "1"),
        "unstarted (Not started)",
        "a column with no mapping resolves to the safe default"
    );
    assert_row_cell_is(
        &list_row(&dir, 1),
        "Not started",
        "a column with no mapping",
    );
}

#[test]
fn t037_two_boards_with_different_columns_report_the_same_category_and_completion() {
    // T037 step 4, the intake's first acceptance scenario at the presentation
    // layer: same mapping, different column names, identical answer.
    let (tmp_a, dir_a) = workflow_repo();
    let _tmp_b = tmp_a;
    // A second repo with the same mapping under different names.
    let tmp_b = TempDir::new().unwrap();
    let dir_b = tmp_b.path().to_path_buf();
    fs::create_dir_all(dir_b.join("docs").join("issues")).unwrap();
    fs::write(
        dir_b.join("tix.toml"),
        "issues_dir = \"docs/issues\"\n\n\
         [kanban.default]\n\
         columns = [\"icebox\", \"doing\", \"verifying\", \"released\", \"dropped\"]\n\
         done_column = \"released\"\n\n\
         [kanban.default.category_map]\n\
         icebox = \"backlog\"\n\
         doing = \"active\"\n\
         verifying = \"active\"\n\
         released = \"completed\"\n\
         dropped = \"canceled\"\n",
    )
    .unwrap();
    tix()
        .current_dir(&dir_b)
        .args(["create", "--title", "Alpha"])
        .assert()
        .success();

    for (dir, column, other) in [(&dir_a, "shipped", "wip"), (&dir_b, "released", "doing")] {
        tix()
            .current_dir(dir)
            .args(["move", "1", column, "--commit", "abc1234"])
            .assert()
            .success();
        // Out of a terminal category, so a reasoned override is required. The first
        // version of this test omitted it and asserted the move succeeded, which is
        // the refusal this mission exists to make — recorded here because a test that
        // fights the policy is a test that will be "fixed" by weakening the policy.
        tix()
            .current_dir(dir)
            .args([
                "move",
                "1",
                other,
                "--reason",
                "reopening for the comparison",
            ])
            .assert()
            .success();
    }
    let a = show_category_line(&dir_a, "1");
    let b = show_category_line(&dir_b, "1");
    assert_eq!(a, b, "two boards, equal mappings, different column names");
    assert_eq!(a, "active (In progress)");
    assert_row_cell_is(
        &list_row(&dir_b, 1),
        last_cell(&list_row(&dir_a, 1)),
        "the two boards' category cells",
    );
}

#[test]
fn t037_an_unknown_category_is_an_error_from_every_surface_that_filters() {
    // T037 step 5. Four surfaces take a filter string, and each one had to be
    // taught the check; a surface that forgot would answer "0 issues" and look
    // like a working filter.
    let (_tmp, dir) = workflow_repo();
    for args in [
        vec!["list", "--filter", "category:finished"],
        vec!["search", "category:finished"],
        vec!["status", "--filter", "category:finished"],
    ] {
        let out = tix().current_dir(&dir).args(&args).output().unwrap();
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            !out.status.success(),
            "{args:?} must fail on an unknown category"
        );
        assert!(
            stderr.contains("unknown category 'finished'"),
            "{args:?} stderr: {stderr}"
        );
    }
}

#[test]
fn t037_a_valid_category_filter_works_from_every_surface_that_filters() {
    // The positive half of the case above: the same filter, spelled correctly,
    // selects the same set on all three.
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc1234"])
        .assert()
        .success();

    let listed = tix()
        .current_dir(&dir)
        // `--all`: the default listing is scoped to your issues in the board's entry
        // column (#1711), and `Alpha` has moved to `shipped`.
        .args(["list", "--all", "--filter", "category:completed"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&listed.stdout).to_string();
    assert!(text.contains("Alpha"), "{text}");
    assert!(!text.contains("Bravo"), "{text}");

    let found = tix()
        .current_dir(&dir)
        .args(["search", "category:completed"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&found.stdout).to_string();
    assert!(text.contains("Alpha"), "{text}");
    // The exclusion matters as much as the inclusion, and the first version of this
    // test omitted it. A `search` that dropped the criterion altogether returns the
    // **whole** board, which still contains `Alpha` — so the positive assertion
    // passed against a filter that was not being applied at all, and the revert that
    // proved it came back green.
    assert!(
        !text.contains("Bravo"),
        "and nothing outside the category:\n{text}"
    );
    // The context line is the `status:` line, because no file contains a
    // `category` line and the derivation is what the user needs to see.
    assert!(
        text.contains("status: shipped"),
        "the matched-lines context must show the derivation: {text}"
    );

    let status = tix()
        .current_dir(&dir)
        .args(["status", "--filter", "category:completed"])
        .output()
        .unwrap();
    // `tix status` is a per-column table, so the claim is that its **counts** reflect
    // the filter: the completed column holds the one issue and every other column
    // holds none. Asserting a `1/1 complete` rollup here would be asserting a format
    // this command does not print — the first version of this test did exactly that
    // and failed against correct output.
    let text = String::from_utf8_lossy(&status.stdout).to_string();
    assert!(
        text.contains("shipped") && text.contains("Total      1"),
        "the summary counts the filtered set:\n{text}"
    );
    assert!(
        !text.contains("Total      2"),
        "and only the filtered set:\n{text}"
    );

    // And an unknown category is an error, not a silent empty set — already
    // asserted above; the negative control here is that a *valid* filter on a
    // category nothing is in returns an empty set **successfully**.
    let empty = tix()
        .current_dir(&dir)
        .args(["list", "--filter", "category:canceled"])
        .output()
        .unwrap();
    assert!(
        empty.status.success(),
        "a valid category with no members is an empty board, not an error"
    );
}

/// A `--filter` token with no arm in `query_matches` matched **nothing**, silently,
/// on the four most obvious criteria (WP08, found while adding `category:`).
///
/// `StructuredFilter` has carried `assignee`, `label`, `status` and `priority` since
/// the filter grammar landed and `evaluate` matches all four, so the TUI's filter
/// modal has always worked. The **token** grammar had no arm for any of them and the
/// catch-all `_ => false` turned each into a filter that matched nothing — an empty
/// table with exit 0, indistinguishable from a correct filter with no matches.
#[test]
fn t037_every_documented_filter_token_actually_filters() {
    let (_tmp, dir) = workflow_repo();
    tix()
        .current_dir(&dir)
        .args(["move", "1", "shipped", "--commit", "abc1234"])
        .assert()
        .success();
    // (token, should-match, should-not-match)
    for (token, hits, misses) in [
        ("status:shipped", "Alpha", "Bravo"),
        ("priority:medium", "Alpha", "nobody"),
        ("assignee:Herbert", "Alpha", "nobody"),
        ("label:urgent", "nobody", "nobody"),
        ("cycle:One", "nobody", "nobody"),
    ] {
        let out = tix()
            .current_dir(&dir)
            // `--all`: the default listing is scoped to your issues in the board's
            // entry column (#1711), and several of these tokens select issues that
            // have moved out of it.
            .args(["list", "--all", "--filter", token])
            .output()
            .unwrap();
        let text = String::from_utf8_lossy(&out.stdout).to_string();
        assert!(out.status.success(), "{token}: must not be an error");
        if hits != "nobody" {
            assert!(text.contains(hits), "{token}: should match {hits}\n{text}");
        }
        if misses != "nobody" {
            assert!(
                !text.contains(misses),
                "{token}: should not match {misses}\n{text}"
            );
        }
    }
    // The negative control: a filter that genuinely matches nothing is also an empty
    // table, and **that** is what made the bug invisible. Asserted so the two cases
    // stay distinguishable.
    let none = tix()
        .current_dir(&dir)
        .args(["list", "--filter", "status:no-such-column"])
        .output()
        .unwrap();
    assert!(none.status.success());
    assert!(
        !String::from_utf8_lossy(&none.stdout).contains("Alpha"),
        "a filter with no matches is an empty board"
    );
}

// ---------------------------------------------------------------------------
// Issue #1492 — archive / restore, end to end through the binary
// ---------------------------------------------------------------------------

/// The single created issue's path and the dot-prefixed name archiving gives it.
fn created_issue(dir: &Path) -> (PathBuf, PathBuf) {
    let file = issue_file(dir);
    let name = file.file_name().unwrap().to_string_lossy().to_string();
    let archived = file.parent().unwrap().join(format!(".{name}"));
    (file, archived)
}

#[test]
fn archive_round_trip_hides_resolves_and_restores() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Only issue"])
        .assert()
        .success();
    let (file, archived) = created_issue(dir);

    // `tix archive 1` renames in place to a dot-prefixed name.
    tix()
        .current_dir(dir)
        .args(["archive", "1"])
        .assert()
        .success();
    assert!(archived.is_file(), "renamed to {}", archived.display());
    assert!(!file.exists(), "the active name is gone");

    // The default list no longer shows it. `--all` so the assertion is about the
    // archive, not about the default scope (#1711).
    tix()
        .current_dir(dir)
        .args(["list", "--all"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Only issue").not());

    // `--with-archived` shows it, marked.
    tix()
        .current_dir(dir)
        .args(["list", "--all", "--with-archived"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Only issue"))
        .stdout(predicate::str::contains("ARCHIVED"));

    // `tix show` still resolves the archived issue, by number and by title.
    tix()
        .current_dir(dir)
        .args(["show", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Only issue"));
    tix()
        .current_dir(dir)
        .args(["show", "Only issue"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Only issue"));

    // `--filter archived:true` composes with `--with-archived`; `archived:false`
    // selects the active set.
    tix()
        .current_dir(dir)
        .args([
            "list",
            "--all",
            "--with-archived",
            "--filter",
            "archived:true",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("Only issue"));
    tix()
        .current_dir(dir)
        .args([
            "list",
            "--all",
            "--with-archived",
            "--filter",
            "archived:false",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("Only issue").not());

    // `tix search` needs the flag too.
    tix()
        .current_dir(dir)
        .args(["search", "Only"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No issues found."));
    tix()
        .current_dir(dir)
        .args(["search", "--with-archived", "Only"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Only issue"));

    // `tix restore 1` brings the file back, and `--all` proves it is listed again
    // without the default scope (#1711) deciding the answer.
    tix()
        .current_dir(dir)
        .args(["restore", "1"])
        .assert()
        .success();
    assert!(file.is_file());
    assert!(!archived.exists());
    tix()
        .current_dir(dir)
        .args(["list", "--all"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Only issue"));
}

#[test]
fn redundant_archive_and_restore_are_refused_with_named_diagnostics() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Only issue"])
        .assert()
        .success();

    // Restoring an active issue is refused.
    tix()
        .current_dir(dir)
        .args(["restore", "1"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("not_archived"));

    tix()
        .current_dir(dir)
        .args(["archive", "1"])
        .assert()
        .success();

    // Re-archiving it is refused.
    tix()
        .current_dir(dir)
        .args(["archive", "1"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("already_archived"));
}

#[test]
fn a_failing_selector_does_not_roll_back_a_successful_one() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Real"])
        .assert()
        .success();
    let (file, archived) = created_issue(dir);

    tix()
        .current_dir(dir)
        .args(["archive", "9999", "1"])
        .assert()
        .failure();

    assert!(
        archived.is_file(),
        "the valid item is archived despite the missing one"
    );
    assert!(!file.exists());
}

/// `tix new` is a real subcommand (#1398): a typo would be an unknown-subcommand
/// error, and the help has to say what it opens — the whole point of the command is
/// that the create form is already on screen.
#[test]
fn new_subcommand_opens_the_create_form_in_the_tui() {
    let out = tix().args(["new", "--help"]).output().unwrap();
    assert!(out.status.success(), "tix new --help must succeed");
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        text.contains("create-issue form"),
        "the help names the form it opens: {text}"
    );

    // And it needs a repository, like the bare TUI: no `tix.toml` anywhere means the
    // contract's `no tix.toml found` guidance (exit 1) rather than a form that could
    // not be submitted.
    let empty = TempDir::new().unwrap();
    tix()
        .current_dir(empty.path())
        .arg("new")
        .assert()
        .failure()
        .stderr(predicate::str::contains("tix.toml"));
}

/// A fresh repository can use the triage inbox without editing its config: `tix init`
/// writes the section *and* the columns it needs, so the feature works on the repo the
/// tool just created.
#[test]
fn init_writes_a_working_triage_inbox() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    let config = fs::read_to_string(dir.join("tix.toml")).unwrap();
    for needle in [
        "[triage]",
        "entry_status = \"triage\"",
        "accepted_status = \"todo\"",
        "declined_status = \"wontfix\"",
    ] {
        assert!(
            config.contains(needle),
            "starter config lacks {needle:?}:\n{config}"
        );
    }
    // Board records moved to the file store; the columns the inbox needs are there.
    let board = fs::read_to_string(dir.join("docs/boards/default.md")).unwrap();
    for needle in ["- triage", "- wontfix", "wontfix: canceled"] {
        assert!(
            board.contains(needle),
            "starter board lacks {needle:?}:\n{board}"
        );
    }

    // A new issue enters the inbox, because `triage` is the board's first column.
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Something broke"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["triage", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Something broke"));

    // Accept lands in `todo`; decline lands in `wontfix` with its reason recorded.
    tix()
        .current_dir(dir)
        .args(["triage", "accept", "1"])
        .assert()
        .success();
    let accepted = fs::read_to_string(issue_file(dir)).unwrap();
    assert!(accepted.contains("status: todo"), "{accepted}");
    assert!(accepted.contains("triage_accepted"), "{accepted}");

    tix()
        .current_dir(dir)
        .args(["create", "--title", "Not a bug"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["triage", "decline", "2", "--reason", "works as intended"])
        .assert()
        .success();
    let declined = find_issue_text(dir, "Not a bug").expect("the declined issue");
    assert!(declined.contains("status: wontfix"), "{declined}");
    assert!(declined.contains("works as intended"), "{declined}");
}

/// The text of the issue whose frontmatter title is `title`.
///
/// The files carry today's date in their name, so a test cannot name the path it
/// wants; it asks for the issue instead.
fn find_issue_text(dir: &std::path::Path, title: &str) -> Option<String> {
    let mut stack = vec![dir.join("docs").join("issues")];
    while let Some(next) = stack.pop() {
        for entry in fs::read_dir(&next).ok()?.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if let Ok(text) = fs::read_to_string(&path)
                && text.contains(&format!("title: {title}"))
            {
                return Some(text);
            }
        }
    }
    None
}

#[test]
fn related_issues_round_trip_edit_and_lint() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Alpha",
            "--related-issues",
            "42,./missing.md,gitlab.com/foo/bar#7",
        ])
        .assert()
        .success();

    let file = issue_file(dir);
    let text = fs::read_to_string(&file).unwrap();
    assert!(text.contains("related_issues:"), "{text}");
    for value in ["42", "./missing.md", "gitlab.com/foo/bar#7"] {
        assert!(text.contains(value), "stored verbatim: {value}\n{text}");
    }

    // Warnings, not errors: an unresolved local entry, a missing path, a remote URL.
    tix()
        .current_dir(dir)
        .arg("lint")
        .assert()
        .success()
        .stderr(predicate::str::contains("related_issue_unresolved"))
        .stderr(predicate::str::contains("related path does not exist"))
        .stderr(predicate::str::contains("not linted (remote)"));

    // `--related-issues` replaces the whole list; `""` clears it.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--related-issues", "99"])
        .assert()
        .success();
    let text = fs::read_to_string(issue_file(dir)).unwrap();
    assert!(text.contains("related_issues:"), "{text}");
    assert!(
        text.contains("99") && !text.contains("gitlab.com/foo/bar"),
        "{text}"
    );
    assert!(
        !text.contains("related_issue_unresolved") || text.contains("99"),
        "the field was replaced, not appended"
    );

    tix()
        .current_dir(dir)
        .args(["edit", "1", "--related-issues", ""])
        .assert()
        .success();
    let text = fs::read_to_string(issue_file(dir)).unwrap();
    assert!(!text.contains("related_issues"), "cleared:\n{text}");
}

#[test]
fn lint_foreign_repositories_merges_and_no_foreign_suppresses() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    let a = root.join("a");
    let b = root.join("b");
    fs::create_dir_all(&a).unwrap();
    fs::create_dir_all(&b).unwrap();
    for repo in [&a, &b] {
        tix().current_dir(repo).arg("init").assert().success();
    }
    // B must have a store to lint; creating one issue also gives it a warning.
    tix()
        .current_dir(&b)
        .args(["create", "--title", "Foreign"])
        .assert()
        .success();

    // A references B's issues directory by absolute path.
    let b_issues = b.join("docs").join("issues");
    tix()
        .current_dir(&a)
        .args([
            "create",
            "--title",
            "Alpha",
            "--related-issues",
            b_issues.to_str().unwrap(),
        ])
        .assert()
        .success();

    // Default (lint_foreign_repositories = true): B's findings are merged in,
    // prefixed with the repo.
    tix()
        .current_dir(&a)
        .arg("lint")
        .assert()
        .success()
        .stderr(predicate::str::contains("[b]"));

    // `--no-foreign` restores a local-only run.
    tix()
        .current_dir(&a)
        .args(["lint", "--no-foreign"])
        .assert()
        .success()
        .stderr(predicate::str::contains("[b]").not());
}

#[test]
fn type_is_written_checked_and_cleared() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    // `tix init` writes the default types.
    let cfg = fs::read_to_string(dir.join("tix.toml")).unwrap();
    assert!(cfg.contains("types = ["), "{cfg}");
    assert!(cfg.contains("\"bug\""), "{cfg}");

    // A known type: no `unknown_type` warning.
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Alpha", "--type", "bug"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .arg("lint")
        .assert()
        .success()
        .stderr(predicate::str::contains("unknown_type").not());
    let text = fs::read_to_string(issue_file(dir)).unwrap();
    assert!(text.contains("type: bug"), "{text}");

    // An unknown type: a warning whose message names the remedy, and the file
    // relocates under the new type directory (`move_on_change`, the default).
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--type", "story"])
        .assert()
        .success();
    let moved = issue_file(dir);
    assert!(
        moved.to_string_lossy().contains("/story/"),
        "relocated under the type directory: {moved:?}"
    );
    tix()
        .current_dir(dir)
        .arg("lint")
        .assert()
        .success()
        .stderr(predicate::str::contains("unknown issue type `story`"))
        .stderr(predicate::str::contains("`types` in tix.toml"));

    // `--type ""` clears it (and the type directory falls back to `default`).
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--type", ""])
        .assert()
        .success();
    let cleared = fs::read_to_string(issue_file(dir)).unwrap();
    assert!(!cleared.contains("type:"), "{cleared}");
    assert!(
        issue_file(dir).to_string_lossy().contains("/default/"),
        "falls back to the default directory"
    );
}

/// Every CLI mutation that changes a templated field relocates the file: here
/// `tix move` (a status move) and `tix triage accept` (the path that writes the
/// status directly, not through the edit core).
#[test]
fn cli_status_changes_relocate_the_file_to_the_status_directory() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    // `tix create` lands in the first column (triage on the starter board).
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Alpha"])
        .assert()
        .success();
    let before = issue_file_named(dir, "Alpha");
    assert!(before.to_string_lossy().contains("/triage/"), "{before:?}");

    tix()
        .current_dir(dir)
        .args(["move", "1", "in progress"])
        .assert()
        .success();
    let after = issue_file_named(dir, "Alpha");
    assert!(
        after.to_string_lossy().contains("/in-progress/"),
        "{after:?}"
    );
    assert!(!before.exists(), "the old path is gone");

    // Triage accept writes the status without the edit core; it too must move.
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Beta"])
        .assert()
        .success();
    let triaged = issue_file_named(dir, "Beta");
    assert!(
        triaged.to_string_lossy().contains("/triage/"),
        "{triaged:?}"
    );
    tix()
        .current_dir(dir)
        .args(["triage", "accept", "2"])
        .assert()
        .success();
    let accepted = issue_file_named(dir, "Beta");
    assert!(
        accepted.to_string_lossy().contains("/todo/"),
        "{accepted:?}"
    );
    assert!(!triaged.exists(), "the old triage path is gone");
}

// ---------------------------------------------------------------------------
// WP05 — projects and association through the real binary (T020–T025)
// ---------------------------------------------------------------------------
//
// Every assertion here runs the compiled `tix`, never the library. The inline
// tests in `src/commands/project.rs` can prove the service was asked the right
// question; only a subprocess can prove the **flag** was accepted, the **exit
// code** was non-zero, the **diagnostic** reached stderr, and the **bytes on
// disk** did not move.
//
// The no-partial-write assertions snapshot the issue files *and* `tix.toml` and
// compare byte-for-byte: an exit code is not evidence that nothing was written.

/// The registry file's exact bytes.
fn registry_bytes(dir: &Path) -> String {
    fs::read_to_string(dir.join("tix.toml")).expect("tix.toml")
}

/// Every issue file's bytes plus `tix.toml`, so a rejection can be shown to have
/// changed **nothing** in the repository.
fn repo_snapshot(dir: &Path) -> (String, Vec<(String, Vec<u8>)>) {
    (registry_bytes(dir), issue_snapshot(dir))
}

/// `tix project create <name>` and the allocated id it prints.
///
/// The id is parsed from `Created <name> (<id>)`, the one place it is announced.
fn project_create(dir: &Path, name: &str) -> String {
    let stdout = tix()
        .current_dir(dir)
        .args(["project", "create", name])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    let open = stdout.rfind('(').expect("a parenthesised id");
    let close = stdout.rfind(')').expect("a closing parenthesis");
    stdout[open + 1..close].to_string()
}

/// `tix project list` rows as `(id, name, member count)`.
fn project_rows(dir: &Path) -> Vec<(String, String, usize)> {
    let stdout = tix()
        .current_dir(dir)
        .args(["project", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    String::from_utf8(stdout)
        .unwrap()
        .lines()
        .map(|line| {
            let mut fields = line.split('\t');
            let id = fields.next().expect("id column").to_string();
            let name = fields.next().expect("name column").to_string();
            let count: usize = fields
                .next()
                .expect("count column")
                .parse()
                .expect("a count");
            assert!(fields.next().is_none(), "exactly three columns: {line:?}");
            (id, name, count)
        })
        .collect()
}

/// A repository with `n` issues titled `Issue N` (through the real binary).
fn repo_with_numbered_issues(count: usize) -> (TempDir, std::path::PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    tix().current_dir(&dir).arg("init").assert().success();
    for i in 1..=count {
        tix()
            .current_dir(&dir)
            .args(["create", "--title", &format!("Issue {i}")])
            .assert()
            .success();
    }
    (tmp, dir)
}

/// The `projects:` list an issue file records, in order.
fn recorded_projects(dir: &Path, title: &str) -> Vec<String> {
    let contents = fs::read_to_string(issue_file_named(dir, title)).unwrap();
    let mut out = Vec::new();
    let mut in_list = false;
    for line in contents.lines() {
        if line == "projects:" {
            in_list = true;
            continue;
        }
        if in_list {
            match line.strip_prefix("- ") {
                Some(id) => out.push(id.trim().to_string()),
                None => break,
            }
        }
    }
    out
}

/// The number of `project_associated`/`project_dissociated` History entries.
fn association_events(dir: &Path, title: &str) -> usize {
    let contents = fs::read_to_string(issue_file_named(dir, title)).unwrap();
    contents
        .lines()
        .filter(|line| line.contains("project_associated") || line.contains("project_dissociated"))
        .count()
}

#[test]
fn cli_project_lifecycle_keeps_the_id_across_a_rename_and_an_edit() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    let platform = project_create(dir, "Platform");
    let infra = project_create(dir, "Infra");
    assert_ne!(platform, infra, "each create allocates its own id");

    // Association is by id, so it survives a rename of the label.
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login", "--projects", &platform])
        .assert()
        .success();

    // A `--name` change is a label change only: the id is not re-keyed and the
    // association is untouched (C-002, SC-005).
    tix()
        .current_dir(dir)
        .args(["project", "edit", &platform, "--name", "Platform hardening"])
        .assert()
        .success();
    let rows = project_rows(dir);
    assert!(
        rows.iter().any(|(id, name, count)| id == &platform
            && name == "Platform hardening"
            && *count == 1),
        "the id survives the rename with its member count: {rows:?}"
    );
    assert_eq!(
        recorded_projects(dir, "Fix login"),
        vec![platform.clone()],
        "the issue still references the id after the rename"
    );

    // Renaming to an existing name is refused, and the registry is unchanged.
    let before = registry_bytes(dir);
    tix()
        .current_dir(dir)
        .args(["project", "edit", &infra, "--name", "Platform hardening"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("duplicate_name"));
    assert_eq!(
        registry_bytes(dir),
        before,
        "a refused rename writes nothing"
    );
}

#[test]
fn cli_project_listing_shows_the_id_and_the_name_and_a_member_count() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let platform = project_create(dir, "Platform");

    let rows = project_rows(dir);
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].0, platform, "the id is a column of its own (C-002)");
    assert_eq!(rows[0].1, "Platform");
    assert_eq!(rows[0].2, 0, "a project with no issues has no members");

    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login", "--projects", &platform])
        .assert()
        .success();
    assert_eq!(project_rows(dir)[0].2, 1, "the member count is derived");
}

#[test]
fn cli_project_show_prints_the_record_and_the_members_with_ids() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let platform = project_create(dir, "Platform");
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login", "--projects", &platform])
        .assert()
        .success();

    let stdout = tix()
        .current_dir(dir)
        .args(["project", "show", &platform])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    assert!(stdout.contains(&format!("id: {platform}")), "{stdout}");
    assert!(stdout.contains("name: Platform"), "{stdout}");
    assert!(stdout.contains("members: 1"), "{stdout}");
    assert!(
        stdout.contains("#1") && stdout.contains("Fix login"),
        "a member is named by number and title: {stdout}"
    );
}

#[test]
fn cli_project_association_create_add_remove_clear_tracks_frontmatter_and_history() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let platform = project_create(dir, "Platform");
    let infra = project_create(dir, "Infra");
    let data = project_create(dir, "Data");

    // Create with two associations: two History entries, one per accepted change.
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Fix login",
            "--projects",
            &format!("{platform},{infra}"),
        ])
        .assert()
        .success();
    assert_eq!(
        recorded_projects(dir, "Fix login"),
        vec![platform.clone(), infra.clone()]
    );
    assert_eq!(association_events(dir, "Fix login"), 2);

    // A third association adds exactly one entry.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--add-project", &data])
        .assert()
        .success();
    assert_eq!(
        recorded_projects(dir, "Fix login"),
        vec![platform.clone(), infra.clone(), data.clone()]
    );
    assert_eq!(association_events(dir, "Fix login"), 3);

    // Re-adding an existing association is a no-op: no write, no second entry —
    // and the success line says so rather than claiming an update.
    let before = fs::read(issue_file_named(dir, "Fix login")).unwrap();
    let stdout = tix()
        .current_dir(dir)
        .args(["edit", "1", "--add-project", &data])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    assert!(
        stdout.contains("(no association change)"),
        "a no-op edit does not claim an update: {stdout}"
    );
    assert_eq!(
        fs::read(issue_file_named(dir, "Fix login")).unwrap(),
        before,
        "a no-op add writes nothing"
    );
    assert_eq!(association_events(dir, "Fix login"), 3);

    // Removing drops only the association.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--remove-project", &infra])
        .assert()
        .success();
    assert_eq!(
        recorded_projects(dir, "Fix login"),
        vec![platform.clone(), data.clone()]
    );
    assert!(
        issue_file_named(dir, "Fix login").is_file(),
        "the issue is kept"
    );

    // `--projects ""` clears every association, one entry per removal.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--projects", ""])
        .assert()
        .success();
    assert!(recorded_projects(dir, "Fix login").is_empty());
    assert_eq!(association_events(dir, "Fix login"), 6);
    assert!(issue_file_named(dir, "Fix login").is_file());
}

#[test]
fn cli_project_bulk_add_reports_partial_success_and_writes_the_good_ones() {
    let (tmp, dir) = repo_with_numbered_issues(3);
    let _tmp = tmp;
    let platform = project_create(&dir, "Platform");

    // One bad selector among the good ones: the good ones still land and the run
    // exits non-zero (the repo's partial-batch convention).
    tix()
        .current_dir(&dir)
        .args(["project", "bulk-add", &platform, "1", "99", "2"])
        .assert()
        .failure()
        .stdout(predicate::str::contains("associated 2 of 3"))
        .stderr(predicate::str::contains("issue #99"));

    assert_eq!(recorded_projects(&dir, "Issue 1"), vec![platform.clone()]);
    assert_eq!(recorded_projects(&dir, "Issue 2"), vec![platform.clone()]);
    assert!(recorded_projects(&dir, "Issue 3").is_empty());

    // A fully successful batch exits zero.
    tix()
        .current_dir(&dir)
        .args(["project", "bulk-add", &platform, "3"])
        .assert()
        .success()
        .stdout(predicate::str::contains("associated 1 of 1"));
    assert_eq!(recorded_projects(&dir, "Issue 3"), vec![platform.clone()]);

    // The project-side `add` is the same operation: independent, per-issue.
    tix()
        .current_dir(&dir)
        .args(["project", "add", &platform, "1", "2"])
        .assert()
        .success()
        .stdout(predicate::str::contains("(2 unchanged)"));
}

#[test]
fn cli_project_unknown_id_is_refused_with_a_named_diagnostic_and_no_write() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let _platform = project_create(dir, "Platform");
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login"])
        .assert()
        .success();
    let before = repo_snapshot(dir);

    for args in [
        vec!["project", "show", "bogus"],
        vec!["project", "edit", "bogus", "--name", "X"],
        vec!["project", "delete", "bogus", "--yes"],
        vec!["project", "add", "bogus", "1"],
        vec!["edit", "1", "--add-project", "bogus"],
        vec!["edit", "1", "--remove-project", "bogus"],
    ] {
        tix()
            .current_dir(dir)
            .args(&args)
            .assert()
            .failure()
            .stderr(predicate::str::contains("unknown_project"));
    }

    // `tix create --projects bogus` refuses the whole create: no issue is written.
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Half associated",
            "--projects",
            "bogus",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown_project"));

    assert_eq!(
        repo_snapshot(dir),
        before,
        "a rejected project operation changes nothing on disk"
    );
}

#[test]
fn cli_project_duplicate_name_and_invalid_dates_are_refused_with_no_write() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let _platform = project_create(dir, "Platform");
    let before = repo_snapshot(dir);

    tix()
        .current_dir(dir)
        .args(["project", "create", "platform"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("duplicate_name"));

    tix()
        .current_dir(dir)
        .args([
            "project",
            "create",
            "Bad dates",
            "--start-date",
            "2026-05-01",
            "--due-date",
            "2026-01-01",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid_dates"));

    tix()
        .current_dir(dir)
        .args(["project", "create", "Bad shape", "--due-date", "not-a-date"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid_dates"));

    assert_eq!(
        repo_snapshot(dir),
        before,
        "a rejected project write changes nothing on disk"
    );
}

#[test]
fn cli_project_delete_retains_the_issues_and_only_removes_the_registry_entry() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let platform = project_create(dir, "Platform");
    let infra = project_create(dir, "Infra");
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Fix login",
            "--projects",
            &format!("{platform},{infra}"),
        ])
        .assert()
        .success();
    let issue_before = fs::read(issue_file_named(dir, "Fix login")).unwrap();

    // The report names the affected issue and states that nothing is deleted.
    tix()
        .current_dir(dir)
        .args(["project", "delete", &platform, "--yes"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Fix login").and(predicate::str::contains("not deleted")));

    // Only the registry entry is gone.
    let registry = registry_bytes(dir);
    assert!(!registry.contains(&platform), "the entry is removed");
    assert!(registry.contains(&infra), "the sibling project survives");
    // The issue is byte-identical: still present, still carrying the reference.
    assert_eq!(
        fs::read(issue_file_named(dir, "Fix login")).unwrap(),
        issue_before,
        "deleting a project must not touch an issue"
    );
    assert_eq!(
        recorded_projects(dir, "Fix login"),
        vec![platform.clone(), infra.clone()],
        "the dangling reference is retained, not dropped (C-005)"
    );
    // The retained reference is repairable: `--remove-project` removes a stale id
    // even though the registry no longer knows it — the repair path C-005 promises.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--remove-project", &platform])
        .assert()
        .success();
    assert_eq!(
        recorded_projects(dir, "Fix login"),
        vec![infra.clone()],
        "the stale reference is removable"
    );
}

#[test]
fn cli_edit_projects_clear_is_the_only_spelling_that_clears() {
    let (tmp, dir) = repo_with_numbered_issues(1);
    let _tmp = tmp;
    let platform = project_create(&dir, "Platform");
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--add-project", &platform])
        .assert()
        .success();
    assert_eq!(recorded_projects(&dir, "Issue 1"), vec![platform.clone()]);

    // A non-blank `--projects` list is refused rather than guessed at; the
    // association list is untouched.
    let before = fs::read(issue_file_named(&dir, "Issue 1")).unwrap();
    tix()
        .current_dir(&dir)
        .args(["edit", "1", "--projects", &platform])
        .assert()
        .failure()
        .stderr(predicate::str::contains("--projects"));
    assert_eq!(fs::read(issue_file_named(&dir, "Issue 1")).unwrap(), before);

    // The documented clearing spelling works.
    let stdout = tix()
        .current_dir(&dir)
        .args(["edit", "1", "--projects", ""])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert!(
        String::from_utf8(stdout).unwrap().starts_with("Updated "),
        "a clearing that changed something is an update"
    );
    assert!(recorded_projects(&dir, "Issue 1").is_empty());

    // Clearing an issue that has no associations writes nothing and says so.
    let before = fs::read(issue_file_named(&dir, "Issue 1")).unwrap();
    let stdout = tix()
        .current_dir(&dir)
        .args(["edit", "1", "--projects", ""])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert!(
        String::from_utf8(stdout)
            .unwrap()
            .contains("(no association change)"),
        "a clearing that changed nothing does not claim an update"
    );
    assert_eq!(fs::read(issue_file_named(&dir, "Issue 1")).unwrap(), before);
}

#[test]
fn cli_project_surface_has_no_template_or_general_bulk_machinery() {
    let stdout = tix()
        .args(["project", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    // The command list is exactly the eight contract verbs — no template surface
    // and no general bulk-edit engine grew here.
    let mut commands: Vec<String> = Vec::new();
    let mut in_commands = false;
    for line in stdout.lines() {
        if line == "Commands:" {
            in_commands = true;
            continue;
        }
        if in_commands {
            if line.trim().is_empty() {
                break;
            }
            if let Some(verb) = line.split_whitespace().next() {
                commands.push(verb.to_string());
            }
        }
    }
    assert_eq!(
        commands,
        vec![
            "create", "edit", "list", "show", "delete", "add", "remove", "bulk-add", "help"
        ],
        "the surface is exactly the contract verbs: {stdout}"
    );
    assert!(
        !stdout.contains("template"),
        "no template machinery is built here: {stdout}"
    );

    // Deleting a project has no cascade knob (C-004).
    let delete_help = tix()
        .args(["project", "delete", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let delete_help = String::from_utf8(delete_help).unwrap();
    assert!(
        !delete_help.contains("--cascade"),
        "no cascade flag: {delete_help}"
    );

    // The clearing convention is documented where a user looks for it.
    let edit_help = tix()
        .args(["edit", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let edit_help = String::from_utf8(edit_help).unwrap();
    assert!(
        edit_help.contains("--add-project")
            && edit_help.contains("--remove-project")
            && edit_help.contains("clear"),
        "the association flags and the clearing convention are documented: {edit_help}"
    );

    // The two `remove` spellings differ deliberately, and the help says which is
    // which: `tix project remove` matches a stale id verbatim and refuses nothing,
    // while `tix edit --remove-project` refuses an unknown reference the issue does
    // not carry.
    let remove_help = tix()
        .args(["project", "remove", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let remove_help = String::from_utf8(remove_help).unwrap();
    assert!(
        remove_help.contains("verbatim")
            && remove_help.contains("0 changed")
            && remove_help.contains("unknown_project"),
        "the remove divergence is documented: {remove_help}"
    );

    let bulk_help = tix()
        .args(["project", "bulk-add", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let bulk_help = String::from_utf8(bulk_help).unwrap();
    assert!(
        bulk_help.contains("unknown_project") && bulk_help.contains("0 changed"),
        "the bulk-add divergence is documented: {bulk_help}"
    );
}

// ---------------------------------------------------------------------------
// WP05 — epics, association and hierarchy navigation through the real binary
// ---------------------------------------------------------------------------
//
// Every assertion here runs the compiled `tix`, never the library: only a
// subprocess can prove the flag was accepted, the exit code was non-zero, the
// diagnostic reached stderr, and the bytes on disk did not move.

/// `tix epic create <name>` and the allocated id it prints.
fn epic_create(dir: &Path, name: &str) -> String {
    let stdout = tix()
        .current_dir(dir)
        .args(["epic", "create", name])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    let open = stdout.rfind('(').expect("a parenthesised id");
    let close = stdout.rfind(')').expect("a closing parenthesis");
    stdout[open + 1..close].to_string()
}

/// `tix epic list` rows as `(id, name, member count, child count)`.
fn epic_rows(dir: &Path) -> Vec<(String, String, usize, usize)> {
    let stdout = tix()
        .current_dir(dir)
        .args(["epic", "list"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    String::from_utf8(stdout)
        .unwrap()
        .lines()
        .map(|line| {
            let mut f = line.split('\t');
            let id = f.next().expect("id").to_string();
            let name = f.next().expect("name").to_string();
            let members: usize = f.next().expect("members").parse().expect("a count");
            let children: usize = f.next().expect("children").parse().expect("a count");
            assert!(f.next().is_none(), "exactly four columns: {line:?}");
            (id, name, members, children)
        })
        .collect()
}

/// The `epics:` list an issue file records, in order.
fn recorded_epics(dir: &Path, title: &str) -> Vec<String> {
    let contents = fs::read_to_string(issue_file_named(dir, title)).unwrap();
    let mut out = Vec::new();
    let mut in_list = false;
    for line in contents.lines() {
        if line == "epics:" {
            in_list = true;
            continue;
        }
        if in_list {
            match line.strip_prefix("- ") {
                Some(id) => out.push(id.trim().to_string()),
                None => break,
            }
        }
    }
    out
}

/// The number of `epic_referenced`/`epic_dereferenced` History entries.
fn epic_events(dir: &Path, title: &str) -> usize {
    let contents = fs::read_to_string(issue_file_named(dir, title)).unwrap();
    contents
        .lines()
        .filter(|line| line.contains("epic_referenced") || line.contains("epic_dereferenced"))
        .count()
}

#[test]
fn cli_epic_lifecycle_keeps_the_id_across_a_rename_and_an_edit() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    let root = epic_create(dir, "Root epic");
    let mid = epic_create(dir, "Mid epic");
    assert_ne!(root, mid, "each create allocates its own id");

    // A reference is by id, so it survives a rename of the label.
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login", "--epics", &mid])
        .assert()
        .success();

    // A `--name` change is a label change only: the id is not re-keyed and the
    // reference is untouched (C-003).
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &mid, "--name", "Mid epic hardened"])
        .assert()
        .success();
    let rows = epic_rows(dir);
    assert!(
        rows.iter().any(|(id, name, members, _)| id == &mid
            && name == "Mid epic hardened"
            && *members == 1),
        "the id survives the rename with its member count: {rows:?}"
    );
    assert_eq!(
        recorded_epics(dir, "Fix login"),
        vec![mid.clone()],
        "the issue still references the id after the rename"
    );

    // An edit that only sets the parent keeps the id too.
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &mid, "--parent", &root])
        .assert()
        .success();
    assert_eq!(
        epic_rows(dir)
            .iter()
            .find(|(id, ..)| id == &root)
            .unwrap()
            .3,
        1,
        "Root now has one child epic"
    );

    // Renaming to an existing name is refused, and the registry is unchanged.
    let before = registry_bytes(dir);
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &mid, "--name", "Root epic"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("duplicate_name"));
    assert_eq!(
        registry_bytes(dir),
        before,
        "a refused rename writes nothing"
    );
}

#[test]
fn cli_epic_listing_shows_the_id_and_the_name_and_counts() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let root = epic_create(dir, "Root");
    let child = epic_create(dir, "Child");
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &child, "--parent", &root])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login", "--epics", &root])
        .assert()
        .success();

    let rows = epic_rows(dir);
    assert_eq!(rows.len(), 2, "declaration order: {rows:?}");
    assert_eq!(rows[0].0, root, "the id is a column of its own (C-003)");
    assert_eq!(rows[0].1, "Root");
    assert_eq!(rows[0].2, 1, "the member count is derived");
    assert_eq!(rows[0].3, 1, "the child count is derived");
    assert_eq!(rows[1].0, child);
    assert_eq!(rows[1].1, "Child");
}

#[test]
fn cli_epic_show_prints_record_hierarchy_figures_and_members_with_ids() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let root = epic_create(dir, "Root");
    let child = epic_create(dir, "Child");
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &child, "--parent", &root])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login", "--epics", &root])
        .assert()
        .success();

    let stdout = tix()
        .current_dir(dir)
        .args(["epic", "show", &root])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    assert!(stdout.contains(&format!("id: {root}")), "{stdout}");
    assert!(stdout.contains("name: Root"), "{stdout}");
    assert!(stdout.contains("children: 1"), "{stdout}");
    assert!(stdout.contains("members: 1"), "{stdout}");
    assert!(
        stdout.contains("progress: 0/1"),
        "the service progress figure: {stdout}"
    );
    assert!(
        stdout.contains(&format!("child: Child ({child})")),
        "a child epic shows its id: {stdout}"
    );
    assert!(
        stdout.contains("#1") && stdout.contains("Fix login"),
        "a member is named by number and title: {stdout}"
    );
}

#[test]
fn cli_epic_navigate_prints_parent_children_ancestors_and_depth_in_order() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let root = epic_create(dir, "Root");
    let mid = epic_create(dir, "Mid");
    let leaf = epic_create(dir, "Leaf");
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &mid, "--parent", &root])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &leaf, "--parent", &mid])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login", "--epics", &leaf])
        .assert()
        .success();

    let stdout = tix()
        .current_dir(dir)
        .args(["epic", "navigate", &leaf])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    let pos = |needle: &str| {
        stdout
            .find(needle)
            .unwrap_or_else(|| panic!("{needle} in {stdout}"))
    };
    // Parent-first: the ancestor Root precedes the parent Mid, which precedes Leaf.
    assert!(pos("Root (") < pos("Mid ("), "root first: {stdout}");
    assert!(pos("Mid (") < pos("Leaf ("), "parent before self: {stdout}");
    assert!(stdout.contains(&format!("parent: Mid ({mid})")), "{stdout}");
    assert!(
        stdout.contains("depth: 2"),
        "the depth is printed: {stdout}"
    );
    assert!(stdout.contains(&format!("epic: Leaf ({leaf})")), "{stdout}");
    assert!(
        stdout.contains("issues: 1") && stdout.contains("Fix login"),
        "direct issue navigation is advertised with the member list: {stdout}"
    );
    assert!(
        stdout.contains("navigate one directly"),
        "FR-004's direct navigation is visible: {stdout}"
    );
}

#[test]
fn cli_epic_delete_retains_members_and_child_epics_and_removes_only_the_entry() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let parent = epic_create(dir, "Parent");
    let child = epic_create(dir, "Child");
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &child, "--parent", &parent])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login", "--epics", &parent])
        .assert()
        .success();
    let issue_before = fs::read(issue_file_named(dir, "Fix login")).unwrap();

    // The report names the member and the child epic and states nothing is deleted.
    tix()
        .current_dir(dir)
        .args(["epic", "delete", &parent, "--yes"])
        .assert()
        .success()
        .stderr(
            predicate::str::contains("Fix login")
                .and(predicate::str::contains("Child"))
                .and(predicate::str::contains("not deleted")),
        );

    // Only the registry entry is gone; the child epic survives.
    let registry = registry_bytes(dir);
    assert!(
        !registry.contains(&format!("[epics.{parent}]")),
        "the entry is removed: {registry}"
    );
    assert!(registry.contains(&child), "the child epic survives");
    assert!(
        epic_rows(dir).iter().all(|(id, ..)| id != &parent),
        "the deleted epic is gone from the listing"
    );
    // The issue is byte-identical: still present, still carrying the reference.
    assert_eq!(
        fs::read(issue_file_named(dir, "Fix login")).unwrap(),
        issue_before,
        "deleting an epic must not touch an issue"
    );
    assert_eq!(recorded_epics(dir, "Fix login"), vec![parent.clone()]);

    // The child keeps its recorded parent, which now reads as unresolved.
    let stdout = tix()
        .current_dir(dir)
        .args(["epic", "navigate", &child])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    assert!(
        stdout.contains("unresolved-parent:"),
        "the recorded parent is retained as unresolved: {stdout}"
    );
}

#[test]
fn cli_epic_association_create_add_remove_clear_tracks_frontmatter_and_history() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let one = epic_create(dir, "One");
    let two = epic_create(dir, "Two");
    let three = epic_create(dir, "Three");

    // Create with two references: two History entries, one per accepted change.
    tix()
        .current_dir(dir)
        .args([
            "create",
            "--title",
            "Fix login",
            "--epics",
            &format!("{one},{two}"),
        ])
        .assert()
        .success();
    assert_eq!(
        recorded_epics(dir, "Fix login"),
        vec![one.clone(), two.clone()]
    );
    assert_eq!(epic_events(dir, "Fix login"), 2);

    // Re-adding an existing reference is a no-op: no write, no second entry.
    let before = fs::read(issue_file_named(dir, "Fix login")).unwrap();
    let stdout = tix()
        .current_dir(dir)
        .args(["edit", "1", "--add-epic", &one])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert!(
        String::from_utf8(stdout)
            .unwrap()
            .contains("(no association change)"),
        "a no-op add does not claim an update"
    );
    assert_eq!(
        fs::read(issue_file_named(dir, "Fix login")).unwrap(),
        before
    );
    assert_eq!(epic_events(dir, "Fix login"), 2);

    // A new reference adds exactly one entry.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--add-epic", &three])
        .assert()
        .success();
    assert_eq!(
        recorded_epics(dir, "Fix login"),
        vec![one.clone(), two.clone(), three.clone()]
    );
    assert_eq!(epic_events(dir, "Fix login"), 3);

    // Removing a reference drops only the reference; the issue is kept.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--remove-epic", &two])
        .assert()
        .success();
    assert_eq!(
        recorded_epics(dir, "Fix login"),
        vec![one.clone(), three.clone()]
    );
    assert!(
        issue_file_named(dir, "Fix login").is_file(),
        "the issue is kept"
    );

    // `--epics ""` clears every reference, one entry per removal.
    tix()
        .current_dir(dir)
        .args(["edit", "1", "--epics", ""])
        .assert()
        .success();
    assert!(recorded_epics(dir, "Fix login").is_empty());
    assert_eq!(epic_events(dir, "Fix login"), 6);
}

#[test]
fn cli_task_labelled_issue_is_an_ordinary_issue_with_a_reference() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let one = epic_create(dir, "One");
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login"])
        .assert()
        .success();

    tix()
        .current_dir(dir)
        .args(["edit", "1", "--labels", "task", "--add-epic", &one])
        .assert()
        .success();
    assert_eq!(recorded_epics(dir, "Fix login"), vec![one.clone()]);

    // C-001: no task entity, file, or frontmatter key is introduced.
    let contents = fs::read_to_string(issue_file_named(dir, "Fix login")).unwrap();
    let frontmatter = contents.split("---").nth(1).expect("a frontmatter block");
    for forbidden in ["task:", "task_id:", "work_item:", "epic_task:"] {
        assert!(
            !frontmatter.contains(forbidden),
            "no task key may exist: {forbidden} in {frontmatter}"
        );
    }
    assert!(
        frontmatter.contains("labels:") && frontmatter.contains("task"),
        "the task label is just a label: {frontmatter}"
    );
}

#[test]
fn cli_epic_bulk_add_reports_partial_success_and_writes_the_good_ones() {
    let (tmp, dir) = repo_with_numbered_issues(3);
    let _tmp = tmp;
    let epic = epic_create(&dir, "Harden");

    // One bad selector among the good ones: the good ones still land and the run
    // exits non-zero (the repo's partial-batch convention).
    tix()
        .current_dir(&dir)
        .args(["epic", "bulk-add", &epic, "1", "99", "2"])
        .assert()
        .failure()
        .stdout(predicate::str::contains("referenced 2 of 3"))
        .stderr(predicate::str::contains("issue #99"));

    assert_eq!(recorded_epics(&dir, "Issue 1"), vec![epic.clone()]);
    assert_eq!(recorded_epics(&dir, "Issue 2"), vec![epic.clone()]);
    assert!(recorded_epics(&dir, "Issue 3").is_empty());
    assert_eq!(epic_events(&dir, "Issue 1"), 1, "exactly one entry");

    // A fully successful batch exits zero.
    tix()
        .current_dir(&dir)
        .args(["epic", "bulk-add", &epic, "3"])
        .assert()
        .success()
        .stdout(predicate::str::contains("referenced 1 of 1"));

    // The epic-side `add` is the same operation: independent, per-issue, and an
    // idempotent re-add reports zero changes.
    tix()
        .current_dir(&dir)
        .args(["epic", "add", &epic, "1", "2"])
        .assert()
        .success()
        .stdout(predicate::str::contains("(2 unchanged)"));
}

#[test]
fn cli_epic_unknown_reference_is_refused_with_a_named_diagnostic_and_no_write() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let _epic = epic_create(dir, "Harden");
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Fix login"])
        .assert()
        .success();
    let before = repo_snapshot(dir);

    for args in [
        vec!["epic", "show", "bogus"],
        vec!["epic", "navigate", "bogus"],
        vec!["epic", "edit", "bogus", "--name", "X"],
        vec!["epic", "delete", "bogus", "--yes"],
        vec!["epic", "add", "bogus", "1"],
        vec!["edit", "1", "--add-epic", "bogus"],
        vec!["edit", "1", "--remove-epic", "bogus"],
    ] {
        tix()
            .current_dir(dir)
            .args(&args)
            .assert()
            .failure()
            .stderr(predicate::str::contains("unknown_epic"));
    }

    // `tix epic remove` uses an unknown reference **verbatim** (the repair path a
    // deletion leaves open), so it is an inert no-op reported as `0 changed`, not a
    // refusal — the one place this differs from `tix edit --remove-epic`.
    tix()
        .current_dir(dir)
        .args(["epic", "remove", "bogus", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("0 of 1"));

    // `tix create --epics bogus` refuses the whole create: no issue is written.
    tix()
        .current_dir(dir)
        .args(["create", "--title", "Half referenced", "--epics", "bogus"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown_epic"));

    assert_eq!(
        repo_snapshot(dir),
        before,
        "a rejected epic operation changes nothing on disk"
    );
}

#[test]
fn cli_epic_lifecycle_refusals_are_named_and_write_nothing() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let one = epic_create(dir, "One");
    let two = epic_create(dir, "Two");
    let three = epic_create(dir, "Three");
    // A chain Two -> One so Three under Two is legal but One under Three is a cycle.
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &two, "--parent", &one])
        .assert()
        .success();
    // Three under Two is *legal* and must not be caught by the cycle walk.
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &three, "--parent", &two])
        .assert()
        .success();
    let before = repo_snapshot(dir);

    // Duplicate name (case-folded).
    tix()
        .current_dir(dir)
        .args(["epic", "create", "one"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("duplicate_name"));
    // Invalid dates (inverted and malformed).
    tix()
        .current_dir(dir)
        .args([
            "epic",
            "create",
            "Bad dates",
            "--start-date",
            "2026-05-01",
            "--due-date",
            "2026-01-01",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid_dates"));
    tix()
        .current_dir(dir)
        .args(["epic", "create", "Bad shape", "--due-date", "not-a-date"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid_dates"));
    // Invalid weight (zero, and a non-integer).
    tix()
        .current_dir(dir)
        .args(["epic", "create", "No weight", "--weight", "0"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid_weight"));
    tix()
        .current_dir(dir)
        .args(["epic", "create", "Bad weight", "--weight", "heavy"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid_weight"));
    // A negative weight reaches the named diagnostic whichever spelling is used:
    // the space-separated `--weight -5` and the `--weight=-5` form must agree, and
    // `tix epic edit` must too.
    for args in [
        vec!["epic", "create", "Neg A", "--weight", "-5"],
        vec!["epic", "create", "Neg B", "--weight=-5"],
    ] {
        tix()
            .current_dir(dir)
            .args(&args)
            .assert()
            .failure()
            .stderr(predicate::str::contains("invalid_weight"));
    }
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &one, "--weight", "-5"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid_weight"));
    // Self-parent.
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &one, "--parent", &one])
        .assert()
        .failure()
        .stderr(predicate::str::contains("self_parent"));
    // Cycle: One under Two closes Two -> One.
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &one, "--parent", &two])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cycle"));

    // Every refusal above left the repository byte-identical.
    assert_eq!(
        repo_snapshot(dir),
        before,
        "a refused epic write changes nothing on disk"
    );
}

#[test]
fn cli_epic_surface_has_the_contract_verbs_and_documents_clearing() {
    let stdout = tix()
        .args(["epic", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(stdout).unwrap();
    let mut commands: Vec<String> = Vec::new();
    let mut in_commands = false;
    for line in stdout.lines() {
        if line == "Commands:" {
            in_commands = true;
            continue;
        }
        if in_commands {
            if line.trim().is_empty() {
                break;
            }
            if let Some(verb) = line.split_whitespace().next() {
                commands.push(verb.to_string());
            }
        }
    }
    assert_eq!(
        commands,
        vec![
            "create", "edit", "list", "show", "navigate", "delete", "add", "remove", "bulk-add",
            "help"
        ],
        "the surface is exactly the contract verbs: {stdout}"
    );

    // Deleting an epic has no cascade knob (C-006).
    let delete_help = tix()
        .args(["epic", "delete", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let delete_help = String::from_utf8(delete_help).unwrap();
    assert!(
        !delete_help.contains("--cascade"),
        "no cascade flag: {delete_help}"
    );

    // The clearing convention is documented where a user looks for it.
    let edit_help = tix()
        .args(["edit", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let edit_help = String::from_utf8(edit_help).unwrap();
    assert!(
        edit_help.contains("--add-epic")
            && edit_help.contains("--remove-epic")
            && edit_help.contains("clear"),
        "the reference flags and the clearing convention are documented: {edit_help}"
    );

    // `tix create --epics` is on the shared create surface.
    let create_help = tix()
        .args(["create", "--help"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let create_help = String::from_utf8(create_help).unwrap();
    assert!(create_help.contains("--epics"), "{create_help}");
}

#[test]
fn cli_epic_projects_milestone_and_cycle_are_stored_and_cleared() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let id = {
        let out = tix()
            .current_dir(dir)
            .args([
                "epic",
                "create",
                "Harden",
                "--projects",
                "p-a,p-b",
                "--milestone",
                "Q4",
                "--cycle",
                "Oct",
            ])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let out = String::from_utf8(out).unwrap();
        out[out.rfind('(').unwrap() + 1..out.rfind(')').unwrap()].to_string()
    };

    let shown = || -> String {
        let out = tix()
            .current_dir(dir)
            .args(["epic", "show", "Harden"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        String::from_utf8(out).unwrap()
    };
    let first = shown();
    assert!(first.contains("projects: p-a, p-b"), "{first}");
    assert!(first.contains("milestone: Q4"), "{first}");
    assert!(first.contains("cycle: Oct"), "{first}");

    // Each is cleared with `--flag ""`, the empty-string-clears convention.
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &id, "--projects", ""])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &id, "--milestone", ""])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["epic", "edit", &id, "--cycle", ""])
        .assert()
        .success();
    let cleared = shown();
    assert!(cleared.contains("projects: -"), "{cleared}");
    assert!(cleared.contains("milestone: -"), "{cleared}");
    assert!(cleared.contains("cycle: -"), "{cleared}");
}

#[test]
fn cli_epic_reference_fields_are_shape_checked_and_dangling_ids_are_stored() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    // A malformed project id is refused *before* anything is written.
    let before = registry_bytes(dir);
    tix()
        .current_dir(dir)
        .args(["epic", "create", "Bad", "--projects", "not valid!"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid_reference"));
    assert_eq!(
        registry_bytes(dir),
        before,
        "a shape refusal writes nothing"
    );

    // A **well-formed** id the registry does not hold is stored, not refused: it is
    // the diagnosable dangling reference C-005 promises, and the service's rollup
    // reports it.
    tix()
        .current_dir(dir)
        .args(["epic", "create", "Harden", "--projects", "p-nowhere"])
        .assert()
        .success();
    assert!(
        registry_bytes(dir).contains("p-nowhere"),
        "the dangling id is stored"
    );
    let out = tix()
        .current_dir(dir)
        .args(["epic", "show", "Harden"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let out = String::from_utf8(out).unwrap();
    assert!(out.contains("missing-references: 1"), "{out}");
}