doctrine 0.9.1

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
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
// SPDX-License-Identifier: GPL-3.0-only
//! `doctrine slice` — create, list, and add design-doc siblings to slices,
//! doctrine's unit of change.
//!
//! A slice is a numeric directory under `.doctrine/slice/` holding a sister
//! TOML (structured metadata) and a scaffolded markdown prose body, with a
//! `<id>-<slug>` symlink as a human alias (slices-spec). A design-doc sibling is
//! a single prose `design.md` under an existing slice dir.
//!
//! Both are `entity::Kind` values over one kind-blind engine: the slice is a
//! top-level reserved 2-file-plus-symlink kind, the design doc a non-reserved
//! single-file sub-artefact. This module owns the *slice-specific* parts — the
//! Kinds and their scaffolds, the `Plan` reader, and thin CLI wiring; the
//! kind-agnostic machinery lives in `crate::entity`, and the shared
//! metadata-list substrate (`Meta`, list reader/formatter) in `crate::meta`.

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

use anyhow::Context;

use serde::Serialize;

use crate::conformance::{self, Status};
use crate::dtoml;
use crate::entity::{
    self, Artifact, Fileset, Inputs, Kind, LocalFs, MaterialiseRequest, ScaffoldCtx,
};
use crate::lifecycle::{Transition, classify, crosses_closure_seam};
use crate::listing::{self, Format, ListArgs};
use crate::meta::{self, Meta};
use crate::plan::Plan;
use crate::tomlfmt::toml_string;

use std::str::FromStr;

use clap::Subcommand;

// ---------------------------------------------------------------------------
// Selector types (SL-147 PHASE-01)
// ---------------------------------------------------------------------------

/// The author-declared relationship between a selector and the slice's work.
/// `scope-relevant` = read-relevant (L0); `design-target` = will-touch (L1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, Serialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum SelectorIntent {
    ScopeRelevant,
    DesignTarget,
}

/// One authored `[[selector]]` entry in the slice's TOML — a path|glob
/// annotation carrying an intent and an optional one-line note.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, Serialize)]
pub(crate) struct Selector {
    /// Path or glob string — identity of the selector.
    #[expect(
        clippy::struct_field_names,
        reason = "`selector` is the canonical noun from RFC-004"
    )]
    pub(crate) selector: String,
    pub(crate) intent: SelectorIntent,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub(crate) note: Option<String>,
}

