doctrine 0.2.0

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
// 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::entity::{
    self, Artifact, Fileset, Inputs, Kind, LocalFs, MaterialiseRequest, ScaffoldCtx,
};
use crate::listing::{self, Format, ListArgs};
use crate::meta::{self, Meta};
use crate::plan::Plan;
use crate::tomlfmt::toml_string;

/// 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: "SL",
    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: "SL",
    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: "SL",
    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: "SL",
    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: PathBuf::from(format!("{name}/slice-{name}.toml")),
            body: render_toml(id, ctx.slug, ctx.title, ctx.date)?,
        },
        Artifact::File {
            rel_path: PathBuf::from(format!("{name}/slice-{name}.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`.
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 title = crate::input::resolve_title(title)?;
    let slug = crate::input::resolve_slug(&title, slug)?;
    let date = crate::clock::today();
    let trunk_ids = crate::git::trunk_entity_ids(&root, SLICE_KIND.dir)?;
    let out = entity::materialise(
        &SLICE_KIND,
        &LocalFs,
        &root,
        &MaterialiseRequest::Fresh,
        &Inputs {
            slug: &slug,
            title: &title,
            date: &date,
        },
        &trunk_ids,
    )?;

    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)?;
    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)
    )?;

    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)?;
    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)
    )?;

    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 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)?;
    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)
    )?;

    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)
            );
        }
    }
    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(())
}

/// The project conduct filename — root-level user config (the structured sibling
/// of `governance.md`), NOT a `.doctrine/` entity (design §5.3, F6).
const DOCTRINE_TOML: &str = "doctrine.toml";

/// 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> {
    let path = root.join(DOCTRINE_TOML);
    match fs::read_to_string(&path) {
        Ok(text) => crate::conduct::parse(&text)
            .with_context(|| format!("Failed to parse {}", path.display())),
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            Ok(crate::conduct::ConductConfig::default())
        }
        Err(e) => Err(e).with_context(|| format!("Failed to read {}", path.display())),
    }
}

/// 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}`"
        ),
        _ => {}
    }

    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 mut doc = text
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| format!("Failed to parse {}", path.display()))?;

    // No-op guard: an unchanged status writes nothing, so mtime/content hold.
    if doc.get("status").and_then(toml_edit::Item::as_str) == Some(to) {
        return Ok(());
    }

    let table = doc.as_table_mut();
    // F-1: `status`/`updated` are scaffold-seeded — edit in place, never create. A
    // tail `insert` on a malformed file would land the key inside the trailing
    // `[relationships]` subtable (silent corruption). Refuse instead.
    if !table.contains_key("status") || !table.contains_key("updated") {
        anyhow::bail!(
            "malformed slice {name}: missing `status`/`updated` (regenerate via `slice new`)"
        );
    }
    table.insert("status", toml_edit::value(to));
    table.insert("updated", toml_edit::value(today));
    fs::write(&path, doc.to_string()).with_context(|| format!("Failed to write {}", path.display()))
}

/// 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`].
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"
}

/// Whether leaving this status is refused by the transition verb — the
/// *reopening-refusal* set (`{done, abandoned}`), F13. A **third**, distinct
/// slice-status predicate: it is NOT [`is_terminal_status`] (divergence,
/// `{done}` — adding `abandoned` there false-flags `⚠`) nor [`is_hidden`]
/// (presentation, semantically unrelated). Reopening a closed/abandoned slice is
/// deliberately deferred, so `set_slice_status` refuses a move out of either
/// (`FromTerminal`); the three predicates diverge by design (design §5.2/§5.3).
fn is_transition_terminal(status: &str) -> bool {
    matches!(status, "done" | "abandoned")
}

/// Whether a `from → to` move crosses the **closure seam** (design §7, D8): the
/// two legitimate terminal advances `audit → reconcile` and `reconcile → done`.
/// Pure — the reverse close-gate ([`run_status`]) fires the RV-blocker scan ONLY
/// on these edges, never on any other transition (VT-4). These are exactly the
/// `to`-targets the `SeamBreach` guard protects (§5.5), taken from their one legal
/// source: structurally, `set_slice_status` is the sole writer of these moves, so
/// this shell is the sole seam-crosser (VT-5).
fn crosses_closure_seam(from: &str, to: &str) -> bool {
    matches!((from, to), ("audit", "reconcile") | ("reconcile", "done"))
}

