doctrine 0.4.2

Project tooling CLI
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
// SPDX-License-Identifier: GPL-3.0-only
//! `doctrine backlog` — lightweight work-intake items (issue / improvement /
//! chore / risk / idea), each a numeric directory under
//! `.doctrine/backlog/<kind>/` holding a sister `backlog-NNN.toml` (structured,
//! queried metadata) and a scaffolded `backlog-NNN.md` prose body, with an
//! `NNN-slug` symlink alias — the ADR/spec/requirement shape (design §5.1/§5.3).
//!
//! Five `ItemKind`s ride five `entity::Kind`s over the same kind-blind engine,
//! each its own tree + reservation namespace (`ISS-001` and `RSK-001` coexist —
//! the counters are independent). The subtypes diverge only in their prefix and
//! whether the scaffold seeds a risk `[facet]`.
//!
//! This module owns the *backlog-specific* parts — the five `Kind`s, their shared
//! scaffold, the render fns, and the three-layer parse model (`RawBacklogToml`
//! tolerant parse → validated `BacklogItem`, with the `"" -> None` validation
//! seam for the optional `resolution`/risk-level fields). The kind-agnostic engine
//! is `crate::entity` (unchanged — five new `Fresh` callers only, the R6 gate).
//!
//! All four verbs (`new`/`list`/`show`/`edit`) are wired into the CLI as of
//! PHASE-06; the only production-dead item left is `KIND_PRECEDENCE` — inert
//! until the PRD-011 multi-kind resolver consumes it. Its dead-code expectation
//! is scoped to that one const (below), NOT module-wide, so genuinely-dead code
//! introduced later still surfaces.

use std::collections::BTreeMap;
use std::io::{self, Write};
use std::path::{Path, PathBuf};

use anyhow::Context;
use serde::{Deserialize, Serialize};

use crate::backlog_order::{BacklogOrder, ItemId, OrderInput, Override, OverrideReason};
// SL-060 PHASE-02: the dep/sequence schema + the strict edit-preserving append now
// live in the shared `dep_seq` leaf. Backlog uses the leaf TYPE (`AfterEdge`) and the
// leaf `RelEdit`/`append` write seam; its own `read_item`/`dep_seq_for` (the one-parse
// `promoted` projection) stay backlog-local.
use crate::dep_seq::{self, AfterEdge, RelEdit};

use crate::entity::{
    self, Artifact, Fileset, Inputs, Kind, LocalFs, MaterialiseRequest, ScaffoldCtx,
};
use crate::listing::{self, Format, ListArgs};
use crate::tomlfmt::toml_string;

/// The toml/md file stem — shared by all five kinds (`backlog-NNN.toml`). Distinct
/// from each `Kind.prefix` (`ISS`/`IMP`/…) and from the per-kind tree dirs.
const BACKLOG_STEM: &str = "backlog";

// ---------------------------------------------------------------------------
// The discriminator + its five engine `Kind`s
// ---------------------------------------------------------------------------

/// Which backlog item this is. Closed set; kebab serde (round-trips the toml's
/// `kind`) and `clap::ValueEnum` (the `backlog new` positional, PHASE-02). Selects
/// the tree, prefix, and scaffold fileset. Fixed at capture (PRD-009 §4 invariant).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ItemKind {
    Issue,
    Improvement,
    Chore,
    Risk,
    Idea,
}

/// The issue kind: a defect / problem to fix. Own tree + reservation namespace.
pub(crate) const ISSUE_KIND: Kind = Kind {
    dir: ".doctrine/backlog/issue",
    prefix: "ISS",
    scaffold: |c| backlog_scaffold(ItemKind::Issue, c),
};

/// The improvement kind: an enhancement to existing behaviour.
pub(crate) const IMPROVEMENT_KIND: Kind = Kind {
    dir: ".doctrine/backlog/improvement",
    prefix: "IMP",
    scaffold: |c| backlog_scaffold(ItemKind::Improvement, c),
};

/// The chore kind: maintenance with no user-visible behaviour change.
pub(crate) const CHORE_KIND: Kind = Kind {
    dir: ".doctrine/backlog/chore",
    prefix: "CHR",
    scaffold: |c| backlog_scaffold(ItemKind::Chore, c),
};

/// The risk kind: a tracked risk — the only kind carrying a `[facet]`.
pub(crate) const RISK_KIND: Kind = Kind {
    dir: ".doctrine/backlog/risk",
    prefix: "RSK",
    scaffold: |c| backlog_scaffold(ItemKind::Risk, c),
};

/// The idea kind: a speculative possibility, not yet committed work.
pub(crate) const IDEA_KIND: Kind = Kind {
    dir: ".doctrine/backlog/idea",
    prefix: "IDE",
    scaffold: |c| backlog_scaffold(ItemKind::Idea, c),
};

/// Boundary precedence for the future multi-kind resolver (PRD-009 §4): when one
/// capture could match several kinds, `risk` wins, then issue/improvement/chore/
/// idea. INERT in v1 — `new` always takes an explicit kind, so this is never
/// exercised; recorded so the order is canon when the resolver lands (PRD-011).
#[expect(
    dead_code,
    reason = "inert until the PRD-011 multi-kind resolver consumes it"
)]
const KIND_PRECEDENCE: [ItemKind; 5] = [
    ItemKind::Risk,
    ItemKind::Issue,
    ItemKind::Improvement,
    ItemKind::Chore,
    ItemKind::Idea,
];

impl ItemKind {
    /// The engine `Kind` for this item kind — the single source of its tree +
    /// prefix + scaffold.
    const fn kind(self) -> &'static Kind {
        match self {
            ItemKind::Issue => &ISSUE_KIND,
            ItemKind::Improvement => &IMPROVEMENT_KIND,
            ItemKind::Chore => &CHORE_KIND,
            ItemKind::Risk => &RISK_KIND,
            ItemKind::Idea => &IDEA_KIND,
        }
    }

    /// The canonical-id prefix (`ISS`/`IMP`/`CHR`/`RSK`/`IDE`), read off the
    /// `Kind` so the prefix is never hardcoded twice. `pub(crate)` so the
    /// `backlog_order` adapter's `ItemId` orders by `(prefix, id)` — the
    /// canonical-id ascending tiebreak — without re-rendering a string per compare.
    pub(crate) const fn prefix(self) -> &'static str {
        self.kind().prefix
    }

    /// The kebab `kind` string written to `backlog-NNN.toml` (matches the serde
    /// rename). Pure; the render mirror for the stored `kind` field.
    const fn as_str(self) -> &'static str {
        match self {
            ItemKind::Issue => "issue",
            ItemKind::Improvement => "improvement",
            ItemKind::Chore => "chore",
            ItemKind::Risk => "risk",
            ItemKind::Idea => "idea",
        }
    }

    /// The canonical ref for an id in this kind's namespace (`ISS-007`) — the
    /// print of `backlog new` and the inverse of `from_prefix`. Prefix from the
    /// `Kind` (single source). `pub(crate)` so the `backlog_order` adapter's
    /// `ItemId` renders through the same single source.
    pub(crate) fn canonical_id(self, id: u32) -> String {
        format!("{}-{id:03}", self.prefix())
    }

    /// Resolve a canonical-id prefix back to its kind (`backlog show <ID>`
    /// auto-detect, PHASE-04). Prefixes come from the `Kind`s — the single source;
    /// the kind set is `ItemKind::ALL` (one declaration, not a second copy).
    fn from_prefix(prefix: &str) -> Option<Self> {
        ItemKind::ALL.into_iter().find(|k| k.prefix() == prefix)
    }

    /// Whether this kind carries a risk `[facet]` (risk only). Selects the
    /// scaffold template and gates facet render.
    const fn has_facet(self) -> bool {
        matches!(self, ItemKind::Risk)
    }

    /// Every kind in DECLARATION order — the single source for the cross-kind
    /// `list` read (each tree in turn) and the `ordinal` grouping key.
    const ALL: [ItemKind; 5] = [
        ItemKind::Issue,
        ItemKind::Improvement,
        ItemKind::Chore,
        ItemKind::Risk,
        ItemKind::Idea,
    ];

    /// The kind's position in declaration order — the primary `list` sort key.
    /// A deterministic GROUPING (Issue…Idea), explicitly NOT a priority claim
    /// (R7; priority is PRD-011, deferred) and NOT `KIND_PRECEDENCE` (risk-first,
    /// the inert future-resolver order).
    const fn ordinal(self) -> usize {
        match self {
            ItemKind::Issue => 0,
            ItemKind::Improvement => 1,
            ItemKind::Chore => 2,
            ItemKind::Risk => 3,
            ItemKind::Idea => 4,
        }
    }
}

// ---------------------------------------------------------------------------
// Closed value enums (kebab serde + an `as_str` render mirror)
// ---------------------------------------------------------------------------

/// A backlog item's lifecycle status. Closed canon set, kebab serde; hand-settable
/// and ungated (slices/ADRs/specs ship this way). `status` is always seeded a real
/// value (`open`), so it serde-parses directly — never the `"" -> None` seam.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Status {
    Open,
    Triaged,
    Started,
    Resolved,
    Closed,
}

impl Status {
    /// The kebab string for render (matches the serde rename). Pure.
    const fn as_str(self) -> &'static str {
        match self {
            Status::Open => "open",
            Status::Triaged => "triaged",
            Status::Started => "started",
            Status::Resolved => "resolved",
            Status::Closed => "closed",
        }
    }

    /// Whether this status is terminal (`resolved`/`closed`). A **backlog-local**
    /// predicate — explicitly NOT `slice::is_terminal_status` (R4): backlog and
    /// slice lifecycles are independent vocabularies. Drives the `resolution ⟺
    /// terminal` coupling (`edit`) and the hide-terminal `list` rule — reused by
    /// `is_hidden` as the SL-025 `backlog list` hide-set (no new predicate, design §5.3).
    const fn is_terminal(self) -> bool {
        matches!(self, Status::Resolved | Status::Closed)
    }
}

/// The `backlog list` known-status set (A-2) — the five `Status` variants, the
/// authority `--status` is validated against. Lockstep-guarded against the enum by
/// `backlog_statuses_matches_the_variants`. backlog has a CLOSED status enum, so a
/// *stored* status is always in-vocabulary — no drift marker is possible.
pub(crate) const BACKLOG_STATUSES: &[&str] = &["open", "triaged", "started", "resolved", "closed"];

/// The `backlog list` hide-set fed to `listing::retain` (design §5.3): the terminal
/// statuses drop from the default list. This is the stringly bridge over the typed
/// [`Status::is_terminal`] — the SAME predicate, no new terminal set. An out-of-vocab
/// token (impossible on a serde-validated item, but `retain` is stringly) is treated
/// as not-hidden. `--all` or any explicit `--status` overrides (handled in `retain`).
fn is_hidden(status: &str) -> bool {
    parse_enum::<Status>(status, "status").is_ok_and(Status::is_terminal)
}

/// Why a terminal item was closed. One generic, kind-agnostic set (PRD-009): a
/// resolution is never a close *reason* hidden in a facet. Optional — present only
/// on a terminal item (the `"" -> None` seam).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Resolution {
    Fixed,
    Done,
    Mitigated,
    Accepted,
    Expired,
    Duplicate,
    WontDo,
    Obsolete,
    Promoted,
}

impl Resolution {
    /// The kebab string for render (matches the serde rename). Pure.
    const fn as_str(self) -> &'static str {
        match self {
            Resolution::Fixed => "fixed",
            Resolution::Done => "done",
            Resolution::Mitigated => "mitigated",
            Resolution::Accepted => "accepted",
            Resolution::Expired => "expired",
            Resolution::Duplicate => "duplicate",
            Resolution::WontDo => "wont-do",
            Resolution::Obsolete => "obsolete",
            Resolution::Promoted => "promoted",
        }
    }
}

/// A risk facet axis level. Closed set, kebab serde; tech of the risk `[facet]`,
/// optional (the `"" -> None` seam — seeded empty until assessed).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum RiskLevel {
    Low,
    Medium,
    High,
    Critical,
}

impl RiskLevel {
    /// The kebab string for render (matches the serde rename). Pure.
    const fn as_str(self) -> &'static str {
        match self {
            RiskLevel::Low => "low",
            RiskLevel::Medium => "medium",
            RiskLevel::High => "high",
            RiskLevel::Critical => "critical",
        }
    }
}

// ---------------------------------------------------------------------------
// Three-layer parse model (the entity-model tolerant-parse tier — §5.3)
// ---------------------------------------------------------------------------

/// The tolerant parse layer. `resolution` and the risk levels are read as raw
/// `String` (they are seeded `""`, which is no enum variant — serde would reject
/// a direct `Option<Resolution>`), so the `"" -> None` mapping is a separate
/// `validate` pass, not a serde derive. `status`/`kind` carry real values and
/// parse to their enums directly. `#[serde(default)]` lets the seeded-empty
/// collections and the absent (non-risk) `[facet]` parse.
#[derive(Debug, Deserialize)]
struct RawBacklogToml {
    id: u32,
    slug: String,
    title: String,
    kind: ItemKind,
    status: Status,
    #[serde(default)]
    resolution: String,
    created: String,
    updated: String,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(default)]
    facet: Option<RawRiskFacet>,
    #[serde(default)]
    relationships: Relationships,
}

/// The tolerant risk-facet layer: the two assessable axes as raw `String` (the
/// `"" -> None` seam), `origin` as raw `String` (empty → absent), `controls` a
/// free list.
#[derive(Debug, Deserialize)]
struct RawRiskFacet {
    #[serde(default)]
    likelihood: String,
    #[serde(default)]
    impact: String,
    #[serde(default)]
    origin: String,
    #[serde(default)]
    controls: Vec<String>,
}

/// The validated entity (design §5.2). `id/slug/title/status` are top-level in the
/// toml so the file also round-trips into the shared `meta::Meta`. `kind` is stored
/// AND implied by the tree dir — stored so one read yields the entity without path
/// inspection. The `"" -> None` optionals are resolved off the raw layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BacklogItem {
    id: u32,
    slug: String,
    title: String,
    kind: ItemKind,
    status: Status,
    resolution: Option<Resolution>,
    created: String,
    updated: String,
    tags: Vec<String>,
    facet: Option<RiskFacet>,
    relationships: Relationships,
    /// SL-048 PHASE-04: the migrated tier-1 cross-kind edges (`slices`/`specs`/
    /// `drift`) read generically from the `[[relation]]` block in canonical order.
    /// Populated by [`read_item`] from the raw TOML text; the `validate` test seam
    /// leaves it empty (those tests assert the typed dep/sequence axes, not tier-1).
    tier1: Vec<crate::relation::RelationEdge>,
}

/// The validated risk facet (risk only). Every axis typed — no untyped bag
/// (PRD-009 invariant). The assessable axes are optional until assessed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RiskFacet {
    likelihood: Option<RiskLevel>,
    impact: Option<RiskLevel>,
    origin: Option<String>,
    controls: Vec<String>,
}

/// A `triggers` rider (PRD-009 §5.7): the source `globs` this item watches, with
/// an optional free-text `note` (default `""` — globs-only). FIELD ONLY this
/// phase — the IMP-026 staleness mask is out of scope.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Trigger {
    #[serde(default)]
    globs: Vec<String>,
    #[serde(default)]
    note: String,
}

/// The item→item dependency / sequence / mask axes (PRD-009) — `needs` (hard
/// prerequisite, payload-free), `after` (soft manual sequence, per-edge optional
/// `rank`), and the `triggers` rider (watched source globs). Shared verbatim by the
/// raw and validated layers (no `"" -> None` seam), seeded empty so `#[serde(default)]`
/// parses a virgin item.
///
/// SL-048 PHASE-04 (the cut): the tier-1 cross-kind axes (`slices`/`specs`/`drift`)
/// migrated to uniform `[[relation]]` rows (read via `relation::read_block` →
/// `BacklogItem::tier1`), so they are NO LONGER typed fields here. The dep/sequence/
/// mask axes (SL-047) carry per-edge payloads and stay typed.
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize)]
struct Relationships {
    #[serde(default)]
    needs: Vec<String>,
    #[serde(default)]
    after: Vec<AfterEdge>,
    #[serde(default)]
    triggers: Vec<Trigger>,
}

/// Parse a kebab token into its closed enum via the serde derive — the single
/// source of the variant↔string mapping (the `as_str` mirrors render only).
/// Errors with serde's "unknown variant" message on a bad token (`what` names the
/// field for the message).
fn parse_enum<T: serde::de::DeserializeOwned>(token: &str, what: &str) -> anyhow::Result<T> {
    use serde::de::IntoDeserializer;
    let de: serde::de::value::StrDeserializer<'_, serde::de::value::Error> =
        token.into_deserializer();
    T::deserialize(de).map_err(|e| anyhow::anyhow!("invalid {what} `{token}`: {e}"))
}

/// The `"" -> None` seam for an optional closed enum: an empty token is absent; a
/// non-empty token parses to its variant (erroring on an unknown one).
fn optional_enum<T: serde::de::DeserializeOwned>(
    token: &str,
    what: &str,
) -> anyhow::Result<Option<T>> {
    if token.is_empty() {
        Ok(None)
    } else {
        parse_enum(token, what).map(Some)
    }
}

/// The `"" -> None` seam for an optional free-text field.
fn optional_text(text: String) -> Option<String> {
    if text.is_empty() { None } else { Some(text) }
}

/// Validate a tolerant `RawBacklogToml` into a typed `BacklogItem` — the second
/// layer of the parse model. Maps the seeded-`""` optionals to `None`, parses any
/// non-empty value to its enum (erroring on an unknown token), and validates the
/// risk facet when present. Consumes the raw layer (its owned strings move across).
fn validate(raw: RawBacklogToml) -> anyhow::Result<BacklogItem> {
    let resolution = optional_enum(&raw.resolution, "resolution")?;
    let facet = match raw.facet {
        Some(f) => Some(validate_facet(f)?),
        None => None,
    };
    Ok(BacklogItem {
        id: raw.id,
        slug: raw.slug,
        title: raw.title,
        kind: raw.kind,
        status: raw.status,
        resolution,
        created: raw.created,
        updated: raw.updated,
        tags: raw.tags,
        facet,
        relationships: raw.relationships,
        // Filled by `read_item` from the raw TOML text (read_block); empty otherwise.
        tier1: Vec::new(),
    })
}

/// Validate a tolerant risk facet: the two axes through the `"" -> None` enum seam,
/// `origin` through the text seam, `controls` passed through.
fn validate_facet(raw: RawRiskFacet) -> anyhow::Result<RiskFacet> {
    Ok(RiskFacet {
        likelihood: optional_enum(&raw.likelihood, "likelihood")?,
        impact: optional_enum(&raw.impact, "impact")?,
        origin: optional_text(raw.origin),
        controls: raw.controls,
    })
}

/// The risk exposure score — `likelihood × impact` (1..=16) when BOTH axes are
/// assessed, else `0`. The within-level ordering fallback the `backlog_order`
/// adapter consumes (design §5.1 tier 3, VT-4): `0` is the baseline shared by
/// every non-risk item (a `None` facet) and every part-assessed risk alike —
/// assessment is all-or-nothing for ordering. Weights are Low=1 … Critical=4 (A3);
/// the product fits `u8`, no cast. The single derivation site — PHASE-03's
/// `project` reads it here, not a second copy (the PHASE-01 self-clearing dead-code
/// scope removed itself once `project` landed).
pub(crate) fn exposure(facet: Option<&RiskFacet>) -> u8 {
    const fn weight(level: RiskLevel) -> u8 {
        match level {
            RiskLevel::Low => 1,
            RiskLevel::Medium => 2,
            RiskLevel::High => 3,
            RiskLevel::Critical => 4,
        }
    }
    match facet.and_then(|f| f.likelihood.zip(f.impact)) {
        Some((l, i)) => weight(l) * weight(i),
        None => 0,
    }
}