/// Subcommands under `doctrine slice selector`.
#[derive(Subcommand)]
pub(crate) enum SelectorCommand {
    /// Add or update one or more selectors (batch, one shared intent).
    Add {
        /// Slice id, e.g. 147.
        id: u32,

        /// One intent for all selectors in this batch.
        #[arg(long, value_parser = clap::value_parser!(SelectorIntent))]
        intent: SelectorIntent,

        /// Path-or-glob selector strings to add/update.
        globs: Vec<String>,

        /// Optional shared note.
        #[arg(long)]
        note: Option<String>,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Upsert the `note` field on one selector.
    Note {
        /// Slice id.
        id: u32,

        /// The exact selector string to annotate.
        selector: String,

        /// The note text.
        text: String,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// List the selectors for a slice.
    List {
        /// Slice id.
        id: u32,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Remove one or more selectors by exact string match.
    Rm {
        /// Slice id.
        id: u32,

        /// Selector strings to remove.
        globs: Vec<String>,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },
}

// ---------------------------------------------------------------------------
// CLI enum & dispatch (PHASE-03 relocation from main.rs)
// ---------------------------------------------------------------------------

#[derive(Subcommand)]
pub(crate) enum SliceCommand {
    /// Allocate the next id and scaffold a new slice.
    New {
        /// Slice title (prompted for if omitted).
        title: Option<String>,

        /// Explicit slug (default: derived from the title).
        #[arg(long)]
        slug: Option<String>,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Scaffold a design-doc sibling into an existing slice.
    Design {
        /// Slice id to attach the design doc to.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Scaffold an implementation plan (plan.toml + plan.md) into a slice.
    Plan {
        /// Slice id to attach the plan to.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Materialise phase tracking from a slice's plan into the state tree.
    Phases {
        /// Slice id whose plan declares the phases.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Remove orphan tracking whose plan phase is gone (destructive).
        #[arg(long)]
        prune: bool,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Scaffold a durable notes.md scratchpad into a slice (on-demand).
    Notes {
        /// Slice id to attach the notes file to.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Record a phase status transition into its runtime tracking.
    Phase {
        /// Slice id owning the phase.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Canonical phase id, e.g. PHASE-01.
        phase_id: String,

        /// New status.
        #[arg(long)]
        status: crate::state::PhaseStatus,

        /// Optional note appended to the progress log.
        #[arg(long)]
        note: Option<String>,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Classify and write a slice lifecycle transition; prints the move's
    /// classification (advance / back-edge / skip / abandon). Refuses the closure
    /// seam (→ reconcile only from audit, → done only from reconcile) and leaving
    /// a terminal status (done / abandoned).
    Status {
        /// Slice id to transition.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Target lifecycle state.
        state: SliceStatus,

        /// Optional note — surfaced in the transition output, not stored.
        #[arg(long)]
        note: Option<String>,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// List slices by id: id, status, phases, slug, title.
    List {
        #[command(flatten)]
        list: crate::CommonListArgs,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Show one slice: its metadata and scope body (not design/plan/notes).
    Show {
        /// Slice reference — `SL-025` or the bare id `25`.
        reference: String,

        /// Output format.
        #[arg(long, value_parser = Format::from_str, default_value_t = Format::Table)]
        format: Format,

        /// Shorthand for `--format json`.
        #[arg(long)]
        json: bool,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Print the file paths of each slice entity directory.
    Paths {
        /// Slice reference(s) — `SL-025` or the bare id `25`.
        refs: Vec<String>,

        #[arg(short = 't', long)]
        toml: bool,
        #[arg(short = 'm', long)]
        md: bool,
        #[arg(short = 'e', long)]
        entity: bool,
        #[arg(short = 's', long)]
        single: bool,

        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Manage the selector list (path|glob + intent) for a slice.
    Selector {
        #[command(subcommand)]
        command: SelectorCommand,
    },

    /// Cross-check a slice's recorded source deltas against its design-target
    /// selectors: undeclared edits (highest signal), undelivered selectors, and
    /// the conformant paths (each with the selector that matched it). Refuses a
    /// clean diff when the registry is unavailable or incomplete (fail-closed).
    Conformance {
        /// Slice id, e.g. 147.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Manually record one phase's source delta into the slice's arm-neutral
    /// registry — the escape hatch beside the automatic solo phase-binding
    /// (correct a recorded range, or bootstrap a pre-binding slice). `start`/`end`
    /// are resolved to oids, guarded (`start` ancestor of `end`, non-merge `end`),
    /// and `UPSERTed` by phase. Resolves to the PRIMARY tree's registry even from a
    /// linked/coordination worktree.
    RecordDelta {
        /// Slice id owning the phase, e.g. 147.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Canonical phase id, e.g. PHASE-01.
        phase: String,

        /// Commit-ish for HEAD before the phase's code landed.
        #[arg(long)]
        start: String,

        /// Commit-ish for the phase's cumulative code tip (pre-knowledge-record).
        #[arg(long)]
        end: String,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// S3 VT existence/shape gate (SL-170): judge every VT-mode verification
    /// criterion in the slice's `plan.toml` against its structured mandate
    /// (`test_file` / `keywords` / `patterns`). Prints a per-phase verdict
    /// summary and exits non-zero iff any `Fail`; `Uncheckable` and `Waived` are
    /// visible, distinct, and non-halting (INV-4). Reads only the authored
    /// `plan.toml` + the mandated source files — never the disposable phase
    /// sheet (INV-3).
    VerifyVt {
        /// Slice id whose plan VT criteria to gate, e.g. 170.
        #[arg(value_parser = parse_cli_id)]
        id: u32,

        /// Explicit project root (default: auto-detect).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },
}

pub(crate) fn dispatch(cmd: SliceCommand, color: bool) -> anyhow::Result<()> {
    match cmd {
        SliceCommand::New { title, slug, path } => run_new(path, title, slug),
        SliceCommand::Design { id, path } => run_design(path, id),
        SliceCommand::Plan { id, path } => run_plan(path, id),
        SliceCommand::Phases { id, prune, path } => run_phases(path, id, prune),
        SliceCommand::Notes { id, path } => run_notes(path, id),
        SliceCommand::Phase {
            id,
            phase_id,
            status,
            note,
            path,
        } => run_phase(path, id, &phase_id, status, note.as_deref()),
        SliceCommand::Status {
            id,
            state,
            note,
            path,
        } => run_status(path, id, state, note.as_deref()),
        SliceCommand::List { list, path } => run_list(path, list.into_list_args(color)),
        SliceCommand::Show {
            reference,
            format,
            json,
            path,
        } => run_show(path, &reference, if json { Format::Json } else { format }),
        SliceCommand::Paths {
            refs,
            toml,
            md,
            entity,
            single,
            path,
        } => {
            let root = crate::root::find(path, &crate::root::default_markers())?;
            let slice_root = root.join(SLICE_DIR);
            let sel = crate::paths::PathSelection {
                toml,
                md,
                entity,
                single,
            };
            let mut all_lines: Vec<String> = Vec::new();
            for r in &refs {
                let id = parse_ref(r)?;
                let name = format!("{id:03}");
                let entity_dir = slice_root.join(&name);
                let toml_name = format!("slice-{name}.toml");
                let md_name = format!("slice-{name}.md");
                let set = crate::paths::scan_entity_dir(
                    &entity_dir,
                    &entity_dir.join(&toml_name),
                    Some(&entity_dir.join(&md_name)),
                    &root,
                )?;
                let lines = crate::paths::select_paths(&set, &sel)?;
                all_lines.extend(lines);
            }
            write!(io::stdout(), "{}", all_lines.join("\n"))?;
            Ok(())
        }
        SliceCommand::Selector { command } => dispatch_selector(command),
        SliceCommand::Conformance { id, path } => run_conformance(path, id),
        SliceCommand::RecordDelta {
            id,
            phase,
            start,
            end,
            path,
        } => run_record_delta(path, id, &phase, &start, &end),
        SliceCommand::VerifyVt { id, path } => run_verify_vt(path, id),
    }
}

// ---------------------------------------------------------------------------

/// Relative dir of the slice tree inside the project root.
const SLICE_DIR: &str = ".doctrine/slice";

/// The top-level reserved slice kind: toml + md + slug symlink.
pub(crate) const SLICE_KIND: Kind = Kind {
    dir: SLICE_DIR,
    prefix: crate::kinds::SL,
    stem: "slice",
    scaffold: slice_scaffold,
};

/// The non-reserved design-doc sibling: one `design.md` under an existing slice.
const DESIGN_KIND: Kind = Kind {
    dir: SLICE_DIR,
    prefix: crate::kinds::SL,
    stem: "",
    scaffold: design_scaffold,
};

/// The implementation-plan facet: `plan.toml` (authored relational `plan.overview`
/// rows) + `plan.md` (prose) under an existing slice — the first multi-file
/// sub-artefact, on the transactional writer (slice-004 D1/D4).
const PLAN_KIND: Kind = Kind {
    dir: SLICE_DIR,
    prefix: crate::kinds::SL,
    stem: "",
    scaffold: plan_scaffold,
};

/// The durable per-slice notes scratchpad: one `notes.md` under an existing
/// slice (the `design.md` single-file pattern; on-demand, slice-004 D8).
const NOTES_KIND: Kind = Kind {
    dir: SLICE_DIR,
    prefix: crate::kinds::SL,
    stem: "",
    scaffold: notes_scaffold,
};

// ---------------------------------------------------------------------------
// Pure: render, scaffolds, list
// ---------------------------------------------------------------------------

/// Render `slice-<id>.toml` from the embedded template by token substitution.
fn render_toml(id: u32, slug: &str, title: &str, date: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/slice.toml")?
        .replace("{{id}}", &id.to_string())
        .replace("{{slug}}", &toml_string(slug))
        .replace("{{title}}", &toml_string(title))
        .replace("{{date}}", date))
}

/// Render `slice-<id>.md` from the embedded template by token substitution.
fn render_md(title: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/slice.md")?.replace("{{title}}", title))
}

/// Render `design.md` from the embedded template: `{{ref}}` (parent canonical
/// id) + `{{title}}` (parent title) — a design doc has no id/slug of its own.
fn render_design(canonical_id: &str, title: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/design.md")?
        .replace("{{ref}}", canonical_id)
        .replace("{{title}}", title))
}

/// The slice fileset: sister TOML, prose body, and `<id>-<slug>` symlink, all
/// relative to the slice tree root (the symlink sits beside the numeric dir).
fn slice_scaffold(ctx: &ScaffoldCtx<'_>) -> anyhow::Result<Fileset> {
    let id = ctx.id;
    let name = format!("{id:03}");
    Ok(vec![
        Artifact::File {
            rel_path: entity::rel_path(&SLICE_KIND, id, entity::Ext::Toml),
            body: render_toml(id, ctx.slug, ctx.title, ctx.date)?,
        },
        Artifact::File {
            rel_path: entity::rel_path(&SLICE_KIND, id, entity::Ext::Md),
            body: render_md(ctx.title)?,
        },
        Artifact::Symlink {
            rel_path: PathBuf::from(format!("{name}-{}", ctx.slug)),
            target: name,
        },
    ])
}

/// The design-doc fileset: one prose `design.md` under the parent slice dir.
fn design_scaffold(ctx: &ScaffoldCtx<'_>) -> anyhow::Result<Fileset> {
    let (id, canonical) = (ctx.id, ctx.canonical);
    let name = format!("{id:03}");
    Ok(vec![Artifact::File {
        rel_path: PathBuf::from(format!("{name}/design.md")),
        body: render_design(canonical, ctx.title)?,
    }])
}

/// Render `plan.toml` from the template: `{{ref}}` is the parent canonical id.
fn render_plan_toml(canonical_id: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/plan.toml")?.replace("{{ref}}", canonical_id))
}

/// Render `plan.md` from the template: `{{ref}}` + parent `{{title}}`.
fn render_plan_md(canonical_id: &str, title: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/plan.md")?
        .replace("{{ref}}", canonical_id)
        .replace("{{title}}", title))
}

/// The IP fileset: authored `plan.toml` + prose `plan.md` under the slice dir.
fn plan_scaffold(ctx: &ScaffoldCtx<'_>) -> anyhow::Result<Fileset> {
    let (id, canonical) = (ctx.id, ctx.canonical);
    let name = format!("{id:03}");
    Ok(vec![
        Artifact::File {
            rel_path: PathBuf::from(format!("{name}/plan.toml")),
            body: render_plan_toml(canonical)?,
        },
        Artifact::File {
            rel_path: PathBuf::from(format!("{name}/plan.md")),
            body: render_plan_md(canonical, ctx.title)?,
        },
    ])
}

/// Render `notes.md` from the template: `{{ref}}` + parent `{{title}}`.
fn render_notes(canonical_id: &str, title: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/notes.md")?
        .replace("{{ref}}", canonical_id)
        .replace("{{title}}", title))
}

/// The notes fileset: one durable `notes.md` under the parent slice dir.
fn notes_scaffold(ctx: &ScaffoldCtx<'_>) -> anyhow::Result<Fileset> {
    let (id, canonical) = (ctx.id, ctx.canonical);
    let name = format!("{id:03}");
    Ok(vec![Artifact::File {
        rel_path: PathBuf::from(format!("{name}/notes.md")),
        body: render_notes(canonical, ctx.title)?,
    }])
}

// ---------------------------------------------------------------------------
// Imperative: the slice-specific reader (clock lives in crate::clock,
// the shared metadata reader in crate::meta)
// ---------------------------------------------------------------------------

/// Read and validate a slice's authored `plan.toml`.
pub(crate) fn read_plan(slice_root: &Path, id: u32) -> anyhow::Result<Plan> {
    let name = format!("{id:03}");
    let path = slice_root.join(&name).join("plan.toml");
    let text = fs::read_to_string(&path)
        .with_context(|| format!("Plan for slice {name} not found at {}", path.display()))?;
    Plan::parse(&text)
}

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

/// `doctrine slice new`.
pub(crate) fn run_new(
    path: Option<PathBuf>,
    title: Option<String>,
    slug: Option<String>,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let trunk_ids = crate::git::trunk_entity_ids(&root, SLICE_KIND.dir)?;
    let (backend, mut reserved) =
        crate::reserve::backend(&root, SLICE_KIND.prefix, crate::install::prompt_confirm)?;
    let title = crate::input::resolve_title(title)?;
    let slug = crate::input::resolve_slug(&title, slug)?;
    let date = crate::clock::today();
    let out = entity::materialise(
        &SLICE_KIND,
        &*backend,
        &root,
        &MaterialiseRequest::Fresh,
        &Inputs {
            slug: &slug,
            title: &title,
            date: &date,
        },
        &trunk_ids,
        &mut reserved,
    )?;

    let id = out
        .eid
        .numeric_id()
        .context("slice kind must yield a numeric id")?;
    writeln!(io::stdout(), "Created slice {id:03}: {}", out.dir.display())?;
    Ok(())
}

/// `doctrine slice design <id>` — scaffold `design.md` into an existing slice.
pub(crate) fn run_design(path: Option<PathBuf>, id: u32) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let slice_root = root.join(SLICE_DIR);
    // The design doc inherits its parent's title (the only context its template
    // needs); reading it confirms the parent exists before we materialise.
    let meta = meta::read_meta(&slice_root, "slice", id, "SL")?;
    let date = crate::clock::today();
    let out = entity::materialise(
        &DESIGN_KIND,
        &LocalFs,
        &root,
        &MaterialiseRequest::InExisting { id },
        &Inputs {
            slug: "",
            title: &meta.title,
            date: &date,
        },
        &[], // inert for InExisting (trunk ids only affect Fresh allocation)
        &mut entity::local_reserved(), // inert for InExisting (no id allocation)
    )?;

    writeln!(
        io::stdout(),
        "Created design doc: {}",
        out.dir.join("design.md").display()
    )?;
    Ok(())
}

/// `doctrine slice plan <id>` — scaffold `plan.{toml,md}` into an existing slice.
pub(crate) fn run_plan(path: Option<PathBuf>, id: u32) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let slice_root = root.join(SLICE_DIR);
    // Reading the parent confirms it exists and supplies the prose title.
    let meta = meta::read_meta(&slice_root, "slice", id, "SL")?;
    let date = crate::clock::today();
    let out = entity::materialise(
        &PLAN_KIND,
        &LocalFs,
        &root,
        &MaterialiseRequest::InExisting { id },
        &Inputs {
            slug: "",
            title: &meta.title,
            date: &date,
        },
        &[], // inert for InExisting (trunk ids only affect Fresh allocation)
        &mut entity::local_reserved(), // inert for InExisting (no id allocation)
    )?;

    writeln!(
        io::stdout(),
        "Created implementation plan: {}",
        out.dir.join("plan.toml").display()
    )?;
    Ok(())
}

/// `doctrine slice phases <id>` — read the plan and materialise phase tracking
/// into the state tree. Reports plan drift (orphans); `--prune` removes them.
pub(crate) fn run_phases(path: Option<PathBuf>, id: u32, prune: bool) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let slice_root = root.join(SLICE_DIR);
    let plan = read_plan(&slice_root, id)?;
    let report = crate::state::init_phases(&root, id, &plan, prune)?;

    let mut out = io::stdout();
    for phase_id in &report.created {
        writeln!(out, "  materialised {phase_id}")?;
    }
    for phase_id in &report.orphan {
        writeln!(
            out,
            "  orphan       {phase_id} (plan phase gone; --prune to remove)"
        )?;
    }
    for phase_id in &report.pruned {
        writeln!(out, "  pruned       {phase_id}")?;
    }
    if report.created.is_empty() && report.orphan.is_empty() && report.pruned.is_empty() {
        writeln!(out, "Phases up to date.")?;
    }
    Ok(())
}

/// `doctrine slice verify-vt <id>` — the S3 VT existence/shape gate (SL-170).
/// Reads the authored `plan.toml`, judges every VT-mode criterion against its
/// structured mandate via the pure [`crate::vtgate`] core (mandated files read
/// relative to the project root), prints the verdict summary, and exits non-zero
/// iff any `Fail` (INV-4). `Uncheckable` / `Waived` are visible but non-halting.
/// Reads only authored plan + mandated source — never the phase sheet (INV-3).
pub(crate) fn run_verify_vt(path: Option<PathBuf>, id: u32) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let slice_root = root.join(SLICE_DIR);
    let plan = read_plan(&slice_root, id)?;
    // The injected reader resolves each mandated `test_file` against the project
    // root; a missing file reads as `None` → the pure core renders it a `Fail`.
    let read_file = |rel: &str| fs::read_to_string(root.join(rel)).ok();
    let reports = crate::vtgate::check_phases(&plan, &read_file);
    write!(io::stdout(), "{}", crate::vtgate::render_summary(&reports))?;
    if crate::vtgate::has_failure(&reports) {
        #[expect(
            clippy::disallowed_methods,
            reason = "verify-vt forwards its gate verdict as the terminal exit code (INV-4)"
        )]
        {
            std::process::exit(1);
        }
    }
    Ok(())
}

/// `doctrine slice notes <id>` — scaffold a durable `notes.md` into a slice.
pub(crate) fn run_notes(path: Option<PathBuf>, id: u32) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let slice_root = root.join(SLICE_DIR);
    let meta = meta::read_meta(&slice_root, "slice", id, "SL")?;
    let date = crate::clock::today();
    let out = entity::materialise(
        &NOTES_KIND,
        &LocalFs,
        &root,
        &MaterialiseRequest::InExisting { id },
        &Inputs {
            slug: "",
            title: &meta.title,
            date: &date,
        },
        &[], // inert for InExisting (trunk ids only affect Fresh allocation)
        &mut entity::local_reserved(), // inert for InExisting (no id allocation)
    )?;

    writeln!(
        io::stdout(),
        "Created notes: {}",
        out.dir.join("notes.md").display()
    )?;
    Ok(())
}

/// `doctrine slice phase <id> <phase-id> --status <s> [--note …]` — fold a
/// runtime status transition into the phase tracking (the `toml_edit` path).
pub(crate) fn run_phase(
    path: Option<PathBuf>,
    id: u32,
    phase_id: &str,
    status: crate::state::PhaseStatus,
    note: Option<&str>,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let now = crate::clock::now_timestamp()?;
    crate::state::set_phase_status(&root, id, phase_id, status, note, &now)?;
    writeln!(io::stdout(), "Updated {phase_id}: {}", status.as_str())?;
    Ok(())
}

/// `doctrine slice status <id> <state> [--note …]` — classify and write a slice
/// lifecycle transition (SL-028, design §5.2). Reads the current authored status,
/// classifies the move via [`classify`], writes it edit-preservingly, and prints
/// the classification (e.g. `started → audit [advance]`). The `--note` is
/// *surfaced only*, never stored: `slice-NNN.toml` has no progress-log field
/// (storage rule — runtime progress lives under `.doctrine/state/`); a stored
/// rationale would be a new authored field, out of scope (plan Decisions).
pub(crate) fn run_status(
    path: Option<PathBuf>,
    id: u32,
    state: SliceStatus,
    note: Option<&str>,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let slice_root = root.join(SLICE_DIR);
    let from = read_status(&slice_root, id)?;
    let to = state.as_str();
    let kind = classify(&from, to);
    // Reverse close-gate (design §7, D8/D-C9b): the gate lives in this close
    // COMMAND SHELL, not the FSM writer (`set_slice_status`) — keeping the writer
    // focused and isolating the one-way `slice-shell → review-query` coupling
    // (ADR-001: `review` never imports `slice`). It fires ONLY on a closure-seam
    // crossing (`audit→reconcile`, `reconcile→done`); a non-seam transition is
    // never gated. A SOLE seam-crossing caller of `set_slice_status` (this shell)
    // means the gate cannot be bypassed (`set_slice_status_is_the_sole_seam_crosser`
    // pins it). The teeth are HERE in the binary — the `slice status …` refusal —
    // not in skill prose.
    if crosses_closure_seam(&from, to) {
        let blockers = crate::review::unresolved_blockers_for(&root, &canonical_id(id))?;
        if !blockers.is_empty() {
            let listed = blockers
                .iter()
                .map(|b| format!("{}/{}", b.rv, b.finding))
                .collect::<Vec<_>>()
                .join(", ");
            anyhow::bail!(
                "slice {} → {to}: refused — unresolved blocker review finding(s): {listed} \
                 (resolve via `review verify`/`review withdraw`, then retry)",
                canonical_id(id)
            );
        }
    }
    // Closure-gate drift predicate (D-B5/D-B3, REQ-113/FR-006): a SECOND gate
    // BESIDE the blocker scan, firing on the SAME closure seam but SPECIFICALLY on
    // the `reconcile → done` crossing only. It COMPOSES with the blocker gate —
    // either can independently refuse this crossing. Undischarged residual drift on
    // any requirement in the gate set (`covered ∪ declared ∪ reconciled`) refuses.
    if from == "reconcile" && to == "done" {
        let undischarged = undischarged_drift(&root, id)?;
        if !undischarged.is_empty() {
            anyhow::bail!(
                "slice {} → {to}: refused — undischarged residual drift on \
                 requirement(s): {} (reconcile each via an `accept` REC whose evidence \
                 covers the current drift, or resolve the drift, then retry)",
                canonical_id(id),
                undischarged.join(", "),
            );
        }
    }
    // Close-integration gate (PHASE-02, EX-1/EX-2; design §3.1): a THIRD gate
    // BESIDE the blocker scan and the drift predicate, firing ONLY on the
    // `reconcile → done` crossing. It COMPOSES — a separate `if` from the drift
    // block, so any one of the three can independently refuse. Dispatched code
    // that never integrated to trunk fails-closed here, in the binary, not in
    // skill prose. The new in-crate edge is `slice → ledger` (command→leaf,
    // downward — no cycle, ADR-001); `ledger` stays ref-agnostic, so the
    // `"refs/heads/main"` literal and the refusal copy live HERE in the shell.
    if from == "reconcile" && to == "done" {
        let deliver_to = crate::dtoml::load_doctrine_toml(&root)?.dispatch.deliver_to;
        match crate::ledger::trunk_integration(&root, id, &deliver_to)? {
            crate::ledger::TrunkIntegration::NotDispatched
            | crate::ledger::TrunkIntegration::Integrated => {}
            crate::ledger::TrunkIntegration::Blocked(reason) => anyhow::bail!(
                "slice {} → {to}: refused — dispatched code not integrated to trunk: \
                 {reason} (run close step-3a `dispatch sync --integrate`, verify, retry)",
                canonical_id(id)
            ),
        }
    }
    set_slice_status(&slice_root, id, &from, state, &crate::clock::today())?;
    // Advisory conduct posture (F15/F19): the SOURCE state's exit posture —
    // `autonomy` governs advancing *out* of `from`. Never blocks; surfaced only.
    let cfg = load_conduct(&root)?;
    let posture = crate::conduct::resolve(&cfg, &from);
    writeln!(
        io::stdout(),
        "{}",
        status_line(&from, to, kind, posture, note)
    )?;
    Ok(())
}

/// Read the project `doctrine.toml [conduct]` table into a [`conduct::ConductConfig`]
/// — the impure shell seam that keeps `conduct` pure (ADR-001). An absent file
/// falls back to the default config (= baked defaults on resolve); a present file
/// is parsed tolerantly (F9), erroring only on genuinely malformed TOML.
fn load_conduct(root: &Path) -> anyhow::Result<crate::conduct::ConductConfig> {
    Ok(crate::dtoml::load_doctrine_toml(root)?.conduct)
}

/// The `slice status` output line (pure — composed from already-resolved data):
/// `{from} → {to} [{classification}] [{posture}]{ — note}`. The posture is the
/// SOURCE state's exit conduct (F19), advisory only. Factored out so the format
/// is unit-testable without capturing stdout (VT-3).
fn status_line(
    from: &str,
    to: &str,
    kind: Transition,
    posture: crate::conduct::Conduct,
    note: Option<&str>,
) -> String {
    let suffix = note.map(|n| format!("{n}")).unwrap_or_default();
    format!(
        "{from}{to} [{}] [{}]{suffix}",
        transition_label(kind),
        posture.label()
    )
}

/// The lower-case label for a [`Transition`] in the verb's output line.
fn transition_label(kind: Transition) -> &'static str {
    match kind {
        Transition::Advance => "advance",
        Transition::BackEdge => "back-edge",
        Transition::Skip => "skip",
        Transition::Abandon => "abandon",
        Transition::Noop => "no-op",
        Transition::FromTerminal => "from-terminal",
        Transition::SeamBreach => "seam-breach",
    }
}

/// Read the current authored `status` of `slice-NNN.toml` (the `from` of a
/// transition). Distinct from the no-op/scaffold guards in [`set_slice_status`]:
/// this surfaces the value for classification + the output line.
fn read_status(slice_root: &Path, id: u32) -> anyhow::Result<String> {
    let name = format!("{id:03}");
    let path = slice_root.join(&name).join(format!("slice-{name}.toml"));
    let text = fs::read_to_string(&path)
        .with_context(|| format!("slice {name} not found at {}", path.display()))?;
    let doc = text
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| format!("Failed to parse {}", path.display()))?;
    doc.get("status")
        .and_then(toml_edit::Item::as_str)
        .map(str::to_string)
        .with_context(|| format!("malformed slice {name}: missing `status`"))
}

/// Edit-preserving lifecycle transition on one authored `slice-NNN.toml`: gate
/// the move via [`classify`] (refuse `FromTerminal` and `SeamBreach`, F12/F13),
/// then set `status` + stamp `updated`. Mirrors `adr::set_adr_status` — the
/// `toml_edit` in-place mutation preserves the inert `[relationships]` table,
/// comments, and unknown keys (the file is never reserialised); carries the
/// no-op guard and the F-1 malformed refuse. The `from` is supplied by the caller
/// (already read for classification), the date by the shell. Unlike adr's flat
/// any→any setter, this is an *ordered* FSM, so the classification gates the write.
fn set_slice_status(
    slice_root: &Path,
    id: u32,
    from: &str,
    state: SliceStatus,
    today: &str,
) -> anyhow::Result<()> {
    let to = state.as_str();
    let name = format!("{id:03}");

    // Gate before any disk write (design §5.2): refuse leaving a terminal source
    // and the two closure-seam breaches; everything else (advance/back/skip/
    // abandon/no-op) is allowed to write. `to` is in-vocab (the `ValueEnum`).
    match classify(from, to) {
        Transition::FromTerminal => anyhow::bail!(
            "slice {name}: refusing to leave terminal status `{from}` (reopening is deferred)"
        ),
        Transition::SeamBreach => anyhow::bail!(
            "slice {name}: `{to}` is reachable only across the closure seam \
             (→ reconcile from audit, → done from reconcile), not from `{from}`"
        ),
        _ => {}
    }

    // Gate passed; delegate the write-core (no-op guard + F-1 refuse + edit-
    // preserving insert) to the shared authored-TOML seam. The classification above
    // stays in this shell — only the WRITE is shared. Hint preserved verbatim (the
    // behaviour-preservation gate scopes the EX-4 rewording to gov + requirement).
    let path = slice_root.join(&name).join(format!("slice-{name}.toml"));
    let hint = format!(
        "malformed slice {name}: missing `status`/`updated` — restore the missing keys and retry; the file is left untouched"
    );
    crate::dep_seq::set_authored_status(&path, &[("status", to), ("updated", today)], &hint)?;
    Ok(())
}

/// The slice status vocabulary — the authority `validate_statuses` checks
/// `--status` against (A-2, D10) and the `SliceStatus` `ValueEnum` mirrors. The
/// expanded SL-028 FSM vocabulary (`slices-spec.md` § Lifecycle): `{proposed,
/// design, plan, ready, started, audit, reconcile, done, abandoned}` — purely
/// additive over the original six (no `review` state, F11), so existing slices
/// need no migration. It guards READ (filter) input only — the write verb
/// (`set_slice_status`) classifies a move via [`classify`] and refuses the
/// closure seam / a terminal source, but an out-of-vocab *stored* status is
/// tolerated on disk and surfaced with a drift marker, not rejected (§5.5
/// vocabulary-drift invariant); see [`is_drifted`].
pub(crate) const SLICE_STATUSES: &[&str] = &[
    "proposed",
    "design",
    "plan",
    "ready",
    "started",
    "audit",
    "reconcile",
    "done",
    "abandoned",
];

/// The `slice list` hide-set (design §5.3): terminal slices — `done` (reconciled)
/// and `abandoned` (dropped before completion) — no longer govern, so they drop
/// from the default list. `--all` or any explicit `--status` reveals them (handled
/// in `listing::retain`). **Distinct from [`is_terminal_status`]**: the hide-set is
/// a presentation predicate fed only to `retain`; the divergence-terminal set
/// stays `{done}` so an `abandoned` slice with incomplete phases is not false-
/// flagged divergent. The two sets diverge deliberately — see notes / design §5.3.
fn is_hidden(status: &str) -> bool {
    matches!(status, "done" | "abandoned")
}

/// Whether an authored status is *out of vocabulary* (§5.5 vocabulary-drift
/// invariant). The read surface guards its own coherence: write-time enforcement
/// is deferred, so a hand-edited `slice-NNN.toml` may carry an unknown status. Such
/// a status is never hidden (the hide-set lists only known terminals) and renders
/// with a trailing `?` drift marker — DISTINCT from the divergence marker `⚠`
/// ([`is_divergent`]); the two are independent predicates on the same column.
fn is_drifted(status: &str) -> bool {
    !SLICE_STATUSES.contains(&status)
}

/// Whether an authored *slice* lifecycle status is terminal (work is meant to be
/// finished). The single source of the terminal-token set — the deferred slice
/// lifecycle-transition verb reuses this rather than re-hardcoding `"done"`
/// (design D3 / R-F2). v1 set: `{"done"}`; membership is provisional, the
/// predicate shape is not. Lives here, beside `is_divergent` and the future
/// transition verb — slice-authored-status semantics, not phase-runtime state.
/// **Not the list hide-set** ([`is_hidden`]): this feeds `is_divergent` only —
/// adding `abandoned` here would false-flag `⚠` on abandoned-incomplete slices.
fn is_terminal_status(authored: &str) -> bool {
    authored == "done"
}

/// The slice lifecycle status as a clap `ValueEnum` — the `slice status <state>`
/// argument. Mirrors [`SLICE_STATUSES`]; the two are pinned in lockstep by
/// `slice_status_enum_matches_the_vocabulary` (a drift canary, cf. adr's
/// `adr_known_set_matches_variants`). Unlike adr, slice keeps the `&[&str]` const
/// as the read-filter authority too, so this enum is the *write*-path mirror.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum SliceStatus {
    Proposed,
    Design,
    Plan,
    Ready,
    Started,
    Audit,
    Reconcile,
    Done,
    Abandoned,
}

impl SliceStatus {
    fn as_str(self) -> &'static str {
        match self {
            Self::Proposed => "proposed",
            Self::Design => "design",
            Self::Plan => "plan",
            Self::Ready => "ready",
            Self::Started => "started",
            Self::Audit => "audit",
            Self::Reconcile => "reconcile",
            Self::Done => "done",
            Self::Abandoned => "abandoned",
        }
    }
}

/// Whether the authored status and the derived phase rollup disagree (design
/// § 5.5). Conservative: suppressed when tracking is anomalous (corruption is not
/// a lifecycle mismatch) or untracked, and keyed on `is_terminal_status` — never
/// a bare `"done"` literal — so a future terminal synonym stops false-flagging in
/// one place.
fn is_divergent(authored: &str, rollup: Option<&crate::state::PhaseRollup>) -> bool {
    let Some(r) = rollup else { return false };
    if r.anomalies() > 0 {
        return false;
    }
    let terminal = is_terminal_status(authored);
    // marked terminal, work outstanding | work complete, not marked terminal
    (terminal && r.completed < r.total())
        || (!terminal && r.total() > 0 && r.completed == r.total())
}

/// The `phases` cell: `completed/total`, with a `!N` blocked marker and a `?N`
/// anomaly marker appended when non-zero; `—` when untracked.
fn phases_cell(rollup: Option<&crate::state::PhaseRollup>) -> String {
    let Some(r) = rollup else {
        return "".to_string();
    };
    let blocked = if r.blocked > 0 {
        format!(" !{}", r.blocked)
    } else {
        String::new()
    };
    let anomalies = if r.anomalies() > 0 {
        format!(" ?{}", r.anomalies())
    } else {
        String::new()
    };
    format!("{}/{}{blocked}{anomalies}", r.completed, r.total())
}

/// The decorated status cell: the authored status plus, independently, a trailing
/// `?` when out of vocabulary (drift, §5.5) and a trailing ` ⚠` when the authored
/// status and the phase rollup disagree (divergence, §5.5). The two markers are
/// computed by separate predicates ([`is_drifted`] / [`is_divergent`]) and compose
/// — a drifted *and* divergent slice shows both (`bogus? ⚠`). Order is fixed:
/// drift hugs the token, the divergence marker trails.
fn decorated_status(status: &str, rollup: Option<&crate::state::PhaseRollup>) -> String {
    let drift = if is_drifted(status) { "?" } else { "" };
    let divergence = if is_divergent(status, rollup) {
        ""
    } else {
        ""
    };
    format!("{status}{drift}{divergence}")
}

/// The table columns `slice list` can show (`--columns` tokens over the existing
/// row tuple `R = (Meta, Option<PhaseRollup>)`, SL-037 §4). Extractors are
/// non-capturing `fn(&R)->String` (D5): the `?`/`⚠` drift+divergence markers ride
/// the `status` cell *value* via [`decorated_status`], and the `completed/total`
/// rollup rides the `phases` cell via [`phases_cell`] — neither is a separate
/// column or per-kind config (the SL-037 R1 canary: markers absorb as plain
/// cell values). Declaration order is what the unknown-column error lists.
type SliceRowTuple = (Meta, Option<crate::state::PhaseRollup>);

const SLICE_COLUMNS: [listing::Column<SliceRowTuple>; 6] = [
    listing::Column {
        name: "id",
        header: "id",
        cell: |(m, _)| canonical_id(m.id),
        paint: listing::ColumnPaint::Fixed(owo_colors::DynColors::Ansi(
            owo_colors::AnsiColors::Cyan,
        )),
    },
    listing::Column {
        name: "status",
        header: "status",
        cell: |(m, r)| decorated_status(&m.status, r.as_ref()),
        // F-4: hue from the row's RAW `m.status`, NOT the decorated `done ⚠`/`bogus?`
        // cell — matching the emitted cell would drop colour on decorated rows.
        paint: listing::ColumnPaint::ByValue(|(m, _)| listing::status_hue(&m.status)),
    },
    listing::Column {
        name: "phases",
        header: "phases",
        cell: |(_, r)| phases_cell(r.as_ref()),
        paint: listing::ColumnPaint::None,
    },
    listing::Column {
        name: "tags",
        header: "tags",
        cell: |(m, _)| m.tags.join(", "),
        paint: listing::ColumnPaint::PerToken {
            split: |(m, _)| m.tags.clone(),
            render: listing::paint_tag,
        },
    },
    listing::Column {
        name: "slug",
        header: "slug",
        cell: |(m, _)| m.slug.clone(),
        paint: listing::ColumnPaint::None,
    },
    listing::Column {
        name: "title",
        header: "title",
        cell: |(m, _)| m.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.
/// `phases` (the variant axis) stays in the default, between status and title.
const SLICE_DEFAULT: &[&str] = &["id", "status", "phases", "title"];

/// One slice projected to its faithful JSON row (design §5.3 — slice owns its
/// serde shape). `phases` is a STRUCTURED value (`completed`/`total`/`blocked`),
/// NOT the rendered `4/6 !1` cell (OQ-1); `null` when phases are untracked. The
/// `?`/`⚠` table markers are display-only and do not appear here.
#[derive(Debug, Serialize)]
struct SliceRow {
    id: String,
    status: String,
    slug: String,
    title: String,
    tags: Vec<String>,
    phases: Option<PhasesJson>,
}

/// The structured `phases` value for JSON (OQ-1) — the rollup's queryable counts,
/// not its rendered cell.
#[derive(Debug, Serialize)]
struct PhasesJson {
    completed: u32,
    total: u32,
    blocked: u32,
}

/// Project a slice `Meta` to its filterable fields (design §5.2). `canonical` is
/// the prefixed id (`SL-025`) — the regex domain. Slice has no tag write verb, so
/// the tag axis is empty (parity with adr).
fn key(m: &Meta) -> listing::FilterFields {
    listing::FilterFields {
        canonical: canonical_id(m.id),
        slug: m.slug.clone(),
        title: m.title.clone(),
        status: m.status.clone(),
        tags: m.tags.clone(),
    }
}

/// The `SL-025` canonical id for a numeric slice id, via the single id-form
/// authority. `SLICE_KIND.prefix` is the stem (`"SL"`).
fn canonical_id(id: u32) -> String {
    listing::canonical_id(SLICE_KIND.prefix, id)
}

// ---------------------------------------------------------------------------
// Closure-gate drift predicate (D-B5/D-B3, REQ-113/FR-006). The shell resolves
// coverage / RECs / authored status from disk+git (ADR-001 impure half); the
// discharge DECISION is pure over those resolved values. One-way coupling: this
// `slice`-close shell QUERIES `coverage`/`coverage_scan`/`rec`/`requirement`; those
// modules NEVER import `slice` — same direction as the blocker gate's
// `slice-shell → review-query` edge (ADR-001).
// ---------------------------------------------------------------------------

/// Read the authored `[gate].extra_reqs` declaration of slice `id` (the `declared`
/// term of the gate set). Absent `[gate]` table ⇒ `∅` (`#[serde(default)]`). Reads
/// only the toml — no `.md` body needed (cf. `read_slice`).
fn read_gate_extra_reqs(slice_root: &Path, id: u32) -> anyhow::Result<Vec<String>> {
    let name = format!("{id:03}");
    let path = slice_root.join(&name).join(format!("slice-{name}.toml"));
    let text = fs::read_to_string(&path)
        .with_context(|| format!("slice {name} not found at {}", path.display()))?;
    let doc: SliceDoc =
        toml::from_str(&text).with_context(|| format!("Failed to parse {}", path.display()))?;
    Ok(doc.gate.extra_reqs)
}

/// The closure-gate requirement set (D-B5, LOCKED) = `covered ∪ declared ∪
/// reconciled` for the closing slice `id`, sorted + DISTINCT. ADDITIVE by
/// construction — the gate can never check LESS than this union. Impure (reads
/// disk): `covered` from S's own `coverage.toml`, `declared` from `[gate]`,
/// `reconciled` from the `status_delta`s of S's owning RECs (codex finding 3 — you
/// cannot reconcile a req via a REC then dodge its gate by not covering/declaring
/// it).
fn gate_requirement_set(
    root: &Path,
    id: u32,
    owned_recs: &[crate::rec::RecDoc],
) -> anyhow::Result<Vec<String>> {
    let canonical = canonical_id(id);
    let slice_root = root.join(SLICE_DIR);

    let mut set = std::collections::BTreeSet::new();
    // covered — S's OWN coverage.toml, validated to cite only S (R-B4).
    set.extend(crate::coverage_scan::slice_local_covered_reqs(
        root, id, &canonical,
    )?);
    // declared — the authored additive `[gate].extra_reqs`.
    set.extend(read_gate_extra_reqs(&slice_root, id)?);
    // reconciled — every req named in a status_delta of S's owning RECs (passed in
    // by the caller; the corpus is read once per close, not per helper).
    set.extend(
        owned_recs
            .iter()
            .flat_map(|rec| rec.status_delta.iter().map(|d| d.requirement.clone())),
    );
    Ok(set.into_iter().collect())
}

/// The requirements in the closing slice's gate set that carry UNDISCHARGED residual
/// drift (D-B5/D-B3). For each gate req R: compute today's residual drift (authored
/// status vs the composite of its scanned coverage); `Coherent` ⇒ no drift, skip.
/// `Divergent`/`Indeterminate` ⇒ residual drift — EXCUSED iff R's latest
/// owning-slice REC discharges it ([`rec_discharges`]); otherwise R is undischarged.
/// Impure (disk+git resolution); the per-req discharge DECISION is pure.
fn undischarged_drift(root: &Path, id: u32) -> anyhow::Result<Vec<String>> {
    let canonical = canonical_id(id);
    let owned_recs = crate::rec::recs_owned_by(root, &canonical)?;
    let mut undischarged = Vec::new();
    for req in gate_requirement_set(root, id, &owned_recs)? {
        let entries = crate::coverage_scan::scan_coverage(root, &req);
        let composite = crate::coverage::composite(&entries);
        let authored = crate::requirement::load(root, &req)
            .with_context(|| format!("closure gate: requirement {req} not found"))?
            .status;
        // Residual drift: anything but Coherent. Coherent ⇒ nothing to discharge.
        if matches!(
            crate::coverage::drift(authored, &composite),
            crate::coverage::Verdict::Coherent
        ) {
            continue;
        }
        // The CURRENT residual-drift evidence keys feeding R's composite — the keys
        // `scan_coverage` returned, DEDUPED (ISS-006: the corpus double-walks a
        // slice's dir + slug symlink, so a key can recur; do not over-demand).
        let residual_keys = crate::coverage::distinct_keys(entries.into_iter().map(|(e, _)| e.key));
        let latest = latest_owning_rec_for(&owned_recs, &req);
        if !rec_discharges(latest, &req, authored, &residual_keys) {
            undischarged.push(req);
        }
    }
    Ok(undischarged)
}

/// R's LATEST owning-slice REC naming R in a `status_delta` (D-B3 / ADR-004):
/// the on-demand reverse scan — filter the already-read owning RECs to those whose
/// `status_delta` names R, take MAX id ("latest"; REC ids are authored + monotonic).
/// NO stored `req→last_rec` field, NO reverse index (the denormalization ADR-004
/// prevents). `None` ⇒ no owning REC reconciled R, so nothing can discharge it.
fn latest_owning_rec_for<'a>(
    owned_recs: &'a [crate::rec::RecDoc],
    req: &str,
) -> Option<&'a crate::rec::RecDoc> {
    owned_recs
        .iter()
        .filter(|rec| rec.status_delta.iter().any(|d| d.requirement == req))
        .max_by_key(|rec| rec.id)
}

/// The discharge predicate (R-B3, LOCKED — strengthened). PURE over resolved
/// values: residual drift on R is EXCUSED iff R's latest owning-slice REC satisfies
/// ALL THREE clauses —
/// (a) `rec.move == "accept"` (an affirm — not revise/redesign);
/// (b) its `status_delta` **for R** has `to == authored` (R's CURRENT authored
///     status — guards a status edited away-and-back). The delta must name R: a REC
///     may carry deltas for several requirements (hand-authored TOML), so matching
///     on `to` alone would let one requirement's delta discharge ANOTHER's drift.
/// (c) its `evidence_ref` set ⊇ the current residual-drift evidence keys (so fresh
///     contradictory evidence arriving AFTER the REC re-opens drift a stale REC
///     cannot excuse).
/// `None` (no owning REC for R) ⇒ never discharged.
fn rec_discharges(
    latest: Option<&crate::rec::RecDoc>,
    req: &str,
    authored: crate::requirement::ReqStatus,
    residual_keys: &[crate::coverage::CoverageKey],
) -> bool {
    let Some(rec) = latest else { return false };
    // (a) an affirm.
    if rec.rec.r#move != "accept" {
        return false;
    }
    // (b) affirmed FOR R at the value R now holds (the delta must name R, not just
    // carry a coinciding `to` for some other requirement).
    let affirmed_at_current = rec
        .status_delta
        .iter()
        .any(|d| d.requirement == req && d.to == authored.as_str());
    if !affirmed_at_current {
        return false;
    }
    // (c) the REC's evidence ⊇ today's residual evidence keys.
    residual_keys
        .iter()
        .all(|k| rec.evidence_ref.iter().any(|e| e == k))
}

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