/// How a `from → to` slice-status move classifies under the lifecycle FSM
/// (design §5.4). Pure data over the edge table — no clock/disk; the verb stamps
/// the shell-injected date. `classify` is total over its `&str` inputs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Transition {
    /// A forward step along the chain, or the legitimate seam edges.
    Advance,
    /// A correction edge that walks back to re-do an invalidated stage.
    BackEdge,
    /// A move neither forward nor a named back-edge — written and surfaced.
    Skip,
    /// `* → abandoned` from any non-terminal source.
    Abandon,
    /// `from == to`; the writer no-ops.
    Noop,
    /// Leaving a terminal source (`{done, abandoned}`) — refused (reopening
    /// deferred).
    FromTerminal,
    /// A closure-seam breach (F12): `→ reconcile` from a non-`audit` source, or
    /// `→ done` from a non-`reconcile` source — refused structurally.
    SeamBreach,
}

/// Classify a `from → to` slice-status move against the FSM (design §5.4),
/// edge-table driven (NOT index arithmetic — `abandoned` is last in the const but
/// is not "after `done`" in the FSM). `to` is assumed in-vocab (the verb boundary
/// guards an out-of-vocab target); `from` may be drifted (out-of-vocab), in which
/// case a non-seam, non-terminal move falls through to `Skip` — but the seam still
/// binds by *target* edge (`→ reconcile`/`→ done` from a drifted source is a
/// `SeamBreach`, §5.5). Precedence: no-op → from-terminal → closure-seam (by
/// target) → abandon → forward/back edges → skip.
pub(crate) fn classify(from: &str, to: &str) -> Transition {
    if from == to {
        return Transition::Noop;
    }
    if is_transition_terminal(from) {
        return Transition::FromTerminal;
    }
    // Closure seam (F12), gated by the *target* edge — binds even from a drifted
    // `from`. The legitimate seam entries are the only way in.
    if to == "reconcile" {
        return if from == "audit" {
            Transition::Advance
        } else {
            Transition::SeamBreach
        };
    }
    if to == "done" {
        return if from == "reconcile" {
            Transition::Advance
        } else {
            Transition::SeamBreach
        };
    }
    if to == "abandoned" {
        return Transition::Abandon;
    }
    // Forward chain (the non-seam advances) and the named back-edges.
    match (from, to) {
        ("proposed", "design")
        | ("design", "plan")
        | ("plan", "ready")
        | ("ready", "started")
        | ("started", "audit") => Transition::Advance,
        ("audit", "started" | "design") | ("reconcile", "audit" | "design") => Transition::BackEdge,
        _ => Transition::Skip,
    }
}

/// 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>; 5] = [
    listing::Column {
        name: "id",
        header: "id",
        cell: |(m, _)| canonical_id(m.id),
    },
    listing::Column {
        name: "status",
        header: "status",
        cell: |(m, r)| decorated_status(&m.status, r.as_ref()),
    },
    listing::Column {
        name: "phases",
        header: "phases",
        cell: |(_, r)| phases_cell(r.as_ref()),
    },
    listing::Column {
        name: "slug",
        header: "slug",
        cell: |(m, _)| m.slug.clone(),
    },
    listing::Column {
        name: "title",
        header: "title",
        cell: |(m, _)| m.title.clone(),
    },
];

/// 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,
    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: Vec::new(),
    }
}

/// 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)
}

/// 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 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")?,
        &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 sel = listing::select_columns(&SLICE_COLUMNS, SLICE_DEFAULT, columns.as_deref())?;
            Ok(listing::render_columns(&rows, &sel))
        }
        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(),
            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 inert `[relationships]` table, read as data for `show` (preserved on disk,
/// ignored by `Meta`). Every axis defaults to empty so a hand-trimmed file parses.
#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Deserialize, Serialize)]
struct Relationships {
    #[serde(default)]
    specs: Vec<String>,
    #[serde(default)]
    requirements: Vec<String>,
    #[serde(default)]
    supersedes: Vec<String>,
}

/// The full `slice-NNN.toml` read as data for `show` — `Meta`'s four list fields
/// plus the dates and the relationships table. JSON-faithful; `Meta` ignores the
/// extra keys on the list path, this surfaces them on the inspect path.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, Serialize)]
struct SliceDoc {
    id: u32,
    slug: String,
    title: String,
    status: String,
    created: String,
    updated: String,
    #[serde(default)]
    relationships: Relationships,
}

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

/// 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.
fn parse_ref(reference: &str) -> anyhow::Result<u32> {
    let digits = reference
        .strip_prefix("SL-")
        .or_else(|| reference.strip_prefix("sl-"))
        .unwrap_or(reference);
    digits.parse::<u32>().with_context(|| {
        format!("not a slice reference: `{reference}` (expected `SL-025` or `25`)")
    })
}

/// `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, body) = read_slice(&root.join(SLICE_DIR), id)?;
    let out = match format {
        Format::Table => {
            // Advisory posture (F19): the displayed (current) state's exit posture.
            let cfg = load_conduct(&root)?;
            let posture = crate::conduct::resolve(&cfg, &doc.status);
            format_show(&doc, &body, posture)
        }
        // JSON stays byte-stable — posture is a Table-line addition only (design §5.2).
        Format::Json => show_json(&doc, &body)?,
    };
    write!(io::stdout(), "{out}")?;
    Ok(())
}