// ---------------------------------------------------------------------------
// Pure: the ordering projection (BacklogItem -> the adapter's OrderInput)
// ---------------------------------------------------------------------------

/// A project-level drop (design §5.6 honest-record, the project half): an authored
/// `needs`/`after` ref that does not even `parse_ref` to a `(kind, id)` — a stale or
/// malformed token that can never become an `ItemId`, so it never reaches the adapter
/// (whose `Dangling` covers the parses-but-not-a-node case). Carries the dependent's
/// `ItemId` and the offending raw ref, so the shell names the drop loudly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AbsentDrop {
    /// The item that authored the bad ref.
    from: ItemId,
    /// The unparseable ref string verbatim.
    reference: String,
}

impl AbsentDrop {
    /// The dependent item that authored the bad ref.
    pub(crate) fn from(&self) -> ItemId {
        self.from
    }

    /// The unparseable ref string.
    pub(crate) fn reference(&self) -> &str {
        &self.reference
    }
}

/// Project the live (non-terminal) corpus into the adapter's inputs (design §5.4,
/// OQ-A "projection in backlog.rs"). PURE — no clock/disk; `items` is the already-read
/// corpus.
///
/// Node set = the **non-terminal** items (`!Status::is_terminal`) across all five
/// kinds (§5.6 — a terminal item cannot participate in a live ordering). For each
/// node, every authored `needs` ref and every `after` edge's `to` is resolved via
/// `parse_ref` to an `ItemId`; a ref that fails to parse is recorded as an
/// [`AbsentDrop`] (never silently dropped) and contributes no edge. Whether a *parsed*
/// `ItemId` is itself a live node is the **adapter's** call (a non-node endpoint
/// surfaces as a `Dangling` override) — `project` never pre-filters edges by node
/// membership, keeping the honest record total.
///
/// **A-distinct (DD4).** The adapter's `by_item`/`by_node` bimap silently corrupts on
/// a duplicate `ItemId` in the input slice. The corpus reads at most one item per
/// `(kind, id)`, but `project` closes the precondition at the boundary: it builds the
/// inputs keyed by `ItemId` (a `BTreeMap`), so the emitted `Vec<OrderInput>` carries
/// strictly distinct `ItemId`s regardless of a malformed corpus.
fn project(items: &[BacklogItem]) -> (Vec<OrderInput>, Vec<AbsentDrop>) {
    let mut inputs: BTreeMap<ItemId, OrderInput> = BTreeMap::new();
    let mut absent: Vec<AbsentDrop> = Vec::new();

    for item in items.iter().filter(|i| !i.status.is_terminal()) {
        let from = ItemId::new(item.kind, item.id);

        let mut resolve = |reference: &str| -> Option<ItemId> {
            if let Ok((kind, id)) = parse_ref(reference) {
                Some(ItemId::new(kind, id))
            } else {
                absent.push(AbsentDrop {
                    from,
                    reference: reference.to_string(),
                });
                None
            }
        };

        let needs: Vec<ItemId> = item
            .relationships
            .needs
            .iter()
            .filter_map(|r| resolve(r))
            .collect();
        let after: Vec<(ItemId, i32)> = item
            .relationships
            .after
            .iter()
            .filter_map(|e| resolve(&e.to).map(|to| (to, e.rank)))
            .collect();

        // A-distinct: the corpus is one row per `(kind, id)`, but key by `ItemId` so a
        // duplicate can never reach the adapter's bimap (DD4).
        inputs.insert(
            from,
            OrderInput::new(
                from,
                item.created.clone(),
                exposure(item.facet.as_ref()),
                needs,
                after,
            ),
        );
    }

    (inputs.into_values().collect(), absent)
}

// ---------------------------------------------------------------------------
// Pure: render, scaffold
// ---------------------------------------------------------------------------

/// Render `backlog-<id>.toml` from the kind's embedded template by token
/// substitution. Risk picks the `[facet]` template; the four plain kinds the
/// light one. The `id/slug/title/status` keys round-trip into `meta::Meta` (VT-2);
/// `{{kind}}` is the stored discriminator (also the tree dir).
fn render_backlog_toml(
    item_kind: ItemKind,
    id: u32,
    slug: &str,
    title: &str,
    date: &str,
) -> anyhow::Result<String> {
    let template = if item_kind.has_facet() {
        "templates/backlog-risk.toml"
    } else {
        "templates/backlog.toml"
    };
    Ok(crate::install::asset_text(template)?
        .replace("{{id}}", &id.to_string())
        .replace("{{slug}}", &toml_string(slug))
        .replace("{{title}}", &toml_string(title))
        .replace("{{kind}}", item_kind.as_str())
        .replace("{{date}}", date))
}

/// Render `backlog-<id>.md` from the embedded prose template: `{{ref}}` (the
/// canonical id, e.g. `ISS-007`) + `{{title}}`. No frontmatter — metadata lives in
/// the sister toml.
fn render_backlog_md(canonical_id: &str, title: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/backlog.md")?
        .replace("{{ref}}", canonical_id)
        .replace("{{title}}", title))
}

/// The backlog fileset: sister TOML, prose body, and `<id>-<slug>` symlink, all
/// relative to the kind's tree root — structurally `requirement_scaffold` (§5.6).
/// The `item_kind` decides only the toml template (risk vs plain); the md and
/// symlink are kind-uniform. Shared by all five `Kind`s via their scaffold closure.
fn backlog_scaffold(item_kind: ItemKind, ctx: &ScaffoldCtx<'_>) -> anyhow::Result<Fileset> {
    let id = ctx.id;
    let name = format!("{id:03}");
    Ok(vec![
        Artifact::File {
            rel_path: PathBuf::from(format!("{name}/{BACKLOG_STEM}-{name}.toml")),
            body: render_backlog_toml(item_kind, id, ctx.slug, ctx.title, ctx.date)?,
        },
        Artifact::File {
            rel_path: PathBuf::from(format!("{name}/{BACKLOG_STEM}-{name}.md")),
            body: render_backlog_md(ctx.canonical, ctx.title)?,
        },
        Artifact::Symlink {
            rel_path: PathBuf::from(format!("{name}-{}", ctx.slug)),
            target: name,
        },
    ])
}

// ---------------------------------------------------------------------------
// CLI entry points (thin)
// ---------------------------------------------------------------------------