/// The `slice list` rows as a string — the compute half of [`run_list`], on the
/// shared spine. `validate_statuses` guards `--status` against the slice vocab
/// (A-2); `listing::build` resolves the filter + format; `retain` applies the
/// hide-set `{done, abandoned}`; slice owns the sort (by id), the phase-rollup join
/// (its variant axis), and the column/JSON projection. The rollup is joined AFTER
/// `retain` — `retain` filters `Meta` alone, so the (impure) state read only runs
/// for the surviving rows.
pub(crate) fn list_rows(root: &Path, mut args: ListArgs) -> anyhow::Result<String> {
    validate_statuses(&args.status, SLICE_STATUSES)?;
    let render = args.render;
    let columns = args.columns.take();
    let (filter, format) = listing::build(args)?;
    let slice_root = root.join(SLICE_DIR);
    let mut metas = listing::retain(
        meta::read_metas(&slice_root, "slice", "SL")?,
        &filter,
        is_hidden,
        key,
    );
    metas.sort_by_key(|m| m.id);
    let rows: Vec<(Meta, Option<crate::state::PhaseRollup>)> = metas
        .into_iter()
        .map(|m| {
            let rollup = crate::state::phase_rollup(root, m.id)?;
            Ok((m, rollup))
        })
        .collect::<anyhow::Result<_>>()?;
    match format {
        Format::Table => {
            let any_tagged = rows.iter().any(|(m, _)| !m.tags.is_empty());
            let effective_default = listing::default_with_tags(SLICE_DEFAULT, any_tagged);
            let sel =
                listing::select_columns(&SLICE_COLUMNS, &effective_default, columns.as_deref())?;
            Ok(listing::render_columns(&rows, &sel, render))
        }
        Format::Json => listing::json_envelope("slice", &json_rows(&rows)),
    }
}

/// Faithful JSON rows (design §5.3) — the prefixed id, the authored list fields,
/// and the structured phase rollup (OQ-1).
fn json_rows(rows: &[(Meta, Option<crate::state::PhaseRollup>)]) -> Vec<SliceRow> {
    rows.iter()
        .map(|(m, rollup)| SliceRow {
            id: canonical_id(m.id),
            status: m.status.clone(),
            slug: m.slug.clone(),
            title: m.title.clone(),
            tags: m.tags.clone(),
            phases: rollup.as_ref().map(|r| PhasesJson {
                completed: r.completed,
                total: r.total(),
                blocked: r.blocked,
            }),
        })
        .collect()
}

/// `doctrine slice list` — the migrated read surface (SL-025): prefixed `SL-` ids
/// and a header, the shared filter flags (`-f/-r/-i/-s/-t/-a` plus
/// `--format/--json`), the `{done, abandoned}` hide-set by default, sorted by id,
/// each row carrying the derived phase rollup (the variant axis).
pub(crate) fn run_list(path: Option<PathBuf>, args: ListArgs) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let mut out = io::stdout();
    write!(out, "{}", list_rows(&root, args)?)?;
    Ok(())
}

// ---------------------------------------------------------------------------
// show — reassemble slice-NNN.toml (as data) + slice-NNN.md (scope body)
// ---------------------------------------------------------------------------

/// The full `slice-NNN.toml` read as data for `show` — `Meta`'s four list fields
/// plus the dates and the `[gate]` table. JSON-faithful; `Meta` ignores the extra
/// keys on the list path, this surfaces them on the inspect path.
///
/// SL-048 PHASE-04 (the cut): the tier-1 relations (`specs`/`requirements`/
/// `supersedes`/`governed_by`) no longer live in a typed `[relationships]` table —
/// they migrated to uniform `[[relation]]` rows, read by `relation::read_block`. The
/// show paths (`relation_edges`/`format_show`/`show_json`) reconstruct them from the
/// raw TOML text, so this struct no longer carries a `relationships` field (slice has
/// no typed tier-2/3 leftovers). `gate` stays typed.
#[derive(Debug, Clone, PartialEq, serde::Deserialize, Serialize)]
struct SliceDoc {
    id: u32,
    slug: String,
    title: String,
    status: String,
    created: String,
    updated: String,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(default)]
    gate: Gate,
    #[serde(default)]
    estimate: Option<crate::estimate::EstimateFacet>,
    #[serde(default)]
    value: Option<crate::value::ValueFacet>,
    /// Selectors — path|glob annotations with intent (SL-147).
    #[serde(default, rename = "selector")]
    selectors: Vec<Selector>,
}

// note: `gate` carries `#[serde(default)]` so a hand-trimmed file with no `[gate]`
// table still parses.

/// The authored `[gate]` table (D-B5): the closure-gate's *declared* requirement
/// term — an additive, risk-calibrated list the slice's own closure gate is
/// answerable for, ON TOP OF its observed coverage. `#[serde(default)]` everywhere
/// so a slice with no `[gate]` table parses to `extra_reqs = ∅` (declared = ∅, the
/// gate still runs on `covered ∪ reconciled`). Authored slice-metadata tier — NOT
/// the observed `coverage.toml`.
#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Deserialize, Serialize)]
struct Gate {
    #[serde(default)]
    extra_reqs: Vec<String>,
}

/// Parse a slice reference — `SL-025`, `sl-25`, or the bare id `25` — to its
/// numeric id. The prefix is optional and case-insensitive; the id may be padded.
pub(crate) fn parse_ref(reference: &str) -> anyhow::Result<u32> {
    crate::governance::parse_entity_ref("SL", "a slice", reference)
}

/// Clap `value_parser` wrapper for [`parse_ref`] — accepts both `SL-NNN` and bare
/// numbers, with a clap-compatible `Result<u32, String>` signature.
fn parse_cli_id(s: &str) -> Result<u32, String> {
    parse_ref(s).map_err(|e| {
        // Strip the anyhow wrapper noise for a clean clap error.
        format!("{e:#}")
    })
}

/// `doctrine slice show <SL-NNN>` — the inspect verb (SL-025 §5.2 show seam).
/// READ-ONLY: resolve the ref, read THAT slice's `slice-NNN.toml` (as data) +
/// `slice-NNN.md` (scope body), render the readable whole (`Table`) or the faithful
/// toml-as-data + body (`Json`). Reassembles **metadata + scope only** —
/// `design.md`/`plan.*`/`notes.md` are distinct artifacts with their own surfaces
/// (A-5), never folded in. No cross-corpus scan.
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 id = parse_ref(reference)?;
    let (doc, toml_text, body) = read_slice(&root.join(SLICE_DIR), id)?;
    // Tier-1 relations now live in `[[relation]]`, read generically (SL-048 PHASE-04).
    let tier1 = crate::relation::tier1_edges(&SLICE_KIND, &toml_text)?;
    // The dep/seq payload axes (`needs`/`after`) live in the typed `[relationships]`
    // table (SL-060), read via the shared leaf off the same `slice-NNN.toml` path. An
    // absent table reads to an empty `DepSeq` (a slice that authors no dep/seq).
    let dep_seq = crate::dep_seq::read(&slice_toml_path(&root.join(SLICE_DIR), id))?;
    let out = match format {
        Format::Table => {
            let cfg = crate::dtoml::load_doctrine_toml(&root)?;
            let posture = crate::conduct::resolve(&cfg.conduct, &doc.status);
            let estimation_unit = crate::estimate::resolve_unit(&cfg.estimation);
            let value_unit = crate::value::resolve_unit(&cfg.value);
            let (lower_pct, upper_pct) = crate::estimate::resolve_confidence(&cfg.estimation)?;
            let facets = crate::facet::EntityFacets {
                estimate: doc.estimate.clone(),
                value: doc.value.clone(),
                risk: None,
                tags: doc.tags.clone(),
            };
            format_show(
                &doc,
                &tier1,
                &dep_seq,
                &body,
                posture,
                &facets,
                &estimation_unit,
                &value_unit,
                lower_pct,
                upper_pct,
            )
        }
        // JSON stays byte-stable — posture is a Table-line addition only (design §5.2).
        Format::Json => show_json(&doc, &tier1, &dep_seq, &body)?,
    };
    write!(io::stdout(), "{out}")?;
    Ok(())
}

/// The on-disk `slice-NNN.toml` metadata path for a slice id under `slice_root`.
/// The single chokepoint the show path and the dep/seq leaf read both key on (DRY).
fn slice_toml_path(slice_root: &Path, id: u32) -> PathBuf {
    let name = format!("{id:03}");
    slice_root.join(&name).join(format!("slice-{name}.toml"))
}

/// Read one slice's `slice-NNN.toml` (as data) and `slice-NNN.md` (scope body)
/// ONLY — never design/plan/notes (A-5). Returns the parsed `SliceDoc`, the raw TOML
/// `text` (so the tier-1 `[[relation]]` block can be read by `relation::read_block` —
/// SL-048 PHASE-04), and the scope body.
fn read_slice(slice_root: &Path, id: u32) -> anyhow::Result<(SliceDoc, String, String)> {
    let name = format!("{id:03}");
    let dir = slice_root.join(&name);
    let toml_path = slice_toml_path(slice_root, id);
    let text = fs::read_to_string(&toml_path)
        .with_context(|| format!("slice {name} not found at {}", toml_path.display()))?;
    let doc: SliceDoc = dtoml::parse_entity_toml(&text, "SL", id)
        .with_context(|| format!("Failed to parse {}", toml_path.display()))?;
    let md_path = dir.join(format!("slice-{name}.md"));
    let body = fs::read_to_string(&md_path)
        .with_context(|| format!("Failed to read {}", md_path.display()))?;
    Ok((doc, text, body))
}

/// The slice's authored outbound relations (SL-046 §5.2 extraction seam). SL-048
/// PHASE-04 (the cut): the tier-1 axes (`specs`/`requirements`/`supersedes`/
/// `governed_by`) now live in uniform `[[relation]]` rows, read generically via
/// `relation::tier1_edges` in canonical [`RELATION_RULES`] order (X1). Slice has NO
/// typed tier-2/3 leftovers, so the tier-1 edges ARE the whole edge set. Reads the
/// raw `slice-NNN.toml` text via the show-path reader (no new TOML parse — cohesion).
pub(crate) fn relation_edges(
    root: &Path,
    id: u32,
) -> anyhow::Result<Vec<crate::relation::RelationEdge>> {
    let (_doc, toml_text, _body) = read_slice(&root.join(SLICE_DIR), id)?;
    crate::relation::tier1_edges(&SLICE_KIND, &toml_text)
}

/// The slice's authored selector strings — the UNION of every intent
/// (`scope-relevant` AND `design-target`), sorted+deduped (SL-147 PHASE-05). The
/// review-prime staleness source-of-truth: every path the slice touches or reads.
/// Mirrors the conformance shell's selector read (`conformance_outcome`) but
/// WITHOUT the design-target filter — staleness cares about the whole declared
/// surface. `root` is the parent tree; the slice subtree is joined internally.
pub(crate) fn selector_paths(root: &Path, id: u32) -> anyhow::Result<Vec<String>> {
    let (doc, _toml, _body) = read_slice(&root.join(SLICE_DIR), id)?;
    let mut set: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for sel in &doc.selectors {
        set.insert(sel.selector.clone());
    }
    Ok(set.into_iter().collect())
}

/// Render the readable whole for `Table` mode: an identity header, the flat
/// fields, the advisory conduct posture line (`resolve(current)`, F15/F19), the
/// non-empty relationship axes, then the scope body verbatim. House style:
/// `Vec<String>` parts joined by `concat` (avoids the `push_str(&format!)`
/// lint). Metadata + scope only (A-5). SL-048 PHASE-04: the tier-1 axes come from
/// `tier1` (read via `read_block`), not a typed `[relationships]` table; the new
/// `governed_by` axis renders only when populated (additive — no current slice
/// authors it, so render output is byte-identical across the migration).
#[expect(
    clippy::too_many_arguments,
    reason = "format_show consolidates all rendering inputs; splitting into a struct adds indirection without reducing coupling"
)]
fn format_show(
    doc: &SliceDoc,
    tier1: &[crate::relation::RelationEdge],
    dep_seq: &crate::dep_seq::DepSeq,
    body: &str,
    posture: crate::conduct::Conduct,
    facets: &crate::facet::EntityFacets,
    estimation_unit: &str,
    value_unit: &str,
    lower_pct: f64,
    upper_pct: f64,
) -> String {
    use crate::relation::{RelationLabel, Role, targets_for, targets_for_role};
    let mut parts: Vec<String> = Vec::new();
    parts.push(format!("{}{}\n", canonical_id(doc.id), doc.title));
    parts.push(format!("{} · {}\n", doc.slug, doc.status));
    // Advisory conduct posture for the current state (F15/F19) — Table only.
    parts.push(format!("conduct: {}\n", posture.label()));
    // Tags — rendered only when non-empty (additive).
    if !doc.tags.is_empty() {
        parts.push(format!("tags: {}\n", doc.tags.join(", ")));
    }
    parts.push(format!(
        "created {} · updated {}\n",
        doc.created, doc.updated
    ));

    // Estimate row — confidence-framed when present (D2). Absent → no row (D3).
    if let Some(ref est) = facets.estimate {
        parts.push(format!(
            "{}\n",
            crate::estimate::display::format_estimate_confidence(
                est,
                lower_pct,
                upper_pct,
                estimation_unit,
            )
        ));
    }

    // Value row — magnitude + resolved unit (D4). Absent → no row (D3).
    if let Some(ref val) = facets.value {
        parts.push(format!(
            "{}\n",
            crate::value::format_value_normal(val, value_unit)
        ));
    }

    // Tier-1 axes in canonical order (supersedes, governed_by, then references per
    // role). Each renders only when non-empty, the block only when any axis is
    // populated. SL-149 PHASE-05: the legacy `specs`/`requirements` axes are gone —
    // the corpus migration rewrote those edges onto `references(implements)` /
    // `references(concerns)`, which render per role, one line each.
    let axes = [
        ("supersedes", targets_for(tier1, RelationLabel::Supersedes)),
        ("governed_by", targets_for(tier1, RelationLabel::GovernedBy)),
        (
            "references(implements)",
            targets_for_role(tier1, RelationLabel::References, Role::Implements),
        ),
        (
            "references(originates_from)",
            targets_for_role(tier1, RelationLabel::References, Role::OriginatesFrom),
        ),
        (
            "references(concerns)",
            targets_for_role(tier1, RelationLabel::References, Role::Concerns),
        ),
    ];
    // The dep/seq payload axes (SL-060) render under the SAME `relationships:` block,
    // after the structural tier-1 axes. `after` edges render `to (rank N)` (rank
    // suffix omitted at the default 0). Each axis (and the whole block) renders only
    // when populated — an unauthored slice's output stays byte-identical (additive).
    let after_line = dep_seq
        .after
        .iter()
        .map(|e| {
            if e.rank == 0 {
                e.to.clone()
            } else {
                format!("{} (rank {})", e.to, e.rank)
            }
        })
        .collect::<Vec<_>>();
    let any_tier1 = axes.iter().any(|(_, refs)| !refs.is_empty());
    let any_dep_seq = !dep_seq.needs.is_empty() || !after_line.is_empty();
    if any_tier1 || any_dep_seq {
        parts.push("\nrelationships:\n".to_string());
        for (label, refs) in &axes {
            if !refs.is_empty() {
                parts.push(format!("  {label}: {}\n", refs.join(", ")));
            }
        }
        if !dep_seq.needs.is_empty() {
            parts.push(format!("  needs: {}\n", dep_seq.needs.join(", ")));
        }
        if !after_line.is_empty() {
            parts.push(format!("  after: {}\n", after_line.join(", ")));
        }
    }

    parts.push(format!("\n{body}"));
    parts.concat()
}

/// Render the `Json` show: the faithful toml-as-data (`SliceDoc`) plus the scope
/// body, under the shared `{kind, …}` envelope. Metadata + scope only (A-5).
///
/// SL-048 PHASE-04 (R2-C2′): the tier-1 relations migrated out of the typed struct
/// into `[[relation]]`, so the serialized `SliceDoc` no longer carries them — they
/// are reconstructed here from `tier1` (read via `read_block`) and spliced back into
/// the `slice` object under the SAME `relationships` key, preserving the byte-exact
/// JSON shape (OD-2). The `supersedes` axis is ALWAYS present (empty `[]` when
/// unauthored); `governed_by` is emitted only when populated. SL-149 PHASE-05: the
/// legacy `specs`/`requirements` keys are gone — the corpus migration rewrote those
/// edges onto the `references` role object below. `serde_json` sorts object keys, so
/// the emitted order is alphabetical.
fn show_json(
    doc: &SliceDoc,
    tier1: &[crate::relation::RelationEdge],
    dep_seq: &crate::dep_seq::DepSeq,
    body: &str,
) -> anyhow::Result<String> {
    use crate::relation::{RelationLabel, Role, targets_for, targets_for_role};
    let mut relationships = serde_json::Map::new();
    relationships.insert(
        "supersedes".to_string(),
        serde_json::json!(targets_for(tier1, RelationLabel::Supersedes)),
    );
    let governed_by = targets_for(tier1, RelationLabel::GovernedBy);
    if !governed_by.is_empty() {
        relationships.insert("governed_by".to_string(), serde_json::json!(governed_by));
    }
    // SL-149: the `references` label projected by role into a sibling object
    // `{ implements, scoped_from, concerns }`, each an array of targets. ALWAYS present
    // (the three role keys present, empty `[]` when unauthored — the legacy-axis
    // convention). PHASE-05's corpus migration moved the old `specs`/`requirements`
    // edges into `references(implements)`/`references(concerns)` here.
    relationships.insert(
        "references".to_string(),
        serde_json::json!({
            "implements": targets_for_role(tier1, RelationLabel::References, Role::Implements),
            "originates_from": targets_for_role(tier1, RelationLabel::References, Role::OriginatesFrom),
            "concerns": targets_for_role(tier1, RelationLabel::References, Role::Concerns),
        }),
    );
    // The dep/seq payload axes (SL-060). Additive — emitted only when populated, so an
    // unauthored slice's JSON object stays byte-identical to the pre-SL-060 shape.
    // `after` serializes as `[{ to, rank }, …]` (the `AfterEdge` derive).
    if !dep_seq.needs.is_empty() {
        relationships.insert("needs".to_string(), serde_json::json!(dep_seq.needs));
    }
    if !dep_seq.after.is_empty() {
        relationships.insert("after".to_string(), serde_json::json!(dep_seq.after));
    }
    let mut slice = serde_json::to_value(doc).context("failed to serialize slice doc")?;
    if let Some(obj) = slice.as_object_mut() {
        obj.insert(
            "relationships".to_string(),
            serde_json::Value::Object(relationships),
        );
    }
    let value = serde_json::json!({ "kind": "slice", "slice": slice, "body": body });
    serde_json::to_string_pretty(&value).context("failed to serialize slice show JSON")
}

// ---------------------------------------------------------------------------
// Selector handlers (SL-147 PHASE-01)
// ---------------------------------------------------------------------------

fn dispatch_selector(cmd: SelectorCommand) -> anyhow::Result<()> {
    match cmd {
        SelectorCommand::Add {
            id,
            intent,
            globs,
            note,
            path,
        } => run_selector_add(path, id, intent, &globs, note.as_deref()),
        SelectorCommand::Note {
            id,
            selector,
            text,
            path,
        } => run_selector_note(path, id, &selector, &text),
        SelectorCommand::List { id, path } => run_selector_list(path, id),
        SelectorCommand::Rm { id, globs, path } => run_selector_rm(path, id, &globs),
    }
}

/// Open a slice's TOML as a `toml_edit::DocumentMut` for edit-preserving writes.
fn open_selector_doc(root: &Path, id: u32) -> anyhow::Result<(PathBuf, toml_edit::DocumentMut)> {
    let slice_root = root.join(SLICE_DIR);
    let toml_path = slice_toml_path(&slice_root, id);
    let text = fs::read_to_string(&toml_path)
        .with_context(|| format!("slice {} not found at {}", id, toml_path.display()))?;
    let doc = text
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| format!("Failed to parse {}", toml_path.display()))?;
    Ok((toml_path, doc))
}

fn run_selector_add(
    path: Option<PathBuf>,
    id: u32,
    intent: SelectorIntent,
    globs: &[String],
    note: Option<&str>,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (toml_path, mut doc) = open_selector_doc(&root, id)?;

    let intent_str = serde_rename_kebab(intent);
    for glob in globs {
        selector_upsert(&mut doc, glob, intent_str, note)?;
    }

    crate::fsutil::write_atomic(&toml_path, doc.to_string().as_bytes())?;
    let cid = canonical_id(id);
    writeln!(
        io::stdout(),
        "{cid}: upserted {} selector(s)\n",
        globs.len()
    )?;
    Ok(())
}

fn run_selector_note(
    path: Option<PathBuf>,
    id: u32,
    selector: &str,
    text: &str,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (toml_path, mut doc) = open_selector_doc(&root, id)?;

    let found = selector_set_note(&mut doc, selector, text);
    if !found {
        let cid = canonical_id(id);
        anyhow::bail!("{cid}: no selector `{selector}` — add it first");
    }

    crate::fsutil::write_atomic(&toml_path, doc.to_string().as_bytes())?;
    writeln!(io::stdout(), "{selector}: note set")?;
    Ok(())
}

fn run_selector_list(path: Option<PathBuf>, id: u32) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let slice_root = root.join(SLICE_DIR);
    let (doc, _toml_text, _body) = read_slice(&slice_root, id)?;

    if doc.selectors.is_empty() {
        writeln!(io::stdout(), "(no selectors)")?;
        return Ok(());
    }
    for s in &doc.selectors {
        let note = s.note.as_deref().unwrap_or("-");
        writeln!(
            io::stdout(),
            "{}  {: <16}  {}",
            s.selector,
            serde_rename_kebab(s.intent),
            note
        )?;
    }
    Ok(())
}

fn run_selector_rm(path: Option<PathBuf>, id: u32, globs: &[String]) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (toml_path, mut doc) = open_selector_doc(&root, id)?;

    let removed = selector_remove_many(&mut doc, globs);
    if removed > 0 {
        crate::fsutil::write_atomic(&toml_path, doc.to_string().as_bytes())?;
    }
    writeln!(io::stdout(), "Removed {removed} selector(s)")?;
    Ok(())
}

// ---------------------------------------------------------------------------
// `slice conformance` — the conformance shell (SL-147 PHASE-03, design D6)
// ---------------------------------------------------------------------------

/// Parse the events out of one `git diff --name-status A..B` line, folding them
/// into `actual`. Plain `A`/`M`/`D` key the path directly; a rename (`R<score>`)
/// presents two paths and is folded as a `Deleted` of the source plus an `Added`
/// of the destination (the conservative reading — the source disappears, the
/// destination appears). Pure (no IO) so it is unit-testable; unknown status
/// letters are ignored. Within one diff, repeated events for a path accumulate
/// in order (the per-phase event set, F-3).
fn fold_name_status_line(line: &str, actual: &mut std::collections::BTreeMap<String, Vec<Status>>) {
    let mut cols = line.split('\t');
    let Some(code) = cols.next() else { return };
    let letter = code.chars().next().unwrap_or(' ');
    match letter {
        'A' | 'M' | 'D' => {
            if let Some(p) = cols.next() {
                let st = match letter {
                    'A' => Status::Added,
                    'D' => Status::Deleted,
                    _ => Status::Modified,
                };
                actual.entry(p.to_string()).or_default().push(st);
            }
        }
        'R' | 'C' => {
            // rename/copy: `<code>\t<src>\t<dst>`. Source removed, dest added.
            let src = cols.next();
            if let Some(dst) = cols.next() {
                if letter == 'R'
                    && let Some(src) = src
                {
                    actual
                        .entry(src.to_string())
                        .or_default()
                        .push(Status::Deleted);
                }
                actual
                    .entry(dst.to_string())
                    .or_default()
                    .push(Status::Added);
            }
        }
        _ => {}
    }
}

/// The degrade-aware result of the conformance shell: either the registry is
/// unavailable (no rows), incomplete (partial coverage, gaps named), or the
/// full three-cell algebra ran. The IO sits in [`conformance_outcome`]; the
/// render in [`render_conformance`] — both off this enum so the degrade ladder
/// (design F-2) is testable without capturing stdout.
#[derive(Debug)]
enum ConformanceOutcome {
    Unavailable,
    Incomplete(Vec<crate::state::CompletenessGap>),
    Computed(conformance::Conformance),
}