/// Read one slice's `slice-NNN.toml` (as data) and `slice-NNN.md` (scope body)
/// ONLY — never design/plan/notes (A-5).
fn read_slice(slice_root: &Path, id: u32) -> anyhow::Result<(SliceDoc, String)> {
    let name = format!("{id:03}");
    let dir = slice_root.join(&name);
    let toml_path = dir.join(format!("slice-{name}.toml"));
    let text = fs::read_to_string(&toml_path)
        .with_context(|| format!("slice {name} not found at {}", toml_path.display()))?;
    let doc: SliceDoc = toml::from_str(&text)
        .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, body))
}

/// 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).
fn format_show(doc: &SliceDoc, body: &str, posture: crate::conduct::Conduct) -> String {
    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()));
    parts.push(format!(
        "created {} · updated {}\n",
        doc.created, doc.updated
    ));

    let rel = &doc.relationships;
    if !rel.specs.is_empty() || !rel.requirements.is_empty() || !rel.supersedes.is_empty() {
        parts.push("\nrelationships:\n".to_string());
        for (label, refs) in [
            ("specs", &rel.specs),
            ("requirements", &rel.requirements),
            ("supersedes", &rel.supersedes),
        ] {
            if !refs.is_empty() {
                parts.push(format!("  {label}: {}\n", refs.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).
fn show_json(doc: &SliceDoc, body: &str) -> anyhow::Result<String> {
    let value = serde_json::json!({ "kind": "slice", "slice": doc, "body": body });
    serde_json::to_string_pretty(&value).context("failed to serialize slice show JSON")
}

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

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

    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(),
        }
    }

    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)
    }

    /// 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)
    }

    #[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 },
            &[],
        )
        .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("doctrine.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").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",
            },
            &[],
        )
        .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",
            },
            &[],
        )
        .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",
            },
            &[],
        )
        .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",
            },
            &[],
        )
        .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",
            },
            &[],
        )
        .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",
            },
            &[],
        )
        .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, body) = read_slice(&slice_root(root), 1).unwrap();
        assert_eq!(doc.id, 1);
        assert_eq!(doc.slug, "my-slug");
        assert_eq!(doc.status, "proposed");
        // the inert relationships table parses as data (empty by default).
        assert!(doc.relationships.specs.is_empty());
        // the md scope body is read verbatim.
        assert!(body.contains("My Title"));
    }

    #[test]
    fn format_show_renders_identity_and_scope_body() {
        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(),
            relationships: Relationships {
                specs: vec!["PRD-010".into()],
                requirements: vec![],
                supersedes: vec![],
            },
        };
        // `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, "# Scope\n\nthe scope body.\n", posture);
        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("specs: PRD-010"), "relationships axis: {out}");
        assert!(
            out.contains("the scope body."),
            "scope body appended: {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, body) = read_slice(&sr, 1).unwrap();
        let posture =
            crate::conduct::resolve(&crate::conduct::ConductConfig::default(), &doc.status);
        let table = format_show(&doc, &body, posture);
        let json = show_json(&doc, &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, body) = read_slice(&slice_root(root), 1).unwrap();

        let out = show_json(&doc, &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");
        assert!(parsed["slice"]["relationships"]["specs"].is_array());
        assert!(parsed["body"].as_str().unwrap().contains("My Title"));
    }

    // --- 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();
        fs::write(
            dir.path().join(DOCTRINE_TOML),
            "[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();
        fs::write(dir.path().join(DOCTRINE_TOML), "[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}");
    }

    // --- 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)"
        );
    }
}