/// `doctrine backlog new <kind> "<title>" [--slug S]` — the capture verb (PRD-009
/// REQ-049). Thin shell (§5.4): resolve the title/slug, inject the clock, reserve
/// the next id in the kind's INDEPENDENT namespace via the shared `Fresh` engine
/// path (monotonic id + race-retry inherited; `ISS-001` and `RSK-001` coexist),
/// then print the canonical `XXX-NNN` id. A pure mirror of `adr`/`spec` `run_new`,
/// dispatching the `Kind` on `item_kind`. Touches disk via the engine only — the
/// engine is unchanged (the R6 gate).
pub(crate) fn run_new(
    path: Option<PathBuf>,
    item_kind: ItemKind,
    title: Option<String>,
    slug: Option<String>,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let title = crate::input::resolve_title(title)?;
    let slug = crate::input::resolve_slug(&title, slug)?;
    let date = crate::clock::today();
    let trunk_ids = crate::git::trunk_entity_ids(&root, item_kind.kind().dir)?;
    let out = entity::materialise(
        item_kind.kind(),
        &LocalFs,
        &root,
        &MaterialiseRequest::Fresh,
        &Inputs {
            slug: &slug,
            title: &title,
            date: &date,
        },
        &trunk_ids,
    )?;
    let id = out
        .eid
        .numeric_id()
        .context("backlog kind must yield a numeric id")?;
    writeln!(
        io::stdout(),
        "Created {}: {}",
        item_kind.canonical_id(id),
        out.dir.display()
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Read: per-kind tree → validated items (total over a missing dir)
// ---------------------------------------------------------------------------

/// Read every item under one kind's tree into validated `BacklogItem`s. Rides
/// `entity::scan_ids` (numeric dirs only; **a missing tree → empty set**, the C2
/// total-function tolerance), then parses + `validate`s each `backlog-NNN.toml`.
/// The full-entity sibling of `meta::read_metas` (which yields only the 4 list
/// keys, no `kind`/`resolution`); `meta.rs` stays untouched (R6/EX-3).
fn read_kind(root: &Path, item_kind: ItemKind) -> anyhow::Result<Vec<BacklogItem>> {
    let tree = root.join(item_kind.kind().dir);
    let mut items = Vec::new();
    for id in entity::scan_ids(&tree)? {
        items.push(read_item(root, item_kind, id)?);
    }
    Ok(items)
}

/// Read ONE item's `backlog-<NNN>.toml` into a validated `BacklogItem` — the
/// single-id read shared by `read_kind`'s loop and `show` (DRY: one parse path).
/// A missing file is a hard error (the id must already be reserved — `show` never
/// implicitly creates, §5.5); the caller owns kind disambiguation (`parse_ref`).
fn read_item(root: &Path, item_kind: ItemKind, id: u32) -> anyhow::Result<BacklogItem> {
    let name = format!("{id:03}");
    let path = root
        .join(item_kind.kind().dir)
        .join(&name)
        .join(format!("{BACKLOG_STEM}-{name}.toml"));
    let text = std::fs::read_to_string(&path)
        .with_context(|| format!("backlog item not found at {}", path.display()))?;
    let raw: RawBacklogToml =
        toml::from_str(&text).with_context(|| format!("Failed to parse {}", path.display()))?;
    let mut item = validate(raw)?;
    // SL-048 PHASE-04: the migrated tier-1 axes (slices/specs/drift) come from the
    // `[[relation]]` block, read generically in canonical order.
    item.tier1 = crate::relation::tier1_edges(item_kind.kind(), &text)?;
    Ok(item)
}

/// Resolve a backlog canonical-id prefix (`ISS`/`IMP`/`CHR`/`RSK`/`IDE`) back to its
/// [`ItemKind`] — the inverse of `ItemKind::prefix`, over the single `ItemKind::ALL`
/// source. `pub(crate)` so the SL-046 cross-kind dispatch (`relation_graph`) routes a
/// backlog prefix to [`relation_edges`] without a second prefix↔kind copy.
pub(crate) fn kind_from_prefix(prefix: &str) -> Option<ItemKind> {
    ItemKind::from_prefix(prefix)
}

/// A backlog item's authored outbound relations (SL-046 §5.2/§5.3): `slices` →
/// [`RelationLabel::Slices`], `specs` → [`RelationLabel::Specs`], and `drift` →
/// [`RelationLabel::Drift`]. `drift` is free-text with no `DRIFT` kind in `KINDS`, so
/// it is a TARGET-UNVALIDATED label (ADR-010 Decision 2): emitted so the data is
/// preserved, but its targets never resolve and surface as danglers at the scan
/// (PHASE-03), never edges. NEVER `needs`/`after`/`triggers` (the dep/sequence/mask
/// axes — SL-047). Reads via the existing `read_item` reader (no new TOML parse). An
/// empty axis emits nothing.
pub(crate) fn relation_edges(
    root: &Path,
    item_kind: ItemKind,
    id: u32,
) -> anyhow::Result<Vec<crate::relation::RelationEdge>> {
    // SL-048 PHASE-04 (the cut): the tier-1 axes (slices/specs/drift) now live in the
    // uniform `[[relation]]` block, read generically into `item.tier1` in canonical
    // [`RELATION_RULES`] order (X1). Backlog has no other tier-1 edges; the typed
    // needs/after/triggers axes are NOT outbound relation edges (the SL-047 dep seam).
    let item = read_item(root, item_kind, id)?;
    Ok(item.tier1)
}

/// A backlog item's `needs`/`after` dependency-sequence edges plus its `promoted`
/// flag, for the cross-kind priority scan (SL-047 §5.2). Targets are the AUTHORED
/// ref strings verbatim (the priority adapter resolves them through its own
/// projection — resolve-only, like `relation_edges`'s targets); each `after` edge
/// carries its per-edge `rank`. `promoted` is `resolution == Resolution::Promoted`
/// — the typed authority (PRD-009 §5.5), a DISTINCT flag from status-terminal and
/// NOT the free-text `origin`. Reads via the existing `read_item` reader (no new
/// TOML parse). Only backlog authors `needs`/`after`; every other kind routes here
/// not at all, so non-backlog nodes carry none (DD-2, dormant until IMP-033).
pub(crate) struct DepSeq {
    pub(crate) needs: Vec<String>,
    pub(crate) after: Vec<(String, i32)>,
    pub(crate) promoted: bool,
}

/// Read one backlog item's [`DepSeq`] (the SL-047 priority adapter's dep/seq +
/// promoted seam).
pub(crate) fn dep_seq_for(root: &Path, item_kind: ItemKind, id: u32) -> anyhow::Result<DepSeq> {
    let item = read_item(root, item_kind, id)?;
    let after = item
        .relationships
        .after
        .iter()
        .map(|e| (e.to.clone(), e.rank))
        .collect();
    Ok(DepSeq {
        needs: item.relationships.needs.clone(),
        after,
        promoted: item.resolution == Some(Resolution::Promoted),
    })
}

/// Read all five kinds' trees, merged (declaration order, pre-sort). Each absent
/// kind dir contributes the empty set, so a virgin repo reads to `[]`.
fn read_all(root: &Path) -> anyhow::Result<Vec<BacklogItem>> {
    let mut items = Vec::new();
    for item_kind in ItemKind::ALL {
        items.extend(read_kind(root, item_kind)?);
    }
    Ok(items)
}

// ---------------------------------------------------------------------------
// Pure: filter (the visibility matrix) + render
// ---------------------------------------------------------------------------

/// Project a `BacklogItem` to its filterable fields (design §5.2). `canonical` is
/// the prefixed id (`ISS-007`) — the regex domain; `status` is the kebab string the
/// hide-set / `--status` filter match on; `tags` are the item's own.
fn key(i: &BacklogItem) -> listing::FilterFields {
    listing::FilterFields {
        canonical: i.kind.canonical_id(i.id),
        slug: i.slug.clone(),
        title: i.title.clone(),
        status: i.status.as_str().to_string(),
        tags: i.tags.clone(),
    }
}

/// Re-export of the spine's status validator, scoped to backlog so callers read
/// intent locally. Guards `--status` against [`BACKLOG_STATUSES`] (READ input only).
fn validate_statuses(given: &[String], known: &[&str]) -> anyhow::Result<()> {
    listing::validate_statuses(given, known)
}

/// One backlog item projected to its faithful JSON row (design §5.3 — backlog owns
/// its serde shape). `id` is the prefixed canonical id; `kind`/`status`/`resolution`
/// are the kebab strings (resolution `null` when absent). The risk facet and
/// relationships are list-irrelevant (they ride `show`), so the list row stays flat.
#[derive(Debug, Serialize)]
struct BacklogRow {
    id: String,
    kind: &'static str,
    status: &'static str,
    resolution: Option<&'static str>,
    slug: String,
    title: String,
    /// The item's own tags — projected UNCONDITIONALLY (flat, never visibility-gated);
    /// an untagged item emits `[]` (SL-067 PHASE-01, EX-4).
    tags: Vec<String>,
}

/// The table columns `backlog list` can show (`--columns` tokens over
/// `R = BacklogItem` — extractors are non-capturing, SL-037 D5; the prefixed id
/// is materialised in the cell from the item's own kind+id). Declaration order is
/// what the unknown-column error lists.
const BL_COLUMNS: [listing::Column<BacklogItem>; 6] = [
    listing::Column {
        name: "id",
        header: "id",
        cell: |i| i.kind.canonical_id(i.id),
        paint: listing::ColumnPaint::Fixed(owo_colors::DynColors::Ansi(
            owo_colors::AnsiColors::Cyan,
        )),
    },
    listing::Column {
        name: "kind",
        header: "kind",
        cell: |i| i.kind.as_str().to_string(),
        paint: listing::ColumnPaint::ByValue(|i| listing::backlog_kind_hue(i.kind.as_str())),
    },
    listing::Column {
        name: "status",
        header: "status",
        cell: |i| i.status.as_str().to_string(),
        paint: listing::ColumnPaint::ByValue(|i| listing::status_hue(i.status.as_str())),
    },
    listing::Column {
        name: "slug",
        header: "slug",
        cell: |i| i.slug.clone(),
        paint: listing::ColumnPaint::None,
    },
    listing::Column {
        name: "tags",
        header: "tags",
        // `cell` (plain) and `split` (coloured) MUST agree byte-for-byte stripped of
        // ANSI: both project the item's tags joined by `", "`.
        cell: |i| i.tags.join(", "),
        paint: listing::ColumnPaint::PerToken {
            split: |i| i.tags.clone(),
            render: listing::paint_tag,
        },
    },
    listing::Column {
        name: "title",
        header: "title",
        cell: |i| i.title.clone(),
        paint: listing::ColumnPaint::Alternate([listing::TITLE_EVEN, listing::TITLE_ODD]),
    },
];

/// The default visible set — slug-free (SL-037 D4); `--columns …,slug` reveals it.
const BL_DEFAULT: &[&str] = &["id", "kind", "status", "title"];

/// How `backlog list` orders its rows (SL-051, the folded-in `order` axis). The
/// default `Sequence` composes the cordage `needs`/`after` work order over the live
/// corpus; `Id` is the classic `(kind.ordinal, id)` grouping.
#[derive(Clone, Copy, Debug, Default, clap::ValueEnum)]
pub(crate) enum OrderBy {
    /// The composed `needs`/`after` work order (default).
    #[default]
    Sequence,
    /// The classic `(kind.ordinal, id)` grouping.
    Id,
}

/// The composed ordering over the live corpus plus its honest-record diagnostic
/// (SL-051 — the folded-in `order` view). The two outcomes are distinct variants so
/// the illegal mixes — a degrade carrying composed positions, a clean compose carrying
/// a warning — are unrepresentable. `footer` (the `render_overrides` honest-record
/// block, `""` when nothing was dropped) rides both.
enum Ordering {
    /// A clean compose: `pos` maps each composed item to its sequence position.
    Composed {
        pos: BTreeMap<ItemId, usize>,
        footer: String,
    },
    /// A `needs` cycle forced the classic id-sort fallback; `warning` is the stderr
    /// advisory naming the cycle.
    Degraded { footer: String, warning: String },
}

/// Compose the `needs`/`after` work order over the live corpus (SL-051 — the former
/// `order_rows` compute, folded into `list`). PURE over the read corpus. Projects the
/// non-terminal node set, builds the adapter, and renders the honest-record `footer`.
/// On a `needs` dependency cycle, `build` still succeeds; `compose` returns
/// `Degraded` (carrying the cycle `warning`), so `list_rows` falls back to the classic
/// id sort and emits the advisory to stderr (no misleading order, never a non-zero
/// exit — SL-051 §4.4). Borrows `corpus` (then `list_rows` MOVES it into `retain`).
fn compose(corpus: &[BacklogItem]) -> anyhow::Result<Ordering> {
    let (inputs, absent) = project(corpus);
    let order = BacklogOrder::build(&inputs)?;
    let cmap: BTreeMap<ItemId, &BacklogItem> = corpus
        .iter()
        .map(|i| (ItemId::new(i.kind, i.id), i))
        .collect();
    let footer = render_overrides(&cmap, &absent, &order.overrides());
    if let Some(cycle) = order.dep_cycles().first() {
        return Ok(Ordering::Degraded {
            footer,
            warning: format!(
                "backlog list: `needs` dependency cycle — {} — ordering by id (resolve, then re-run)",
                name_cycle(cycle)
            ),
        });
    }
    let pos = order
        .ordered()
        .iter()
        .enumerate()
        .map(|(i, id)| (*id, i))
        .collect();
    Ok(Ordering::Composed { pos, footer })
}

/// The `list_rows` output split — the two destination streams named so the `run_list`
/// shell cannot transpose them (a swap would misroute the cycle warning into stdout
/// and corrupt the goldens — SL-051 §4.3). The type, not a doc-comment, is the guard.
struct ListOutput {
    stdout: String,
    stderr: String,
}

/// The `backlog list` output — the compute half of `run_list`, on the shared spine.
/// Returns a [`ListOutput`]: `stdout` carries the rendered rows (plus the honest-record
/// `footer` in table mode); `stderr` carries the cycle `warning` (and, under `--json`,
/// the advisory `footer`).
///
/// `validate_statuses` guards `--status` (A-2); `listing::build` resolves the filter +
/// format; `retain` applies the shared substr/regex/status/tag axes + the terminal
/// hide-set ([`is_hidden`], reusing `Status::is_terminal`); the kind-specific `--kind`
/// filter (not a shared axis) is applied here. The corpus is read ONCE: `--by
/// sequence` composes the work order over the FULL non-terminal corpus (`compose`
/// borrows first), then `retain` MOVES the corpus and the surviving rows tail by
/// `(usize::MAX, kind.ordinal, id)` for off-sequence items. `--by id` (or a
/// cycle-degrade) skips the graph and sorts by `(kind.ordinal, id)` (§5.3). Membership
/// is EXACTLY `retain ∩ --kind` either way (A-2 invariant) — the ordering never filters.
fn list_rows(
    root: &Path,
    kind: Option<ItemKind>,
    by: OrderBy,
    mut args: ListArgs,
) -> anyhow::Result<ListOutput> {
    validate_statuses(&args.status, BACKLOG_STATUSES)?;
    let render = args.render;
    let columns = args.columns.take();
    // Fold the `-t/--tag` filter inputs through the lenient `fold_filter_tag` so a
    // mixed-case input round-trips the lowercased store (`-t Security` → `security`),
    // WITHOUT the write-path charset reject (a filter matching nothing succeeds
    // silently — SL-067 PHASE-01, EX-5/§5). `tags_admit`'s exact-match is unchanged.
    args.tags = args.tags.iter().map(|t| fold_filter_tag(t)).collect();
    let (filter, format) = listing::build(args)?;
    let corpus = read_all(root)?;
    let ordering = match by {
        OrderBy::Sequence => Some(compose(&corpus)?),
        OrderBy::Id => None,
    };
    let mut items = listing::retain(corpus, &filter, is_hidden, key);
    items.retain(|i| kind.is_none_or(|k| i.kind == k));
    // Dynamic tags-column visibility (D2): the column shows iff the FINAL displayed set
    // (post-retain ∩ post-`--kind`) carries at least one tagged row. Computed once, on
    // the visible rows, and reused across any `--by id` layout (uniform).
    let any_tagged = items.iter().any(|i| !i.tags.is_empty());
    // Only a clean `Composed` sorts by sequence; a `Degraded` cycle and `--by id`
    // both fall to the classic `(kind.ordinal, id)`. Off-sequence rows tail via the
    // `usize::MAX` sentinel.
    match &ordering {
        Some(Ordering::Composed { pos, .. }) => items.sort_by_key(|i| {
            (
                pos.get(&ItemId::new(i.kind, i.id))
                    .copied()
                    .unwrap_or(usize::MAX),
                i.kind.ordinal(),
                i.id,
            )
        }),
        _ => items.sort_by_key(|i| (i.kind.ordinal(), i.id)),
    }
    let (footer, warning) = match &ordering {
        Some(Ordering::Composed { footer, .. }) => (footer.as_str(), ""),
        Some(Ordering::Degraded { footer, warning }) => (footer.as_str(), warning.as_str()),
        None => ("", ""),
    };
    match format {
        Format::Table => {
            // Build the effective default LOCALLY (never mutate the `BL_DEFAULT` const):
            // splice `"tags"` before `"title"` IFF a visible row is tagged. With
            // `--columns` given, `select_columns` ignores `default` entirely (the user's
            // order wins verbatim — tags shown iff requested, even all-empty).
            let effective_default: Vec<&str> = if any_tagged {
                BL_DEFAULT
                    .iter()
                    .flat_map(|&c| {
                        if c == "title" {
                            vec!["tags", "title"]
                        } else {
                            vec![c]
                        }
                    })
                    .collect()
            } else {
                BL_DEFAULT.to_vec()
            };
            let sel = listing::select_columns(&BL_COLUMNS, &effective_default, columns.as_deref())?;
            let table = listing::render_columns(&items, &sel, render);
            // Table: rows + footer to stdout; the cycle warning to stderr.
            Ok(ListOutput {
                stdout: format!("{table}{footer}"),
                stderr: warning.to_string(),
            })
        }
        Format::Json => {
            // JSON: the envelope (rows in composed sequence) to stdout; the warning
            // and the advisory footer to stderr (the honest-record stays out of the
            // envelope — no listing.rs change).
            let envelope = listing::json_envelope("backlog", &json_rows(&items))?;
            Ok(ListOutput {
                stdout: envelope,
                stderr: format!("{warning}{footer}"),
            })
        }
    }
}

/// Faithful JSON rows (D7) — the prefixed id plus the flat list fields.
fn json_rows(items: &[BacklogItem]) -> Vec<BacklogRow> {
    items
        .iter()
        .map(|i| BacklogRow {
            id: i.kind.canonical_id(i.id),
            kind: i.kind.as_str(),
            status: i.status.as_str(),
            resolution: i.resolution.map(Resolution::as_str),
            slug: i.slug.clone(),
            title: i.title.clone(),
            tags: i.tags.clone(),
        })
        .collect()
}

/// `doctrine backlog list [--kind K] [-f SUBSTR] [-r RE] [-i] [-s S,…] [-t T] [-a]
/// [--format F | --json] [<SUBSTR>]` — the survey verb (PRD-009 REQ-050), on the
/// shared spine. Thin shell (§5.4): find the root, lower the args, print the rows
/// verbatim (`list_rows` carries `render_table`'s own trailing newline). `--kind`
/// is the one kind-specific axis; the positional `[SUBSTR]` is folded into the
/// shared substr by the caller (deprecated alias — `--filter` wins, A-7).
pub(crate) fn run_list(
    path: Option<PathBuf>,
    kind: Option<ItemKind>,
    by: OrderBy,
    args: ListArgs,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let ListOutput { stdout, stderr } = list_rows(&root, kind, by, args)?;
    write!(io::stdout(), "{stdout}")?;
    if !stderr.is_empty() {
        write!(io::stderr(), "{stderr}")?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Pure: id parse + show render
// ---------------------------------------------------------------------------

/// Parse a canonical ref (`ISS-007`) into its `(kind, id)` — the `show` auto-detect
/// (§5.5 / R3). Split on the LAST `-`, upper-case the prefix (`iss-7` is tolerated),
/// resolve it via `ItemKind::from_prefix`, and parse the numeric tail as `u32`
/// (`ISS-7` and `ISS-007` both yield 7). An unknown prefix or a non-numeric tail is
/// a hard error — never an implicit create. The five counters are independent, so
/// the prefix is load-bearing for disambiguation (`ISS-1` ≠ `RSK-1`).
///
/// Deliberately NOT shared with `spec::resolve_spec_ref`: that sibling does NOT
/// upper-case (spec refs are always canonical), whereas backlog tolerates case here.
fn parse_ref(reference: &str) -> anyhow::Result<(ItemKind, u32)> {
    let (prefix, tail) = reference.rsplit_once('-').with_context(|| {
        format!("`{reference}` is not a canonical backlog ref (expected e.g. ISS-007)")
    })?;
    let kind = ItemKind::from_prefix(&prefix.to_uppercase()).with_context(|| {
        format!("unknown backlog prefix `{prefix}` in `{reference}` (expected ISS/IMP/CHR/RSK/IDE)")
    })?;
    let id: u32 = tail
        .parse()
        .with_context(|| format!("`{tail}` is not a numeric id in `{reference}`"))?;
    Ok((kind, id))
}

/// Render a `BacklogItem` for `show` — a pure fn of the item's OWN local state
/// ("cannot go stale"), so it reads no other file and surfaces no inbound refs
/// (the reverse view is the deferred registry surface's, ADR-004). House style:
/// `Vec<String>` parts each carrying their own newline, joined by `concat()` (the
/// `spec::render`/`format_rows` precedent — avoids the `push_str(&format!)` lint).
/// The facet block is gated on `item.facet` (risk only); relationship axes and the
/// optional fields render only when populated.
fn format_show(item: &BacklogItem) -> String {
    use crate::relation::{RelationLabel, targets_for};
    let mut parts: Vec<String> = Vec::new();

    // identity + the flat fields (resolution shown only on a terminal item).
    parts.push(format!(
        "{}{}\n",
        item.kind.canonical_id(item.id),
        item.title
    ));
    let resolution = match item.resolution {
        Some(r) => format!(" · {}", r.as_str()),
        None => String::new(),
    };
    parts.push(format!(
        "{} · {} · {}{resolution}\n",
        item.slug,
        item.kind.as_str(),
        item.status.as_str(),
    ));
    parts.push(format!(
        "created {} · updated {}\n",
        item.created, item.updated
    ));
    if !item.tags.is_empty() {
        parts.push(format!("tags: {}\n", item.tags.join(", ")));
    }

    // risk facet (gated on the kind carrying one); each axis only when assessed.
    if let Some(facet) = &item.facet {
        parts.push("\n[facet]\n".to_string());
        if let Some(likelihood) = facet.likelihood {
            parts.push(format!("  likelihood: {}\n", likelihood.as_str()));
        }
        if let Some(impact) = facet.impact {
            parts.push(format!("  impact: {}\n", impact.as_str()));
        }
        if let Some(origin) = &facet.origin {
            parts.push(format!("  origin: {origin}\n"));
        }
        if !facet.controls.is_empty() {
            parts.push(format!("  controls: {}\n", facet.controls.join(", ")));
        }
    }

    // outbound relations (§5.5) — each axis only when non-empty; inbound is the
    // deferred registry surface's, NOT computed here (D-PHASE04-2 / ADR-004).
    // SL-048 PHASE-04: the tier-1 axes (slices/specs/drift) come from `item.tier1`
    // (read via `read_block`), the dep/sequence axes stay typed; render order and
    // gating are unchanged, so output is byte-identical across the migration.
    let rel = &item.relationships;
    let slices = targets_for(&item.tier1, RelationLabel::Slices);
    let specs = targets_for(&item.tier1, RelationLabel::Specs);
    let drift = targets_for(&item.tier1, RelationLabel::Drift);
    if !slices.is_empty()
        || !specs.is_empty()
        || !drift.is_empty()
        || !rel.needs.is_empty()
        || !rel.after.is_empty()
        || !rel.triggers.is_empty()
    {
        parts.push("\nrelationships:\n".to_string());
        // the four string axes share the one loop; `after`/`triggers` carry payload
        // (per-edge rank, glob+note) and render bespoke below, in §5.2 key order.
        for (label, refs) in [
            ("slices", &slices),
            ("specs", &specs),
            ("drift", &drift),
            ("needs", &rel.needs),
        ] {
            if !refs.is_empty() {
                parts.push(format!("  {label}: {}\n", refs.join(", ")));
            }
        }
        if !rel.after.is_empty() {
            let rendered = rel
                .after
                .iter()
                .map(|e| {
                    if e.rank == 0 {
                        e.to.clone()
                    } else {
                        format!("{} (rank {})", e.to, e.rank)
                    }
                })
                .collect::<Vec<_>>()
                .join(", ");
            parts.push(format!("  after: {rendered}\n"));
        }
        if !rel.triggers.is_empty() {
            let rendered = rel
                .triggers
                .iter()
                .map(|t| {
                    let globs = t.globs.join(", ");
                    if t.note.is_empty() {
                        format!("[{globs}]")
                    } else {
                        format!("[{globs}] {}", t.note)
                    }
                })
                .collect::<Vec<_>>()
                .join("; ");
            parts.push(format!("  triggers: {rendered}\n"));
        }
    }

    parts.concat()
}

/// `doctrine backlog show <ID>` — the inspect verb (PRD-009 REQ-051, §5.4). Thin
/// shell: find the root, `parse_ref` the id to its kind (prefix auto-detect), read
/// THAT item's single toml, render it to stdout. READ-ONLY — no mutation, no
/// cross-corpus scan (only the one item's file is opened); the render is pure over
/// the item's own state.
pub(crate) fn run_show(
    path: Option<PathBuf>,
    reference: &str,
    format: Format,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (item_kind, id) = parse_ref(reference)?;
    let item = read_item(&root, item_kind, id)?;
    let out = match format {
        Format::Table => format_show(&item),
        Format::Json => show_json(&item)?,
    };
    write!(io::stdout(), "{out}")?;
    Ok(())
}

/// Render the `Json` show: the item's faithful state under the shared `{kind, …}`
/// envelope (the `adr::show_json` precedent). The validated `BacklogItem`'s fields
/// are private and its closed enums render via `as_str`, so the JSON is projected by
/// hand here (not a derive): the flat identity, the optional resolution, the risk
/// `[facet]` (risk only), and the outbound relationships — the same data the table
/// reassembles, structured. Pure over the item's own state (no cross-corpus scan).
fn show_json(item: &BacklogItem) -> anyhow::Result<String> {
    use crate::relation::{RelationLabel, targets_for};
    let facet = item.facet.as_ref().map(|f| {
        serde_json::json!({
            "likelihood": f.likelihood.map(RiskLevel::as_str),
            "impact": f.impact.map(RiskLevel::as_str),
            "origin": f.origin,
            "controls": f.controls,
        })
    });
    // SL-048 PHASE-04 (R2-C2′): the tier-1 axes (slices/specs/drift) migrated to
    // `[[relation]]`, so they are reconstructed from `item.tier1` (read via
    // `read_block`) into the SAME `relationships` JSON shape, preserving OD-2's
    // byte-identical `show --json`. serde_json sorts object keys, unchanged.
    let rel = &item.relationships;
    let value = serde_json::json!({
        "kind": "backlog",
        "backlog": {
            "id": item.kind.canonical_id(item.id),
            "kind": item.kind.as_str(),
            "slug": item.slug,
            "title": item.title,
            "status": item.status.as_str(),
            "resolution": item.resolution.map(Resolution::as_str),
            "created": item.created,
            "updated": item.updated,
            "tags": item.tags,
            "facet": facet,
            "relationships": {
                "slices": targets_for(&item.tier1, RelationLabel::Slices),
                "specs": targets_for(&item.tier1, RelationLabel::Specs),
                "drift": targets_for(&item.tier1, RelationLabel::Drift),
                "needs": rel.needs,
                "after": rel.after,
                "triggers": rel.triggers,
            },
        },
    });
    serde_json::to_string_pretty(&value).context("failed to serialize backlog show JSON")
}

// ---------------------------------------------------------------------------
// Pure: the status ⟺ resolution coupling + impure: the edit-in-place transition
// ---------------------------------------------------------------------------

/// The `status ⟺ resolution` coupling (PRD-009 REQ-059 / §5.5) plus the D9
/// re-open clear — a PURE decision over the *target* state, returning the
/// resolution string to write. A terminal status REQUIRES a `--resolution`; a
/// non-terminal status FORBIDS one and AUTO-CLEARS any prior resolution to `""`
/// (D9 — re-opening is one command, and the `resolution ⟺ terminal` invariant
/// holds post-write). `--resolution promoted` by hand is accepted (the promote
/// bridge is deferred; v1 is ungated). No clock/disk — the shell stamps `updated`.
fn validate_transition(
    status: Status,
    resolution: Option<Resolution>,
) -> anyhow::Result<&'static str> {
    match (status.is_terminal(), resolution) {
        (true, Some(r)) => Ok(r.as_str()),
        (true, None) => anyhow::bail!(
            "a terminal status (`{}`) requires `--resolution`",
            status.as_str()
        ),
        (false, Some(r)) => anyhow::bail!(
            "a non-terminal status (`{}`) takes no `--resolution` (got `{}`)",
            status.as_str(),
            r.as_str()
        ),
        (false, None) => Ok(""),
    }
}

/// Edit-preserving status/resolution transition on one authored `backlog-NNN.toml`
/// — the `adr::set_adr_status` precedent: `toml_edit` mutates the file in place, so
/// the inert `[facet]`/`[relationships]` tables, hand-added comments, and unknown
/// keys all survive (the file is never reserialised). Resolves the coupling via
/// `validate_transition`, carries the I5 no-op guard (an unchanged status+resolution
/// writes nothing), and the F-1 refuse (a malformed item missing a seeded key is
/// rejected, never corrupted by a tail-`insert` into a trailing subtable). The date
/// is injected by the shell; returns the resolution string written (for its confirm
/// line). A missing item file errors (read fails) — never an implicit create.
fn set_backlog_status(
    root: &Path,
    item_kind: ItemKind,
    id: u32,
    status: Status,
    resolution: Option<Resolution>,
    today: &str,
) -> anyhow::Result<&'static str> {
    // Gate in the shell: the status⟺resolution coupling + D9 reopen clear. Keep it
    // here, BEFORE the delegated write; the resolution string is still returned to the
    // caller's confirm line.
    let resolution = validate_transition(status, resolution)?;
    let name = format!("{id:03}");
    let path = root
        .join(item_kind.kind().dir)
        .join(&name)
        .join(format!("{BACKLOG_STEM}-{name}.toml"));
    // Delegate the write-core (no-op guard + F-1 refuse + edit-preserving insert) to
    // the shared authored-TOML seam. The three managed pairs prove the longest shape.
    // Hint preserved verbatim (EX-4 rewording is scoped to gov + requirement).
    let hint = format!(
        "malformed backlog item {name}: missing seeded `status`/`resolution`/`updated` (regenerate via `backlog new`)"
    );
    dep_seq::set_authored_status(
        &path,
        &[
            ("status", status.as_str()),
            ("resolution", resolution),
            ("updated", today),
        ],
        &hint,
    )?;
    Ok(resolution)
}

/// One outbound item→item relationship-axis append (PHASE-03 set verbs). Resolves
/// the item's `backlog-NNN.toml` path and delegates to the shared `dep_seq::append`
/// write seam (SL-060 PHASE-02 lift) — the strict edit-preserving `toml_edit` append
/// that refuses (F-1, non-destructively) on a missing seeded array. Backlog keeps
/// this thin wrapper so its callers stay path-blind (root + kind + id), while the
/// schema + write body are shared with the future slice consumer. The `RelEdit`
/// variants are the leaf's, re-imported above.
fn append_relationship(
    root: &Path,
    item_kind: ItemKind,
    id: u32,
    edit: &RelEdit<'_>,
) -> anyhow::Result<()> {
    let name = format!("{id:03}");
    let path = root
        .join(item_kind.kind().dir)
        .join(&name)
        .join(format!("{BACKLOG_STEM}-{name}.toml"));
    dep_seq::append(&path, edit)
}

/// `doctrine backlog edit <ID> --status <s> [--resolution <r>]` — the transition
/// verb (PRD-009 REQ-057/REQ-059, §5.4). Thin shell: find the root, `parse_ref` the
/// id to its kind (prefix auto-detect), apply the coupled edit in place (clock
/// injected), print the new state. A missing id hard-errors (never implicit create).
pub(crate) fn run_edit(
    path: Option<PathBuf>,
    reference: &str,
    status: Status,
    resolution: Option<Resolution>,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (item_kind, id) = parse_ref(reference)?;
    let written = set_backlog_status(
        &root,
        item_kind,
        id,
        status,
        resolution,
        &crate::clock::today(),
    )?;
    let suffix = if written.is_empty() {
        String::new()
    } else {
        format!(" · {written}")
    };
    writeln!(
        io::stdout(),
        "Edited {}: {}{suffix}",
        item_kind.canonical_id(id),
        status.as_str()
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// PHASE-03 set verbs: `backlog needs` / `backlog after` (the thin impure shells)
// ---------------------------------------------------------------------------

/// Validate that a backlog ref names an existing item — `parse_ref` then a read.
/// A bad prefix / non-numeric tail (`parse_ref` Err) or a missing file is a HARD
/// user error (`bail!` via the `?`), never a soft drop: a set verb must reject a
/// stale ref at author time (design §5.6 — the absent case is rejected here, so
/// `list`'s sequence compose only ever defends against later staleness). Returns the
/// resolved id.
fn require_item(root: &Path, reference: &str) -> anyhow::Result<(ItemKind, u32)> {
    let (kind, id) = parse_ref(reference)?;
    read_item(root, kind, id)?;
    Ok((kind, id))
}

/// Render a diagnosed `needs` cycle as a stable, sorted member list (`A, B, C`) for
/// the refuse/error message — `ItemId` canonical refs only (no `NodeId` internals, R1).
fn name_cycle(members: &std::collections::BTreeSet<ItemId>) -> String {
    members
        .iter()
        .map(|id| id.render())
        .collect::<Vec<_>>()
        .join(", ")
}

/// The `needs` set verb's pure refuse oracle (A-setcycle / DD2): would adding
/// `new_needs` to `ITEM` close a `needs` cycle? Injects the proposed edges into a
/// CLONE of the corpus, projects, builds, and asks the adapter's `dep_cycles` (the
/// single cycle oracle — no parallel impl). Returns the offending cycles (empty ⇒
/// safe to append). Pure over the read corpus + the proposed edges.
fn needs_would_cycle(
    items: &[BacklogItem],
    target: (ItemKind, u32),
    new_needs: &[String],
) -> anyhow::Result<Vec<std::collections::BTreeSet<ItemId>>> {
    let mut corpus: Vec<BacklogItem> = items.to_vec();
    if let Some(item) = corpus
        .iter_mut()
        .find(|i| i.kind == target.0 && i.id == target.1)
    {
        item.relationships.needs.extend_from_slice(new_needs);
    }
    let (inputs, _) = project(&corpus);
    Ok(BacklogOrder::build(&inputs)?.dep_cycles())
}

/// `doctrine backlog needs <ITEM> <PREREQ>…` — append hard prerequisites (PRD-009,
/// design §5.5). Thin shell: find the root, validate ITEM + every PREREQ exists
/// (a bad ref is a hard user error), then **build the dep graph including the
/// proposed edges and refuse on a closing cycle** (naming members; nothing written
/// — validate-then-build-then-write). Else append edit-in-place + confirm.
pub(crate) fn run_needs(
    path: Option<PathBuf>,
    reference: &str,
    prereqs: &[String],
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let target = require_item(&root, reference)?;
    for prereq in prereqs {
        require_item(&root, prereq)?;
    }

    // refuse a closing cycle BEFORE any write (the adapter is the single oracle).
    let items = read_all(&root)?;
    let cycles = needs_would_cycle(&items, target, prereqs)?;
    if let Some(cycle) = cycles.first() {
        anyhow::bail!(
            "`backlog needs` would close a dependency cycle: {} (nothing written)",
            name_cycle(cycle)
        );
    }

    append_relationship(&root, target.0, target.1, &RelEdit::Needs(prereqs))?;
    writeln!(
        io::stdout(),
        "{} needs {}",
        target.0.canonical_id(target.1),
        prereqs.join(", ")
    )?;
    Ok(())
}

/// `doctrine backlog after <ITEM> <TO> [--rank N]` — append ONE soft-sequence edge
/// (PRD-009, design §5.5). Thin shell: validate ITEM + the single TO exists, then
/// append `{ to, rank }` (rank optional, default 0). **Never** rejects a cycle — a
/// soft `after` cycle is surfaced (and an edge evicted) when `list` composes the
/// sequence (VT-6).
pub(crate) fn run_after(
    path: Option<PathBuf>,
    reference: &str,
    to: &str,
    rank: i32,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let target = require_item(&root, reference)?;
    require_item(&root, to)?;

    append_relationship(&root, target.0, target.1, &RelEdit::After { to, rank })?;
    let suffix = if rank == 0 {
        String::new()
    } else {
        format!(" (rank {rank})")
    };
    writeln!(
        io::stdout(),
        "{} after {to}{suffix}",
        target.0.canonical_id(target.1),
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// SL-067 PHASE-01: the `backlog tag` verb — tag normalisation + the
// edit-preserving set-replace write, plus the two divergent folds
// ---------------------------------------------------------------------------

/// Normalise ONE tag on the WRITE path — the single chokepoint that decides what
/// lands in the store (cf. `resolve_slug` for authored slugs). Trim, lowercase,
/// then validate every char is `[a-z0-9_:-]` (colon allowed for namespacing, e.g.
/// `area:backlog`); empty after trim, or any other char, is a HARD user error
/// (`bail!`) NAMING the offending token so the author can fix it (EX-2). DISTINCT
/// from [`fold_filter_tag`] — the filter fold is lenient by design (§4.2).
fn normalize_tag(raw: &str) -> anyhow::Result<String> {
    let tag = raw.trim().to_lowercase();
    if tag.is_empty() {
        anyhow::bail!("empty tag `{raw}` — tags must be non-empty `[a-z0-9_:-]`");
    }
    if !tag
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | ':' | '-'))
    {
        anyhow::bail!(
            "invalid tag `{raw}` — tags must be `[a-z0-9_:-]` (lowercased, e.g. `area:backlog`)"
        );
    }
    Ok(tag)
}

/// Normalise a `-t/--tag` FILTER input — the lenient, SEPARATE fold (§4.2): trim +
/// lowercase, with NO charset reject. A filter matching nothing must succeed
/// silently (never `bail!`), so this MUST NOT route through [`normalize_tag`]; the
/// two folds diverge by design. `tags_admit` keeps its exact-match semantics — only
/// the input is folded so `-t Security` round-trips the stored `security`.
fn fold_filter_tag(raw: &str) -> String {
    raw.trim().to_lowercase()
}

/// Pure write core: apply a tag add/remove SET edit to a held `&mut DocumentMut`,
/// edit-preserving. No disk, no clock — the shell injects `today`.
///
/// - **F-1 strict refuse**: the `tags` key absent from the top-level table → the
///   entity is malformed/hand-edited (a well-formed file seeds `tags = []`); a
///   tail-insert would land the array inside a trailing subtable (silent corruption).
///   `bail!`, NEVER create — the file is left untouched.
/// - **The set algebra**: `new = (current ∪ normalize(adds)) ∖ normalize(removes)`,
///   stored SORTED. The current set is read off the existing array verbatim (a
///   hand-authored store may be unsorted — that is fine, the no-op guard compares as
///   SETS).
/// - **No-op guard (set-compare)**: if `set(new) == set(current)`, return `Ok(false)`
///   with NO mutation (content + mtime hold). Set-compare (not ordered-vec) is
///   REQUIRED so an idempotent re-add against an UNSORTED hand-authored store does
///   not spuriously write + stamp `updated`.
/// - Else replace `tags` with the fresh SORTED array and stamp `updated = today`,
///   returning `Ok(true)`. Everything OUTSIDE the array (comments, inert tables,
///   unknown keys) is preserved by `toml_edit`.
fn apply_tags(
    doc: &mut toml_edit::DocumentMut,
    adds: &std::collections::BTreeSet<String>,
    removes: &std::collections::BTreeSet<String>,
    today: &str,
) -> anyhow::Result<bool> {
    let array = doc
        .as_table()
        .get("tags")
        .and_then(toml_edit::Item::as_array)
        .with_context(|| {
            "malformed backlog item: missing seeded `tags` array (a well-formed item \
             seeds `tags = []`); restore it before tagging — the file is left untouched"
                .to_string()
        })?;
    let current: std::collections::BTreeSet<String> = array
        .iter()
        .filter_map(|v| v.as_str().map(str::to_string))
        .collect();

    let mut new: std::collections::BTreeSet<String> = current.clone();
    new.extend(adds.iter().cloned());
    for r in removes {
        new.remove(r);
    }

    // Set-compare no-op guard: an idempotent re-add / absent-remove (or an UNSORTED
    // hand store whose set is already correct) writes nothing — mtime + content hold.
    if new == current {
        return Ok(false);
    }

    // Full sorted-array replace, preserving the doc outside the array. `BTreeSet`
    // iterates sorted, so the stored array is sorted.
    let mut fresh = toml_edit::Array::new();
    for tag in &new {
        fresh.push(tag.as_str());
    }
    let table = doc.as_table_mut();
    table.insert("tags", toml_edit::value(fresh));
    // Stamp `updated` — F-1 already proved `tags` present; `updated` is a sibling
    // seeded key, so a plain insert edits it in place (no tail-subtable risk).
    table.insert("updated", toml_edit::value(today));
    Ok(true)
}

/// `doctrine backlog tag <ID> [TAGS]… [--remove/-d <TAGS>…]` — the tag-edit verb
/// (SL-067 PHASE-01, §4.1/§4.3). Thin impure shell: find the root, `parse_ref` +
/// `require_item` (a missing id hard-errors, never an implicit create), normalise
/// the adds/removes through the WRITE chokepoint [`normalize_tag`], reject an
/// add∩remove overlap (a user error), then apply the edit-preserving set-replace
/// in place (clock injected) and print the post-state. At least one add OR remove is
/// required (clap enforces neither alone, so the shell does — EX-1).
pub(crate) fn run_tag(
    path: Option<PathBuf>,
    reference: &str,
    adds: &[String],
    removes: &[String],
) -> anyhow::Result<()> {
    if adds.is_empty() && removes.is_empty() {
        anyhow::bail!("`backlog tag` needs at least one tag to add or remove (--remove/-d)");
    }
    let add_set: std::collections::BTreeSet<String> = adds
        .iter()
        .map(|t| normalize_tag(t))
        .collect::<anyhow::Result<_>>()?;
    let remove_set: std::collections::BTreeSet<String> = removes
        .iter()
        .map(|t| normalize_tag(t))
        .collect::<anyhow::Result<_>>()?;
    // A tag in BOTH add and remove (after normalisation) is contradictory — reject
    // rather than silently letting the remove win (user error, §4.1).
    let overlap: Vec<&String> = add_set.intersection(&remove_set).collect();
    if let Some(first) = overlap.first() {
        anyhow::bail!("tag `{first}` is in both add and remove (pick one)");
    }

    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (item_kind, id) = require_item(&root, reference)?;
    let name = format!("{id:03}");
    let item_path = root
        .join(item_kind.kind().dir)
        .join(&name)
        .join(format!("{BACKLOG_STEM}-{name}.toml"));

    let text = std::fs::read_to_string(&item_path)
        .with_context(|| format!("backlog item not found at {}", item_path.display()))?;
    let mut doc = text
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| format!("Failed to parse {}", item_path.display()))?;
    let changed = apply_tags(&mut doc, &add_set, &remove_set, &crate::clock::today())?;
    if changed {
        std::fs::write(&item_path, doc.to_string())
            .with_context(|| format!("Failed to write {}", item_path.display()))?;
    }

    // Print the post-state (the resulting tag set, sorted) — re-derived from the doc
    // so it is faithful whether or not a write occurred.
    let final_tags: Vec<String> = doc
        .as_table()
        .get("tags")
        .and_then(toml_edit::Item::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();
    let listed = if final_tags.is_empty() {
        "(none)".to_string()
    } else {
        final_tags.join(", ")
    };
    writeln!(
        io::stdout(),
        "Tagged {}: {listed}",
        item_kind.canonical_id(id),
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// The honest-record block (SL-051: folded into `backlog list --by sequence`)
// ---------------------------------------------------------------------------

/// Name a `Dangling` endpoint loudly (A-classify / DD1 / design §5.6 E1): the
/// status/resolution vocabulary is supplied SHELL-side from the corpus, keeping the
/// adapter id-only (the R-C kill). `endpoint` is the adapter's `Dangling.from()` — the
/// missing endpoint. Looked up in `corpus`:
/// - **present but terminal** (`resolved`/`closed`) ⇒ `"<status>/<resolution>"`
///   (e.g. `closed/wont-do`) — the author judges staleness from the named resolution,
///   never a silent satisfied-claim;
/// - **not present** (a stale ref to a never-existed / since-deleted id) ⇒ `"absent"`.
///
/// (A present-but-NON-terminal endpoint cannot be `Dangling` — it would be a live
/// node — so that arm is unreachable; rendered defensively as `"absent"`.)
fn classify_dangling(corpus: &BTreeMap<ItemId, &BacklogItem>, endpoint: ItemId) -> String {
    match corpus.get(&endpoint) {
        Some(item) if item.status.is_terminal() => {
            let resolution = item.resolution.map_or("?", Resolution::as_str);
            format!("{}/{resolution}", item.status.as_str())
        }
        _ => "absent".to_string(),
    }
}

/// Render the honest-record `overrides:` block (design §5.6, R1): one terse line per
/// dropped edge — `<from> → <to> dropped (<why>)` — `ItemId` refs + reason words only
/// (no NodeId/ordering internals leak). Covers BOTH the project-level [`AbsentDrop`]s
/// (unparseable refs that never reached the adapter) and the adapter's `overrides()`
/// (soft-cycle evictions, contradictions, and the parses-but-not-a-node `Dangling`s,
/// each named with status+resolution). Empty when nothing was dropped (no block).
fn render_overrides(
    corpus: &BTreeMap<ItemId, &BacklogItem>,
    absent: &[AbsentDrop],
    overrides: &[Override],
) -> String {
    let mut lines: Vec<String> = Vec::new();

    // project-level drops: an unparseable ref never became an ItemId.
    for drop in absent {
        lines.push(format!(
            "  {}{} dropped (dangling: {} absent)\n",
            drop.from().render(),
            drop.reference(),
            drop.reference(),
        ));
    }

    // adapter-level drops.
    for ov in overrides {
        let line = match ov.reason() {
            OverrideReason::SoftCycleEvicted => format!(
                "  {}{} dropped (soft cycle)\n",
                ov.from().render(),
                ov.to().render()
            ),
            OverrideReason::Contradicted => format!(
                "  {}{} dropped (contradicts a need)\n",
                ov.from().render(),
                ov.to().render()
            ),
            OverrideReason::Dangling => format!(
                "  {}{} dropped (dangling: {} {})\n",
                ov.from().render(),
                ov.to().render(),
                ov.from().render(),
                classify_dangling(corpus, ov.from()),
            ),
        };
        lines.push(line);
    }

    if lines.is_empty() {
        return String::new();
    }
    let mut out = vec!["\noverrides:\n".to_string()];
    out.extend(lines);
    out.concat()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entity::{self, Inputs, LocalFs, MaterialiseRequest};
    use crate::meta::Meta;
    use std::fs;
    use std::path::Path;

    fn ctx_for(item_kind: ItemKind) -> ScaffoldCtx<'static> {
        let canonical: &'static str = match item_kind {
            ItemKind::Issue => "ISS-003",
            ItemKind::Improvement => "IMP-003",
            ItemKind::Chore => "CHR-003",
            ItemKind::Risk => "RSK-003",
            ItemKind::Idea => "IDE-003",
        };
        ScaffoldCtx {
            id: 3,
            canonical,
            slug: "token-expiry",
            title: "Token expiry",
            date: "2026-06-08",
        }
    }

    fn fresh(root: &Path, item_kind: ItemKind, slug: &str, title: &str) -> entity::Materialised {
        entity::materialise(
            item_kind.kind(),
            &LocalFs,
            root,
            &MaterialiseRequest::Fresh,
            &Inputs {
                slug,
                title,
                date: "2026-06-08",
            },
            &[],
        )
        .unwrap()
    }

    // --- VT-1: per-kind scaffold fileset ---

    #[test]
    fn backlog_scaffold_lays_out_toml_md_symlink() {
        for kind in ItemKind::ALL {
            let ctx = ctx_for(kind);
            let fileset = backlog_scaffold(kind, &ctx).unwrap();
            assert_eq!(fileset.len(), 3, "{kind:?}: toml + md + symlink");

            assert!(
                matches!(&fileset[0],
                    Artifact::File { rel_path, body }
                    if rel_path == Path::new("003/backlog-003.toml")
                        && body.contains(&format!("kind = \"{}\"", kind.as_str()))),
                "{kind:?}: toml at tree-relative path with the stored kind"
            );
            assert!(
                matches!(&fileset[1],
                    Artifact::File { rel_path, body }
                    if rel_path == Path::new("003/backlog-003.md")
                        && body.contains(&format!("{}: Token expiry", ctx.canonical))),
                "{kind:?}: md carries the canonical ref"
            );
            assert!(
                matches!(&fileset[2],
                    Artifact::Symlink { rel_path, target }
                    if rel_path == Path::new("003-token-expiry") && target == "003"),
                "{kind:?}: NNN-slug alias last"
            );

            // risk carries `[facet]`; the four plain kinds omit it.
            let toml_body = match &fileset[0] {
                Artifact::File { body, .. } => body,
                Artifact::Symlink { .. } => panic!("first artifact is the toml"),
            };
            assert_eq!(
                toml_body.contains("[facet]"),
                kind.has_facet(),
                "{kind:?}: [facet] iff risk"
            );
        }
    }

    // --- VT-3: every kind seeds the mutable keys (the edit-in-place precondition) ---

    #[test]
    fn all_five_kinds_seed_status_resolution_updated_tags() {
        for kind in ItemKind::ALL {
            let body = render_backlog_toml(kind, 1, "s", "T", "2026-06-08").unwrap();
            assert!(
                body.contains("status = \"open\""),
                "{kind:?}: status seeded"
            );
            assert!(
                body.contains("resolution = \"\""),
                "{kind:?}: resolution seeded"
            );
            assert!(
                body.contains("updated = \"2026-06-08\""),
                "{kind:?}: updated seeded"
            );
            assert!(body.contains("tags = []"), "{kind:?}: tags seeded");
            assert!(!body.contains("{{"), "{kind:?}: no token survives render");
        }
    }

    // --- VT-2: the shared-Meta + full-entity round-trip, and the "" -> None seam ---

    #[test]
    fn rendered_toml_round_trips_into_meta_and_backlog_item() {
        let body = render_backlog_toml(ItemKind::Issue, 7, "fast-boot", "Fast boot", "2026-06-08")
            .unwrap();

        // the four list fields parse into the shared meta::Meta (status is a String there).
        let meta: Meta = toml::from_str(&body).unwrap();
        assert_eq!(
            meta,
            Meta {
                id: 7,
                slug: "fast-boot".to_string(),
                title: "Fast boot".to_string(),
                status: "open".to_string(),
            }
        );

        // the full entity validates; the seeded resolution `""` maps to None.
        let item = validate(toml::from_str::<RawBacklogToml>(&body).unwrap()).unwrap();
        assert_eq!(item.kind, ItemKind::Issue);
        assert_eq!(item.status, Status::Open);
        assert_eq!(item.resolution, None);
        assert!(item.facet.is_none(), "a plain kind has no facet");
        assert_eq!(item.relationships, Relationships::default());
        // the three PRD-009 item→item axes default to `[]` on a virgin item (VT-1).
        assert!(item.relationships.needs.is_empty());
        assert!(item.relationships.after.is_empty());
        assert!(item.relationships.triggers.is_empty());
    }

    #[test]
    fn render_backlog_toml_escapes_hostile_title_and_slug() {
        // SL-024: quoted-literal breakers (`"`, `\`, newline) round-trip.
        let title = crate::tomlfmt::HOSTILE_TITLE;
        let slug = crate::tomlfmt::HOSTILE_SLUG;
        let body = render_backlog_toml(ItemKind::Issue, 7, slug, title, "2026-06-08").unwrap();
        let parsed: Meta = toml::from_str(&body).unwrap();
        assert_eq!(parsed.slug, slug);
        assert_eq!(parsed.title, title);
    }

    #[test]
    fn risk_facet_levels_map_empty_to_none_and_parse_non_empty() {
        // a seeded risk toml: every facet axis empty → None.
        let seeded = render_backlog_toml(ItemKind::Risk, 1, "r", "R", "2026-06-08").unwrap();
        let item = validate(toml::from_str::<RawBacklogToml>(&seeded).unwrap()).unwrap();
        let facet = item.facet.expect("risk carries a facet");
        assert_eq!(facet.likelihood, None);
        assert_eq!(facet.impact, None);
        assert_eq!(facet.origin, None);
        assert!(facet.controls.is_empty());

        // an assessed risk: non-empty axes parse to their levels.
        let assessed = "\
id = 1
slug = \"r\"
title = \"R\"
kind = \"risk\"
status = \"open\"
resolution = \"\"
created = \"2026-06-08\"
updated = \"2026-06-08\"
tags = []

[facet]
likelihood = \"high\"
impact = \"critical\"
origin = \"audit\"
controls = [\"rate-limit\"]

[relationships]
slices = [\"SL-020\"]
specs = []
drift = []
";
        let item = validate(toml::from_str::<RawBacklogToml>(assessed).unwrap()).unwrap();
        let facet = item.facet.unwrap();
        assert_eq!(facet.likelihood, Some(RiskLevel::High));
        assert_eq!(facet.impact, Some(RiskLevel::Critical));
        assert_eq!(facet.origin.as_deref(), Some("audit"));
        assert_eq!(facet.controls, vec!["rate-limit"]);
        // SL-048: `slices` is no longer a typed `[relationships]` field — it migrated
        // to `[[relation]]` (read by `read_item` via `read_block`, not `validate`). A
        // stray `[relationships].slices` key in the fixture is now simply ignored on
        // parse. The tier-1 read seam is covered by the show/relation_edges tests.
    }

    #[test]
    fn validate_errors_on_an_unknown_enum_token() {
        let body = "\
id = 1
slug = \"s\"
title = \"T\"
kind = \"issue\"
status = \"open\"
resolution = \"bogus\"
created = \"2026-06-08\"
updated = \"2026-06-08\"
tags = []
";
        let raw: RawBacklogToml = toml::from_str(body).unwrap();
        assert!(
            validate(raw).is_err(),
            "an unknown resolution token is rejected"
        );
    }

    // --- the value mirrors + discriminator helpers ---

    #[test]
    fn status_is_terminal_is_backlog_local() {
        assert!(Status::Resolved.is_terminal());
        assert!(Status::Closed.is_terminal());
        assert!(!Status::Open.is_terminal());
        assert!(!Status::Triaged.is_terminal());
        assert!(!Status::Started.is_terminal());
    }

    #[test]
    fn item_kind_from_prefix_round_trips_each_kind() {
        for kind in ItemKind::ALL {
            assert_eq!(ItemKind::from_prefix(kind.prefix()), Some(kind));
        }
        assert_eq!(ItemKind::from_prefix("REQ"), None);
        // the five prefixes are distinct.
        let prefixes: std::collections::BTreeSet<&str> =
            ItemKind::ALL.iter().map(|k| k.prefix()).collect();
        assert_eq!(prefixes.len(), 5);
    }

    #[test]
    fn resolution_and_risk_level_render_mirror_serde() {
        assert_eq!(Resolution::WontDo.as_str(), "wont-do");
        assert_eq!(Resolution::Promoted.as_str(), "promoted");
        assert_eq!(RiskLevel::Critical.as_str(), "critical");
        // the mirror matches the parse direction.
        assert_eq!(
            parse_enum::<Resolution>("wont-do", "resolution").unwrap(),
            Resolution::WontDo
        );
    }

    // --- EX-1 / VT-1: materialise(Fresh) reserves per-kind, counters independent ---

    #[test]
    fn materialise_fresh_reserves_each_kind_in_its_own_namespace() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();

        // issue and risk both start at 001 — independent reservation namespaces.
        let i1 = fresh(root, ItemKind::Issue, "auth", "Auth");
        let r1 = fresh(root, ItemKind::Risk, "expiry", "Expiry");
        assert_eq!(i1.eid.numeric_id(), Some(1));
        assert_eq!(r1.eid.numeric_id(), Some(1));

        assert!(
            root.join(".doctrine/backlog/issue/001/backlog-001.toml")
                .is_file()
        );
        assert!(
            root.join(".doctrine/backlog/issue/001/backlog-001.md")
                .is_file()
        );
        assert_eq!(
            fs::read_link(root.join(".doctrine/backlog/issue/001-auth")).unwrap(),
            Path::new("001")
        );

        // the risk item on disk carries the `[facet]`; the issue item does not.
        let risk_toml =
            fs::read_to_string(root.join(".doctrine/backlog/risk/001/backlog-001.toml")).unwrap();
        assert!(risk_toml.contains("[facet]"));
        let issue_toml =
            fs::read_to_string(root.join(".doctrine/backlog/issue/001/backlog-001.toml")).unwrap();
        assert!(!issue_toml.contains("[facet]"));

        // a second issue lands 002; the risk counter is untouched (separate dirs).
        let i2 = fresh(root, ItemKind::Issue, "login", "Login");
        assert_eq!(i2.eid.numeric_id(), Some(2));
        let r2 = fresh(root, ItemKind::Risk, "leak", "Leak");
        assert_eq!(r2.eid.numeric_id(), Some(2));

        // the materialised toml round-trips through validate end-to-end.
        let item = validate(toml::from_str::<RawBacklogToml>(&risk_toml).unwrap()).unwrap();
        assert_eq!(item.kind, ItemKind::Risk);
        assert_eq!(item.id, 1);
    }

    // --- PHASE-02: the `backlog new` verb (thin shell over the engine) ---

    /// Drive the real `new` verb with an explicit root (short-circuits detection)
    /// and an explicit title (avoids stdin).
    fn new_item(root: &Path, kind: ItemKind, title: &str) {
        run_new(
            Some(root.to_path_buf()),
            kind,
            Some(title.to_string()),
            None,
        )
        .unwrap();
    }

    fn issue_dir(root: &Path, id: &str) -> PathBuf {
        root.join(format!(".doctrine/backlog/issue/{id}"))
    }

    // --- VT-1: monotonic per kind ---

    #[test]
    fn backlog_new_reserves_monotonic_per_kind() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth");
        new_item(root, ItemKind::Issue, "Login");

        assert!(issue_dir(root, "001").join("backlog-001.toml").is_file());
        assert!(issue_dir(root, "001").join("backlog-001.md").is_file());
        assert_eq!(
            fs::read_link(root.join(".doctrine/backlog/issue/001-auth")).unwrap(),
            Path::new("001")
        );
        // a second `new` lands the next id (engine race-retry inherited).
        assert!(issue_dir(root, "002").join("backlog-002.toml").is_file());
    }

    // --- VT-1: the five counters are independent (separate dirs) ---

    #[test]
    fn backlog_new_counters_isolated_across_kinds() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // an issue and a risk both open at 001 — independent namespaces.
        new_item(root, ItemKind::Issue, "Auth");
        new_item(root, ItemKind::Risk, "Expiry");
        assert!(issue_dir(root, "001").join("backlog-001.toml").is_file());
        assert!(
            root.join(".doctrine/backlog/risk/001/backlog-001.toml")
                .is_file()
        );

        // a second issue advances to 002; the risk counter is untouched.
        new_item(root, ItemKind::Issue, "Login");
        assert!(issue_dir(root, "002").join("backlog-002.toml").is_file());
        assert!(
            !root.join(".doctrine/backlog/risk/002").exists(),
            "an issue create must not advance the risk counter"
        );
    }

    // --- VT-2: the kind-correct template seeds onto disk ---

    #[test]
    fn backlog_new_seeds_kind_template() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Risk, "Token expiry");
        new_item(root, ItemKind::Issue, "Token expiry");

        // risk seeds `[facet]`; the plain issue does not. Both default `open`.
        let risk =
            fs::read_to_string(root.join(".doctrine/backlog/risk/001/backlog-001.toml")).unwrap();
        assert!(risk.contains("[facet]"), "risk seeds a facet");
        assert!(risk.contains("status = \"open\""), "status defaults open");

        let issue = fs::read_to_string(issue_dir(root, "001").join("backlog-001.toml")).unwrap();
        assert!(!issue.contains("[facet]"), "a plain kind has no facet");
        assert!(issue.contains("status = \"open\""));

        // the printed canonical id (`ISS-001`) matches the reserved dir: the item
        // validates and carries id 1 under the issue tree.
        let item = validate(toml::from_str::<RawBacklogToml>(&issue).unwrap()).unwrap();
        assert_eq!(item.kind, ItemKind::Issue);
        assert_eq!(item.id, 1);
        assert_eq!(ItemKind::Issue.canonical_id(item.id), "ISS-001");
    }

    // --- VT-3: the gitignore negation makes a created item git-addable (R5) ---

    #[test]
    fn created_backlog_item_is_git_addable() {
        fn git(root: &Path, args: &[&str]) -> std::process::Output {
            std::process::Command::new("git")
                .arg("-C")
                .arg(root)
                .args(args)
                .output()
                .expect("spawn git")
        }

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        assert!(git(root, &["init", "-b", "main"]).status.success());
        // the dogfood blanket-ignore + the PHASE-02 backlog negation (no inline #).
        fs::write(
            root.join(".gitignore"),
            ".doctrine/*\n!.doctrine/backlog/\n",
        )
        .unwrap();

        new_item(root, ItemKind::Issue, "Auth");
        let item = ".doctrine/backlog/issue/001/backlog-001.toml";

        // `check-ignore -q` exits 1 when the path is NOT ignored — negation is live.
        assert_eq!(
            git(root, &["check-ignore", "-q", item]).status.code(),
            Some(1),
            "the negation must un-ignore the backlog item"
        );
        // and `git add` of the item succeeds (no "paths are ignored").
        let add = git(root, &["add", item]);
        assert!(
            add.status.success(),
            "git add failed: {}",
            String::from_utf8_lossy(&add.stderr)
        );
    }

    // --- PHASE-03: the `backlog list` survey (visibility / filter / order) ---

    /// A backlog-NNN.toml fixture spec — the single source of the test fixture
    /// literal. `'a` (not `'static`) because `write_related` passes borrowed
    /// `slices`/`specs`. `facet`/`rels` absent → that block is omitted.
    struct Fixture<'a> {
        kind: ItemKind,
        id: u32,
        slug: &'a str,
        title: &'a str,
        status: &'a str,
        resolution: &'a str,
        tags: &'a [&'a str],
        facet: Option<FacetLit<'a>>,
        rels: Option<RelLit<'a>>,
    }

    struct FacetLit<'a> {
        likelihood: &'a str,
        impact: &'a str,
        origin: &'a str,
        controls: &'a [&'a str],
    }

    struct RelLit<'a> {
        slices: &'a [&'a str],
        specs: &'a [&'a str],
        needs: &'a [&'a str],
        after: &'a [AfterLit<'a>],
        triggers: &'a [TriggerLit<'a>],
    }

    struct AfterLit<'a> {
        to: &'a str,
        rank: i32,
    }

    struct TriggerLit<'a> {
        globs: &'a [&'a str],
        note: &'a str,
    }

    /// The sole list-literal quoting: `[] → ""`, `["a","b"] → "\"a\", \"b\""`.
    fn toml_list(xs: &[&str]) -> String {
        xs.iter()
            .map(|x| format!("\"{x}\""))
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// `after` array-of-inline-tables literal: each edge `{ to = "X", rank = N }`.
    fn toml_after(xs: &[AfterLit<'_>]) -> String {
        xs.iter()
            .map(|e| format!("{{ to = \"{}\", rank = {} }}", e.to, e.rank))
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// `triggers` array-of-inline-tables literal: each `{ globs = [...], note = "" }`.
    fn toml_triggers(xs: &[TriggerLit<'_>]) -> String {
        xs.iter()
            .map(|t| {
                format!(
                    "{{ globs = [{}], note = \"{}\" }}",
                    toml_list(t.globs),
                    t.note
                )
            })
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// The sole fixture TOML literal: core head + optional `[facet]` + optional
    /// `[relationships]`. Segments concatenate (each `""` when absent) rather than
    /// `push_str(&format!(..))`, honouring the repo string-build convention.
    fn render_fixture_toml(f: &Fixture<'_>) -> String {
        let head = format!(
            "id = {}\nslug = \"{}\"\ntitle = \"{}\"\nkind = \"{}\"\n\
             status = \"{}\"\nresolution = \"{}\"\n\
             created = \"2026-06-08\"\nupdated = \"2026-06-08\"\ntags = [{}]\n",
            f.id,
            f.slug,
            f.title,
            f.kind.as_str(),
            f.status,
            f.resolution,
            toml_list(f.tags),
        );
        let facet = f.facet.as_ref().map_or_else(String::new, |x| {
            format!(
                "\n[facet]\nlikelihood = \"{}\"\nimpact = \"{}\"\norigin = \"{}\"\ncontrols = [{}]\n",
                x.likelihood,
                x.impact,
                x.origin,
                toml_list(x.controls),
            )
        });
        // SL-048 PHASE-04 (the cut): the migrated tier-1 axes (slices/specs/drift) are
        // emitted as `[[relation]]` rows AFTER the typed `[relationships]` table (F1 —
        // typed tables precede all arrays-of-tables). The dep/sequence axes stay typed.
        let rels = f.rels.as_ref().map_or_else(String::new, |x| {
            format!(
                "\n[relationships]\nneeds = [{}]\nafter = [{}]\ntriggers = [{}]\n",
                toml_list(x.needs),
                toml_after(x.after),
                toml_triggers(x.triggers),
            )
        });
        let mut relation_rows = String::new();
        if let Some(x) = f.rels.as_ref() {
            for s in x.slices {
                relation_rows.push_str(&format!(
                    "\n[[relation]]\nlabel = \"slices\"\ntarget = \"{s}\"\n"
                ));
            }
            for s in x.specs {
                relation_rows.push_str(&format!(
                    "\n[[relation]]\nlabel = \"specs\"\ntarget = \"{s}\"\n"
                ));
            }
        }
        format!("{head}{facet}{rels}{relation_rows}")
    }

    /// The sole path/dir/write: render the fixture and lay it under its kind tree.
    fn write_fixture(root: &Path, f: Fixture<'_>) {
        let name = format!("{:03}", f.id);
        let dir = root.join(f.kind.kind().dir).join(&name);
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join(format!("backlog-{name}.toml")),
            render_fixture_toml(&f),
        )
        .unwrap();
    }

    /// Write a complete `backlog-NNN.toml` directly under a kind's tree — a true
    /// unit fixture (the `meta::tests::write_meta_toml` precedent) that lets a
    /// non-`open`/terminal status + a resolution be seeded without the (unbuilt,
    /// PHASE-05) `edit` verb. Exercises the real reader: `scan_ids` + `validate`.
    fn write_item(
        root: &Path,
        kind: ItemKind,
        id: u32,
        status: &str,
        resolution: &str,
        slug: &str,
        title: &str,
        tags: &[&str],
    ) {
        write_fixture(
            root,
            Fixture {
                kind,
                id,
                slug,
                title,
                status,
                resolution,
                tags,
                facet: None,
                rels: None,
            },
        );
    }

    /// The first column (canonical id) of each rendered row, in render order.
    /// Skips the §5.5 header line; an empty `""` (suppressed header) → no ids.
    fn ids(out: &str) -> Vec<String> {
        out.lines()
            .skip(1)
            .map(|l| l.split_whitespace().next().unwrap().to_string())
            .collect()
    }

    /// A no-constraint `ListArgs` (the default `backlog list`).
    fn list_args() -> ListArgs {
        ListArgs::default()
    }

    /// Drive `list_rows` in the classic `--by id` mode and return just stdout — the
    /// shape every pre-SL-051 list test expected (membership / filter / column
    /// behaviour, asserted against the `(kind.ordinal, id)` grouping). The composed
    /// `--by sequence` default is exercised separately (VT-1 / VT-2).
    fn list_id(root: &Path, kind: Option<ItemKind>, args: ListArgs) -> anyhow::Result<String> {
        list_rows(root, kind, OrderBy::Id, args).map(|o| o.stdout)
    }

    // --- §5.5: the uniform table header (extends to backlog) ---

    #[test]
    fn backlog_list_emits_a_header_then_prefixed_ids() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);

        let out = list_id(root, None, list_args()).unwrap();
        let lines: Vec<&str> = out.lines().collect();
        // §5.5: rows present → a header row naming the columns, then the data.
        assert!(lines[0].starts_with("id"), "header row: {:?}", lines[0]);
        assert!(
            lines[0].contains("kind") && lines[0].contains("status"),
            "header names columns: {:?}",
            lines[0]
        );
        assert!(lines[1].starts_with("ISS-001"), "first data row prefixed");
    }

    #[test]
    fn backlog_list_empty_suppresses_the_header() {
        let dir = tempfile::tempdir().unwrap();
        // no items written → "" (header suppressed, §5.5 virgin-repo contract).
        assert_eq!(list_id(dir.path(), None, list_args()).unwrap(), "");
    }

    // --- SL-037: the column model (default omits slug, --columns reveals) ---

    /// A `ListArgs` requesting an explicit column set (SL-037 `--columns`).
    fn columns_args(cols: &[&str]) -> ListArgs {
        ListArgs {
            columns: Some(cols.iter().map(|s| (*s).to_string()).collect()),
            ..Default::default()
        }
    }

    #[test]
    fn backlog_list_default_omits_slug() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(
            root,
            ItemKind::Issue,
            1,
            "open",
            "",
            "token-expiry",
            "Alpha",
            &[],
        );

        let out = list_id(root, None, list_args()).unwrap();
        let header = out.lines().next().unwrap();
        // SL-037 D4: default visible set is [id, kind, status, title] — slug hidden.
        assert!(
            !header.contains("slug"),
            "default header omits slug: {header:?}"
        );
        assert!(
            !out.contains("token-expiry"),
            "slug value hidden by default: {out}"
        );
        assert!(
            header.contains("kind") && header.contains("status") && header.contains("title"),
            "default keeps id/kind/status/title: {header:?}"
        );
    }

    #[test]
    fn backlog_list_columns_reveals_and_orders_slug() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(
            root,
            ItemKind::Issue,
            1,
            "open",
            "",
            "token-expiry",
            "Alpha",
            &[],
        );

        // Reorder slug ahead of title and reveal it.
        let out = list_id(root, None, columns_args(&["id", "slug", "title"])).unwrap();
        let header = out.lines().next().unwrap();
        assert_eq!(
            header.split_whitespace().collect::<Vec<_>>(),
            vec!["id", "", "slug", "", "title"]
        );
        assert!(
            out.contains("token-expiry"),
            "slug revealed by --columns: {out}"
        );
    }

    #[test]
    fn backlog_list_columns_unknown_errors_with_available_set() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);

        let err = list_id(root, None, columns_args(&["bogus"]))
            .err()
            .map(|e| e.to_string())
            .unwrap_or_default();
        assert!(
            err.contains("unknown column `bogus`"),
            "uniform error: {err}"
        );
        assert!(
            err.contains("id") && err.contains("slug"),
            "lists available set: {err}"
        );
    }

    // --- SL-067 PHASE-02: the dynamic `tags` column (D2) ---

    /// VT-4: an UNTAGGED corpus shows NO `tags` column (the golden-corpus invariant —
    /// untagged lists stay byte-identical to pre-SL-067).
    #[test]
    fn backlog_list_untagged_corpus_hides_tags_column() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);

        let out = list_id(root, None, list_args()).unwrap();
        let header = out.lines().next().unwrap();
        assert!(
            !header.contains("tags"),
            "untagged corpus omits the tags column: {header:?}"
        );
    }

    /// VT-4: ≥1 tagged row → the `tags` column appears, spliced before `title`.
    #[test]
    fn backlog_list_tagged_corpus_shows_tags_before_title() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &["cli"]);

        let out = list_id(root, None, list_args()).unwrap();
        let header = out.lines().next().unwrap();
        assert_eq!(
            header.split_whitespace().collect::<Vec<_>>(),
            vec!["id", "", "kind", "", "status", "", "tags", "", "title"],
            "tags spliced before title: {header:?}"
        );
        assert!(out.contains("cli"), "the tag value renders: {out}");
    }

    /// VT-4: `--columns id,tags` FORCES the tags column even when every row is empty
    /// (the explicit request honoured verbatim — the dynamic default is bypassed).
    #[test]
    fn backlog_list_columns_forces_tags_even_when_all_empty() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);

        let out = list_id(root, None, columns_args(&["id", "tags"])).unwrap();
        let header = out.lines().next().unwrap();
        assert_eq!(
            header.split_whitespace().collect::<Vec<_>>(),
            vec!["id", "", "tags"],
            "explicit --columns shows tags despite all-empty: {header:?}"
        );
    }

    /// VT-4: `--columns` omitting tags HIDES it despite tagged rows (the explicit set
    /// wins; the dynamic default never overrides an explicit request).
    #[test]
    fn backlog_list_columns_omitting_tags_hides_it_despite_tagged_rows() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &["cli"]);

        let out = list_id(root, None, columns_args(&["id", "title"])).unwrap();
        let header = out.lines().next().unwrap();
        assert!(
            !header.contains("tags"),
            "explicit columns omitting tags hides it: {header:?}"
        );
    }

    /// VT-4: a tagged item FILTERED OUT by `--kind` leaves no tagged row in the visible
    /// set → no tags column (the visibility keys on the FINAL displayed set, post-kind).
    #[test]
    fn backlog_list_tagged_row_filtered_by_kind_hides_tags_column() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // The only tagged item is an Issue; we list Improvements → it is filtered out.
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &["cli"]);
        write_item(
            root,
            ItemKind::Improvement,
            1,
            "open",
            "",
            "b",
            "Bravo",
            &[],
        );

        let out = list_id(root, Some(ItemKind::Improvement), list_args()).unwrap();
        let header = out.lines().next().unwrap();
        assert!(
            !header.contains("tags"),
            "no visible tagged row after --kind → no tags column: {header:?}"
        );
    }

    /// VT-1 (backlog wiring smoke): under colour the tagged cell carries ANSI and
    /// stripping it reproduces the plain render — the PerToken column is wired and
    /// byte-clean-coupled end to end.
    #[test]
    fn backlog_list_tags_column_colour_strips_to_plain() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(
            root,
            ItemKind::Issue,
            1,
            "open",
            "",
            "a",
            "Alpha",
            &["cli:command", "security"],
        );

        let plain = list_id(root, None, list_args()).unwrap();
        let coloured = list_id(
            root,
            None,
            ListArgs {
                render: listing::RenderOpts {
                    color: true,
                    term_width: None,
                },
                ..Default::default()
            },
        )
        .unwrap();
        assert!(
            coloured.contains('\u{1b}'),
            "the tagged cell carries ANSI under colour"
        );
        assert_eq!(
            crate::listing::strip_ansi(&coloured),
            plain,
            "stripping the coloured backlog render reproduces the plain layout"
        );
    }

    // --- VT-1: the visibility matrix ---

    #[test]
    fn backlog_list_default_hides_terminal() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);
        write_item(root, ItemKind::Issue, 2, "triaged", "", "b", "Bravo", &[]);
        write_item(root, ItemKind::Issue, 3, "started", "", "c", "Charlie", &[]);
        write_item(
            root,
            ItemKind::Issue,
            4,
            "resolved",
            "fixed",
            "d",
            "Delta",
            &[],
        );
        write_item(root, ItemKind::Issue, 5, "closed", "done", "e", "Echo", &[]);

        let out = list_id(root, None, list_args()).unwrap();
        assert_eq!(
            ids(&out),
            vec!["ISS-001", "ISS-002", "ISS-003"],
            "default shows only the active states; resolved/closed hidden"
        );
    }

    #[test]
    fn backlog_list_all_and_explicit_status_reveal() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);
        write_item(
            root,
            ItemKind::Issue,
            4,
            "resolved",
            "fixed",
            "d",
            "Delta",
            &[],
        );
        write_item(root, ItemKind::Issue, 5, "closed", "done", "e", "Echo", &[]);
        // a promoted item is terminal (status resolved, resolution=promoted) — it
        // must hide by default and reveal by the terminal rule, no special branch.
        write_item(
            root,
            ItemKind::Issue,
            6,
            "resolved",
            "promoted",
            "f",
            "Foxtrot",
            &[],
        );

        // --all reveals every state.
        let all = list_id(
            root,
            None,
            ListArgs {
                all: true,
                ..ListArgs::default()
            },
        )
        .unwrap();
        assert_eq!(
            ids(&all),
            vec!["ISS-001", "ISS-004", "ISS-005", "ISS-006"],
            "--all shows active + terminal + promoted"
        );

        // an explicit --status resolved reveals exactly that terminal state
        // (open hidden, closed hidden; the promoted resolved item included).
        let resolved = list_id(
            root,
            None,
            ListArgs {
                status: vec!["resolved".into()],
                ..ListArgs::default()
            },
        )
        .unwrap();
        assert_eq!(
            ids(&resolved),
            vec!["ISS-004", "ISS-006"],
            "--status resolved reveals the resolved (incl. promoted) items only"
        );
    }

    // --- VT-2: filters AND together; kind-then-id order ---

    #[test]
    fn backlog_list_filters_and_together() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(
            root,
            ItemKind::Issue,
            1,
            "open",
            "",
            "auth-bug",
            "Auth bug",
            &["security"],
        );
        write_item(
            root,
            ItemKind::Issue,
            2,
            "open",
            "",
            "login",
            "Login flow",
            &["ui"],
        );
        write_item(
            root,
            ItemKind::Risk,
            1,
            "open",
            "",
            "auth-risk",
            "Auth risk",
            &["security"],
        );

        // --kind issue AND --tag security AND substring "auth" → only ISS-001.
        let out = list_id(
            root,
            Some(ItemKind::Issue),
            ListArgs {
                tags: vec!["security".to_string()],
                substr: Some("auth".to_string()),
                ..ListArgs::default()
            },
        )
        .unwrap();
        assert_eq!(
            ids(&out),
            vec!["ISS-001"],
            "the axes intersect: ISS-002 lacks the tag/substr, RSK-001 is the wrong kind"
        );
    }

    #[test]
    fn backlog_list_kind_then_id_order() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // write out of order, across kinds, to prove the sort (not insertion order).
        write_item(root, ItemKind::Risk, 1, "open", "", "r", "R", &[]);
        write_item(root, ItemKind::Issue, 2, "open", "", "i2", "I2", &[]);
        write_item(root, ItemKind::Issue, 1, "open", "", "i1", "I1", &[]);
        write_item(root, ItemKind::Idea, 1, "open", "", "d", "D", &[]);
        write_item(root, ItemKind::Chore, 1, "open", "", "c", "C", &[]);

        let out = list_id(root, None, list_args()).unwrap();
        assert_eq!(
            ids(&out),
            vec!["ISS-001", "ISS-002", "CHR-001", "RSK-001", "IDE-001"],
            "kind declaration order (issue/improvement/chore/risk/idea) then ascending id"
        );
    }

    // --- VT-3: total-function reads (missing dir / virgin repo) ---

    #[test]
    fn backlog_list_missing_dir_is_empty_set() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // only the issue tree exists; the other four kind dirs are absent.
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);

        let out = list_id(root, None, list_args()).unwrap();
        assert_eq!(
            ids(&out),
            vec!["ISS-001"],
            "an absent kind dir contributes the empty set, never an error"
        );
    }

    #[test]
    fn backlog_list_virgin_repo_empty_table() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // no `.doctrine/backlog` at all — every kind reads empty.
        let out = list_id(root, None, list_args()).unwrap();
        assert_eq!(
            out, "",
            "a virgin repo prints an empty table, never an error"
        );
    }

    // --- SL-025 EX-3: the shared spine — regexp / case / hide-set / json ---

    #[test]
    fn backlog_list_regexp_matches_canonical_id_case_insensitive() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);
        write_item(root, ItemKind::Risk, 1, "open", "", "r", "Risky", &[]);

        // --regexp over the canonical-id domain, made case-insensitive (-i): the
        // lower-case `iss` matches `ISS-001` only.
        let out = list_id(
            root,
            None,
            ListArgs {
                regexp: Some("iss-".into()),
                case_insensitive: true,
                ..ListArgs::default()
            },
        )
        .unwrap();
        assert_eq!(
            ids(&out),
            vec!["ISS-001"],
            "regexp on the prefixed id: {out}"
        );
    }

    #[test]
    fn backlog_list_json_is_one_envelope_with_prefixed_ids() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &["x"]);
        write_item(
            root,
            ItemKind::Issue,
            2,
            "resolved",
            "fixed",
            "b",
            "Bravo",
            &[],
        );

        let json = list_id(
            root,
            None,
            ListArgs {
                json: true,
                ..ListArgs::default()
            },
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["kind"], "backlog");
        let rows = v["rows"].as_array().expect("rows is an array");
        // the resolved item is hidden by default → one row; the open one survives.
        assert_eq!(rows.len(), 1, "hide-set applies under json too: {json}");
        let row = rows.first().expect("the open row");
        assert_eq!(row["id"], "ISS-001");
        assert_eq!(row["kind"], "issue");
        assert_eq!(row["status"], "open");
        assert_eq!(row["resolution"], serde_json::Value::Null);
    }

    #[test]
    fn backlog_list_rejects_an_unknown_status_with_the_uniform_error() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]);
        let err = list_id(
            root,
            None,
            ListArgs {
                status: vec!["bogus".into()],
                ..ListArgs::default()
            },
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("bogus"),
            "names the bad value: {err}"
        );
    }

    /// Drift canary: the `BACKLOG_STATUSES` known-set must stay in lockstep with
    /// the `Status` enum's kebab serde (A-2).
    #[test]
    fn backlog_statuses_matches_the_variants() {
        let from_variants: Vec<&str> = [
            Status::Open,
            Status::Triaged,
            Status::Started,
            Status::Resolved,
            Status::Closed,
        ]
        .iter()
        .map(|s| s.as_str())
        .collect();
        assert_eq!(from_variants, BACKLOG_STATUSES.to_vec());
    }

    #[test]
    fn is_hidden_reuses_status_is_terminal() {
        // the hide-set IS Status::is_terminal over the stringly token (no new set).
        assert!(is_hidden("resolved"));
        assert!(is_hidden("closed"));
        assert!(!is_hidden("open"));
        assert!(!is_hidden("triaged"));
        assert!(!is_hidden("started"));
        // an out-of-vocab token is not hidden (retain is stringly; serde can't store it).
        assert!(!is_hidden("bogus"));
    }

    // --- SL-025 EX-4 / VT-3: backlog show --json ---

    #[test]
    fn backlog_show_json_is_faithful_item_state() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // a fully-assessed risk: facet + relationships + a terminal resolution.
        write_fixture(
            root,
            Fixture {
                kind: ItemKind::Risk,
                id: 1,
                slug: "leak",
                title: "Token leak",
                status: "resolved",
                resolution: "mitigated",
                tags: &["security"],
                facet: Some(FacetLit {
                    likelihood: "high",
                    impact: "critical",
                    origin: "audit",
                    controls: &["rotate"],
                }),
                rels: Some(RelLit {
                    slices: &["SL-020"],
                    specs: &[],
                    needs: &[],
                    after: &[],
                    triggers: &[],
                }),
            },
        );

        let item = read_item(root, ItemKind::Risk, 1).unwrap();
        let json = show_json(&item).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["kind"], "backlog");
        let b = &v["backlog"];
        assert_eq!(b["id"], "RSK-001");
        assert_eq!(b["status"], "resolved");
        assert_eq!(b["resolution"], "mitigated");
        assert_eq!(b["tags"][0], "security");
        assert_eq!(b["facet"]["likelihood"], "high");
        assert_eq!(b["facet"]["impact"], "critical");
        assert_eq!(b["relationships"]["slices"][0], "SL-020");
    }

    // --- PHASE-04: the `backlog show <ID>` inspect verb (id parse + render) ---

    // --- VT-2: id-parse tolerance + both hard-error modes ---

    #[test]
    fn backlog_show_id_parse_tolerance() {
        // `ISS-7` and `ISS-007` both parse to (Issue, 7); case is tolerated.
        assert_eq!(parse_ref("ISS-7").unwrap(), (ItemKind::Issue, 7));
        assert_eq!(parse_ref("ISS-007").unwrap(), (ItemKind::Issue, 7));
        assert_eq!(parse_ref("iss-7").unwrap(), (ItemKind::Issue, 7));
        // each prefix routes to its own kind — the counters are independent.
        assert_eq!(parse_ref("RSK-001").unwrap(), (ItemKind::Risk, 1));
        assert_eq!(parse_ref("IDE-12").unwrap(), (ItemKind::Idea, 12));
    }

    #[test]
    fn backlog_show_unknown_prefix_errors() {
        // an unknown prefix and a non-numeric tail each hard-error (never a create).
        assert!(parse_ref("REQ-001").is_err(), "unknown prefix rejected");
        assert!(parse_ref("ISS-abc").is_err(), "non-numeric tail rejected");
        assert!(
            parse_ref("nodash").is_err(),
            "a ref with no `-` is rejected"
        );
    }

    // --- VT-1: auto-detect kind from prefix; identity + facet + relations render ---

    #[test]
    fn backlog_show_auto_detects_kind_from_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // a plain issue and an assessed risk, both reserved id 1 (independent trees).
        new_item(root, ItemKind::Issue, "Auth bug");
        let issue = read_item(root, ItemKind::Issue, 1).unwrap();
        let issue_out = format_show(&issue);
        assert!(
            issue_out.starts_with("ISS-001 — Auth bug\n"),
            "identity line: {issue_out}"
        );
        assert!(
            issue_out.contains("· issue · open"),
            "flat field line carries kind + status: {issue_out}"
        );
        assert!(
            !issue_out.contains("[facet]"),
            "a plain kind shows no facet block: {issue_out}"
        );

        // an assessed risk (seeded directly) shows its facet axes.
        write_assessed_risk(root, 1);
        let risk = read_item(root, ItemKind::Risk, 1).unwrap();
        let risk_out = format_show(&risk);
        assert!(risk_out.starts_with("RSK-001 — Token expiry\n"));
        assert!(risk_out.contains("[facet]"), "risk shows the facet block");
        assert!(risk_out.contains("likelihood: high"));
        assert!(risk_out.contains("impact: critical"));
        assert!(risk_out.contains("controls: rate-limit"));
    }

    // --- VT-3: outbound relations render; inbound is NOT surfaced (ADR-004) ---

    #[test]
    fn backlog_show_renders_outbound_only() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // ISS-001 points OUT at SL-020; a *separate* item (ISS-002) points AT it.
        write_related(root, ItemKind::Issue, 1, &["SL-020"], &["PRD-009"]);
        write_related(root, ItemKind::Issue, 2, &[], &[]);

        let out = format_show(&read_item(root, ItemKind::Issue, 1).unwrap());
        assert!(out.contains("relationships:"), "the outbound seam renders");
        assert!(out.contains("slices: SL-020"), "outbound slice ref shown");
        assert!(out.contains("specs: PRD-009"), "outbound spec ref shown");

        // an item with no outbound relations renders no relationships block —
        // and the reverse view (who points AT it) is never computed here.
        let bare = format_show(&read_item(root, ItemKind::Issue, 2).unwrap());
        assert!(
            !bare.contains("relationships:"),
            "no outbound relations → no block (inbound never surfaced): {bare}"
        );
    }

    // --- VT-1: the three PRD-009 item→item axes (needs / after / triggers) ---

    #[test]
    fn after_edge_round_trips_with_optional_rank() {
        // a ranked edge keeps its `rank`; a bare `{ to }` defaults to rank 0.
        let rel: Relationships =
            toml::from_str("after = [{ to = \"ISS-002\", rank = 2 }, { to = \"ISS-003\" }]\n")
                .unwrap();
        assert_eq!(
            rel.after,
            vec![
                AfterEdge {
                    to: "ISS-002".to_string(),
                    rank: 2,
                },
                AfterEdge {
                    to: "ISS-003".to_string(),
                    rank: 0,
                },
            ]
        );
    }

    #[test]
    fn trigger_round_trips_with_optional_note() {
        // a noted trigger keeps its `note`; a globs-only `{ globs }` defaults to "".
        let rel: Relationships = toml::from_str(
            "triggers = [{ globs = [\"src/x/**\"], note = \"watch x\" }, \
             { globs = [\"src/y/**\"] }]\n",
        )
        .unwrap();
        assert_eq!(
            rel.triggers,
            vec![
                Trigger {
                    globs: vec!["src/x/**".to_string()],
                    note: "watch x".to_string(),
                },
                Trigger {
                    globs: vec!["src/y/**".to_string()],
                    note: String::new(),
                },
            ]
        );
    }

    #[test]
    fn backlog_show_renders_all_three_item_axes() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // a populated item carrying all three PRD-009 outbound axes.
        write_fixture(
            root,
            Fixture {
                kind: ItemKind::Issue,
                id: 1,
                slug: "s",
                title: "T",
                status: "open",
                resolution: "",
                tags: &[],
                facet: None,
                rels: Some(RelLit {
                    slices: &[],
                    specs: &[],
                    needs: &["ISS-002"],
                    after: &[AfterLit {
                        to: "ISS-003",
                        rank: 2,
                    }],
                    triggers: &[TriggerLit {
                        globs: &["src/x/**"],
                        note: "watch x",
                    }],
                }),
            },
        );
        let item = read_item(root, ItemKind::Issue, 1).unwrap();

        // table seam: each axis renders, in fixed §5.2 order (needs/after/triggers);
        // a non-zero `after` rank annotates, the trigger note trails its globs.
        let out = format_show(&item);
        assert!(out.contains("needs: ISS-002"), "hard prereq axis: {out}");
        assert!(
            out.contains("after: ISS-003 (rank 2)"),
            "soft seq axis with rank: {out}"
        );
        assert!(
            out.contains("triggers: [src/x/**] watch x"),
            "triggers rider: {out}"
        );

        // JSON seam: needs is a string array; after/triggers are arrays of tables.
        let json = show_json(&item).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let rel = &v["backlog"]["relationships"];
        assert_eq!(rel["needs"][0], "ISS-002");
        assert_eq!(rel["after"][0]["to"], "ISS-003");
        assert_eq!(rel["after"][0]["rank"], 2);
        assert_eq!(rel["triggers"][0]["globs"][0], "src/x/**");
        assert_eq!(rel["triggers"][0]["note"], "watch x");
    }

    /// Overwrite a reserved risk item with an assessed `[facet]` — exercises the
    /// real read+validate path for a populated facet without the (PHASE-05) `edit`.
    fn write_assessed_risk(root: &Path, id: u32) {
        write_fixture(
            root,
            Fixture {
                kind: ItemKind::Risk,
                id,
                slug: "token-expiry",
                title: "Token expiry",
                status: "open",
                resolution: "",
                tags: &[],
                facet: Some(FacetLit {
                    likelihood: "high",
                    impact: "critical",
                    origin: "audit",
                    controls: &["rate-limit"],
                }),
                rels: Some(RelLit {
                    slices: &[],
                    specs: &[],
                    needs: &[],
                    after: &[],
                    triggers: &[],
                }),
            },
        );
    }

    /// Write an item carrying seeded OUTBOUND `slices`/`specs` relations directly.
    fn write_related(root: &Path, kind: ItemKind, id: u32, slices: &[&str], specs: &[&str]) {
        write_fixture(
            root,
            Fixture {
                kind,
                id,
                slug: "s",
                title: "T",
                status: "open",
                resolution: "",
                tags: &[],
                facet: None,
                rels: Some(RelLit {
                    slices,
                    specs,
                    needs: &[],
                    after: &[],
                    triggers: &[],
                }),
            },
        );
    }

    // --- PHASE-05: the `backlog edit` coupled transition ---

    /// Validate one item's on-disk state via the real reader. Panics if absent.
    fn read_back(root: &Path, kind: ItemKind, id: u32) -> BacklogItem {
        read_item(root, kind, id).unwrap()
    }

    // --- VT-1 / VT-2: the coupling + D9, as a pure decision ---

    #[test]
    fn validate_transition_couples_both_directions_and_d9_clears() {
        // a terminal status REQUIRES a resolution (both terminal states).
        assert!(validate_transition(Status::Resolved, None).is_err());
        assert!(validate_transition(Status::Closed, None).is_err());
        // terminal + resolution → that resolution's kebab string.
        assert_eq!(
            validate_transition(Status::Resolved, Some(Resolution::Fixed)).unwrap(),
            "fixed"
        );
        // a non-terminal status FORBIDS a resolution (rejected outright).
        assert!(validate_transition(Status::Started, Some(Resolution::Fixed)).is_err());
        assert!(validate_transition(Status::Open, Some(Resolution::Promoted)).is_err());
        // a non-terminal status with no resolution → D9 auto-clear to "".
        assert_eq!(validate_transition(Status::Open, None).unwrap(), "");
        assert_eq!(validate_transition(Status::Triaged, None).unwrap(), "");
    }

    // --- SL-039 VT-4: exposure = likelihood × impact, baseline otherwise ---

    fn facet(likelihood: Option<RiskLevel>, impact: Option<RiskLevel>) -> RiskFacet {
        RiskFacet {
            likelihood,
            impact,
            origin: None,
            controls: Vec::new(),
        }
    }

    #[test]
    fn exposure_scores_a_fully_assessed_risk() {
        use RiskLevel::{Critical, High, Low};
        assert_eq!(exposure(Some(&facet(Some(High), Some(Critical)))), 12);
        assert_eq!(exposure(Some(&facet(Some(Low), Some(Low)))), 1);
        assert_eq!(exposure(Some(&facet(Some(Critical), Some(Critical)))), 16);
    }

    #[test]
    fn exposure_is_baseline_when_unassessed_or_non_risk() {
        use RiskLevel::High;
        // one axis only → baseline.
        assert_eq!(exposure(Some(&facet(Some(High), None))), 0);
        assert_eq!(exposure(Some(&facet(None, Some(High)))), 0);
        // no axis → baseline.
        assert_eq!(exposure(Some(&facet(None, None))), 0);
        // non-risk item (no facet) → baseline.
        assert_eq!(exposure(None), 0);
    }

    // --- VT-3: edit-preserving (comments/unknowns survive); updated bumps ---

    #[test]
    fn backlog_edit_is_edit_preserving() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth"); // real template: [relationships] subtable
        let path = issue_dir(root, "001").join("backlog-001.toml");

        // hand-add an inert top-level table + a comment (the F-1 corruption hazard the
        // in-place edit must NOT disturb).
        let mut body = fs::read_to_string(&path).unwrap();
        body.push_str("\n# hand note — keep me\n[custom]\nkeep = \"yes\"\n");
        fs::write(&path, &body).unwrap();

        set_backlog_status(
            root,
            ItemKind::Issue,
            1,
            Status::Resolved,
            Some(Resolution::Fixed),
            "2026-07-01",
        )
        .unwrap();

        let after = fs::read_to_string(&path).unwrap();
        assert!(after.contains("# hand note — keep me"), "comment survives");
        assert!(after.contains("[custom]"), "inert table survives verbatim");
        assert!(after.contains("keep = \"yes\""), "unknown key survives");
        assert!(
            after.contains("[relationships]"),
            "seeded subtable survives"
        );
        assert!(after.contains("status = \"resolved\""));
        assert!(after.contains("resolution = \"fixed\""));
        assert!(after.contains("updated = \"2026-07-01\""), "updated bumps");

        // and it still round-trips the reader.
        let item = read_back(root, ItemKind::Issue, 1);
        assert_eq!(item.status, Status::Resolved);
        assert_eq!(item.resolution, Some(Resolution::Fixed));
    }

    // --- VT-3: the no-op guard writes nothing ---

    #[test]
    fn backlog_edit_noop_writes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth"); // status open, resolution ""
        let path = issue_dir(root, "001").join("backlog-001.toml");
        let before = fs::read_to_string(&path).unwrap();
        let mtime_before = fs::metadata(&path).unwrap().modified().unwrap();

        // re-open an already-open item (status open, no resolution) → no-op.
        let written =
            set_backlog_status(root, ItemKind::Issue, 1, Status::Open, None, "2026-07-01").unwrap();
        assert_eq!(
            written, "",
            "the no-op still reports the resolved (empty) state"
        );

        assert_eq!(
            before,
            fs::read_to_string(&path).unwrap(),
            "a no-op writes nothing — content byte-identical"
        );
        assert_eq!(
            mtime_before,
            fs::metadata(&path).unwrap().modified().unwrap(),
            "a no-op leaves mtime untouched"
        );
    }

    // --- VT-3: a malformed item (missing a seeded key) is refused, not corrupted ---

    #[test]
    fn backlog_edit_refuses_malformed_missing_seeded_key() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // hand-corrupted: the seeded `resolution` key is gone.
        let d = root.join(ItemKind::Issue.kind().dir).join("001");
        fs::create_dir_all(&d).unwrap();
        let malformed = "id = 1\nslug = \"a\"\ntitle = \"A\"\nkind = \"issue\"\n\
             status = \"open\"\ncreated = \"2026-06-08\"\nupdated = \"2026-06-08\"\ntags = []\n";
        let path = d.join("backlog-001.toml");
        fs::write(&path, malformed).unwrap();

        let err = set_backlog_status(
            root,
            ItemKind::Issue,
            1,
            Status::Resolved,
            Some(Resolution::Fixed),
            "2026-07-01",
        );
        assert!(err.is_err(), "a missing seeded key is refused");
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            malformed,
            "the file is untouched — never tail-inserted into corruption"
        );
    }

    // --- VT-3: a missing id hard-errors, never an implicit create ---

    #[test]
    fn backlog_edit_missing_id_hard_errors() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let err = set_backlog_status(
            root,
            ItemKind::Issue,
            99,
            Status::Started,
            None,
            "2026-07-01",
        );
        assert!(err.is_err(), "editing a nonexistent id errors");
        assert!(
            !issue_dir(root, "099").exists(),
            "the failed edit creates nothing"
        );
    }

    // --- VT-2: re-open auto-clears the resolution (D9); promoted is ungated ---

    #[test]
    fn backlog_edit_reopen_auto_clears_resolution() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth");

        // resolve it.
        set_backlog_status(
            root,
            ItemKind::Issue,
            1,
            Status::Resolved,
            Some(Resolution::Fixed),
            "2026-07-01",
        )
        .unwrap();
        let resolved = read_back(root, ItemKind::Issue, 1);
        assert_eq!(resolved.status, Status::Resolved);
        assert_eq!(resolved.resolution, Some(Resolution::Fixed));

        // re-open (no --resolution) → D9 clears the resolution; the invariant holds.
        set_backlog_status(root, ItemKind::Issue, 1, Status::Open, None, "2026-07-02").unwrap();
        let reopened = read_back(root, ItemKind::Issue, 1);
        assert_eq!(reopened.status, Status::Open);
        assert_eq!(reopened.resolution, None, "D9: re-open clears resolution");

        // a `promoted` item is hand-re-openable (ungated — the OQ-003 escape hatch).
        set_backlog_status(
            root,
            ItemKind::Issue,
            1,
            Status::Closed,
            Some(Resolution::Promoted),
            "2026-07-03",
        )
        .unwrap();
        set_backlog_status(root, ItemKind::Issue, 1, Status::Open, None, "2026-07-04").unwrap();
        let after = read_back(root, ItemKind::Issue, 1);
        assert_eq!(after.status, Status::Open);
        assert_eq!(after.resolution, None, "a promoted item re-opens ungated");
    }

    // --- VT-5: non-canon status/resolution rejected at the clap ValueEnum boundary ---

    #[test]
    fn backlog_edit_rejects_noncanon_status_and_resolution() {
        use clap::ValueEnum;
        assert!(Status::from_str("bogus", false).is_err());
        assert!(Resolution::from_str("nope", false).is_err());
        // the canon tokens (kebab) still parse — the lifecycle stays otherwise ungated.
        assert_eq!(Status::from_str("started", false).unwrap(), Status::Started);
        assert_eq!(
            Resolution::from_str("wont-do", false).unwrap(),
            Resolution::WontDo
        );
    }

    // --- VT-1: coupling both directions + missing id, through the real shell ---

    #[test]
    fn run_edit_drives_the_coupled_transition() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Risk, "Token leak");

        // a terminal status without a resolution is rejected through the shell.
        assert!(run_edit(Some(root.to_path_buf()), "RSK-001", Status::Resolved, None).is_err());
        // a valid terminal+resolution is accepted.
        run_edit(
            Some(root.to_path_buf()),
            "RSK-001",
            Status::Resolved,
            Some(Resolution::Mitigated),
        )
        .unwrap();
        let item = read_back(root, ItemKind::Risk, 1);
        assert_eq!(item.status, Status::Resolved);
        assert_eq!(item.resolution, Some(Resolution::Mitigated));

        // a missing id hard-errors through the shell (never an implicit create).
        assert!(run_edit(Some(root.to_path_buf()), "RSK-099", Status::Started, None).is_err());
    }

    // --- PHASE-03 T1: the ordering projection (project) ---

    /// Seed one item carrying outbound `needs`/`after` axes (the `project` input).
    fn write_rel_item(
        root: &Path,
        kind: ItemKind,
        id: u32,
        status: &str,
        needs: &[&str],
        after: &[AfterLit<'_>],
    ) {
        write_fixture(
            root,
            Fixture {
                kind,
                id,
                slug: "s",
                title: "T",
                status,
                resolution: if matches!(status, "resolved" | "closed") {
                    "done"
                } else {
                    ""
                },
                tags: &[],
                facet: None,
                rels: Some(RelLit {
                    slices: &[],
                    specs: &[],
                    needs,
                    after,
                    triggers: &[],
                }),
            },
        );
    }

    /// The rendered canonical ids of a built order, in composed order.
    fn ordered_ids(inputs: &[OrderInput]) -> Vec<String> {
        BacklogOrder::build(inputs)
            .unwrap()
            .ordered()
            .iter()
            .map(|id| id.render())
            .collect()
    }

    #[test]
    fn project_keeps_non_terminal_nodes_only() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_rel_item(root, ItemKind::Issue, 1, "open", &[], &[]);
        write_rel_item(root, ItemKind::Issue, 2, "resolved", &[], &[]);
        write_rel_item(root, ItemKind::Issue, 3, "closed", &[], &[]);
        write_rel_item(root, ItemKind::Issue, 4, "started", &[], &[]);

        let (inputs, absent) = project(&read_all(root).unwrap());
        assert!(absent.is_empty());
        // only the two non-terminal items (open, started) survive as nodes.
        let mut ids = ordered_ids(&inputs);
        ids.sort();
        assert_eq!(ids, vec!["ISS-001", "ISS-004"]);
    }

    #[test]
    fn project_wires_a_hard_needs_edge_into_the_order() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // ISS-001 needs ISS-002 ⇒ B(002) must precede A(001).
        write_rel_item(root, ItemKind::Issue, 1, "open", &["ISS-002"], &[]);
        write_rel_item(root, ItemKind::Issue, 2, "open", &[], &[]);

        let (inputs, _) = project(&read_all(root).unwrap());
        assert_eq!(ordered_ids(&inputs), vec!["ISS-002", "ISS-001"]);
    }

    #[test]
    fn project_honours_a_cross_kind_after_edge_with_rank() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // a cross-kind soft edge: CHR-001 after RSK-001 ⇒ RSK-001 precedes CHR-001.
        write_rel_item(
            root,
            ItemKind::Chore,
            1,
            "open",
            &[],
            &[AfterLit {
                to: "RSK-001",
                rank: 3,
            }],
        );
        write_rel_item(root, ItemKind::Risk, 1, "open", &[], &[]);

        let (inputs, absent) = project(&read_all(root).unwrap());
        assert!(absent.is_empty(), "both endpoints are live nodes");
        assert_eq!(ordered_ids(&inputs), vec!["RSK-001", "CHR-001"]);
    }

    #[test]
    fn project_records_an_unparseable_ref_as_an_absent_drop() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // a stale/garbage ref that cannot even parse to (kind, id).
        write_rel_item(root, ItemKind::Issue, 1, "open", &["NOPE-1"], &[]);

        let (inputs, absent) = project(&read_all(root).unwrap());
        assert_eq!(
            absent.len(),
            1,
            "the unparseable ref is recorded, not silent"
        );
        assert_eq!(absent[0].from().render(), "ISS-001");
        assert_eq!(absent[0].reference(), "NOPE-1");
        // the node itself still orders (the bad edge just contributes nothing).
        assert_eq!(ordered_ids(&inputs), vec!["ISS-001"]);
    }

    #[test]
    fn project_emits_distinct_item_ids_one_row_per_item() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_rel_item(root, ItemKind::Issue, 1, "open", &[], &[]);
        write_rel_item(root, ItemKind::Risk, 1, "open", &[], &[]);

        let (inputs, _) = project(&read_all(root).unwrap());
        // A-distinct/DD4: the bimap precondition — strictly distinct ItemIds. ISS-001
        // and RSK-001 share a numeric id but differ by kind, so both survive as rows
        // and the build never overwrites a node (would panic/corrupt otherwise).
        assert_eq!(ordered_ids(&inputs).len(), 2);
        assert!(BacklogOrder::build(&inputs).is_ok());
    }

    // --- PHASE-03 T2: edit-preserving relationship-array append ---

    #[test]
    fn append_needs_preserves_comments_and_inert_tables() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth"); // real template: seeded [relationships]
        let path = issue_dir(root, "001").join("backlog-001.toml");

        // hand-add an inert table + a comment (the F-1 corruption hazard).
        let mut body = fs::read_to_string(&path).unwrap();
        body.push_str("\n# hand note — keep me\n[custom]\nkeep = \"yes\"\n");
        fs::write(&path, &body).unwrap();

        append_relationship(
            root,
            ItemKind::Issue,
            1,
            &RelEdit::Needs(&["ISS-002".to_string(), "RSK-001".to_string()]),
        )
        .unwrap();

        let after = fs::read_to_string(&path).unwrap();
        assert!(after.contains("# hand note — keep me"), "comment survives");
        assert!(after.contains("[custom]"), "inert table survives");
        assert!(after.contains("keep = \"yes\""), "unknown key survives");

        // the reader sees both new prereqs on the live axis.
        let item = read_item(root, ItemKind::Issue, 1).unwrap();
        assert_eq!(item.relationships.needs, vec!["ISS-002", "RSK-001"]);
    }

    #[test]
    fn append_after_round_trips_to_and_rank() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth");

        append_relationship(
            root,
            ItemKind::Issue,
            1,
            &RelEdit::After {
                to: "ISS-002",
                rank: 5,
            },
        )
        .unwrap();

        let item = read_item(root, ItemKind::Issue, 1).unwrap();
        assert_eq!(
            item.relationships.after,
            vec![AfterEdge {
                to: "ISS-002".to_string(),
                rank: 5,
            }]
        );
    }

    #[test]
    fn append_relationship_is_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth");
        let path = issue_dir(root, "001").join("backlog-001.toml");

        append_relationship(
            root,
            ItemKind::Issue,
            1,
            &RelEdit::Needs(&["ISS-002".to_string()]),
        )
        .unwrap();
        let once = fs::read_to_string(&path).unwrap();

        // a second identical append is a no-op — byte-identical, never duplicated.
        append_relationship(
            root,
            ItemKind::Issue,
            1,
            &RelEdit::Needs(&["ISS-002".to_string()]),
        )
        .unwrap();
        assert_eq!(
            once,
            fs::read_to_string(&path).unwrap(),
            "idempotent append"
        );

        let item = read_item(root, ItemKind::Issue, 1).unwrap();
        assert_eq!(item.relationships.needs, vec!["ISS-002"], "not duplicated");
    }

    #[test]
    fn append_relationship_refuses_a_malformed_missing_array() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // hand-corrupted: a `[relationships]` table that omits the seeded `needs` array.
        let d = root.join(ItemKind::Issue.kind().dir).join("001");
        fs::create_dir_all(&d).unwrap();
        let malformed = "id = 1\nslug = \"a\"\ntitle = \"A\"\nkind = \"issue\"\n\
             status = \"open\"\nresolution = \"\"\ncreated = \"2026-06-08\"\n\
             updated = \"2026-06-08\"\ntags = []\n\n[relationships]\nslices = []\n";
        let path = d.join("backlog-001.toml");
        fs::write(&path, malformed).unwrap();

        let err = append_relationship(
            root,
            ItemKind::Issue,
            1,
            &RelEdit::Needs(&["ISS-002".to_string()]),
        );
        assert!(err.is_err(), "a missing seeded array is refused");
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            malformed,
            "the file is untouched on refuse"
        );
    }

    // --- PHASE-03 T3: `run_needs` shell (VT-5 set-refuse) ---

    #[test]
    fn run_needs_appends_a_validated_prereq() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth"); // ISS-001
        new_item(root, ItemKind::Issue, "Login"); // ISS-002

        run_needs(
            Some(root.to_path_buf()),
            "ISS-001",
            &["ISS-002".to_string()],
        )
        .unwrap();

        let item = read_item(root, ItemKind::Issue, 1).unwrap();
        assert_eq!(item.relationships.needs, vec!["ISS-002"]);
    }

    #[test]
    fn run_needs_rejects_a_missing_prereq_ref() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth"); // ISS-001 only
        let path = issue_dir(root, "001").join("backlog-001.toml");
        let before = fs::read_to_string(&path).unwrap();

        // ISS-099 does not exist — a hard user error, nothing written.
        let err = run_needs(
            Some(root.to_path_buf()),
            "ISS-001",
            &["ISS-099".to_string()],
        );
        assert!(
            err.is_err(),
            "a missing prereq ref is rejected at author time"
        );
        assert_eq!(
            before,
            fs::read_to_string(&path).unwrap(),
            "nothing written"
        );
    }

    #[test]
    fn run_needs_refuses_a_closing_cycle_naming_members_nothing_written() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // VT-5: seed A.needs=[B]; `needs B A` would close the {A,B} cycle.
        write_rel_item(root, ItemKind::Issue, 1, "open", &["ISS-002"], &[]); // A=001 needs B=002
        write_rel_item(root, ItemKind::Issue, 2, "open", &[], &[]); // B=002
        let path_b = issue_dir(root, "002").join("backlog-002.toml");
        let before_b = fs::read_to_string(&path_b).unwrap();

        let err = run_needs(
            Some(root.to_path_buf()),
            "ISS-002",
            &["ISS-001".to_string()],
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("cycle"), "the refuse names the failure: {msg}");
        assert!(
            msg.contains("ISS-001") && msg.contains("ISS-002"),
            "names members: {msg}"
        );

        // nothing written — B's file is byte-identical.
        assert_eq!(
            before_b,
            fs::read_to_string(&path_b).unwrap(),
            "nothing written on refuse"
        );
    }

    // --- PHASE-03 T4: `run_after` shell (soft — never rejects a cycle) ---

    #[test]
    fn run_after_appends_one_edge_with_default_rank_zero() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth"); // ISS-001
        new_item(root, ItemKind::Issue, "Login"); // ISS-002

        run_after(Some(root.to_path_buf()), "ISS-001", "ISS-002", 0).unwrap();

        let item = read_item(root, ItemKind::Issue, 1).unwrap();
        assert_eq!(
            item.relationships.after,
            vec![AfterEdge {
                to: "ISS-002".to_string(),
                rank: 0,
            }]
        );
    }

    #[test]
    fn run_after_never_rejects_a_soft_cycle() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // X.after=[Y] already; `after X Y`-style reciprocal would cycle — but `after`
        // is soft, so it is ACCEPTED (the eviction surfaces at order time, VT-6).
        write_rel_item(
            root,
            ItemKind::Issue,
            1,
            "open",
            &[],
            &[AfterLit {
                to: "ISS-002",
                rank: 1,
            }],
        );
        write_rel_item(root, ItemKind::Issue, 2, "open", &[], &[]);

        // close the reciprocal soft edge Y.after=[X] — must NOT be rejected.
        run_after(Some(root.to_path_buf()), "ISS-002", "ISS-001", 5).unwrap();
        let item = read_item(root, ItemKind::Issue, 2).unwrap();
        assert_eq!(
            item.relationships.after,
            vec![AfterEdge {
                to: "ISS-001".to_string(),
                rank: 5,
            }]
        );
    }

    // --- SL-067 PHASE-01: the `backlog tag` verb + the normalise/filter folds ---

    fn item_path(root: &Path, kind: ItemKind, id: u32) -> PathBuf {
        let name = format!("{id:03}");
        root.join(kind.kind().dir)
            .join(&name)
            .join(format!("backlog-{name}.toml"))
    }

    fn s(xs: &[&str]) -> Vec<String> {
        xs.iter().map(|x| (*x).to_string()).collect()
    }

    /// VT-1: round-trip e2e — add surfaces via the (folded) `-t` filter, remove drops it.
    #[test]
    fn run_tag_round_trips_add_filter_remove() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth"); // ISS-001, tags = []

        run_tag(Some(root.to_path_buf()), "ISS-001", &s(&["a", "b"]), &[]).unwrap();
        assert_eq!(
            read_item(root, ItemKind::Issue, 1).unwrap().tags,
            s(&["a", "b"])
        );

        // surfaces under the tag filter (input folded → exact-match the store).
        let json = list_id(
            root,
            None,
            ListArgs {
                json: true,
                tags: s(&["a"]),
                ..ListArgs::default()
            },
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(
            v["rows"].as_array().unwrap().len(),
            1,
            "tag filter matches: {json}"
        );

        run_tag(Some(root.to_path_buf()), "ISS-001", &[], &s(&["a"])).unwrap();
        assert_eq!(read_item(root, ItemKind::Issue, 1).unwrap().tags, s(&["b"]));
    }

    /// VT-2: normalisation — case-fold, charset reject naming the token, colon accepted.
    #[test]
    fn run_tag_normalises_and_rejects_bad_charset() {
        assert_eq!(normalize_tag("Security").unwrap(), "security");
        assert_eq!(normalize_tag("  Area:Backlog ").unwrap(), "area:backlog");
        // colon namespacing accepted; underscore/hyphen/digits accepted.
        assert_eq!(normalize_tag("a_b-1:c").unwrap(), "a_b-1:c");

        for bad in ["a b", "a@b"] {
            let err = normalize_tag(bad).unwrap_err().to_string();
            assert!(
                err.contains(bad),
                "the reject names the offending token: {err}"
            );
        }
        assert!(
            normalize_tag("   ").is_err(),
            "empty-after-trim is rejected"
        );

        // The verb routes adds through the chokepoint — a bad add hard-errors.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth");
        let path = item_path(root, ItemKind::Issue, 1);
        let before = fs::read_to_string(&path).unwrap();
        assert!(run_tag(Some(root.to_path_buf()), "ISS-001", &s(&["a@b"]), &[]).is_err());
        assert_eq!(
            before,
            fs::read_to_string(&path).unwrap(),
            "rejected before any write"
        );

        // A `Security` add lands lowercased.
        run_tag(Some(root.to_path_buf()), "ISS-001", &s(&["Security"]), &[]).unwrap();
        assert_eq!(
            read_item(root, ItemKind::Issue, 1).unwrap().tags,
            s(&["security"])
        );
    }

    /// VT-3: idempotency — re-add present / remove absent are no-ops (mtime unchanged,
    /// proven against an UNSORTED hand store); add∩remove overlap is rejected.
    #[test]
    fn run_tag_idempotent_no_op_holds_mtime_on_unsorted_store() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // Hand-author an UNSORTED store: tags = ["b", "a"]. The set is already {a,b}.
        fs::create_dir_all(item_path(root, ItemKind::Issue, 1).parent().unwrap()).unwrap();
        let toml = "id = 1\nslug = \"a\"\ntitle = \"A\"\nkind = \"issue\"\n\
             status = \"open\"\nresolution = \"\"\ncreated = \"2026-06-08\"\n\
             updated = \"2026-06-08\"\ntags = [\"b\", \"a\"]\n";
        let path = item_path(root, ItemKind::Issue, 1);
        fs::write(&path, toml).unwrap();
        let before = fs::read_to_string(&path).unwrap();
        let mtime0 = fs::metadata(&path).unwrap().modified().unwrap();

        // Re-add a present tag (set already {a,b}) — set-compare no-op, NO write+stamp.
        run_tag(Some(root.to_path_buf()), "ISS-001", &s(&["a"]), &[]).unwrap();
        assert_eq!(
            before,
            fs::read_to_string(&path).unwrap(),
            "no-op: content held"
        );
        assert_eq!(
            mtime0,
            fs::metadata(&path).unwrap().modified().unwrap(),
            "mtime held"
        );

        // Remove an absent tag — also a no-op.
        run_tag(Some(root.to_path_buf()), "ISS-001", &[], &s(&["zzz"])).unwrap();
        assert_eq!(
            before,
            fs::read_to_string(&path).unwrap(),
            "remove-absent no-op"
        );

        // add∩remove overlap (after normalisation) is rejected, nothing written.
        let err = run_tag(Some(root.to_path_buf()), "ISS-001", &s(&["X"]), &s(&["x"]));
        assert!(err.is_err(), "an add∩remove overlap is rejected");
        assert_eq!(
            before,
            fs::read_to_string(&path).unwrap(),
            "nothing written on reject"
        );
    }

    /// VT-3 (no-input): neither an add nor a remove is a hard error.
    #[test]
    fn run_tag_requires_at_least_one_edit() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        new_item(root, ItemKind::Issue, "Auth");
        assert!(run_tag(Some(root.to_path_buf()), "ISS-001", &[], &[]).is_err());
    }

    /// VT-4: `list --json` — untagged emits `[]`, tagged emits its array unconditionally.
    #[test]
    fn run_tag_json_projects_tags_unconditionally() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(root, ItemKind::Issue, 1, "open", "", "a", "Alpha", &[]); // untagged
        write_item(
            root,
            ItemKind::Issue,
            2,
            "open",
            "",
            "b",
            "Bravo",
            &["security"],
        );

        let json = list_id(
            root,
            None,
            ListArgs {
                json: true,
                ..ListArgs::default()
            },
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let rows = v["rows"].as_array().unwrap();
        let by_id = |id: &str| {
            rows.iter()
                .find(|r| r["id"] == id)
                .unwrap_or_else(|| panic!("row {id}"))
        };
        // untagged → empty array (present, not omitted, never gated).
        assert_eq!(by_id("ISS-001")["tags"], serde_json::json!([]));
        assert_eq!(by_id("ISS-002")["tags"], serde_json::json!(["security"]));
    }

    /// VT-5: edit-preserving — a comment / inert table / unknown key survive; `updated`
    /// stamped; unrelated keys untouched. And an F-1 missing-`tags` file is refused
    /// byte-unchanged.
    #[test]
    fn run_tag_is_edit_preserving_and_refuses_missing_tags() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        fs::create_dir_all(item_path(root, ItemKind::Issue, 1).parent().unwrap()).unwrap();
        let path = item_path(root, ItemKind::Issue, 1);
        // A hand comment, an inert `[relationships]` table, an unknown key.
        let toml = "# keep me\nid = 1\nslug = \"a\"\ntitle = \"A\"\nkind = \"issue\"\n\
             status = \"open\"\nresolution = \"\"\ncreated = \"2026-06-08\"\n\
             updated = \"2026-06-08\"\ntags = []\nunknown = \"survives\"\n\
             \n[relationships]\nneeds = []\n";
        fs::write(&path, toml).unwrap();

        run_tag(Some(root.to_path_buf()), "ISS-001", &s(&["security"]), &[]).unwrap();
        let after = fs::read_to_string(&path).unwrap();
        assert!(after.contains("# keep me"), "comment survives: {after}");
        assert!(
            after.contains("unknown = \"survives\""),
            "unknown key survives"
        );
        assert!(after.contains("[relationships]"), "inert table survives");
        assert!(
            after.contains("tags = [\"security\"]"),
            "tag written: {after}"
        );
        assert!(
            !after.contains("updated = \"2026-06-08\""),
            "updated stamped"
        );

        // F-1: a file with NO `tags` key is refused byte-unchanged.
        fs::create_dir_all(item_path(root, ItemKind::Issue, 2).parent().unwrap()).unwrap();
        let path2 = item_path(root, ItemKind::Issue, 2);
        let no_tags = "id = 2\nslug = \"b\"\ntitle = \"B\"\nkind = \"issue\"\n\
             status = \"open\"\nresolution = \"\"\ncreated = \"2026-06-08\"\n\
             updated = \"2026-06-08\"\n";
        fs::write(&path2, no_tags).unwrap();
        let err = run_tag(Some(root.to_path_buf()), "ISS-002", &s(&["x"]), &[]);
        assert!(err.is_err(), "a missing seeded `tags` array is refused");
        assert_eq!(
            no_tags,
            fs::read_to_string(&path2).unwrap(),
            "refused byte-unchanged"
        );
    }

    /// EX-5: the filter fold is LENIENT — a mixed-case / surrounding-space input never
    /// errors and round-trips the store; a no-match input succeeds silently.
    #[test]
    fn filter_fold_is_lenient_and_distinct_from_write_normalise() {
        assert_eq!(fold_filter_tag("  Security "), "security");
        // The lenient fold accepts what the write chokepoint rejects (no bail).
        assert_eq!(fold_filter_tag("a b"), "a b");

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        write_item(
            root,
            ItemKind::Issue,
            1,
            "open",
            "",
            "a",
            "Alpha",
            &["security"],
        );
        // `-t Security` (mixed case) folds to `security` and matches the store.
        let hit = list_id(
            root,
            None,
            ListArgs {
                json: true,
                tags: s(&["Security"]),
                ..ListArgs::default()
            },
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&hit).unwrap();
        assert_eq!(
            v["rows"].as_array().unwrap().len(),
            1,
            "case-folded filter hits"
        );
        // A no-match input succeeds silently (zero rows, no error).
        let miss = list_id(
            root,
            None,
            ListArgs {
                json: true,
                tags: s(&["nomatch at all"]),
                ..ListArgs::default()
            },
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&miss).unwrap();
        assert_eq!(
            v["rows"].as_array().unwrap().len(),
            0,
            "no-match filter is silent"
        );
    }

    // --- SL-051: the composed `backlog list --by sequence` (the folded-in order) ---

    /// Drive `list_rows` in the default `--by sequence` mode, returning `(stdout,
    /// stderr)` — the SL-051 tuple shape (rows + footer on stdout, the cycle advisory
    /// on stderr).
    fn list_seq(root: &Path, args: ListArgs) -> (String, String) {
        let out = list_rows(root, None, OrderBy::Sequence, args).unwrap();
        (out.stdout, out.stderr)
    }

    /// The composed-order ids from a `--by sequence` stdout (before the `overrides:`
    /// honest-record footer). Reuses [`ids`] over just the table half.
    fn seq_ids(out: &str) -> Vec<String> {
        let table = out.split("\noverrides:").next().unwrap_or(out);
        ids(table)
    }

    #[test]
    fn list_sequence_composes_a_hard_needs_order() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // ISS-001 needs ISS-002 ⇒ ISS-002 must precede ISS-001 in the order.
        write_rel_item(root, ItemKind::Issue, 1, "open", &["ISS-002"], &[]);
        write_rel_item(root, ItemKind::Issue, 2, "open", &[], &[]);

        let (out, err) = list_seq(root, list_args());
        assert_eq!(
            seq_ids(&out),
            vec!["ISS-002", "ISS-001"],
            "B precedes A: {out}"
        );
        assert!(!out.contains("overrides:"), "no drops, no footer: {out}");
        assert!(err.is_empty(), "no advisory on a clean compose: {err:?}");
    }

    // --- VT-1: --by sequence vs --by id share membership; differ on order ---

    #[test]
    fn list_sequence_and_id_share_membership_differ_on_order() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // ISS-001 needs ISS-002 — the sequence flips them; the id sort does not.
        write_rel_item(root, ItemKind::Issue, 1, "open", &["ISS-002"], &[]);
        write_rel_item(root, ItemKind::Issue, 2, "open", &[], &[]);
        write_rel_item(root, ItemKind::Issue, 3, "open", &[], &[]);

        let (seq, _) = list_seq(root, list_args());
        let by_id = list_id(root, None, list_args()).unwrap();

        // default sequence: the prerequisite (ISS-002) precedes its dependent (ISS-001);
        // the unconstrained ISS-003 sits where the tie-break (id asc) places it — the
        // key point is 002-before-001, which the plain id sort would NOT produce.
        let seq_order = seq_ids(&seq);
        let pos = |id: &str| seq_order.iter().position(|x| x == id).unwrap();
        assert!(
            pos("ISS-002") < pos("ISS-001"),
            "needs flips 002 ahead of its dependent 001: {seq}"
        );
        // classic id sort: ascending id, unaffected by the dependency.
        assert_eq!(
            ids(&by_id),
            vec!["ISS-001", "ISS-002", "ISS-003"],
            "--by id is plain ascending: {by_id}"
        );
        // A-2: the two orderings are PERMUTATIONS — identical membership sets.
        let mut a = seq_ids(&seq);
        let mut b = ids(&by_id);
        a.sort();
        b.sort();
        assert_eq!(a, b, "sequence and id list the same items, reordered");
    }

    // --- VT-2: a `needs` cycle degrades to the id sort with a stderr advisory ---

    #[test]
    fn compose_degrades_on_a_needs_cycle() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // a mutual needs cycle {ISS-001, ISS-002}.
        write_rel_item(root, ItemKind::Issue, 1, "open", &["ISS-002"], &[]);
        write_rel_item(root, ItemKind::Issue, 2, "open", &["ISS-001"], &[]);

        let corpus = read_all(root).unwrap();
        let Ordering::Degraded { warning, .. } = compose(&corpus).unwrap() else {
            panic!("a needs cycle degrades to Ordering::Degraded");
        };
        assert!(warning.contains("cycle"), "names the failure: {warning}");
        assert!(
            warning.contains("ISS-001") && warning.contains("ISS-002"),
            "names members: {warning}"
        );

        // end to end: `list --by sequence` falls back to the id sort, EXITS 0 (no
        // error), and routes the advisory to stderr — never an empty / misleading list.
        let (out, err) = list_seq(root, list_args());
        assert_eq!(
            ids(&out),
            vec!["ISS-001", "ISS-002"],
            "degrade falls back to the id sort, never empty: {out}"
        );
        assert!(err.contains("cycle"), "the advisory is on stderr: {err}");
    }

    #[test]
    fn list_sequence_evicts_the_lower_rank_edge_of_a_soft_cycle() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // VT-6: X.after=[{to=Y,rank=1}], Y.after=[{to=X,rank=5}] ⇒ the strictly
        // lower-rank edge is evicted. The order is still produced; the eviction is
        // recorded in the stdout footer.
        write_rel_item(
            root,
            ItemKind::Issue,
            1,
            "open",
            &[],
            &[AfterLit {
                to: "ISS-002",
                rank: 1,
            }],
        );
        write_rel_item(
            root,
            ItemKind::Issue,
            2,
            "open",
            &[],
            &[AfterLit {
                to: "ISS-001",
                rank: 5,
            }],
        );

        let (out, _) = list_seq(root, list_args());
        // both nodes still ordered (the cycle was linearized, not refused).
        let mut shown = seq_ids(&out);
        shown.sort();
        assert_eq!(shown, vec!["ISS-001", "ISS-002"]);
        // exactly the soft-cycle eviction is recorded in the footer.
        assert!(
            out.contains("overrides:"),
            "the eviction is recorded: {out}"
        );
        assert!(out.contains("soft cycle"), "named a soft-cycle drop: {out}");
    }

    #[test]
    fn list_sequence_records_terminal_and_absent_drops_with_status_and_resolution() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // VT-7: ISS-001 needs a terminal (CHR-001 closed/wont-do) AND an absent ref.
        write_rel_item(
            root,
            ItemKind::Issue,
            1,
            "open",
            &["CHR-001", "ISS-099"],
            &[],
        );
        // CHR-001 is terminal — closed with a wont-do resolution (abandoned).
        write_item(
            root,
            ItemKind::Chore,
            1,
            "closed",
            "wont-do",
            "drop-me",
            "Dropped chore",
            &[],
        );

        let (out, _) = list_seq(root, list_args());
        // the live node still orders.
        assert_eq!(
            seq_ids(&out),
            vec!["ISS-001"],
            "the live node survives: {out}"
        );
        assert!(out.contains("overrides:"));
        // the terminal dep is named with status+resolution (never silently satisfied).
        assert!(
            out.contains("CHR-001") && out.contains("closed/wont-do"),
            "terminal dep named status/resolution: {out}"
        );
        // the absent ref is named absent.
        assert!(
            out.contains("ISS-099") && out.contains("absent"),
            "absent ref named: {out}"
        );
    }
}