/// The conformance shell IO (design Data flow): resolve the design-target
/// selectors + the recorded registry, run the completeness gate, then fold each
/// row's git name-status diff into the `actual` map and run the pure algebra.
/// Fails closed: an empty registry → `Unavailable`, an incomplete registry →
/// `Incomplete` (never a misleading clean diff from partial coverage). `root`
/// resolves both the shared registry (via the primary worktree) and the local
/// phase-sheet state tree.
fn conformance_outcome(root: &Path, id: u32) -> anyhow::Result<ConformanceOutcome> {
    let slice_root = root.join(SLICE_DIR);
    let (doc, _toml, _body) = read_slice(&slice_root, id)?;

    let selectors: Vec<String> = doc
        .selectors
        .iter()
        .filter(|s| s.intent == SelectorIntent::DesignTarget)
        .map(|s| s.selector.clone())
        .collect();

    let rows = crate::state::read_source_deltas(root, id)?;
    if rows.is_empty() {
        return Ok(ConformanceOutcome::Unavailable);
    }

    if let crate::state::Completeness::Incomplete { gaps } =
        crate::state::registry_completeness(root, root, id)?
    {
        return Ok(ConformanceOutcome::Incomplete(gaps));
    }

    let mut actual: std::collections::BTreeMap<String, Vec<Status>> =
        std::collections::BTreeMap::new();
    for row in &rows {
        let diff = crate::git::git_text(
            root,
            &[
                "diff",
                "--name-status",
                &format!("{}..{}", row.code_start_oid, row.code_end_oid),
            ],
        )?;
        for line in diff.lines().filter(|l| !l.trim().is_empty()) {
            fold_name_status_line(line, &mut actual);
        }
    }

    Ok(ConformanceOutcome::Computed(conformance::compute(
        &selectors, &actual,
    )))
}

/// `slice conformance <SL>` — resolve the root, compute the outcome, render it.
fn run_conformance(path: Option<PathBuf>, id: u32) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let cid = canonical_id(id);
    let mut out = io::stdout();
    match conformance_outcome(&root, id)? {
        ConformanceOutcome::Unavailable => {
            writeln!(
                out,
                "{cid}: conformance unavailable — no recorded source deltas"
            )?;
            Ok(())
        }
        ConformanceOutcome::Incomplete(gaps) => {
            writeln!(out, "{cid}: conformance incomplete — partial coverage")?;
            for gap in &gaps {
                writeln!(out, "  - {}", gap.describe())?;
            }
            Ok(())
        }
        ConformanceOutcome::Computed(result) => render_conformance(&cid, &result),
    }
}

/// `slice record-delta <id> <PHASE-NN> --start <ref> --end <ref>` (SL-147
/// PHASE-04) — the MANUAL escape hatch beside the automatic solo phase-binding.
/// Resolves `start`/`end` to full oids (against the resolved root's repo), builds
/// the [`BoundaryRow`], and calls [`record_source_delta`] (F-6 guard +
/// upsert) — which resolves the one shared registry file against the PRIMARY tree,
/// so this works from a linked/coordination worktree as well as the main tree.
/// Mutually exclusive with the solo binding by USE, not by mechanism: an operator
/// runs this to correct a range or bootstrap a slice recorded before the binding
/// existed.
fn run_record_delta(
    path: Option<PathBuf>,
    id: u32,
    phase: &str,
    start: &str,
    end: &str,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let resolve = |refish: &str| -> anyhow::Result<String> {
        crate::git::resolve_ref(&root, refish)?
            .with_context(|| format!("record-delta: {refish} does not resolve to a commit"))
    };
    crate::state::record_source_delta(
        &root,
        id,
        crate::boundary::BoundaryRow {
            phase: phase.to_string(),
            code_start_oid: resolve(start)?,
            code_end_oid: resolve(end)?,
            // record-delta is the manual escape hatch (design §5.3). As an
            // incoming `Manual` it never reclassifies an existing landing path —
            // the PHASE-01 sticky merge preserves any prior Solo/Funnel/Unknown.
            provenance: crate::boundary::Provenance::Manual,
        },
    )?;
    writeln!(
        io::stdout(),
        "{}: recorded source delta for {phase}",
        canonical_id(id)
    )?;
    Ok(())
}

/// Render the three conformance cells (design Data flow step 5): undeclared
/// first (highest signal, each with its A/M/D net verb), then undelivered (the
/// unmatched design-target selectors), then a conformant count with the matched
/// selector per conformant path (F-7).
fn render_conformance(cid: &str, result: &conformance::Conformance) -> anyhow::Result<()> {
    let mut out = io::stdout();
    writeln!(out, "{cid}: conformance")?;

    writeln!(out, "undeclared ({}):", result.undeclared.len())?;
    for u in &result.undeclared {
        writeln!(out, "  {} {}", u.verb.marker(), u.path)?;
    }

    writeln!(out, "undelivered ({}):", result.undelivered.len())?;
    for sel in &result.undelivered {
        writeln!(out, "  {sel}")?;
    }

    writeln!(out, "conformant ({}):", result.conformant.len())?;
    for c in &result.conformant {
        writeln!(out, "  {}{}", c.path, c.matched_selector)?;
    }
    Ok(())
}

// -- pure helpers (edit `toml_edit::DocumentMut`) ----------------------------

/// Serialise a `SelectorIntent` as its kebab-case wire value.
fn serde_rename_kebab(intent: SelectorIntent) -> &'static str {
    match intent {
        SelectorIntent::ScopeRelevant => "scope-relevant",
        SelectorIntent::DesignTarget => "design-target",
    }
}

/// Upsert one selector row into `doc`'s `[[selector]]` array-of-tables.
/// Identity = the `selector` string. When a row with the same string exists,
/// its `intent` (and optionally `note`) are updated in-place rather than
/// appended.
fn selector_upsert(
    doc: &mut toml_edit::DocumentMut,
    glob: &str,
    intent: &str,
    note: Option<&str>,
) -> anyhow::Result<()> {
    let array = doc
        .as_table_mut()
        .entry("selector")
        .or_insert_with(|| toml_edit::Item::ArrayOfTables(toml_edit::ArrayOfTables::new()))
        .as_array_of_tables_mut()
        .ok_or_else(|| {
            anyhow::anyhow!("`selector` key exists but is not an array-of-tables (corrupt file)")
        })?;

    // In-place update if the selector string already exists.
    for row in array.iter_mut() {
        if row
            .get("selector")
            .and_then(toml_edit::Item::as_str)
            .is_some_and(|s| s == glob)
        {
            row.insert("intent", toml_edit::value(intent));
            if let Some(n) = note {
                row.insert("note", toml_edit::value(n));
            }
            return Ok(());
        }
    }

    // Append a new row.
    let mut row = toml_edit::Table::new();
    row.insert("selector", toml_edit::value(glob));
    row.insert("intent", toml_edit::value(intent));
    if let Some(n) = note {
        row.insert("note", toml_edit::value(n));
    }
    array.push(row);
    Ok(())
}

/// Set `note` on the selector row whose `selector` string matches exactly.
/// Returns `true` when a row was found and updated.
fn selector_set_note(doc: &mut toml_edit::DocumentMut, selector: &str, text: &str) -> bool {
    let Some(array) = doc
        .as_table_mut()
        .get_mut("selector")
        .and_then(toml_edit::Item::as_array_of_tables_mut)
    else {
        return false;
    };
    for row in array.iter_mut() {
        if row
            .get("selector")
            .and_then(toml_edit::Item::as_str)
            .is_some_and(|s| s == selector)
        {
            row.insert("note", toml_edit::value(text));
            return true;
        }
    }
    false
}

/// Remove every selector row whose selector string matches one of `globs`.
/// Returns the count of rows removed.
fn selector_remove_many(doc: &mut toml_edit::DocumentMut, globs: &[String]) -> usize {
    let Some(array) = doc
        .as_table_mut()
        .get_mut("selector")
        .and_then(toml_edit::Item::as_array_of_tables_mut)
    else {
        return 0;
    };
    let before = array.len();
    array.retain(|row| {
        let s = row
            .get("selector")
            .and_then(toml_edit::Item::as_str)
            .unwrap_or("");
        !globs.iter().any(|g| g == s)
    });
    before - array.len()
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lifecycle::is_transition_terminal;
    use crate::meta::Meta;
    use crate::test_support::SCHEMA_PLAN_OVERVIEW;

    fn meta(id: u32, status: &str, slug: &str, title: &str) -> Meta {
        Meta {
            id,
            slug: slug.to_string(),
            title: title.to_string(),
            status: status.to_string(),
            tags: Vec::new(),
        }
    }

    use crate::state::PhaseRollup;

    /// A rollup with the given completed/planned counts (total = sum); other
    /// buckets default to zero unless a test overrides them.
    fn rollup(completed: u32, planned: u32) -> PhaseRollup {
        PhaseRollup {
            completed,
            planned,
            ..Default::default()
        }
    }

    // --- is_divergent ---

    #[test]
    fn divergence_flags_the_two_unambiguous_mismatches() {
        // marked terminal ("done"), work outstanding
        assert!(is_divergent("done", Some(&rollup(2, 4))));
        // work complete, not marked terminal
        assert!(is_divergent("proposed", Some(&rollup(6, 0))));
    }

    #[test]
    fn divergence_is_quiet_when_consistent_untracked_or_anomalous() {
        // terminal + complete → consistent
        assert!(!is_divergent("done", Some(&rollup(6, 0))));
        // non-terminal + incomplete → consistent
        assert!(!is_divergent("proposed", Some(&rollup(2, 4))));
        // untracked → nothing to compare
        assert!(!is_divergent("done", None));
        // anomalies present → corruption, not a lifecycle mismatch (suppressed)
        let anomalous = PhaseRollup {
            completed: 2,
            planned: 3,
            unknown: 1,
            ..Default::default()
        };
        assert!(!is_divergent("done", Some(&anomalous)));
    }

    // --- phases_cell ---

    #[test]
    fn phases_cell_renders_markers() {
        assert_eq!(phases_cell(None), "");
        assert_eq!(phases_cell(Some(&rollup(4, 2))), "4/6");
        let blocked = PhaseRollup {
            completed: 2,
            planned: 3,
            blocked: 1,
            ..Default::default()
        };
        assert_eq!(phases_cell(Some(&blocked)), "2/6 !1");
        let anomalous = PhaseRollup {
            completed: 3,
            planned: 2,
            unknown: 1,
            ..Default::default()
        };
        assert_eq!(phases_cell(Some(&anomalous)), "3/6 ?1");
    }

    // --- SL-037 column model (the slice grid: prefixed ids + variant axis) ---

    /// Render rows over the default column set (the migrated `render_table` path).
    fn render_default(rows: &[SliceRowTuple]) -> String {
        let sel = listing::select_columns(&SLICE_COLUMNS, SLICE_DEFAULT, None).unwrap();
        listing::render_columns(rows, &sel, listing::RenderOpts::default())
    }

    /// Render rows over an explicit `--columns` set.
    fn render_cols(rows: &[SliceRowTuple], cols: &[&str]) -> String {
        let owned: Vec<String> = cols.iter().map(|s| (*s).to_string()).collect();
        let sel = listing::select_columns(&SLICE_COLUMNS, SLICE_DEFAULT, Some(&owned)).unwrap();
        listing::render_columns(rows, &sel, listing::RenderOpts::default())
    }

    #[test]
    fn slice_list_empty_suppresses_the_header() {
        assert_eq!(render_default(&[]), "");
    }

    #[test]
    fn slice_list_default_renders_prefixed_ids_rollup_and_divergence() {
        let rows = vec![
            (
                meta(1, "done", "entity-v1", "Entity v1"),
                Some(rollup(6, 0)),
            ),
            (
                meta(7, "done", "anchoring", "Anchoring"),
                Some(rollup(2, 4)),
            ),
            (meta(9, "proposed", "rollup", "Rollup"), None),
        ];
        let out = render_default(&rows);
        let lines: Vec<&str> = out.lines().collect();
        assert!(lines[0].starts_with("id"), "header: {:?}", lines[0]);
        assert!(lines[0].contains("phases"), "phases column: {:?}", lines[0]);
        // SL-025: prefixed ids, not bare `001`.
        // consistent terminal slice: no ⚠, full rollup
        assert!(lines[1].starts_with("SL-001 │ done"), "{:?}", lines[1]);
        assert!(lines[1].contains("6/6"));
        // done but 2/6 → divergent ⚠ (marker preserved in the status cell value)
        assert!(lines[2].starts_with("SL-007 │ done ⚠"), "{:?}", lines[2]);
        assert!(lines[2].contains("2/6"));
        // untracked → —
        assert!(lines[3].starts_with("SL-009 │ proposed"), "{:?}", lines[3]);
        assert!(lines[3].contains(""));
        // no bare numeric id anywhere
        assert!(!out.contains("\n001  "), "no bare numeric id: {out}");
    }

    #[test]
    fn slice_list_default_omits_slug() {
        let rows = vec![(meta(1, "proposed", "entity-v1", "Entity v1"), None)];
        let out = render_default(&rows);
        let header = out.lines().next().unwrap();
        // SL-037 D4: default visible set is [id, status, phases, title] — slug hidden.
        assert!(
            !header.contains("slug"),
            "default header omits slug: {header:?}"
        );
        assert!(
            !out.contains("entity-v1"),
            "slug value hidden by default: {out}"
        );
        assert!(header.contains("title"), "default keeps title: {header:?}");
    }

    #[test]
    fn slice_list_columns_reveals_slug_and_preserves_markers() {
        let rows = vec![(
            meta(7, "done", "anchoring", "Anchoring"),
            Some(rollup(2, 4)),
        )];
        // Reveal slug; status cell still carries the ⚠ divergence marker, phases intact.
        let out = render_cols(&rows, &["id", "status", "phases", "slug"]);
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(
            lines[0].split_whitespace().collect::<Vec<_>>(),
            vec!["id", "", "status", "", "phases", "", "slug"]
        );
        assert!(
            out.contains("anchoring"),
            "slug revealed by --columns: {out}"
        );
        assert!(
            lines[1].contains("done ⚠"),
            "⚠ marker preserved: {:?}",
            lines[1]
        );
        assert!(
            lines[1].contains("2/6"),
            "phases cell intact: {:?}",
            lines[1]
        );
    }

    // --- decorated_status: drift `?` and divergence `⚠` are independent ---

    #[test]
    fn decorated_status_composes_drift_and_divergence() {
        // in-vocab, consistent → bare
        assert_eq!(decorated_status("proposed", None), "proposed");
        // in-vocab, divergent (done + work outstanding) → ⚠ only
        assert_eq!(decorated_status("done", Some(&rollup(2, 4))), "done ⚠");
        // out-of-vocab, consistent → `?` only (never hidden, §5.5)
        assert_eq!(decorated_status("bogus", None), "bogus?");
        // out-of-vocab AND divergent → both markers, drift hugs the token
        assert_eq!(decorated_status("bogus", Some(&rollup(6, 0))), "bogus? ⚠");
        // abandoned + incomplete is NOT divergent (terminal set stays {done}) → bare
        assert_eq!(
            decorated_status("abandoned", Some(&rollup(2, 4))),
            "abandoned"
        );
    }

    // --- is_drifted / is_hidden: vocab vs hide-set are distinct ---

    #[test]
    fn is_drifted_flags_only_out_of_vocab() {
        for s in SLICE_STATUSES {
            assert!(!is_drifted(s), "in-vocab `{s}` is not drift");
        }
        assert!(is_drifted("bogus"));
        assert!(is_drifted("superseded")); // the migrated-away value is now drift
    }

    #[test]
    fn is_hidden_is_the_terminal_presentation_set_not_divergence() {
        // hide-set: terminal slices drop from the default list
        assert!(is_hidden("done"));
        assert!(is_hidden("abandoned"));
        assert!(!is_hidden("proposed"));
        // an out-of-vocab status is NEVER hidden (§5.5)
        assert!(!is_hidden("bogus"));
        // the divergence-terminal set is narrower (done only) — abandoned is NOT
        // terminal for divergence even though it IS hidden.
        assert!(is_terminal_status("done"));
        assert!(!is_terminal_status("abandoned"));
    }

    /// Materialise a slice the way `run_new` does, for behaviour-preservation
    /// tests (the slice-001 gate).
    fn make_slice(root: &Path, slug: &str, title: &str, date: &str) -> entity::Materialised {
        entity::materialise(
            &SLICE_KIND,
            &LocalFs,
            root,
            &MaterialiseRequest::Fresh,
            &Inputs { slug, title, date },
            &[],
            &mut entity::local_reserved(),
        )
        .unwrap()
    }

    // --- render / round-trip ---

    #[test]
    fn render_toml_round_trips_to_metadata() {
        let body = render_toml(7, "my-slug", "My Title", "2026-06-03").unwrap();
        let parsed: Meta = toml::from_str(&body).unwrap();
        assert_eq!(parsed, meta(7, "proposed", "my-slug", "My Title"));
        // injected date survives
        assert!(body.contains("created = \"2026-06-03\""));
    }

    #[test]
    fn render_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_toml(7, slug, title, "2026-06-03").unwrap();
        let parsed: Meta = toml::from_str(&body).unwrap();
        assert_eq!(parsed.slug, slug);
        assert_eq!(parsed.title, title);
    }

    #[test]
    fn render_md_substitutes_title() {
        let body = render_md("My Title").unwrap();
        assert!(body.contains("My Title"));
        assert!(!body.contains("{{title}}"));
    }

    #[test]
    fn render_design_substitutes_ref_and_title() {
        let body = render_design("SL-003", "My Title").unwrap();
        assert!(body.contains("Design SL-003: My Title"));
        assert!(!body.contains("{{ref}}"));
        assert!(!body.contains("{{title}}"));
    }

    // --- scaffolds ---

    #[test]
    fn slice_scaffold_lays_out_two_files_and_a_symlink() {
        let ctx = ScaffoldCtx {
            id: 3,
            canonical: "SL-003",
            slug: "vendor-skills",
            title: "Vendor skills",
            date: "2026-06-03",
        };
        let fileset = slice_scaffold(&ctx).unwrap();
        assert_eq!(fileset.len(), 3);
        assert!(matches!(&fileset[0],
            Artifact::File { rel_path, body }
            if rel_path == Path::new("003/slice-003.toml") && body.contains("2026-06-03")));
        assert!(matches!(&fileset[1],
            Artifact::File { rel_path, body }
            if rel_path == Path::new("003/slice-003.md") && body.contains("Vendor skills")));
        assert!(matches!(&fileset[2],
            Artifact::Symlink { rel_path, target }
            if rel_path == Path::new("003-vendor-skills") && target == "003"));
    }

    #[test]
    fn render_plan_toml_substitutes_ref_and_parses() {
        let body = render_plan_toml("SL-004").unwrap();
        assert!(body.contains("slice   = \"SL-004\""));
        assert!(!body.contains("{{ref}}"));
        // it is valid TOML carrying the plan.overview shape
        let doc: toml::Value = toml::from_str(&body).unwrap();
        assert_eq!(doc["schema"].as_str(), Some(SCHEMA_PLAN_OVERVIEW));
        assert_eq!(doc["version"].as_integer(), Some(1));
        assert_eq!(doc["phase"][0]["id"].as_str(), Some("PHASE-01"));
    }

    #[test]
    fn render_plan_md_substitutes_ref_and_title() {
        let body = render_plan_md("SL-004", "My Title").unwrap();
        assert!(body.contains("Implementation Plan SL-004: My Title"));
        assert!(!body.contains("{{ref}}"));
        assert!(!body.contains("{{title}}"));
    }

    #[test]
    fn plan_scaffold_lays_out_toml_and_md() {
        let ctx = ScaffoldCtx {
            id: 4,
            canonical: "SL-004",
            slug: "",
            title: "Plan title",
            date: "2026-06-04",
        };
        let fileset = plan_scaffold(&ctx).unwrap();
        assert_eq!(fileset.len(), 2);
        assert!(matches!(&fileset[0],
            Artifact::File { rel_path, body }
            if rel_path == Path::new("004/plan.toml") && body.contains("SL-004")));
        assert!(matches!(&fileset[1],
            Artifact::File { rel_path, body }
            if rel_path == Path::new("004/plan.md") && body.contains("Plan title")));
    }

    // --- Plan read model (pure parser tests live in `crate::plan`; SL-016) ---

    #[test]
    fn plan_parse_accepts_the_scaffold_template() {
        let body = render_plan_toml("SL-004").unwrap();
        let plan = Plan::parse(&body).unwrap();
        assert_eq!(plan.phases.len(), 1);
        assert_eq!(plan.phases[0].id, "PHASE-01");
    }

    #[test]
    fn design_scaffold_is_a_single_file_no_symlink() {
        let ctx = ScaffoldCtx {
            id: 3,
            canonical: "SL-003",
            slug: "",
            title: "Vendor skills",
            date: "2026-06-03",
        };
        let fileset = design_scaffold(&ctx).unwrap();
        assert_eq!(fileset.len(), 1);
        assert!(matches!(&fileset[0],
            Artifact::File { rel_path, body }
            if rel_path == Path::new("003/design.md") && body.contains("Design SL-003: Vendor skills")));
    }

    // --- behaviour preservation: a materialised slice is well-formed ---

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

        let s = make_slice(root, "my-slug", "My Title", "2026-06-03");
        let slice_root = root.join(SLICE_DIR);

        assert_eq!(s.eid.numeric_id(), Some(1));
        assert!(slice_root.join("001").is_dir());
        assert!(slice_root.join("001/slice-001.toml").is_file());
        assert!(slice_root.join("001/slice-001.md").is_file());
        assert_eq!(
            fs::read_link(slice_root.join("001-my-slug")).unwrap(),
            Path::new("001")
        );

        let toml_body = fs::read_to_string(slice_root.join("001/slice-001.toml")).unwrap();
        assert!(toml_body.contains("id = 1"));
        assert!(toml_body.contains("2026-06-03"));
    }

    // --- list: slice ↔ meta integration (the pure list helpers are unit-tested
    //     in crate::meta; this proves `slice list` reads what `slice new` writes) ---

    #[test]
    fn meta_read_metas_round_trips_a_created_slice() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-03");

        let metas = meta::read_metas(&root.join(SLICE_DIR), "slice", "SL").unwrap();
        assert_eq!(metas, vec![meta(1, "proposed", "my-slug", "My Title")]);
    }

    // --- design verb: non-reserved sibling over an existing slice ---

    #[test]
    fn design_materialises_under_an_existing_slice_with_no_symlink() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-03");
        let slice_root = root.join(SLICE_DIR);

        let out = entity::materialise(
            &DESIGN_KIND,
            &LocalFs,
            root,
            &MaterialiseRequest::InExisting { id: 1 },
            &Inputs {
                slug: "",
                title: "My Title",
                date: "2026-06-03",
            },
            &[],
            &mut entity::local_reserved(),
        )
        .unwrap();

        assert_eq!(out.eid.numeric_id(), Some(1));
        let body = fs::read_to_string(slice_root.join("001/design.md")).unwrap();
        assert!(body.contains("Design SL-001: My Title"));
        // no second numeric dir, no extra symlink
        assert!(!slice_root.join("002").exists());
    }

    #[test]
    fn design_refuses_to_clobber_an_existing_doc() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-03");
        let slice_root = root.join(SLICE_DIR);
        fs::write(slice_root.join("001/design.md"), "hand-written").unwrap();

        let err = entity::materialise(
            &DESIGN_KIND,
            &LocalFs,
            root,
            &MaterialiseRequest::InExisting { id: 1 },
            &Inputs {
                slug: "",
                title: "My Title",
                date: "2026-06-03",
            },
            &[],
            &mut entity::local_reserved(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("Refusing to overwrite"));
        assert_eq!(
            fs::read_to_string(slice_root.join("001/design.md")).unwrap(),
            "hand-written"
        );
    }

    // --- plan facet: the first multi-file sub-artefact ---

    #[test]
    fn plan_materialises_two_files_under_an_existing_slice() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-04");
        let slice_root = root.join(SLICE_DIR);

        let out = entity::materialise(
            &PLAN_KIND,
            &LocalFs,
            root,
            &MaterialiseRequest::InExisting { id: 1 },
            &Inputs {
                slug: "",
                title: "My Title",
                date: "2026-06-04",
            },
            &[],
            &mut entity::local_reserved(),
        )
        .unwrap();

        assert_eq!(out.eid.numeric_id(), Some(1));
        let toml_body = fs::read_to_string(slice_root.join("001/plan.toml")).unwrap();
        assert!(toml_body.contains("slice   = \"SL-001\""));
        let md_body = fs::read_to_string(slice_root.join("001/plan.md")).unwrap();
        assert!(md_body.contains("Implementation Plan SL-001: My Title"));
        // no second numeric dir, no extra symlink
        assert!(!slice_root.join("002").exists());
    }

    #[test]
    fn plan_refuses_to_clobber_an_existing_plan() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-04");
        let slice_root = root.join(SLICE_DIR);
        fs::write(slice_root.join("001/plan.toml"), "hand-written").unwrap();

        let err = entity::materialise(
            &PLAN_KIND,
            &LocalFs,
            root,
            &MaterialiseRequest::InExisting { id: 1 },
            &Inputs {
                slug: "",
                title: "My Title",
                date: "2026-06-04",
            },
            &[],
            &mut entity::local_reserved(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("Refusing to overwrite"));
        assert_eq!(
            fs::read_to_string(slice_root.join("001/plan.toml")).unwrap(),
            "hand-written"
        );
        // the partial sibling write was rolled back — no plan.md leftover
        assert!(!slice_root.join("001/plan.md").exists());
    }

    // --- notes facet: durable single-file scaffold ---

    #[test]
    fn notes_materialises_under_an_existing_slice() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-04");
        let slice_root = root.join(SLICE_DIR);

        entity::materialise(
            &NOTES_KIND,
            &LocalFs,
            root,
            &MaterialiseRequest::InExisting { id: 1 },
            &Inputs {
                slug: "",
                title: "My Title",
                date: "2026-06-04",
            },
            &[],
            &mut entity::local_reserved(),
        )
        .unwrap();

        let body = fs::read_to_string(slice_root.join("001/notes.md")).unwrap();
        assert!(body.contains("Notes SL-001: My Title"));
    }

    #[test]
    fn notes_refuses_to_clobber() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-04");
        let slice_root = root.join(SLICE_DIR);
        fs::write(slice_root.join("001/notes.md"), "hand-written").unwrap();

        let err = entity::materialise(
            &NOTES_KIND,
            &LocalFs,
            root,
            &MaterialiseRequest::InExisting { id: 1 },
            &Inputs {
                slug: "",
                title: "My Title",
                date: "2026-06-04",
            },
            &[],
            &mut entity::local_reserved(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("Refusing to overwrite"));
        assert_eq!(
            fs::read_to_string(slice_root.join("001/notes.md")).unwrap(),
            "hand-written"
        );
    }

    // --- SL-025: list_rows on the spine — prefixed ids, header, hide-set, drift ---

    fn slice_root(root: &Path) -> PathBuf {
        root.join(SLICE_DIR)
    }

    /// Raw-rewrite a created slice's authored status (slice has no status verb;
    /// this proves the list reads/filters the authored field). The status is the
    /// only field touched — `created`/`updated`/`[relationships]` survive.
    fn set_status_raw(root: &Path, id: u32, status: &str) {
        let name = format!("{id:03}");
        let p = slice_root(root)
            .join(&name)
            .join(format!("slice-{name}.toml"));
        let flipped = fs::read_to_string(&p)
            .unwrap()
            .replace("status = \"proposed\"", &format!("status = \"{status}\""));
        fs::write(&p, flipped).unwrap();
    }

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

    #[test]
    fn list_rows_emits_prefixed_ids_and_a_header() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "first", "First", "2026-06-04");
        make_slice(root, "second", "Second", "2026-06-04");

        let out = list_rows(root, list_args()).unwrap();
        let lines: Vec<&str> = out.lines().collect();
        assert!(lines[0].starts_with("id"), "header row: {:?}", lines[0]);
        assert!(lines[0].contains("phases"), "phases column named");
        assert!(out.contains("SL-001 │ proposed"), "prefixed id: {out}");
        assert!(out.contains("SL-002"), "second slice present: {out}");
        assert!(!out.contains("\n001  "), "no bare numeric id: {out}");
    }

    #[test]
    fn list_rows_hide_set_drops_done_and_abandoned_by_default() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "live", "Live", "2026-06-04");
        make_slice(root, "shipped", "Shipped", "2026-06-04");
        make_slice(root, "dropped", "Dropped", "2026-06-04");
        set_status_raw(root, 2, "done");
        set_status_raw(root, 3, "abandoned");

        let out = list_rows(root, list_args()).unwrap();
        assert!(out.contains("SL-001"), "live slice kept: {out}");
        assert!(!out.contains("SL-002"), "done hidden by default: {out}");
        assert!(
            !out.contains("SL-003"),
            "abandoned hidden by default: {out}"
        );
    }

    #[test]
    fn list_rows_all_and_explicit_status_reveal_the_hide_set() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "live", "Live", "2026-06-04");
        make_slice(root, "dropped", "Dropped", "2026-06-04");
        set_status_raw(root, 2, "abandoned");

        // --all reveals it.
        let all = list_rows(
            root,
            ListArgs {
                all: true,
                ..Default::default()
            },
        )
        .unwrap();
        assert!(all.contains("SL-002"), "--all reveals abandoned: {all}");

        // an explicit --status also reveals it (terminal-hide override).
        let by_status = list_rows(
            root,
            ListArgs {
                status: vec!["abandoned".into()],
                ..Default::default()
            },
        )
        .unwrap();
        assert!(
            by_status.contains("SL-002"),
            "explicit status reveals: {by_status}"
        );
        assert!(
            !by_status.contains("SL-001"),
            "and filters to it: {by_status}"
        );
    }

    #[test]
    fn list_rows_out_of_vocab_stored_status_is_never_hidden_and_drift_marked() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "weird", "Weird", "2026-06-04");
        set_status_raw(root, 1, "bogus");

        // §5.5: a drifted stored status is NOT hidden (hide-set lists known
        // terminals only) and renders with a trailing `?` drift marker.
        let out = list_rows(root, list_args()).unwrap();
        assert!(out.contains("SL-001"), "drifted slice not hidden: {out}");
        assert!(out.contains("bogus?"), "drift `?` marker present: {out}");
        // distinct from divergence: no ⚠ here (no rollup → not divergent).
        assert!(!out.contains(""), "no spurious divergence marker: {out}");
    }

    #[test]
    fn list_rows_filter_matches_slug_and_title() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "use-rust", "Use Rust", "2026-06-04");
        make_slice(root, "adopt-ci", "Adopt CI", "2026-06-04");

        let out = list_rows(
            root,
            ListArgs {
                substr: Some("adopt".into()),
                ..Default::default()
            },
        )
        .unwrap();
        assert!(out.contains("SL-002"), "substr matches adopt-ci: {out}");
        assert!(!out.contains("SL-001"), "use-rust filtered out: {out}");
    }

    #[test]
    fn list_rows_regexp_matches_canonical_id() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "one", "One", "2026-06-04");
        make_slice(root, "two", "Two", "2026-06-04");

        let out = list_rows(
            root,
            ListArgs {
                regexp: Some("SL-002".into()),
                ..Default::default()
            },
        )
        .unwrap();
        assert!(out.contains("SL-002"), "regex matches canonical: {out}");
        assert!(!out.contains("SL-001"), "non-matching dropped: {out}");
    }

    #[test]
    fn list_rows_json_is_the_shared_envelope_with_structured_phases() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "first", "First", "2026-06-04");

        let out = list_rows(
            root,
            ListArgs {
                json: true,
                ..Default::default()
            },
        )
        .unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(parsed["kind"], "slice");
        let rows = parsed["rows"].as_array().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["id"], "SL-001");
        assert_eq!(rows[0]["status"], "proposed");
        assert_eq!(rows[0]["slug"], "first");
        // OQ-1: phases is structured (null when untracked), NOT a rendered cell.
        assert!(
            rows[0]["phases"].is_null(),
            "untracked phases → null: {out}"
        );
        assert!(!out.contains("4/6"), "no rendered phase cell in json");
    }

    #[test]
    fn list_rows_empty_tree_is_the_empty_string() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(list_rows(dir.path(), list_args()).unwrap(), "");
    }

    // --- VT-3: --status validates against the slice vocabulary (A-2 / D10) ---

    #[test]
    fn list_rows_rejects_an_unknown_status_with_the_uniform_error() {
        let dir = tempfile::tempdir().unwrap();
        let err = list_rows(
            dir.path(),
            ListArgs {
                status: vec!["bogus".into()],
                ..Default::default()
            },
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("bogus"), "names the bad value: {err}");
        assert!(err.contains("abandoned"), "lists the known set: {err}");
    }

    #[test]
    fn list_rows_accepts_every_known_status() {
        let dir = tempfile::tempdir().unwrap();
        for s in SLICE_STATUSES {
            assert!(
                list_rows(
                    dir.path(),
                    ListArgs {
                        status: vec![(*s).to_string()],
                        ..Default::default()
                    },
                )
                .is_ok(),
                "known status `{s}` accepted"
            );
        }
    }

    #[test]
    fn list_rows_accepts_abandoned_and_rejects_superseded() {
        // The migrated vocabulary: `abandoned` is in, `superseded` (the old ADR
        // value once stored on SL-002) is out.
        let dir = tempfile::tempdir().unwrap();
        assert!(
            list_rows(
                dir.path(),
                ListArgs {
                    status: vec!["abandoned".into()],
                    ..Default::default()
                },
            )
            .is_ok()
        );
        let err = list_rows(
            dir.path(),
            ListArgs {
                status: vec!["superseded".into()],
                ..Default::default()
            },
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("superseded"), "superseded rejected: {err}");
    }

    /// The vocabulary known-set must mirror `slices-spec.md` § Lifecycle. Slice has
    /// no status enum, so this pins the set against the spec's stated members.
    #[test]
    fn slice_statuses_matches_the_spec_vocabulary() {
        assert_eq!(
            SLICE_STATUSES,
            &[
                "proposed",
                "design",
                "plan",
                "ready",
                "started",
                "audit",
                "reconcile",
                "done",
                "abandoned"
            ]
        );
    }

    // --- SL-025 PHASE-06 EX-2 / VT-2: ordering-preservation through list_rows ---

    /// Write a slice's authored toml directly at an explicit id (creating its dir),
    /// bypassing the monotonic `Fresh` allocator so the fixture's creation order
    /// can differ from id order. Only the spine-read fields are written.
    fn slice_at(root: &Path, id: u32, status: &str, slug: &str, title: &str) {
        let name = format!("{id:03}");
        let dir = slice_root(root).join(&name);
        fs::create_dir_all(&dir).unwrap();
        let toml = format!(
            "id = {id}\nslug = \"{slug}\"\ntitle = \"{title}\"\nstatus = \"{status}\"\ncreated = \"2026-06-04\"\nupdated = \"2026-06-04\"\n"
        );
        fs::write(dir.join(format!("slice-{name}.toml")), toml).unwrap();
    }

    #[test]
    fn list_rows_orders_by_id_ascending_regardless_of_creation_order() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // Create OUT of id order: 003, then 001, then 002.
        slice_at(root, 3, "proposed", "gamma", "Gamma");
        slice_at(root, 1, "proposed", "alpha", "Alpha");
        slice_at(root, 2, "proposed", "beta", "Beta");

        let out = list_rows(root, list_args()).unwrap();
        let off = |id: &str| {
            out.find(id)
                .unwrap_or_else(|| panic!("{id} present: {out}"))
        };
        assert!(
            off("SL-001") < off("SL-002") && off("SL-002") < off("SL-003"),
            "slice rows must render in ascending id order (sort, not read order): {out}"
        );
    }

    // --- VT-4: slice show — table + json, metadata + scope only (A-5) ---

    #[test]
    fn parse_ref_accepts_prefixed_padded_and_bare_ids() {
        assert_eq!(parse_ref("SL-025").unwrap(), 25);
        assert_eq!(parse_ref("sl-25").unwrap(), 25);
        assert_eq!(parse_ref("25").unwrap(), 25);
        assert_eq!(parse_ref("002").unwrap(), 2);
        assert!(parse_ref("nope").is_err());
    }

    #[test]
    fn read_slice_reassembles_toml_as_data_and_md_scope_body() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-04");

        let (doc, toml_text, body) = read_slice(&slice_root(root), 1).unwrap();
        assert_eq!(doc.id, 1);
        assert_eq!(doc.slug, "my-slug");
        assert_eq!(doc.status, "proposed");
        // SL-048: tier-1 relations come from the `[[relation]]` block; a virgin slice
        // has none, so `read_block` yields no edges.
        let edges = crate::relation::tier1_edges(&SLICE_KIND, &toml_text).unwrap();
        assert!(edges.is_empty());
        // the md scope body is read verbatim.
        assert!(body.contains("My Title"));
    }

    #[test]
    fn format_show_renders_identity_and_scope_body() {
        use crate::relation::{RelationEdge, RelationLabel, Role};
        let doc = SliceDoc {
            id: 25,
            slug: "uniform-cli".into(),
            title: "Uniform CLI".into(),
            status: "started".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-08".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        // SL-048: tier-1 edges are passed in (read from `[[relation]]`), not a struct.
        let tier1 = vec![RelationEdge::with_role(
            RelationLabel::References,
            Some(Role::Implements),
            "PRD-010".into(),
        )];
        // `started` defaults to self/auto (no plan/reconcile gate) — VT-3 show side.
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let out = format_show(
            &doc,
            &tier1,
            &crate::dep_seq::DepSeq::default(),
            "# Scope\n\nthe scope body.\n",
            posture,
            &crate::facet::EntityFacets::default(),
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        assert!(out.contains("SL-025 — Uniform CLI"), "identity: {out}");
        assert!(out.contains("uniform-cli · started"), "flat fields: {out}");
        assert!(out.contains("conduct: self/auto"), "conduct posture: {out}");
        assert!(out.contains("created 2026-06-01 · updated 2026-06-08"));
        assert!(
            out.contains("references(implements): PRD-010"),
            "relationships axis: {out}"
        );
        assert!(
            out.contains("the scope body."),
            "scope body appended: {out}"
        );
    }

    // VT-5: absent facets → byte-identical to pre-change format_show output (golden).
    #[test]
    fn vt5_format_show_absent_facets_is_byte_identical() {
        use crate::relation::{RelationEdge, RelationLabel, Role};
        let doc = SliceDoc {
            id: 25,
            slug: "uniform-cli".into(),
            title: "Uniform CLI".into(),
            status: "started".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-08".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let tier1 = vec![RelationEdge::with_role(
            RelationLabel::References,
            Some(Role::Implements),
            "PRD-010".into(),
        )];
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let out = format_show(
            &doc,
            &tier1,
            &crate::dep_seq::DepSeq::default(),
            "# Scope\n\nthe scope body.\n",
            posture,
            &crate::facet::EntityFacets::default(),
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        let expected = concat!(
            "SL-025 — Uniform CLI\n",
            "uniform-cli · started\n",
            "conduct: self/auto\n",
            "created 2026-06-01 · updated 2026-06-08\n",
            "\n",
            "relationships:\n",
            "  references(implements): PRD-010\n",
            "\n",
            "# Scope\n",
            "\n",
            "the scope body.\n",
        );
        assert_eq!(
            out, expected,
            "absent facets must be byte-identical to pre-change format_show output"
        );
    }

    // VT-1: estimate present → confidence row rendered in show output.
    #[test]
    fn vt1_format_show_estimate_present_renders_confidence_row() {
        use crate::relation::{RelationEdge, RelationLabel, Role};
        let doc = SliceDoc {
            id: 25,
            slug: "uniform-cli".into(),
            title: "Uniform CLI".into(),
            status: "started".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-08".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let tier1 = vec![RelationEdge::with_role(
            RelationLabel::References,
            Some(Role::Implements),
            "PRD-010".into(),
        )];
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let facets = crate::facet::EntityFacets {
            estimate: Some(crate::estimate::EstimateFacet {
                lower: 3.0,
                upper: 5.0,
            }),
            value: None,
            risk: None,
            tags: vec![],
        };
        let out = format_show(
            &doc,
            &tier1,
            &crate::dep_seq::DepSeq::default(),
            "# Scope\n",
            posture,
            &facets,
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        assert!(
            out.contains("estimate: 3.2–4.8 espresso_shots (80% confidence)"),
            "VT-1 estimate row: {out}"
        );
    }

    // VT-2: estimate absent → no estimate: line in output.
    #[test]
    fn vt2_format_show_estimate_absent_no_row() {
        let doc = SliceDoc {
            id: 25,
            slug: "uniform-cli".into(),
            title: "Uniform CLI".into(),
            status: "started".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-08".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let out = format_show(
            &doc,
            &[],
            &crate::dep_seq::DepSeq::default(),
            "# Scope\n",
            posture,
            &crate::facet::EntityFacets::default(),
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        assert!(
            !out.contains("estimate:"),
            "VT-2: estimate row must not appear when absent: {out}"
        );
    }

    // VT-3: value present → 'value: {magnitude} {unit}' appears.
    #[test]
    fn vt3_format_show_value_present_renders_row() {
        let doc = SliceDoc {
            id: 25,
            slug: "uniform-cli".into(),
            title: "Uniform CLI".into(),
            status: "started".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-08".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let facets = crate::facet::EntityFacets {
            estimate: None,
            value: Some(crate::value::ValueFacet { value: 5.0 }),
            risk: None,
            tags: vec![],
        };
        let out = format_show(
            &doc,
            &[],
            &crate::dep_seq::DepSeq::default(),
            "# Scope\n",
            posture,
            &facets,
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        assert!(
            out.contains("value: 5.0 magic_beans"),
            "VT-3 value row: {out}"
        );
    }

    // VT-4: value absent → no value: line.
    #[test]
    fn vt4_format_show_value_absent_no_row() {
        let doc = SliceDoc {
            id: 25,
            slug: "uniform-cli".into(),
            title: "Uniform CLI".into(),
            status: "started".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-08".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let out = format_show(
            &doc,
            &[],
            &crate::dep_seq::DepSeq::default(),
            "# Scope\n",
            posture,
            &crate::facet::EntityFacets::default(),
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        assert!(
            !out.contains("value:"),
            "VT-4: value row must not appear when absent: {out}"
        );
    }

    // VT-9: custom confidence bounds in doctrine.toml → correct percentile band.
    #[test]
    fn vt9_format_show_custom_confidence_bounds() {
        let doc = SliceDoc {
            id: 25,
            slug: "uniform-cli".into(),
            title: "Uniform CLI".into(),
            status: "started".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-08".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let facets = crate::facet::EntityFacets {
            estimate: Some(crate::estimate::EstimateFacet {
                lower: 3.0,
                upper: 5.0,
            }),
            value: None,
            risk: None,
            tags: vec![],
        };
        // 25%–75% band → 50% confidence
        let out = format_show(
            &doc,
            &[],
            &crate::dep_seq::DepSeq::default(),
            "# Scope\n",
            posture,
            &facets,
            "espresso_shots",
            "magic_beans",
            0.25,
            0.75,
        );
        assert!(
            out.contains("estimate: 3.5–4.5 espresso_shots (50% confidence)"),
            "VT-9 custom bounds: {out}"
        );
    }

    // VT-10: zero-width estimate (lower==upper) → single-value display.
    #[test]
    fn vt10_format_show_zero_width_estimate() {
        let doc = SliceDoc {
            id: 25,
            slug: "uniform-cli".into(),
            title: "Uniform CLI".into(),
            status: "started".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-08".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let facets = crate::facet::EntityFacets {
            estimate: Some(crate::estimate::EstimateFacet {
                lower: 5.0,
                upper: 5.0,
            }),
            value: None,
            risk: None,
            tags: vec![],
        };
        let out = format_show(
            &doc,
            &[],
            &crate::dep_seq::DepSeq::default(),
            "# Scope\n",
            posture,
            &facets,
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        assert!(
            out.contains("estimate: 5.0–5.0 espresso_shots (80% confidence)"),
            "VT-10 zero-width: {out}"
        );
    }

    #[test]
    fn show_does_not_fold_in_design_plan_or_notes() {
        // A-5: slice show reassembles metadata + scope ONLY. Even with sibling
        // artifacts on disk, neither table nor json surfaces them.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-04");
        let sr = slice_root(root);
        fs::write(sr.join("001/design.md"), "DESIGN_SECRET").unwrap();
        fs::write(sr.join("001/plan.md"), "PLAN_SECRET").unwrap();
        fs::write(sr.join("001/notes.md"), "NOTES_SECRET").unwrap();

        let (doc, toml_text, body) = read_slice(&sr, 1).unwrap();
        let tier1 = crate::relation::tier1_edges(&SLICE_KIND, &toml_text).unwrap();
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let ds = crate::dep_seq::DepSeq::default();
        let table = format_show(
            &doc,
            &tier1,
            &ds,
            &body,
            posture,
            &crate::facet::EntityFacets::default(),
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        let json = show_json(&doc, &tier1, &ds, &body).unwrap();
        for needle in ["DESIGN_SECRET", "PLAN_SECRET", "NOTES_SECRET"] {
            assert!(!table.contains(needle), "table leaked {needle}: {table}");
            assert!(!json.contains(needle), "json leaked {needle}: {json}");
        }
    }

    #[test]
    fn show_json_is_faithful_toml_as_data_plus_scope_body() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "my-slug", "My Title", "2026-06-04");
        let (doc, toml_text, body) = read_slice(&slice_root(root), 1).unwrap();
        let tier1 = crate::relation::tier1_edges(&SLICE_KIND, &toml_text).unwrap();

        let out = show_json(&doc, &tier1, &crate::dep_seq::DepSeq::default(), &body).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(parsed["kind"], "slice");
        assert_eq!(parsed["slice"]["id"], 1);
        assert_eq!(parsed["slice"]["slug"], "my-slug");
        assert_eq!(parsed["slice"]["status"], "proposed");
        // SL-048: the `relationships` object is reconstructed from `[[relation]]`.
        // SL-149 PHASE-05: the legacy specs/requirements axes are gone; `supersedes` and
        // the `references` role object are present (empty here — a virgin slice).
        let rel = &parsed["slice"]["relationships"];
        assert!(rel.get("specs").is_none());
        assert!(rel.get("requirements").is_none());
        assert!(rel["supersedes"].is_array());
        assert!(rel["references"]["implements"].is_array());
        assert!(parsed["body"].as_str().unwrap().contains("My Title"));
    }

    /// A minimal `SliceDoc` for the show_json schema tests — identity only, no facets.
    fn doc_for_json(id: u32) -> SliceDoc {
        SliceDoc {
            id,
            slug: "refs".into(),
            title: "Refs".into(),
            status: "proposed".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-01".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        }
    }

    #[test]
    fn show_json_groups_references_by_role() {
        // SL-149 PHASE-05: a fixture authoring references(implements/scoped_from/concerns)
        // → the JSON carries a `references` object grouped by role; the legacy
        // `specs`/`requirements` keys are gone (the corpus migration retired them).
        use crate::relation::{RelationEdge, RelationLabel, Role};
        let tier1 = vec![
            RelationEdge::with_role(
                RelationLabel::References,
                Some(Role::Implements),
                "SPEC-018".into(),
            ),
            RelationEdge::with_role(
                RelationLabel::References,
                Some(Role::OriginatesFrom),
                "IMP-012".into(),
            ),
            RelationEdge::with_role(
                RelationLabel::References,
                Some(Role::Concerns),
                "RFC-003".into(),
            ),
        ];
        let json = show_json(
            &doc_for_json(149),
            &tier1,
            &crate::dep_seq::DepSeq::default(),
            "# b\n",
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let rel = &v["slice"]["relationships"];
        // references grouped by role
        assert_eq!(
            rel["references"]["implements"],
            serde_json::json!(["SPEC-018"])
        );
        assert_eq!(
            rel["references"]["originates_from"],
            serde_json::json!(["IMP-012"])
        );
        assert_eq!(
            rel["references"]["concerns"],
            serde_json::json!(["RFC-003"])
        );
        // legacy keys removed (the hard cut)
        assert!(rel.get("specs").is_none(), "legacy specs key removed");
        assert!(
            rel.get("requirements").is_none(),
            "legacy requirements key removed"
        );
    }

    #[test]
    fn show_json_references_implements_carries_spec_and_req() {
        // SL-149 PHASE-05: a slice authoring references(implements) to both a SPEC and a
        // REQ (the migration target of the old specs/requirements edges) → both land in
        // the `implements` bucket; no legacy keys.
        use crate::relation::{RelationEdge, RelationLabel, Role};
        let tier1 = vec![
            RelationEdge::with_role(
                RelationLabel::References,
                Some(Role::Implements),
                "SPEC-018".into(),
            ),
            RelationEdge::with_role(
                RelationLabel::References,
                Some(Role::Implements),
                "REQ-002".into(),
            ),
        ];
        let json = show_json(
            &doc_for_json(149),
            &tier1,
            &crate::dep_seq::DepSeq::default(),
            "# b\n",
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let rel = &v["slice"]["relationships"];
        assert_eq!(
            rel["references"]["implements"],
            serde_json::json!(["SPEC-018", "REQ-002"])
        );
        assert!(rel.get("specs").is_none());
        assert!(rel.get("requirements").is_none());
    }

    #[test]
    fn show_surfaces_dep_seq_axes_in_table_and_json() {
        // SL-060: `needs`/`after` render under the same `relationships:` block (Table)
        // and the same `relationships` object (JSON), after the structural tier-1 axes.
        use crate::dep_seq::{AfterEdge, DepSeq};
        let doc = SliceDoc {
            id: 60,
            slug: "dep-seq".into(),
            title: "Dep Seq".into(),
            status: "proposed".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-01".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let tier1 = Vec::new();
        let ds = DepSeq {
            needs: vec!["SL-047".into()],
            after: vec![
                AfterEdge {
                    to: "SL-002".into(),
                    rank: 0,
                },
                AfterEdge {
                    to: "SL-003".into(),
                    rank: 5,
                },
            ],
        };
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let table = format_show(
            &doc,
            &tier1,
            &ds,
            "# body\n",
            posture,
            &crate::facet::EntityFacets::default(),
            "espresso_shots",
            "magic_beans",
            0.1,
            0.9,
        );
        assert!(table.contains("relationships:"), "block renders: {table}");
        assert!(table.contains("needs: SL-047"), "needs axis: {table}");
        // rank 0 omits the suffix; a non-zero rank renders `(rank N)`.
        assert!(
            table.contains("after: SL-002, SL-003 (rank 5)"),
            "after axis with rank suffix: {table}"
        );

        let json = show_json(&doc, &tier1, &ds, "# body\n").unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(
            v["slice"]["relationships"]["needs"],
            serde_json::json!(["SL-047"])
        );
        assert_eq!(
            v["slice"]["relationships"]["after"],
            serde_json::json!([
                { "to": "SL-002", "rank": 0 },
                { "to": "SL-003", "rank": 5 },
            ])
        );
    }

    #[test]
    fn show_omits_dep_seq_keys_when_unauthored() {
        // Additive: an unauthored slice's relationships object carries NO `needs`/
        // `after` keys (byte-stable with the pre-SL-060 shape).
        let doc = SliceDoc {
            id: 1,
            slug: "v".into(),
            title: "V".into(),
            status: "proposed".into(),
            created: "2026-06-01".into(),
            updated: "2026-06-01".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };
        let json = show_json(&doc, &[], &crate::dep_seq::DepSeq::default(), "# body\n").unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let rel = &v["slice"]["relationships"];
        assert!(rel.get("needs").is_none(), "no needs key when unauthored");
        assert!(rel.get("after").is_none(), "no after key when unauthored");
    }

    #[test]
    fn slice_doc_round_trips_estimate_facet() {
        let doc = SliceDoc {
            id: 17,
            slug: "estimate-facet".into(),
            title: "Estimate Facet".into(),
            status: "proposed".into(),
            created: "2026-06-18".into(),
            updated: "2026-06-18".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: Some(crate::estimate::EstimateFacet {
                lower: 2.0,
                upper: 8.0,
            }),
            value: None,
            selectors: vec![],
        };

        let toml = toml::to_string_pretty(&doc).unwrap();
        let parsed: SliceDoc = toml::from_str(&toml).unwrap();
        let estimate = parsed.estimate.expect("estimate facet present");
        assert_eq!(estimate.lower, 2.0);
        assert_eq!(estimate.upper, 8.0);
        assert_eq!(parsed.value, None);
    }

    #[test]
    fn slice_doc_round_trips_value_facet() {
        let doc = SliceDoc {
            id: 17,
            slug: "value-facet".into(),
            title: "Value Facet".into(),
            status: "proposed".into(),
            created: "2026-06-18".into(),
            updated: "2026-06-18".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: Some(crate::value::ValueFacet { value: 5.0 }),
            selectors: vec![],
        };

        let toml = toml::to_string_pretty(&doc).unwrap();
        let parsed: SliceDoc = toml::from_str(&toml).unwrap();
        assert_eq!(parsed.estimate, None);
        assert_eq!(
            parsed.value.expect("value facet present"),
            crate::value::ValueFacet { value: 5.0 }
        );
    }

    #[test]
    fn slice_doc_serde_omits_absent_facets() {
        let doc = SliceDoc {
            id: 18,
            slug: "no-facets".into(),
            title: "No Facets".into(),
            status: "proposed".into(),
            created: "2026-06-18".into(),
            updated: "2026-06-18".into(),
            tags: vec![],
            gate: Gate::default(),
            estimate: None,
            value: None,
            selectors: vec![],
        };

        let toml = toml::to_string_pretty(&doc).unwrap();
        assert!(
            !toml.contains("[estimate]"),
            "unexpected estimate table: {toml}"
        );
        assert!(!toml.contains("[value]"), "unexpected value table: {toml}");

        let parsed: SliceDoc = toml::from_str(&toml).unwrap();
        assert_eq!(parsed.estimate, None);
        assert_eq!(parsed.value, None);
    }

    #[test]
    fn slice_doc_malformed_facet_errors_at_parse() {
        // Validation is live via the SliceDoc serde path (VT-3): a non-finite
        // value facet on a slice toml errors at parse, not silently carried.
        let text = "id = 1\nslug = \"x\"\ntitle = \"X\"\nstatus = \"proposed\"\n\
                    created = \"2026-06-18\"\nupdated = \"2026-06-18\"\n[value]\nvalue = nan\n";
        let err = toml::from_str::<SliceDoc>(text).unwrap_err().to_string();
        assert!(err.contains("must be finite"), "got: {err}");
    }

    // --- SL-028 PHASE-02: conduct shell seam (T5/T6) ---

    #[test]
    fn load_conduct_absent_file_is_baked_defaults() {
        // No doctrine.toml at root → default config → resolve gives the baked
        // posture (T5: absent file shows the default; VT-1 absent-file fallback).
        let dir = tempfile::tempdir().unwrap();
        let cfg = load_conduct(dir.path()).unwrap();
        assert_eq!(cfg, crate::conduct::ConductConfig::default());
        // plan-source exit posture is the baked gate even with no file.
        assert_eq!(crate::conduct::resolve(&cfg, "plan").label(), "self/gate");
        // a non-gate source is self/auto.
        assert_eq!(
            crate::conduct::resolve(&cfg, "started").label(),
            "self/auto"
        );
    }

    #[test]
    fn load_conduct_reflects_a_root_override() {
        // A root doctrine.toml [conduct] override is read by the shell and folds
        // into resolve (T5: an override is reflected in the posture).
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join(crate::dtoml::DOCTRINE_TOML);
        std::fs::create_dir_all(config.parent().unwrap()).unwrap();
        fs::write(
            &config,
            "[conduct]\ndefault-actor = \"agent\"\n[conduct.ready]\nautonomy = \"gate\"\n",
        )
        .unwrap();
        let cfg = load_conduct(dir.path()).unwrap();
        // ready now gates, actor inherits the project default-actor (agent).
        assert_eq!(crate::conduct::resolve(&cfg, "ready").label(), "agent/gate");
    }

    #[test]
    fn load_conduct_refuses_malformed_doctrine_toml() {
        // A genuinely malformed file surfaces an error (not silent) — but the
        // FSM gates are untouched (this is the conduct read, advisory only).
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join(crate::dtoml::DOCTRINE_TOML);
        std::fs::create_dir_all(config.parent().unwrap()).unwrap();
        fs::write(&config, "[conduct\nbroken =").unwrap();
        assert!(load_conduct(dir.path()).is_err());
    }

    #[test]
    fn run_show_on_a_missing_slice_errors() {
        let dir = tempfile::tempdir().unwrap();
        let err = run_show(Some(dir.path().to_path_buf()), "SL-009", Format::Table).unwrap_err();
        assert!(err.to_string().contains("not found"), "got: {err}");
    }

    // VT-11: shell integration — run_show against a fixture slice with [estimate] +
    // doctrine.toml with [estimation] → confidence row in output.
    #[test]
    fn vt11_run_show_fixture_with_estimate_renders_confidence_row() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();

        // doctrine.toml with custom estimation config
        let config = root.join(crate::dtoml::DOCTRINE_TOML);
        std::fs::create_dir_all(config.parent().unwrap()).unwrap();
        fs::write(
            &config,
            "[estimation]\nunit = \"story_points\"\nlower_confidence = 0.1\nupper_confidence = 0.9\n",
        )
        .unwrap();

        // slice TOML with estimate
        let sr = slice_root(root);
        fs::create_dir_all(sr.join("001")).unwrap();
        fs::write(
            sr.join("001/slice-001.toml"),
            "id = 1\nslug = \"test\"\ntitle = \"Test\"\nstatus = \"proposed\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\n[estimate]\nlower = 3\nupper = 8\n",
        )
        .unwrap();
        fs::write(sr.join("001/slice-001.md"), "# Test slice\n").unwrap();

        let (doc, toml_text, body) = read_slice(&sr, 1).unwrap();
        let cfg = crate::dtoml::load_doctrine_toml(root).unwrap();
        let posture = crate::conduct::resolve(&cfg.conduct, &doc.status);
        let estimation_unit = crate::estimate::resolve_unit(&cfg.estimation);
        let value_unit = crate::value::resolve_unit(&cfg.value);
        let (lower_pct, upper_pct) = crate::estimate::resolve_confidence(&cfg.estimation).unwrap();
        let facets = crate::facet::EntityFacets {
            estimate: doc.estimate.clone(),
            value: doc.value.clone(),
            risk: None,
            tags: doc.tags.clone(),
        };
        let tier1 = crate::relation::tier1_edges(&SLICE_KIND, &toml_text).unwrap();
        let dep_seq = crate::dep_seq::DepSeq::default();
        let out = format_show(
            &doc,
            &tier1,
            &dep_seq,
            &body,
            posture,
            &facets,
            &estimation_unit,
            &value_unit,
            lower_pct,
            upper_pct,
        );
        assert!(
            out.contains("estimate: 3.5–7.5 story_points (80% confidence)"),
            "VT-11: {out}"
        );
    }

    // VT-12: malformed doctrine.toml → run_show returns Err (not silently defaulted).
    #[test]
    fn vt12_run_show_malformed_doctrine_toml_propagates_error() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();

        // Malformed TOML — missing `=`
        let config = root.join(crate::dtoml::DOCTRINE_TOML);
        std::fs::create_dir_all(config.parent().unwrap()).unwrap();
        fs::write(&config, "[estimation\nunit = broken").unwrap();

        // A valid slice must exist so it's the doctrine.toml that fails
        let sr = slice_root(root);
        fs::create_dir_all(sr.join("001")).unwrap();
        fs::write(
            sr.join("001/slice-001.toml"),
            "id = 1\nslug = \"test\"\ntitle = \"Test\"\nstatus = \"proposed\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n",
        )
        .unwrap();
        fs::write(sr.join("001/slice-001.md"), "# Test\n").unwrap();

        let err = run_show(Some(root.to_path_buf()), "SL-001", Format::Table).unwrap_err();
        assert!(
            err.to_string().contains("Failed to parse"),
            "VT-12: error must propagate, got: {err}"
        );
    }

    // --- SL-028 PHASE-01: lifecycle FSM ---

    // VT-1: classify table (design §5.4/§9). Edge-table driven; covers advance,
    // each back-edge, skip, abandon, noop, from-terminal, seam-breach (incl. from
    // a drifted source), and the legit seam path audit→reconcile→done = Advance.

    #[test]
    fn classify_forward_chain_is_advance() {
        for (from, to) in [
            ("proposed", "design"),
            ("design", "plan"),
            ("plan", "ready"),
            ("ready", "started"),
            ("started", "audit"),
        ] {
            assert_eq!(classify(from, to), Transition::Advance, "{from} → {to}");
        }
    }

    #[test]
    fn classify_legit_closure_seam_path_is_advance() {
        // audit → reconcile → done — the ADR-003 §7/§8 spine.
        assert_eq!(classify("audit", "reconcile"), Transition::Advance);
        assert_eq!(classify("reconcile", "done"), Transition::Advance);
    }

    #[test]
    fn classify_named_back_edges() {
        for (from, to) in [
            ("audit", "started"),
            ("audit", "design"),
            ("reconcile", "audit"),
            ("reconcile", "design"),
        ] {
            assert_eq!(classify(from, to), Transition::BackEdge, "{from} → {to}");
        }
    }

    #[test]
    fn classify_abandon_from_each_non_terminal() {
        for from in [
            "proposed",
            "design",
            "plan",
            "ready",
            "started",
            "audit",
            "reconcile",
        ] {
            assert_eq!(
                classify(from, "abandoned"),
                Transition::Abandon,
                "{from} → abandoned"
            );
        }
    }

    #[test]
    fn classify_noop_when_unchanged() {
        assert_eq!(classify("started", "started"), Transition::Noop);
        // No-op precedes from-terminal: done → done is a no-op, not a refusal.
        assert_eq!(classify("done", "done"), Transition::Noop);
    }

    #[test]
    fn classify_from_terminal_refused() {
        for from in ["done", "abandoned"] {
            assert_eq!(
                classify(from, "design"),
                Transition::FromTerminal,
                "{from} → design"
            );
        }
    }

    #[test]
    fn classify_seam_breach_to_reconcile_from_non_audit() {
        for from in ["proposed", "design", "plan", "ready", "started"] {
            assert_eq!(
                classify(from, "reconcile"),
                Transition::SeamBreach,
                "{from} → reconcile"
            );
        }
    }

    #[test]
    fn classify_seam_breach_to_done_from_non_reconcile() {
        for from in ["proposed", "design", "plan", "ready", "started", "audit"] {
            assert_eq!(
                classify(from, "done"),
                Transition::SeamBreach,
                "{from} → done"
            );
        }
    }

    #[test]
    fn classify_seam_binds_even_from_a_drifted_source() {
        // The seam is about the target edge, not the source's validity (§5.5).
        assert_eq!(classify("bogus", "reconcile"), Transition::SeamBreach);
        assert_eq!(classify("bogus", "done"), Transition::SeamBreach);
    }

    #[test]
    fn classify_move_out_of_drift_is_skip_not_refused() {
        // Out-of-vocab `from`, non-seam, non-terminal target → Skip (allowed).
        assert_eq!(classify("bogus", "started"), Transition::Skip);
    }

    #[test]
    fn classify_non_chain_move_is_skip() {
        // A legal-vocab pair the FSM never names (and not a seam target) → Skip.
        assert_eq!(classify("proposed", "started"), Transition::Skip);
        assert_eq!(classify("design", "started"), Transition::Skip);
    }

    // VT-1: the third predicate, distinct from the other two (F13).

    #[test]
    fn is_transition_terminal_is_a_distinct_third_predicate() {
        assert!(is_transition_terminal("done"));
        assert!(is_transition_terminal("abandoned"));
        assert!(!is_transition_terminal("started"));
        // Diverges from is_terminal_status ({done}) on `abandoned`...
        assert!(is_transition_terminal("abandoned") && !is_terminal_status("abandoned"));
        // ...and from is_hidden (presentation) which agrees on the set but is a
        // semantically unrelated predicate — they must not be conflated.
        assert_eq!(is_transition_terminal("done"), is_hidden("done"));
    }

    // T5: the ValueEnum ↔ const lockstep canary (cf. adr_known_set_matches_variants).

    #[test]
    fn slice_status_enum_matches_the_vocabulary() {
        let variants = [
            SliceStatus::Proposed,
            SliceStatus::Design,
            SliceStatus::Plan,
            SliceStatus::Ready,
            SliceStatus::Started,
            SliceStatus::Audit,
            SliceStatus::Reconcile,
            SliceStatus::Done,
            SliceStatus::Abandoned,
        ];
        let from_variants: Vec<&str> = variants.iter().map(|v| v.as_str()).collect();
        assert_eq!(from_variants, SLICE_STATUSES.to_vec());
    }

    // VT-2: set_slice_status — round-trip, no-op, malformed/refusal guards.

    /// Read the raw on-disk slice toml text.
    fn slice_text(root: &Path, id: u32) -> String {
        let name = format!("{id:03}");
        fs::read_to_string(
            slice_root(root)
                .join(&name)
                .join(format!("slice-{name}.toml")),
        )
        .unwrap()
    }

    #[test]
    fn set_slice_status_advances_and_preserves_comments_and_relationships() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        let before = slice_text(root, 1);
        assert!(
            before.contains("[relationships]"),
            "fixture has relationships"
        );
        let comment = before
            .lines()
            .find(|l| l.trim_start().starts_with('#'))
            .is_some();

        // proposed → design (advance).
        set_slice_status(
            &slice_root(root),
            1,
            "proposed",
            SliceStatus::Design,
            "2099-01-01",
        )
        .unwrap();
        let after = slice_text(root, 1);
        assert!(
            after.contains("status = \"design\""),
            "status written: {after}"
        );
        assert!(
            after.contains("updated = \"2099-01-01\""),
            "date stamped: {after}"
        );
        assert!(
            after.contains("[relationships]"),
            "relationships survive: {after}"
        );
        if comment {
            assert!(after.contains('#'), "comments survive: {after}");
        }
    }

    #[test]
    fn set_slice_status_noop_holds_content_and_mtime() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        let p = slice_root(root).join("001").join("slice-001.toml");
        let before = fs::read_to_string(&p).unwrap();
        let mtime_before = fs::metadata(&p).unwrap().modified().unwrap();

        // proposed → proposed: no-op, nothing written.
        set_slice_status(
            &slice_root(root),
            1,
            "proposed",
            SliceStatus::Proposed,
            "2099-01-01",
        )
        .unwrap();
        assert_eq!(fs::read_to_string(&p).unwrap(), before, "content held");
        assert_eq!(
            fs::metadata(&p).unwrap().modified().unwrap(),
            mtime_before,
            "mtime held"
        );
    }

    #[test]
    fn set_slice_status_refuses_from_terminal() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        for from in [SliceStatus::Done, SliceStatus::Abandoned] {
            let err = set_slice_status(
                &slice_root(root),
                1,
                from.as_str(),
                SliceStatus::Design,
                "x",
            )
            .unwrap_err()
            .to_string();
            assert!(err.contains("terminal"), "{}: {err}", from.as_str());
        }
        // Disk untouched (still proposed).
        assert!(slice_text(root, 1).contains("status = \"proposed\""));
    }

    #[test]
    fn set_slice_status_refuses_seam_breach() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        // started → done (skip-to-done) is a seam breach.
        let err = set_slice_status(&slice_root(root), 1, "started", SliceStatus::Done, "x")
            .unwrap_err()
            .to_string();
        assert!(err.contains("closure seam"), "skip-to-done refused: {err}");
        // design → reconcile (non-audit source) is a seam breach.
        let err2 = set_slice_status(&slice_root(root), 1, "design", SliceStatus::Reconcile, "x")
            .unwrap_err()
            .to_string();
        assert!(
            err2.contains("closure seam"),
            "non-audit → reconcile refused: {err2}"
        );
        assert!(
            slice_text(root, 1).contains("status = \"proposed\""),
            "disk untouched"
        );
    }

    #[test]
    fn set_slice_status_seam_breach_from_a_drifted_source() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        set_status_raw(root, 1, "bogus");
        // → done from a drifted source still breaches the seam (target edge).
        let err = set_slice_status(&slice_root(root), 1, "bogus", SliceStatus::Done, "x")
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("closure seam"),
            "drifted → done refused: {err}"
        );
    }

    #[test]
    fn set_slice_status_refuses_malformed_toml() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // A slice toml missing the `updated` scaffold key (hand-edited corruption).
        let d = slice_root(root).join("001");
        fs::create_dir_all(&d).unwrap();
        fs::write(
            d.join("slice-001.toml"),
            "id = 1\nslug = \"s\"\ntitle = \"S\"\nstatus = \"started\"\n",
        )
        .unwrap();
        let err = set_slice_status(&slice_root(root), 1, "started", SliceStatus::Audit, "x")
            .unwrap_err()
            .to_string();
        assert!(err.contains("malformed"), "missing key refused: {err}");
    }

    #[test]
    fn run_status_prints_classification_with_note() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        set_status_raw(root, 1, "started");
        // started → audit (advance); run_status is the thin shell, asserts no error
        // and the write landed (output goes to stdout — the writer is the unit).
        run_status(
            Some(root.to_path_buf()),
            1,
            SliceStatus::Audit,
            Some("done impl"),
        )
        .unwrap();
        assert!(
            slice_text(root, 1).contains("status = \"audit\""),
            "write landed"
        );
    }

    #[test]
    fn status_line_carries_the_source_exit_posture() {
        // VT-3 (status side): the design's example line — reconcile gates by
        // default, so its exit posture is self/gate (F19, resolve(from)).
        let cfg = crate::conduct::ConductConfig::default();
        let line = status_line(
            "reconcile",
            "done",
            classify("reconcile", "done"),
            crate::conduct::resolve(&cfg, "reconcile"),
            None,
        );
        assert_eq!(line, "reconcile → done [advance] [self/gate]");
    }

    #[test]
    fn status_line_appends_the_note_after_the_posture() {
        let cfg = crate::conduct::ConductConfig::default();
        let line = status_line(
            "started",
            "audit",
            classify("started", "audit"),
            crate::conduct::resolve(&cfg, "started"),
            Some("done impl"),
        );
        assert_eq!(line, "started → audit [advance] [self/auto] — done impl");
    }

    #[test]
    fn read_status_surfaces_the_current_authored_status() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        set_status_raw(root, 1, "reconcile");
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "reconcile");
    }

    // --- PHASE-04: reverse close-gate (design §7, D8/D-C9b) ---

    /// VT-4: `crosses_closure_seam` is true for EXACTLY the two terminal advances
    /// and false for every other edge — the gate's firing predicate.
    #[test]
    fn vt4_crosses_closure_seam_is_only_the_two_terminal_advances() {
        assert!(crosses_closure_seam("audit", "reconcile"));
        assert!(crosses_closure_seam("reconcile", "done"));
        // Non-seam transitions — never gated.
        for (from, to) in [
            ("started", "audit"),
            ("ready", "started"),
            ("plan", "ready"),
            ("audit", "started"),   // a back-edge
            ("reconcile", "audit"), // a back-edge
            ("started", "abandoned"),
            ("audit", "audit"), // no-op
        ] {
            assert!(
                !crosses_closure_seam(from, to),
                "{from} → {to} must NOT be a closure-seam crossing"
            );
        }
    }

    /// Raise one `blocker` finding on a fresh RV targeting `SL-<target_id>`. Returns
    /// the project root unchanged. Drives the real verb path (raise under the turn
    /// guard) so the ledger is authentic.
    fn raise_blocker_rv(root: &Path, target_id: u32) {
        let target = canonical_id(target_id);
        crate::review::run_new(
            Some(root.to_path_buf()),
            &crate::review::NewArgs {
                facet: crate::review::Facet::Reconciliation,
                target: target.clone(),
                phase: None,
                title: None,
                raiser: None,
                responder: None,
            },
        )
        .unwrap();
        crate::review::run_raise(
            Some(root.to_path_buf()),
            &crate::review::RaiseArgs {
                reference: "RV-001".to_owned(),
                severity: crate::review::Severity::Blocker,
                title: "must fix".to_owned(),
                detail: "d".to_owned(),
            },
            crate::review::Role::Raiser,
        )
        .unwrap();
    }

    /// VT-2 (refuse half): crossing the closure seam `audit → reconcile` is REFUSED
    /// while an Active RV targeting the slice holds an unresolved blocker, the
    /// refusal naming `RV-NNN/F-n`; the authored status is left untouched.
    #[test]
    fn vt2_close_seam_refused_on_an_unresolved_blocker() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        set_status_raw(root, 1, "audit");
        raise_blocker_rv(root, 1);

        let err = run_status(Some(root.to_path_buf()), 1, SliceStatus::Reconcile, None)
            .unwrap_err()
            .to_string();
        assert!(err.contains("RV-001/F-1"), "names the blocker: {err}");
        assert!(err.contains("refused"), "refusal wording: {err}");
        // The transition was refused BEFORE the write — status unchanged.
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "audit");
    }

    /// VT-2 (pass half): the SAME seam crossing PASSES once the blocker is verified
    /// (terminal ⇒ the RV is Done ⇒ no unresolved blocker remains).
    #[test]
    fn vt2_close_seam_passes_after_the_blocker_is_verified() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        set_status_raw(root, 1, "audit");
        raise_blocker_rv(root, 1);

        // Resolve the blocker: dispose (answered) then verify (terminal).
        crate::review::run_dispose(
            Some(root.to_path_buf()),
            &crate::review::DisposeArgs {
                reference: "RV-001".to_owned(),
                finding: "F-1".to_owned(),
                disposition: "fixed".to_owned(),
                response: "done".to_owned(),
            },
            crate::review::Role::Responder,
        )
        .unwrap();
        crate::review::run_verify(
            Some(root.to_path_buf()),
            "RV-001",
            "F-1",
            None,
            crate::review::Role::Raiser,
        )
        .unwrap();

        run_status(Some(root.to_path_buf()), 1, SliceStatus::Reconcile, None).unwrap();
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "reconcile");
    }

    /// VT-2 (withdraw variant): withdrawing the blocker also unblocks the seam.
    #[test]
    fn vt2_close_seam_passes_after_the_blocker_is_withdrawn() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        set_status_raw(root, 1, "audit");
        raise_blocker_rv(root, 1);

        crate::review::run_withdraw(
            Some(root.to_path_buf()),
            "RV-001",
            "F-1",
            crate::review::Role::Raiser,
        )
        .unwrap();
        run_status(Some(root.to_path_buf()), 1, SliceStatus::Reconcile, None).unwrap();
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "reconcile");
    }

    /// VT-4: the gate fires ONLY on the closure seam — a NON-seam slice transition
    /// (`started → audit`) is NOT gated even with an unresolved blocker present.
    #[test]
    fn vt4_non_seam_transition_is_not_gated() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "s", "S", "2026-06-04");
        set_status_raw(root, 1, "started");
        raise_blocker_rv(root, 1);

        // started → audit is a forward Advance but NOT the closure seam — passes.
        run_status(Some(root.to_path_buf()), 1, SliceStatus::Audit, None).unwrap();
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "audit");
    }

    /// VT-5 (bypass guard, Charge VIII): the close command shell (`run_status` via
    /// `set_slice_status`) is the SOLE caller crossing the closure seam. This is a
    /// SOURCE-level assertion: `set_slice_status` is private to this module, and a
    /// grep of the whole module body finds exactly ONE call site (in `run_status`,
    /// the close shell) — so no other path can cross `audit→reconcile` /
    /// `reconcile→done` and thereby bypass the gate. If a SECOND call site ever
    /// appears, this test fails, forcing that caller to re-invoke the gate (or the
    /// design to move the gate into the FSM writer).
    #[test]
    fn vt5_close_shell_is_the_sole_seam_crossing_caller_of_set_slice_status() {
        let src = include_str!("slice.rs");
        // Scope to PRODUCTION code only — `set_slice_status` is module-private, so
        // the FSM writer reaches disk via exactly the call sites in this module.
        // Test-only callers (which exercise the writer directly) are excluded by
        // cutting at the `#[cfg(test)]` boundary; my own comment mentions live past
        // it too. The production region must hold exactly ONE call site.
        let production = src.split_once("#[cfg(test)]").map_or(src, |(head, _)| head);
        let call_sites = production
            .match_indices("set_slice_status(")
            .filter(|(i, _)| {
                // Exclude the definition `fn set_slice_status(`.
                !production.get(..*i).unwrap_or("").ends_with("fn ")
            })
            .count();
        assert_eq!(
            call_sites, 1,
            "exactly ONE production caller may cross the closure seam (the close \
             shell `run_status`); a second `set_slice_status(` call site bypasses \
             the close-gate (design §7 Charge VIII — re-invoke the gate, or move \
             it into the FSM writer)"
        );
    }

    // -----------------------------------------------------------------------
    // B·P3 — closure-gate drift predicate (D-B5/D-B3, REQ-113/FR-006).
    //
    // A real born git repo so coverage staleness resolves (anchor..HEAD over the
    // touched paths): Fresh evidence ⇒ live drift; the discharge clause (c) demands
    // the REC's evidence cover today's residual keys.
    // -----------------------------------------------------------------------

    use crate::coverage::CoverageKey;
    use crate::rec::{RecDoc, RecMeta, StatusDelta};
    use crate::requirement::{self, ReqKind, ReqStatus};

    fn git(root: &Path, args: &[&str]) -> String {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(root)
            .args([
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "-c",
                "commit.gpgsign=false",
            ])
            .args(args)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8(out.stdout).unwrap().trim().to_owned()
    }

    /// A born git repo at a tempdir root, with one committed source file whose HEAD
    /// SHA is returned as the universal coverage anchor (Fresh when paths untouched
    /// since). Caller keeps the `TempDir` alive.
    fn drift_repo() -> (tempfile::TempDir, String) {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        git(root, &["init", "-q", "-b", "main"]);
        std::fs::write(root.join("src.rs"), "fn a() {}\n").unwrap();
        git(root, &["add", "src.rs"]);
        git(root, &["commit", "-q", "-m", "seed"]);
        let anchor = git(root, &["rev-parse", "HEAD"]);
        (dir, anchor)
    }

    /// Mint a requirement at `status`, returning its canonical FK (`REQ-NNN`).
    fn mint_req(root: &Path, status: ReqStatus) -> String {
        let id = requirement::reserve(root, "fast-boot", "Fast boot", "2026-06-12")
            .unwrap()
            .eid
            .numeric_id()
            .unwrap();
        requirement::set_kind(root, id, ReqKind::Functional).unwrap();
        requirement::set_status(root, id, status).unwrap();
        requirement::canonical_id(id)
    }

    /// Write a slice's OWN `coverage.toml` carrying one `Verified` entry for `req`,
    /// anchored at `anchor` over `src.rs` (Fresh in the seeded repo). `cov_slice` is
    /// the entry's `slice =` field — usually the owning slice, foreign for the
    /// integrity test.
    fn write_own_coverage(root: &Path, dir_id: u32, cov_slice: &str, req: &str, anchor: &str) {
        let d = root.join(SLICE_DIR).join(format!("{dir_id:03}"));
        fs::create_dir_all(&d).unwrap();
        let body = format!(
            "[[entry]]\nslice = \"{cov_slice}\"\nrequirement = \"{req}\"\n\
             contributing_change = \"{cov_slice}\"\nmode = \"VT\"\n\
             status = \"verified\"\ngit_anchor = \"{anchor}\"\n\
             touched_paths = [\"src.rs\"]\n"
        );
        fs::write(d.join("coverage.toml"), body).unwrap();
    }

    /// The DISTINCT coverage key the seeded `write_own_coverage` cell carries — what
    /// a discharging REC's `evidence_ref` must cover (clause c).
    fn cov_key(cov_slice: &str, req: &str) -> CoverageKey {
        CoverageKey {
            slice: cov_slice.to_owned(),
            requirement: req.to_owned(),
            contributing_change: cov_slice.to_owned(),
            mode: "VT".to_owned(),
        }
    }

    /// Materialise an owning-slice REC: `move`, one `status_delta` (req: from→to),
    /// and the given evidence keys. Returns the assigned REC id.
    fn mint_rec(
        root: &Path,
        owning: &str,
        r#move: &str,
        req: &str,
        from: ReqStatus,
        to: ReqStatus,
        evidence: Vec<CoverageKey>,
    ) -> u32 {
        let doc = RecDoc {
            tags: Vec::new(),
            id: 0,
            slug: format!("{move}-{}", req.to_lowercase()),
            title: format!("{move} {req}"),
            rec: RecMeta {
                r#move: r#move.to_owned(),
                owning_slice: Some(owning.to_owned()),
                decision_ref: None,
            },
            status_delta: vec![StatusDelta {
                requirement: req.to_owned(),
                from: from.as_str().to_owned(),
                to: to.as_str().to_owned(),
            }],
            evidence_ref: evidence,
        };
        crate::rec::materialise_populated(root, &doc).unwrap()
    }

    /// Drive the closing slice to `reconcile` (the legal source for `→ done`).
    fn slice_at_reconcile(root: &Path) {
        make_slice(root, "s", "S", "2026-06-12");
        set_status_raw(root, 1, "reconcile");
    }

    /// Attempt the `reconcile → done` crossing; return the error string (the gate
    /// refusal) — panics if it unexpectedly SUCCEEDS.
    fn expect_close_refused(root: &Path) -> String {
        run_status(Some(root.to_path_buf()), 1, SliceStatus::Done, None)
            .expect_err("reconcile → done should be refused")
            .to_string()
    }

    // --- VT-1: residual drift on a COVERED req refuses; F12 topology refuses an
    //           out-of-seam crossing INDEPENDENT of the drift check. ------------

    #[test]
    fn vt1_covered_req_residual_drift_refuses_close() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        // `pending` req with Fresh Verified coverage ⇒ Divergent(EvidenceOutruns).
        let req = mint_req(root, ReqStatus::Pending);
        write_own_coverage(root, 1, "SL-001", &req, &anchor);

        let err = expect_close_refused(root);
        assert!(err.contains("undischarged residual drift"), "{err}");
        assert!(err.contains(&req), "names the offending req: {err}");
        // Refused BEFORE the write — status stays at reconcile.
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "reconcile");
    }

    #[test]
    fn vt1_f12_topology_refuses_out_of_seam_independent_of_drift() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        // A slice in `started` (NOT `reconcile`) → `done` is an F12 SeamBreach,
        // refused structurally — no coverage/REC in sight, the drift gate never runs.
        make_slice(root, "s", "S", "2026-06-12");
        set_status_raw(root, 1, "started");
        let err = run_status(Some(root.to_path_buf()), 1, SliceStatus::Done, None)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("reconcile") && !err.contains("residual drift"),
            "F12 topology refusal, not the drift gate: {err}"
        );
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "started");
    }

    // --- VT-2 (D-B5): declared + reconciled reqs each block; additive floor. ----

    #[test]
    fn vt2_declared_extra_req_blocks_on_residual_drift() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        // The req is NOT in S's coverage.toml — only DECLARED via [gate].extra_reqs;
        // its drift must still gate. Coverage lives under a foreign slice dir so the
        // composite (corpus scan) sees it, but S's own coverage stays empty.
        let req = mint_req(root, ReqStatus::Pending);
        write_own_coverage(root, 999, "SL-999", &req, &anchor);
        // Declare it on the closing slice.
        let p = slice_root(root).join("001").join("slice-001.toml");
        let mut toml = fs::read_to_string(&p).unwrap();
        toml.push_str(&format!("\n[gate]\nextra_reqs = [\"{req}\"]\n"));
        fs::write(&p, toml).unwrap();

        let err = expect_close_refused(root);
        assert!(err.contains(&req), "declared req gates: {err}");
    }

    #[test]
    fn vt2_reconciled_req_blocks_on_residual_drift() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        // Reconciled-only: named in an owning REC's status_delta, NOT in S's
        // coverage.toml nor declared. A `revise` REC (not accept) cannot discharge,
        // so the drift it left behind still gates (the opt-in dodge is closed).
        let req = mint_req(root, ReqStatus::Pending);
        write_own_coverage(root, 999, "SL-999", &req, &anchor);
        mint_rec(
            root,
            "SL-001",
            "revise",
            &req,
            ReqStatus::Pending,
            ReqStatus::Pending,
            vec![cov_key("SL-999", &req)],
        );

        let err = expect_close_refused(root);
        assert!(err.contains(&req), "reconciled req gates: {err}");
    }

    #[test]
    fn vt2_no_gate_table_runs_on_covered_union_reconciled() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        // No [gate] table at all (declared = ∅). A covered req with residual drift
        // still gates — the floor is `covered ∪ reconciled`.
        let req = mint_req(root, ReqStatus::Pending);
        write_own_coverage(root, 1, "SL-001", &req, &anchor);
        let toml = fs::read_to_string(slice_root(root).join("001").join("slice-001.toml")).unwrap();
        assert!(!toml.contains("[gate]"), "fixture has no [gate] table");

        let err = expect_close_refused(root);
        assert!(err.contains(&req), "{err}");
    }

    // --- VT-3 (R-B4): slice-local reader — distinct reqs; foreign slice refused. -

    #[test]
    fn vt3_slice_local_reader_returns_distinct_reqs() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let d = root.join(SLICE_DIR).join("001");
        fs::create_dir_all(&d).unwrap();
        // Two entries for REQ-001 (distinct modes) + one for REQ-002 → {001, 002}.
        let body = "\
            [[entry]]\nslice = \"SL-001\"\nrequirement = \"REQ-001\"\n\
            contributing_change = \"SL-001\"\nmode = \"VT\"\nstatus = \"planned\"\n\
            git_anchor = \"a\"\n\
            [[entry]]\nslice = \"SL-001\"\nrequirement = \"REQ-001\"\n\
            contributing_change = \"SL-001\"\nmode = \"VA\"\nstatus = \"planned\"\n\
            git_anchor = \"a\"\n\
            [[entry]]\nslice = \"SL-001\"\nrequirement = \"REQ-002\"\n\
            contributing_change = \"SL-001\"\nmode = \"VT\"\nstatus = \"planned\"\n\
            git_anchor = \"a\"\n";
        fs::write(d.join("coverage.toml"), body).unwrap();
        let reqs = crate::coverage_scan::slice_local_covered_reqs(root, 1, "SL-001").unwrap();
        assert_eq!(reqs, vec!["REQ-001".to_owned(), "REQ-002".to_owned()]);
    }

    #[test]
    fn vt3_foreign_slice_in_own_coverage_is_an_integrity_error() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let d = root.join(SLICE_DIR).join("001");
        fs::create_dir_all(&d).unwrap();
        // SL-001's OWN coverage.toml citing SL-042 — a foreign slice =, refused.
        let body = "[[entry]]\nslice = \"SL-042\"\nrequirement = \"REQ-001\"\n\
            contributing_change = \"SL-042\"\nmode = \"VT\"\nstatus = \"planned\"\n\
            git_anchor = \"a\"\n";
        fs::write(d.join("coverage.toml"), body).unwrap();
        let err = crate::coverage_scan::slice_local_covered_reqs(root, 1, "SL-001")
            .unwrap_err()
            .to_string();
        assert!(err.contains("integrity error"), "{err}");
        assert!(err.contains("SL-042"), "names the foreign slice: {err}");
    }

    #[test]
    fn vt3_absent_coverage_is_empty_not_error() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        assert!(
            crate::coverage_scan::slice_local_covered_reqs(root, 1, "SL-001")
                .unwrap()
                .is_empty()
        );
    }

    // --- F-3 regression: the discharge is FOR R — a multi-delta REC must not -----
    // discharge R's drift on the strength of a foreign requirement's coinciding `to`.

    #[test]
    fn multi_delta_rec_does_not_discharge_via_foreign_requirement() {
        // A single accept REC carrying deltas for TWO requirements: R1's own delta
        // moves it to `active` (NOT R1's current authored `pending`), while R2's
        // delta happens to land on `pending`. R1 is queried at authored=pending with
        // no residual evidence. Clause (b) must look at R1's OWN delta (to=active ≠
        // pending ⇒ NOT discharged), never R2's coinciding to=pending.
        let rec = RecDoc {
            id: 1,
            slug: "accept-req-001".to_owned(),
            title: "accept REQ-001".to_owned(),
            rec: RecMeta {
                r#move: "accept".to_owned(),
                owning_slice: Some("SL-001".to_owned()),
                decision_ref: None,
            },
            tags: Vec::new(),
            status_delta: vec![
                StatusDelta {
                    requirement: "REQ-001".to_owned(),
                    from: "pending".to_owned(),
                    to: "active".to_owned(),
                },
                StatusDelta {
                    requirement: "REQ-002".to_owned(),
                    from: "active".to_owned(),
                    to: "pending".to_owned(),
                },
            ],
            evidence_ref: Vec::new(),
        };
        assert!(
            !rec_discharges(Some(&rec), "REQ-001", ReqStatus::Pending, &[]),
            "a foreign requirement's coinciding `to` laundered R1's drift"
        );
        // Control: a single-delta REC that affirms R1 AT its current status discharges.
        let affirm = RecDoc {
            status_delta: vec![StatusDelta {
                requirement: "REQ-001".to_owned(),
                from: "pending".to_owned(),
                to: "pending".to_owned(),
            }],
            ..rec
        };
        assert!(
            rec_discharges(Some(&affirm), "REQ-001", ReqStatus::Pending, &[]),
            "an accept REC affirming R1 at its current status should discharge"
        );
    }

    // --- VT-4 (discharge i): accept + to==current + evidence ⊇ residual ⇒ close. -

    #[test]
    fn vt4_matching_accept_rec_discharges_the_drift() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        // `active` req with Fresh Verified coverage: drift is Coherent for active —
        // so instead use a residual-drift status the REC then affirms. A `pending`
        // req carries Divergent drift; an accept REC with `to == pending` (current)
        // whose evidence covers the key discharges it.
        let req = mint_req(root, ReqStatus::Pending);
        write_own_coverage(root, 1, "SL-001", &req, &anchor);
        mint_rec(
            root,
            "SL-001",
            "accept",
            &req,
            ReqStatus::Pending,
            ReqStatus::Pending,
            vec![cov_key("SL-001", &req)],
        );

        run_status(Some(root.to_path_buf()), 1, SliceStatus::Done, None).unwrap();
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "done");
    }

    // --- VT-5 (discharge ii, clause c): post-REC fresh evidence re-opens drift. --

    #[test]
    fn vt5_post_rec_fresh_evidence_undischarges() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        let req = mint_req(root, ReqStatus::Pending);
        // S's coverage has the original VT cell; the REC affirms over THAT key only.
        write_own_coverage(root, 1, "SL-001", &req, &anchor);
        mint_rec(
            root,
            "SL-001",
            "accept",
            &req,
            ReqStatus::Pending,
            ReqStatus::Pending,
            vec![cov_key("SL-001", &req)],
        );
        // Fresh contradictory evidence arrives AFTER the REC: a NEW key (different
        // contributing_change) the REC's evidence_ref does not cover. The composite
        // now carries a residual key clause (c) lacks → undischarged.
        let d = root.join(SLICE_DIR).join("001");
        let extra = format!(
            "\n[[entry]]\nslice = \"SL-001\"\nrequirement = \"{req}\"\n\
             contributing_change = \"SL-002\"\nmode = \"VT\"\nstatus = \"verified\"\n\
             git_anchor = \"{anchor}\"\ntouched_paths = [\"src.rs\"]\n"
        );
        let p = d.join("coverage.toml");
        let mut body = fs::read_to_string(&p).unwrap();
        body.push_str(&extra);
        fs::write(&p, body).unwrap();

        let err = expect_close_refused(root);
        assert!(
            err.contains(&req),
            "stale REC cannot excuse fresh evidence: {err}"
        );
    }

    // --- VT-6 (discharge iii/iv): revise/redesign + foreign-slice REC don't. -----

    #[test]
    fn vt6_revise_rec_does_not_discharge() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        let req = mint_req(root, ReqStatus::Pending);
        write_own_coverage(root, 1, "SL-001", &req, &anchor);
        // A `revise` REC (move != accept) cannot discharge — clause (a) fails.
        mint_rec(
            root,
            "SL-001",
            "revise",
            &req,
            ReqStatus::Pending,
            ReqStatus::Pending,
            vec![cov_key("SL-001", &req)],
        );
        let err = expect_close_refused(root);
        assert!(err.contains(&req), "revise REC does not discharge: {err}");
    }

    #[test]
    fn vt6_foreign_owning_slice_rec_does_not_discharge() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        let req = mint_req(root, ReqStatus::Pending);
        write_own_coverage(root, 1, "SL-001", &req, &anchor);
        // An accept REC that would discharge — but owned by a DIFFERENT slice. A
        // gate honours only its OWN slice's RECs, so it is not even in scope.
        mint_rec(
            root,
            "SL-777",
            "accept",
            &req,
            ReqStatus::Pending,
            ReqStatus::Pending,
            vec![cov_key("SL-001", &req)],
        );
        let err = expect_close_refused(root);
        assert!(
            err.contains(&req),
            "foreign-slice REC does not discharge: {err}"
        );
    }

    // --- VT-7: composes with D-C9b — blocker AND drift each independently refuse. -

    #[test]
    fn vt7_blocker_and_drift_each_independently_refuse() {
        let (dir, anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        let req = mint_req(root, ReqStatus::Pending);
        write_own_coverage(root, 1, "SL-001", &req, &anchor);

        // (i) Blocker alone refuses: discharge the drift (matching accept REC), then
        // raise an unresolved blocker — the blocker gate must still refuse.
        let rec_id = mint_rec(
            root,
            "SL-001",
            "accept",
            &req,
            ReqStatus::Pending,
            ReqStatus::Pending,
            vec![cov_key("SL-001", &req)],
        );
        let _ = rec_id;
        raise_blocker_rv(root, 1);
        let err_blocker = expect_close_refused(root);
        assert!(
            err_blocker.contains("blocker review finding"),
            "blocker gate refuses independently: {err_blocker}"
        );

        // (ii) Drift alone refuses: a SEPARATE slice with residual drift but NO
        // blocker — the drift gate refuses on its own.
        let (dir2, anchor2) = drift_repo();
        let root2 = dir2.path();
        slice_at_reconcile(root2);
        let req2 = mint_req(root2, ReqStatus::Pending);
        write_own_coverage(root2, 1, "SL-001", &req2, &anchor2);
        let err_drift = expect_close_refused(root2);
        assert!(
            err_drift.contains("residual drift"),
            "drift gate refuses independently: {err_drift}"
        );
    }

    // NF-001: the closure gate cannot branch on estimate/value presence — the facet is
    // structurally absent from Gate's input type. Exhaustive (no `..`): a future
    // estimate/value field on Gate breaks this compile.
    #[test]
    fn nf001_gate_destructure_is_exhaustive_and_facet_free() {
        let Gate { extra_reqs: _ } = Gate::default();
    }

    // -----------------------------------------------------------------------
    // PHASE-02 close-integration gate (EX-1/EX-2, VT-1..VT-6). The THIRD reverse
    // close-gate: `reconcile → done` refuses when a DISPATCHED slice's code never
    // integrated to trunk. Composes with the blocker + drift gates above.
    //
    // Fixtures mirror `ledger::tests::JournalRepo` — a `journal.toml` committed on
    // an orphan `refs/heads/dispatch/<slice:03>` branch (the coordination ref tree
    // the query reads, never the working filesystem), built BEFORE the slice
    // entity so the slice's untracked working-tree files are never disturbed.
    // -----------------------------------------------------------------------

    /// A single journal row in on-disk TOML form (only the query-relevant fields
    /// carry meaning; the rest satisfy the non-`default` serde requirements).
    /// Mirrors `ledger::tests::journal_row_toml` (leaf-tier sibling — no shared
    /// cross-module test harness).
    fn dispatch_row_toml(target_ref: &str, planned_new_oid: &str) -> String {
        format!(
            "[[row]]\n\
             source_oid = \"src\"\n\
             target_ref = \"{target_ref}\"\n\
             expected_old_oid = \"{zero}\"\n\
             planned_new_oid = \"{planned_new_oid}\"\n\
             status = \"pending\"\n",
            zero = "0".repeat(40),
        )
    }

    /// Commit `body` as `journal.toml` onto an orphan `dispatch/<slice:03>` branch,
    /// leaving the working branch on `main`. Mirrors `JournalRepo::commit_journal`.
    fn commit_dispatch_journal(root: &Path, slice: u32, body: &str) {
        let branch = format!("dispatch/{slice:03}");
        git(root, &["checkout", "-q", "--orphan", &branch]);
        git(root, &["rm", "-rf", "--cached", "--ignore-unmatch", "."]);
        let rel = format!(".doctrine/dispatch/{slice:03}/journal.toml");
        let full = root.join(&rel);
        fs::create_dir_all(full.parent().unwrap()).unwrap();
        fs::write(&full, body).unwrap();
        git(root, &["add", &rel]);
        git(root, &["commit", "-q", "-m", "coordinate: journal"]);
        git(root, &["checkout", "-f", "main"]);
    }

    /// Create a fresh dispatch branch carrying ONLY a placeholder (no `journal.toml`),
    /// leaving the working branch on `main`.
    fn commit_dispatch_no_journal(root: &Path, slice: u32) {
        let branch = format!("dispatch/{slice:03}");
        git(root, &["checkout", "-q", "--orphan", &branch]);
        git(root, &["rm", "-rf", "--cached", "--ignore-unmatch", "."]);
        fs::write(root.join("placeholder.txt"), "x").unwrap();
        git(root, &["add", "placeholder.txt"]);
        git(root, &["commit", "-q", "-m", "coordinate: no journal"]);
        git(root, &["checkout", "-f", "main"]);
    }

    /// Drive `reconcile → done` to SUCCESS; panic if the gate refuses.
    fn expect_close_succeeds(root: &Path) {
        run_status(Some(root.to_path_buf()), 1, SliceStatus::Done, None)
            .expect("reconcile → done should succeed");
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "done");
    }

    // VT-1: never dispatched (no `dispatch/001` ref) ⇒ the gate is silent; the
    // crossing succeeds.
    #[test]
    fn vt1_close_integration_not_dispatched_succeeds() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        slice_at_reconcile(root);
        expect_close_succeeds(root);
    }

    // VT-1b: dispatch ref present but the journal has zero rows ⇒ NotDispatched ⇒
    // the crossing succeeds (a coordinated-but-never-projected slice).
    #[test]
    fn vt1b_close_integration_dispatched_empty_journal_succeeds() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        commit_dispatch_journal(root, 1, "");
        slice_at_reconcile(root);
        expect_close_succeeds(root);
    }

    // VT-2: dispatched, the trunk row's planned oid IS an ancestor of
    // `refs/heads/main` ⇒ Integrated ⇒ the crossing succeeds.
    #[test]
    fn vt2_close_integration_planned_on_trunk_succeeds() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        // Advance `main` so the recorded planned oid is a strict ancestor of the tip.
        std::fs::write(root.join("src.rs"), "fn a() {}\nfn b() {}\n").unwrap();
        git(root, &["add", "src.rs"]);
        git(root, &["commit", "-q", "-m", "landed"]);
        let landed = git(root, &["rev-parse", "HEAD"]);
        std::fs::write(root.join("src.rs"), "fn a() {}\nfn b() {}\nfn c() {}\n").unwrap();
        git(root, &["add", "src.rs"]);
        git(root, &["commit", "-q", "-m", "advance trunk"]);
        commit_dispatch_journal(root, 1, &dispatch_row_toml("refs/heads/main", &landed));
        slice_at_reconcile(root);
        expect_close_succeeds(root);
    }

    // VT-3: dispatched, the planned oid is NOT on trunk ⇒ Blocked ⇒ REFUSED. The
    // refusal carries both the anomaly reason token AND the retry guidance.
    #[test]
    fn vt3_close_integration_planned_off_trunk_refuses() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        // A divergent commit on a side branch, never merged into main.
        git(root, &["checkout", "-q", "-b", "side"]);
        std::fs::write(root.join("side.rs"), "fn x() {}\n").unwrap();
        git(root, &["add", "side.rs"]);
        git(root, &["commit", "-q", "-m", "divergent"]);
        let orphaned = git(root, &["rev-parse", "HEAD"]);
        git(root, &["checkout", "-f", "main"]);
        commit_dispatch_journal(root, 1, &dispatch_row_toml("refs/heads/main", &orphaned));
        slice_at_reconcile(root);

        let err = expect_close_refused(root);
        assert!(
            err.contains("not integrated to trunk"),
            "names the integration anomaly: {err}"
        );
        assert!(
            err.contains("planned tip not on trunk"),
            "carries the leaf reason token: {err}"
        );
        assert!(
            err.contains("dispatch sync --integrate"),
            "carries the retry guidance: {err}"
        );
        // Refused BEFORE the write — status stays at reconcile.
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "reconcile");
    }

    // VT-4: dispatched (journal HAS rows) but NO `refs/heads/main` row ⇒ Blocked ⇒
    // REFUSED (fail-closed — integrate --trunk never completed).
    #[test]
    fn vt4_close_integration_no_trunk_row_refuses_fail_closed() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        let oid = git(root, &["rev-parse", "HEAD"]);
        commit_dispatch_journal(root, 1, &dispatch_row_toml("refs/heads/edge", &oid));
        slice_at_reconcile(root);

        let err = expect_close_refused(root);
        assert!(
            err.contains("no trunk row") && err.contains("integrate --trunk never completed"),
            "fail-closed on a missing trunk row: {err}"
        );
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "reconcile");
    }

    // VT-5: the integration gate fires ONLY on `reconcile → done`. An unintegrated
    // dispatched slice crossing `audit → reconcile` is NOT refused by THIS gate
    // (the blocker gate runs there, but with no blocker the crossing passes).
    #[test]
    fn vt5_close_integration_does_not_fire_off_the_reconcile_done_crossing() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        // A planned oid off trunk — would Block the `reconcile → done` gate.
        git(root, &["checkout", "-q", "-b", "side"]);
        std::fs::write(root.join("side.rs"), "fn x() {}\n").unwrap();
        git(root, &["add", "side.rs"]);
        git(root, &["commit", "-q", "-m", "divergent"]);
        let orphaned = git(root, &["rev-parse", "HEAD"]);
        git(root, &["checkout", "-f", "main"]);
        commit_dispatch_journal(root, 1, &dispatch_row_toml("refs/heads/main", &orphaned));
        // Slice at `audit` — the legal source for `→ reconcile`.
        make_slice(root, "s", "S", "2026-06-12");
        set_status_raw(root, 1, "audit");

        run_status(Some(root.to_path_buf()), 1, SliceStatus::Reconcile, None)
            .expect("audit → reconcile is not gated by the integration check");
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "reconcile");
    }

    // VT-6: composition — an unintegrated slice that ALSO has an unresolved blocker
    // is refused; each gate independently suffices on the `reconcile → done`
    // crossing (the blocker gate runs first and refuses here).
    #[test]
    fn vt6_close_integration_composes_with_the_blocker_gate() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        git(root, &["checkout", "-q", "-b", "side"]);
        std::fs::write(root.join("side.rs"), "fn x() {}\n").unwrap();
        git(root, &["add", "side.rs"]);
        git(root, &["commit", "-q", "-m", "divergent"]);
        let orphaned = git(root, &["rev-parse", "HEAD"]);
        git(root, &["checkout", "-f", "main"]);
        commit_dispatch_journal(root, 1, &dispatch_row_toml("refs/heads/main", &orphaned));
        slice_at_reconcile(root);
        raise_blocker_rv(root, 1);

        // Both gates would refuse; the crossing is refused (blocker first).
        let err = expect_close_refused(root);
        assert!(
            err.contains("blocker review finding"),
            "an unresolved blocker independently refuses: {err}"
        );
        assert_eq!(read_status(&slice_root(root), 1).unwrap(), "reconcile");
    }

    // VT-6 (integration-alone half): the SAME unintegrated slice with NO blocker is
    // still refused — proving the integration gate refuses on its own.
    #[test]
    fn vt6_close_integration_refuses_independently_of_the_blocker() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        git(root, &["checkout", "-q", "-b", "side"]);
        std::fs::write(root.join("side.rs"), "fn x() {}\n").unwrap();
        git(root, &["add", "side.rs"]);
        git(root, &["commit", "-q", "-m", "divergent"]);
        let orphaned = git(root, &["rev-parse", "HEAD"]);
        git(root, &["checkout", "-f", "main"]);
        commit_dispatch_journal(root, 1, &dispatch_row_toml("refs/heads/main", &orphaned));
        slice_at_reconcile(root);

        let err = expect_close_refused(root);
        assert!(
            err.contains("not integrated to trunk"),
            "integration gate refuses with no blocker present: {err}"
        );
    }

    // Belt-and-braces: silence the unused-helper lint if `commit_dispatch_no_journal`
    // is the only at-ref-present-no-journal path exercised via the leaf unit suite;
    // here it drives a NotDispatched success the gate must wave through.
    #[test]
    fn vt1c_close_integration_dispatch_ref_present_no_journal_succeeds() {
        let (dir, _anchor) = drift_repo();
        let root = dir.path();
        commit_dispatch_no_journal(root, 1);
        slice_at_reconcile(root);
        expect_close_succeeds(root);
    }

    // --- SL-139 PHASE-03 paths verb tests ---

    fn paths_slice_fixture(root: &Path, id: u32, extra: &[&str]) {
        let slice_root = root.join(SLICE_DIR);
        let name = format!("{id:03}");
        let dir = slice_root.join(&name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(format!("slice-{name}.toml")), "toml").unwrap();
        std::fs::write(dir.join(format!("slice-{name}.md")), "md").unwrap();
        for e in extra {
            std::fs::write(dir.join(e), e).unwrap();
        }
    }

    #[test]
    fn paths_slice_full_output() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        paths_slice_fixture(root, 1, &["notes.md"]);
        let sel = crate::paths::PathSelection {
            toml: false,
            md: false,
            entity: false,
            single: false,
        };
        let slice_root = root.join(SLICE_DIR);
        let entity_dir = slice_root.join("001");
        let set = crate::paths::scan_entity_dir(
            &entity_dir,
            &entity_dir.join("slice-001.toml"),
            Some(&entity_dir.join("slice-001.md")),
            root,
        )
        .unwrap();
        let lines = crate::paths::select_paths(&set, &sel).unwrap();
        assert_eq!(
            lines,
            vec![
                ".doctrine/slice/001/slice-001.toml",
                ".doctrine/slice/001/slice-001.md",
                ".doctrine/slice/001/notes.md"
            ]
        );
    }

    #[test]
    fn paths_slice_single() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        paths_slice_fixture(root, 1, &["design.md"]);
        let sel = crate::paths::PathSelection {
            toml: false,
            md: false,
            entity: false,
            single: true,
        };
        let slice_root = root.join(SLICE_DIR);
        let entity_dir = slice_root.join("001");
        let set = crate::paths::scan_entity_dir(
            &entity_dir,
            &entity_dir.join("slice-001.toml"),
            Some(&entity_dir.join("slice-001.md")),
            root,
        )
        .unwrap();
        let lines = crate::paths::select_paths(&set, &sel).unwrap();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0], ".doctrine/slice/001/slice-001.toml");
    }

    #[test]
    fn paths_slice_missing_entity_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        // No slice dir at all.
        let slice_root = root.join(SLICE_DIR);
        let result = crate::paths::scan_entity_dir(
            &slice_root.join("999"),
            &slice_root.join("999/slice-999.toml"),
            Some(&slice_root.join("999/slice-999.md")),
            root,
        );
        assert!(result.is_err());
    }

    // -- SL-147 PHASE-01: selector tests -------------------------------

    #[test]
    fn selector_intent_serde_kebab_case_round_trip() {
        // VT-2: kebab-case round-trip via Selector struct
        let selector: Selector =
            toml::from_str("selector = \"src/x.rs\"\nintent = \"scope-relevant\"\n").unwrap();
        assert_eq!(selector.intent, SelectorIntent::ScopeRelevant);

        let selector: Selector =
            toml::from_str("selector = \"src/y.rs\"\nintent = \"design-target\"\nnote = \"hi\"\n")
                .unwrap();
        assert_eq!(selector.intent, SelectorIntent::DesignTarget);
        assert_eq!(selector.note.as_deref(), Some("hi"));

        // Unknown variant rejected
        let err = toml::from_str::<Selector>("selector = \"x\"\nintent = \"bogus\"\n");
        assert!(err.is_err(), "unknown intent should be rejected");
    }

    #[test]
    fn slice_doc_without_selectors_deserializes_empty() {
        // EX-1 / VT-2: absent [[selector]] → empty Vec
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "no-selectors", "No Selectors", "2026-06-24");
        let (doc, _toml_text, _body) = read_slice(&slice_root(root), 1).unwrap();
        assert!(doc.selectors.is_empty());
    }

    #[test]
    fn selector_add_and_read_back() {
        // VT-1: add selectors, read back via (re)deserialization
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "test", "Test", "2026-06-24");

        let slice_root = root.join(SLICE_DIR);
        let toml_path = slice_toml_path(&slice_root, 1);

        // Add 3 selectors
        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        selector_upsert(&mut doc, "src/x.rs", "design-target", None).unwrap();
        selector_upsert(&mut doc, "src/y.rs", "design-target", Some("shared note")).unwrap();
        selector_upsert(&mut doc, "docs/*.md", "scope-relevant", None).unwrap();
        fs::write(&toml_path, doc.to_string()).unwrap();

        // Re-read as SliceDoc
        let (doc, _toml_text, _body) = read_slice(&slice_root, 1).unwrap();
        assert_eq!(doc.selectors.len(), 3);
        assert_eq!(doc.selectors[0].selector, "src/x.rs");
        assert_eq!(doc.selectors[0].intent, SelectorIntent::DesignTarget);
        assert_eq!(doc.selectors[0].note, None);
        assert_eq!(doc.selectors[1].selector, "src/y.rs");
        assert_eq!(doc.selectors[1].note.as_deref(), Some("shared note"));
        assert_eq!(doc.selectors[2].selector, "docs/*.md");
        assert_eq!(doc.selectors[2].intent, SelectorIntent::ScopeRelevant);
    }

    #[test]
    fn selector_upsert_is_idempotent() {
        // VT-1: re-add same selector updates intent/note
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "test", "Test", "2026-06-24");

        let slice_root = root.join(SLICE_DIR);
        let toml_path = slice_toml_path(&slice_root, 1);

        // First add
        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        selector_upsert(&mut doc, "src/x.rs", "scope-relevant", Some("first")).unwrap();
        fs::write(&toml_path, doc.to_string()).unwrap();

        // Re-add with different intent + note
        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        selector_upsert(&mut doc, "src/x.rs", "design-target", Some("updated")).unwrap();
        fs::write(&toml_path, doc.to_string()).unwrap();

        // Read back — should have ONE entry with updated values
        let (doc, _toml_text, _body) = read_slice(&slice_root, 1).unwrap();
        assert_eq!(doc.selectors.len(), 1, "upsert should not duplicate");
        assert_eq!(doc.selectors[0].selector, "src/x.rs");
        assert_eq!(doc.selectors[0].intent, SelectorIntent::DesignTarget);
        assert_eq!(doc.selectors[0].note.as_deref(), Some("updated"));
    }

    #[test]
    fn selector_note_sets_per_file_note() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "test", "Test", "2026-06-24");

        let slice_root = root.join(SLICE_DIR);
        let toml_path = slice_toml_path(&slice_root, 1);

        // Add two selectors with shared note
        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        selector_upsert(&mut doc, "src/x.rs", "design-target", Some("shared")).unwrap();
        selector_upsert(&mut doc, "src/y.rs", "design-target", Some("shared")).unwrap();
        fs::write(&toml_path, doc.to_string()).unwrap();

        // Override note on just one
        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        assert!(selector_set_note(&mut doc, "src/x.rs", "per-file override"));
        fs::write(&toml_path, doc.to_string()).unwrap();

        let (doc, _toml_text, _body) = read_slice(&slice_root, 1).unwrap();
        assert_eq!(doc.selectors.len(), 2);
        assert_eq!(doc.selectors[0].note.as_deref(), Some("per-file override"));
        assert_eq!(doc.selectors[1].note.as_deref(), Some("shared"));
    }

    #[test]
    fn selector_note_missing_fails() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "test", "Test", "2026-06-24");

        let slice_root = root.join(SLICE_DIR);
        let toml_path = slice_toml_path(&slice_root, 1);
        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        assert!(!selector_set_note(&mut doc, "nonexistent", "note"));
    }

    #[test]
    fn selector_rm_variadic() {
        // VT-1: add 3, rm 2, verify 1 remains
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "test", "Test", "2026-06-24");

        let slice_root = root.join(SLICE_DIR);
        let toml_path = slice_toml_path(&slice_root, 1);

        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        selector_upsert(&mut doc, "src/a.rs", "design-target", None).unwrap();
        selector_upsert(&mut doc, "src/b.rs", "design-target", None).unwrap();
        selector_upsert(&mut doc, "src/c.rs", "design-target", None).unwrap();
        fs::write(&toml_path, doc.to_string()).unwrap();

        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        let removed = selector_remove_many(&mut doc, &["src/a.rs".into(), "src/b.rs".into()]);
        assert_eq!(removed, 2);
        fs::write(&toml_path, doc.to_string()).unwrap();

        let (doc, _toml_text, _body) = read_slice(&slice_root, 1).unwrap();
        assert_eq!(doc.selectors.len(), 1);
        assert_eq!(doc.selectors[0].selector, "src/c.rs");
    }

    #[test]
    fn selector_rm_noop_on_missing() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        make_slice(root, "test", "Test", "2026-06-24");

        let slice_root = root.join(SLICE_DIR);
        let toml_path = slice_toml_path(&slice_root, 1);
        let mut doc = fs::read_to_string(&toml_path)
            .unwrap()
            .parse::<toml_edit::DocumentMut>()
            .unwrap();
        let removed = selector_remove_many(&mut doc, &["nonexistent".into()]);
        assert_eq!(removed, 0);
    }

    // --- conformance shell (SL-147 PHASE-03, design D6 / Data flow) --------

    // VT-1: the name-status fold parses A/M/D and folds a rename to D(src)+A(dst).
    #[test]
    fn fold_name_status_parses_each_class_and_renames() {
        let mut actual: std::collections::BTreeMap<String, Vec<Status>> =
            std::collections::BTreeMap::new();
        fold_name_status_line("A\tsrc/new.rs", &mut actual);
        fold_name_status_line("M\tsrc/state.rs", &mut actual);
        fold_name_status_line("D\tsrc/gone.rs", &mut actual);
        fold_name_status_line("R100\tsrc/old.rs\tsrc/moved.rs", &mut actual);

        assert_eq!(actual["src/new.rs"], vec![Status::Added]);
        assert_eq!(actual["src/state.rs"], vec![Status::Modified]);
        assert_eq!(actual["src/gone.rs"], vec![Status::Deleted]);
        assert_eq!(actual["src/old.rs"], vec![Status::Deleted]);
        assert_eq!(actual["src/moved.rs"], vec![Status::Added]);
    }

    /// Commit `path` (relative to `repo`) with `content`, returning the new HEAD.
    fn commit_file(repo: &Path, path: &str, content: &str) -> String {
        let full = repo.join(path);
        fs::create_dir_all(full.parent().unwrap()).unwrap();
        fs::write(&full, content).unwrap();
        git(repo, &["add", path]);
        git(repo, &["commit", "-q", "-m", &format!("touch {path}")]);
        git(repo, &["rev-parse", "HEAD"])
    }

    fn write_phase_completed(repo: &Path, slice_id: u32, stem: &str) {
        let dir = crate::state::phases_dir(repo, slice_id);
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join(format!("{stem}.toml")), "status = \"completed\"\n").unwrap();
    }

    // VT-3: a complete registry over a fixture slice yields the three cells, and
    // every conformant path carries the selector that matched it (F-7).
    #[test]
    fn conformance_partitions_into_the_three_cells_with_matched_selectors() {
        let dir = tempfile::tempdir().unwrap();
        // canonicalize so the primary-worktree resolution aligns with `root`.
        let repo = fs::canonicalize(dir.path()).unwrap();
        git(&repo, &["init", "-q", "-b", "main"]);
        git(&repo, &["commit", "-q", "--allow-empty", "-m", "root"]);
        let base = git(&repo, &["rev-parse", "HEAD"]);

        // The fixture slice + its design-target selectors. `src/**` is declared
        // and delivered; `docs/missing.md` is declared but never touched.
        make_slice(&repo, "conf", "Conformance Fixture", "2026-06-24");
        run_selector_add(
            Some(repo.clone()),
            1,
            SelectorIntent::DesignTarget,
            &["src/**".to_string(), "docs/missing.md".to_string()],
            None,
        )
        .unwrap();
        // a scope-relevant selector must be ignored by conformance.
        run_selector_add(
            Some(repo.clone()),
            1,
            SelectorIntent::ScopeRelevant,
            &["Cargo.toml".to_string()],
            None,
        )
        .unwrap();

        // PHASE-01 touches a declared path; PHASE-02 touches an undeclared one.
        let p1 = commit_file(&repo, "src/feature.rs", "fn f() {}\n");
        let p2 = commit_file(&repo, "README.md", "surprise\n");

        write_phase_completed(&repo, 1, "phase-01");
        write_phase_completed(&repo, 1, "phase-02");
        crate::state::record_source_delta(
            &repo,
            1,
            crate::boundary::BoundaryRow {
                phase: "PHASE-01".into(),
                code_start_oid: base.clone(),
                code_end_oid: p1.clone(),
                provenance: crate::boundary::Provenance::Manual,
            },
        )
        .unwrap();
        crate::state::record_source_delta(
            &repo,
            1,
            crate::boundary::BoundaryRow {
                phase: "PHASE-02".into(),
                code_start_oid: p1.clone(),
                code_end_oid: p2.clone(),
                provenance: crate::boundary::Provenance::Manual,
            },
        )
        .unwrap();

        let ConformanceOutcome::Computed(result) = conformance_outcome(&repo, 1).unwrap() else {
            panic!("expected a computed outcome");
        };

        // conformant: src/feature.rs, matched by `src/**`.
        assert_eq!(result.conformant.len(), 1);
        assert_eq!(result.conformant[0].path, "src/feature.rs");
        assert_eq!(result.conformant[0].matched_selector, "src/**");
        // undeclared: README.md, added.
        assert_eq!(result.undeclared.len(), 1);
        assert_eq!(result.undeclared[0].path, "README.md");
        assert_eq!(result.undeclared[0].verb, conformance::Verb::Added);
        // undelivered: docs/missing.md (declared, never touched).
        assert_eq!(result.undelivered, vec!["docs/missing.md".to_string()]);
    }

    // VT-2: an empty registry degrades to `Unavailable` (never a clean diff).
    #[test]
    fn conformance_is_unavailable_with_no_recorded_deltas() {
        let dir = tempfile::tempdir().unwrap();
        let repo = fs::canonicalize(dir.path()).unwrap();
        git(&repo, &["init", "-q", "-b", "main"]);
        git(&repo, &["commit", "-q", "--allow-empty", "-m", "root"]);
        make_slice(&repo, "conf", "Conf", "2026-06-24");

        assert!(matches!(
            conformance_outcome(&repo, 1).unwrap(),
            ConformanceOutcome::Unavailable
        ));
    }

    // VT-2: a completed phase with no recorded row degrades to `Incomplete`,
    // naming the gap — partial coverage never reads as conformance.
    #[test]
    fn conformance_is_incomplete_on_partial_coverage() {
        let dir = tempfile::tempdir().unwrap();
        let repo = fs::canonicalize(dir.path()).unwrap();
        git(&repo, &["init", "-q", "-b", "main"]);
        git(&repo, &["commit", "-q", "--allow-empty", "-m", "root"]);
        let base = git(&repo, &["rev-parse", "HEAD"]);
        make_slice(&repo, "conf", "Conf", "2026-06-24");

        let p1 = commit_file(&repo, "src/a.rs", "x\n");
        write_phase_completed(&repo, 1, "phase-01");
        write_phase_completed(&repo, 1, "phase-02"); // completed, but no row.
        crate::state::record_source_delta(
            &repo,
            1,
            crate::boundary::BoundaryRow {
                phase: "PHASE-01".into(),
                code_start_oid: base,
                code_end_oid: p1,
                provenance: crate::boundary::Provenance::Manual,
            },
        )
        .unwrap();

        let ConformanceOutcome::Incomplete(gaps) = conformance_outcome(&repo, 1).unwrap() else {
            panic!("expected incomplete");
        };
        assert!(
            gaps.iter().any(|g| g.describe().contains("PHASE-02")),
            "names the uncovered phase: {gaps:?}"
        );
    }
}