doctrine 0.33.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
// SPDX-License-Identifier: GPL-3.0-only
//! Top-level CLI dispatch — the `Command` enum, its sub-enums, and the thin
//! dispatch match that routes each verb. Moved here from `main.rs` in SL-115
//! PHASE-04 so `main.rs` is reduced to the binary entrypoint stub (~250 LOC).

use std::io::Write;
use std::path::PathBuf;
use std::str::FromStr;

use anyhow::Result;
use clap::CommandFactory;
use clap::Subcommand;

use crate::commands::compare::CompareArgs;
use crate::commands::config::ConfigCommand;
use crate::commands::facet::{
    EstimateClearArgs, EstimatePinArgs, EstimateSetArgs, RiskClearArgs, RiskSetArgs,
    ValueClearArgs, ValuePinArgs, ValueSetArgs,
};
use crate::commands::graph::GraphFormat;
use crate::commands::publication::PublicationCommand;
use crate::listing::Format;
use crate::search::SearchArgs;

/// `inspect --direction` — the command-layer walk-direction flag (SL-138). Maps DOWN
/// to the engine's [`crate::relation_graph::TransitiveDir`] (ADR-001 — the engine
/// never depends on this clap type). `up`/`down` are mnemonic aliases: `up` = inbound
/// (blast radius — what depends on this), `down` = outbound (derivation / governance
/// ancestry).
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum DirArg {
    #[value(alias = "up")]
    Inbound,
    #[value(alias = "down")]
    Outbound,
    Both,
}

impl DirArg {
    /// Map the clap flag DOWN to the engine direction (ADR-001).
    pub(crate) fn to_transitive(self) -> crate::relation_graph::TransitiveDir {
        use crate::relation_graph::TransitiveDir;
        match self {
            Self::Inbound => TransitiveDir::Inbound,
            Self::Outbound => TransitiveDir::Outbound,
            Self::Both => TransitiveDir::Both,
        }
    }
}

// ── shared action enums (Estimate / Value) ──────────────────────────────────

#[derive(clap::Subcommand)]
pub(crate) enum EstimateAction {
    /// Set estimate bounds (SL-222 PHASE-06) — mints a session-of-one cost-anchor row
    Set(EstimateSetArgs),
    /// Pin an estimate, or --retire the active pin (gated, operator-only)
    Pin(EstimatePinArgs),
    /// Clear the active estimate anchor rows on the subject
    Clear(EstimateClearArgs),
}

#[derive(clap::Subcommand)]
pub(crate) enum ValueAction {
    /// Set a value anchor (SL-220 §4) — mints a session-of-one claim
    Set(ValueSetArgs),
    /// Pin a value anchor, or `--retire` the active pin (gated, operator-only)
    Pin(ValuePinArgs),
    /// Clear the active value anchor rows on the subject
    Clear(ValueClearArgs),
}

/// `doctrine risk set` / `doctrine risk clear`
#[derive(clap::Subcommand)]
pub(crate) enum RiskAction {
    /// Set risk likelihood/impact/origin/controls
    Set(RiskSetArgs),
    /// Clear the risk facet
    Clear(RiskClearArgs),
}

// ── top-level Command enum ──────────────────────────────────────────────────

#[derive(Subcommand)]
pub(crate) enum Command {
    /// Install doctrine files into a project.
    Install {
        /// Explicit project root (default: auto-detect by walking up
        /// from CWD looking for .git, .jj, .project, etc.).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,

        /// Target agent(s); repeatable. Default: auto-detect.
        #[arg(short = 'a', long)]
        agent: Vec<String>,

        /// Skill id(s) to install; repeatable. Default: all.
        #[arg(short = 's', long)]
        skill: Vec<String>,

        /// Domain(s) to install; repeatable. Default: all.
        #[arg(short = 'd', long)]
        domain: Vec<String>,

        /// Install only the memory skills (record-memory + retrieve-memory).
        /// Mutually exclusive with --skill / --domain.
        #[arg(long, conflicts_with_all = ["skill", "domain"])]
        only_memory: bool,

        /// Install to the user directory instead of the project.
        #[arg(short = 'g', long)]
        global: bool,

        /// Print the plan and exit without making changes.
        #[arg(long)]
        dry_run: bool,

        /// Skip the confirmation prompt.
        #[arg(short = 'y', long)]
        yes: bool,

        /// Register the claude marketplace from the local project root (live
        /// plugin load, no network) instead of the github `install.repo` slug.
        /// Requires `.claude-plugin/marketplace.json` at the root.
        #[arg(long)]
        dev: bool,
    },

    /// Debug catalog inspection.
    ///
    /// Thin JSON dump of the hydrated entity corpus (`scan`) and its graph
    /// projection (`graph`). Developer-facing; not gating for acceptance (SL-071 D12).
    Catalog {
        #[command(subcommand)]
        command: crate::catalog::CatalogCommand,
    },

    /// Start the local map explorer web server.
    Map {
        #[command(subcommand)]
        command: crate::commands::map::MapCommand,
    },

    /// Open the map focused on the onboarding memory (human onboarding entry).
    Onboard,

    /// Create, list, and show concept maps — DSL-driven relationship diagrams.
    ConceptMap {
        #[command(subcommand)]
        command: crate::concept_map::ConceptMapCommand,
    },

    /// Create and list slices — the unit of intentional change.
    Slice {
        #[command(subcommand)]
        command: crate::slice::SliceCommand,
    },

    /// Record, show, and list memories.
    Memory {
        #[command(subcommand)]
        command: crate::memory::MemoryCommand,
    },

    /// Create, show, and list adversarial-review ledgers (the RV kind, ADR-007).
    Review {
        #[command(subcommand)]
        command: crate::review::ReviewCommand,
    },

    /// Create, show, and list reconciliation records (the REC kind, SPEC-002).
    Rec {
        #[command(subcommand)]
        command: crate::rec::RecCommand,
    },

    /// Full-text search over the entity corpus.
    Search(SearchArgs),

    /// Create, show, and transition revisions (the REV change-axis kind, ADR-013).
    Revision {
        #[command(subcommand)]
        command: crate::revision::RevisionCommand,
    },

    /// Reconcile ONE requirement against observed coverage.
    ///
    /// The sole author of reconciled requirement status (SL-044). Applies exactly
    /// one move and emits one atomic REC. `--to` is required for accept/revise,
    /// omitted for redesign.
    Reconcile {
        /// The requirement to reconcile, canonical `REQ-NNN`.
        req: String,

        /// The owning slice this act is recorded against, canonical `SL-NNN`.
        #[arg(long)]
        slice: String,

        /// The reconciliation move: accept | revise | redesign.
        #[arg(long = "move", value_parser = crate::rec::RecMove::parse)]
        r#move: crate::rec::RecMove,

        /// The explicit target status (required for accept/revise; omit for
        /// redesign). The WRITTEN status — never derived from coverage (NF-001).
        #[arg(long, value_enum)]
        to: Option<crate::requirement::ReqStatus>,

        /// Optional operator note (surfaced; not stored in the REC).
        #[arg(long)]
        note: Option<String>,

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

    /// Requirement coverage.
    ///
    /// The read-only drift view (`show`) plus the observed-tier write path
    /// (`record`/`verify`/`forget`, SL-057).
    Coverage {
        #[command(subcommand)]
        command: crate::commands::coverage::CoverageCommand,
    },

    /// Proxy-run a project-declared check command by cadence (SL-163).
    ///
    /// Resolves the argv from the owned `[verification]` config
    /// (`quick`/`commit`/`gate`) and proxy-executes it — inherited stdio, no
    /// timeout, the child's exit code forwarded. Informs from `just check`/`just
    /// gate` defaults; never carries a host convention as correctness (POL-002).
    Check {
        #[command(subcommand)]
        command: crate::commands::check::CheckCommand,
    },

    /// Read-only cross-kind relation view.
    ///
    /// Shows one entity's authored outbound relations, derived inbound relations,
    /// and any unresolved / free-text dangling targets — grouped, direct-only
    /// (one hop).
    Inspect {
        /// Canonical ref of the entity to inspect (e.g. `SL-046`, `ADR-004`).
        id: String,

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

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

        /// Walk relations transitively (N-hop) instead of the 1-hop relation view.
        /// Relation-only — no actionability block.
        #[arg(long)]
        transitive: bool,

        /// Walk direction (transitive only): `inbound` (blast radius) | `outbound`
        /// (derivation) | `both` (default). `up`/`down` aliases.
        #[arg(long, value_enum, default_value_t = DirArg::Both, requires = "transitive")]
        direction: DirArg,

        /// Restrict the transitive walk to these labels (comma-separated). Default:
        /// every overlay-backed label.
        #[arg(
            long = "labels",
            alias = "label",
            value_delimiter = ',',
            requires = "transitive"
        )]
        labels: Vec<String>,

        /// Transitive depth cap. Absent → 5; `0` or `all` → unbounded; `N` → N.
        #[arg(long, requires = "transitive")]
        max_depth: Option<String>,

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

    /// Read-only cross-kind importance survey.
    ///
    /// Every ELIGIBLE entity in importance order (actionability, then consequence
    /// desc, then canonical-id). Blocked rows render their id in red (no separate
    /// BLOCKED column). Terminal and promoted-backlog items are excluded unless
    /// `--all`. `--hide-blocked` drops blocked rows entirely. Pagination via
    /// `--limit`/`--offset`/`--page`. Advisory — never writes.
    Survey {
        /// Include terminal + promoted-backlog items (the complete view).
        #[arg(long)]
        all: bool,

        /// Exclude blocked items.
        #[arg(long)]
        hide_blocked: bool,

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

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

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

        /// Max rows to show (default 20). Use 0 for uncapped.
        #[arg(long, default_value_t = crate::priority::SURVEY_LIMIT_DEFAULT)]
        limit: usize,

        /// Skip first N rows (default 0).
        #[arg(long, default_value_t = 0)]
        offset: usize,

        /// Page number (1-based; sugar over --offset). Mutually exclusive with --offset.
        #[arg(long, conflicts_with = "offset")]
        page: Option<usize>,
    },

    /// Read-only advisory worklist.
    ///
    /// The ACTIONABLE entities (eligible AND unblocked), in composed
    /// dependency/sequence order. Blocked items are absent (the divergence from
    /// `survey`). Mutates nothing.
    Next {
        /// Output format (table | json).
        #[arg(long, value_parser = Format::from_str, default_value_t = Format::Table)]
        format: Format,

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

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

        /// Columns to display (CSV). Available: id, kind, status, score, estimate, value, tags, title.
        #[arg(long, value_delimiter = ',')]
        columns: Option<Vec<String>>,

        /// Max rows to show (default 20). Use 0 for uncapped.
        #[arg(long, default_value_t = crate::priority::NEXT_LIMIT_DEFAULT)]
        limit: usize,

        /// Skip first N rows (default 0).
        #[arg(long, default_value_t = 0)]
        offset: usize,

        /// Page number (1-based; sugar over --offset). Mutually exclusive with --offset.
        #[arg(long, conflicts_with = "offset")]
        page: Option<usize>,

        /// Also surface composition tension callouts (SL-218 — `value_dim` vs
        /// full-score divergences), not only structure ones. JSON always carries both.
        #[arg(long)]
        verbose: bool,
    },

    /// Read-only blocker view.
    ///
    /// Shows one entity's direct blocked-by prerequisites + the items it is
    /// blocking. `--transitive` walks both chains. Display depth never reorders.
    Blockers {
        /// Canonical ref of the entity (e.g. `ISS-007`, `SL-046`).
        id: String,

        /// Walk the full transitive blocked-by / blocking chains.
        #[arg(long)]
        transitive: bool,

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

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

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

    /// Read-only structured priority explanation.
    ///
    /// Explains one entity's priority: its eligibility reason, the transitive
    /// blocker chain, the order-key contributors, any evicted soft-sequence edges,
    /// and its consequence — always to root.
    Explain {
        /// Canonical ref of the entity (e.g. `ISS-007`, `SL-046`).
        id: String,

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

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

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

    /// Read-only entity graph projection — filters, neighbourhood, and render (SL-226).
    Graph {
        /// Optional focus entity (canonical ref like `SL-226`, or memory ref `mem_<uid>` / `mem.<key>`).
        focus: Option<String>,

        /// Maximum undirected hop distance from the focus.  Default: 1.  0 = focus alone.
        #[arg(long, default_value_t = 1)]
        depth: u32,

        /// Restrict to these entity kinds (repeatable).  Prefixes: e.g. `SL`, `ADR`, `MEM`.
        #[arg(long = "kind", value_name = "K")]
        kind: Vec<String>,

        /// Filter edges to exactly this label (e.g. `requirements`).
        #[arg(long)]
        label: Option<String>,

        /// Include memory-source entities and edges (excluded by default).
        #[arg(long)]
        include_memory: bool,

        /// Output format: `dot` (Graphviz) or `json`.
        #[arg(long, default_value_t = GraphFormat::Dot, value_parser = GraphFormat::from_str)]
        format: super::graph::GraphFormat,

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

    /// Read-only interestingness findings over the priority graph.
    ///
    /// Surfaces the aggregate / relational structure a flat `next`/`survey` list cannot
    /// show: forks, joins, gating fan-out, value inversions, order displacements, score
    /// plateaus, and provenance (evicted soft edges + degraded dep cycles), grouped by
    /// kind. Advisory — never writes.
    Findings {
        /// Output format (table | json).
        #[arg(long, value_parser = Format::from_str, default_value_t = Format::Table)]
        format: Format,

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

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

    /// Create and list architecture decision records.
    Adr {
        #[command(subcommand)]
        command: crate::adr::AdrCommand,
    },

    /// Create and list governance policies (standing rules).
    Policy {
        #[command(subcommand)]
        command: crate::policy::PolicyCommand,
    },

    /// Create and list governance standards (standing conventions of practice).
    Standard {
        #[command(subcommand)]
        command: crate::standard::StandardCommand,
    },

    /// Create and list RFC discussion artifacts — governance-neutral deliberation.
    Rfc {
        #[command(subcommand)]
        command: crate::rfc::RfcCommand,
    },

    /// Create and list product / technical specifications.
    Spec {
        #[command(subcommand)]
        command: crate::spec::SpecCommand,
    },

    /// Export the doctrine corpus to an external interchange format.
    Export {
        #[command(subcommand)]
        command: ExportCommand,
    },

    /// Capture and survey backlog work-intake items (issue / improvement /
    /// chore / risk / idea).
    Backlog {
        #[command(subcommand)]
        command: crate::backlog::BacklogCommand,
    },

    /// Capture and survey durable knowledge records (assumption / decision /
    /// question / constraint / evidence / hypothesis / concept).
    Knowledge {
        #[command(subcommand)]
        command: crate::knowledge::KnowledgeCommand,
    },

    /// Add or remove tags on entity kinds that surface tags (SL-136).
    Tag {
        #[command(subcommand)]
        command: crate::commands::tag::TagCommand,
    },

    /// Survey held remote id reservations (`refs/doctrine/reservation/*`, SL-148).
    Reservation {
        #[command(subcommand)]
        command: crate::commands::reservation::ReservationCommand,
    },

    /// Start the MCP stdio server (`serve --mcp`).
    Serve {
        #[command(flatten)]
        args: crate::commands::serve::ServeArgs,
    },

    /// Regenerate the governance snapshot.
    ///
    /// Regenerate the cache-friendly governance snapshot, or `boot install` to wire it.
    Boot {
        /// Wire the `@`-import + per-harness session refresh (omit to regenerate).
        #[command(subcommand)]
        command: Option<crate::boot::BootCommand>,

        /// Emit the snapshot to stdout after regenerating (mutually exclusive with --check).
        #[arg(long, conflicts_with = "check")]
        emit: bool,

        /// Wrap the `--emit` stdout as a Cursor `sessionStart` hook JSON envelope
        /// (`{"additional_context": "<snapshot>"}`) instead of raw markdown.
        #[arg(long, requires = "emit")]
        json: bool,

        /// Report disk staleness + unpopulated sections without writing (the
        /// disk sentry). Ignored when the `install` subcommand is given.
        #[arg(long)]
        check: bool,

        /// Explicit project root (default: auto-detect). Used by the bare
        /// regenerate; `boot install` carries its own `-p`.
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Provision a worktree fork (allowlisted copy, coordination tier excluded).
    Worktree {
        #[command(subcommand)]
        command: crate::worktree::WorktreeCommand,
    },

    /// Dispatch coordination-branch projection.
    ///
    /// The integration-sync seam (SL-064 / ADR-012) that materialises reviewable
    /// refs from `dispatch/<slice>`. Orchestrator-classed — refused under worker-mode.
    Dispatch {
        #[command(subcommand)]
        command: crate::dispatch::DispatchCommand,
    },

    /// Scan entity ids for integrity violations.
    ///
    /// Scans every numbered entity kind for id-integrity violations (ADR-006 D3
    /// detect-half): dir basename == toml id, no intra-kind duplicate id, and
    /// alias target equality. Exits non-zero on any violation.
    Validate {
        /// Explicit project root (default: auto-detect from CWD).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Full corpus health scan — all eight checks.
    ///
    /// Runs id integrity, relation integrity, spec FK, memory health, lifecycle,
    /// raw label, TOML parse, and prose citation checks over the corpus. Exits
    /// non-zero on any error-severity finding.
    Doctor {
        /// Explicit project root (default: auto-detect from CWD).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,

        /// Emit findings as a JSON array.
        #[arg(long)]
        json: bool,

        /// Show all findings including expected noise (raw labels, reference-doc exemplars).
        #[arg(long)]
        verbose: bool,

        /// Include prose-citation findings from terminal-status slices (done, abandoned).
        /// By default, terminal slices are excluded from `ProseCite` warnings.
        #[arg(long)]
        with_terminal_slices: bool,
    },

    /// Renumber an entity's canonical id.
    ///
    /// ADR-006 D3 repair. Takes a canonical ref (`SL-031`), moves it to the next
    /// free trunk-aware id or `--to <NNN>`, and reports inbound prose citations as
    /// danglers (never rewrites them).
    Reseat {
        /// Canonical ref to renumber, e.g. `SL-031` (never a bare id).
        reference: String,

        /// Explicit target id (default: the next free trunk-aware id).
        #[arg(long)]
        to: Option<u32>,

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

    /// Read-only relation projection views (SL-137).
    ///
    /// `doctrine relation list` — filter-and-project relation edges.
    /// `doctrine relation census` — group edges by label with resolution tallies.
    Relation {
        #[command(subcommand)]
        command: crate::commands::relation::RelationCommand,
    },

    /// Author a tier-1 relation edge.
    ///
    /// `link SL-048 governed_by ADR-010` (SL-048 §5.4). The label must be
    /// `link`-writable for the source kind, and the target must resolve to an entity
    /// of a legal kind (forward-edge validation, §5.5). Idempotent — re-linking an
    /// existing edge is a no-op.
    Link {
        /// The source entity's canonical ref (e.g. `SL-048`) or memory ref (`mem_<uid>`, `mem.<key>`).
        source: String,
        /// The relation label, e.g. `governed_by`, `consumes`, `related`.
        label: String,
        /// The intent role refining a `references` edge (SL-149): `implements`,
        /// `originates_from`, or `concerns`. Required for `references`; refused for
        /// label-only labels.
        #[arg(long)]
        role: Option<String>,
        /// The completion degree for a `fulfils` edge: `partial` or `full` (default).
        /// Only valid for the `fulfils` label; refused for all others.
        #[arg(long)]
        degree: Option<String>,
        /// A free-text descriptor stating what the edge is about (SL-196). Only valid
        /// on a `references --role concerns` edge; refused for all others. Non-empty.
        #[arg(long)]
        descriptor: Option<String>,
        /// The target — a canonical ref (`ADR-010`) for validated labels, free text
        /// for `drift`.
        target: String,
        /// Explicit project root (default: auto-detect from CWD).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Inspect and modify doctrine.toml [priority] coefficients.
    Config {
        #[command(subcommand)]
        command: ConfigCommand,
    },

    /// Validate the publication declaration (SL-223 — the public asset set).
    Publication {
        #[command(subcommand)]
        command: PublicationCommand,
    },

    /// Read the published framework asset library (SL-227 — list, tree, show).
    Library {
        #[command(subcommand)]
        command: crate::commands::library::LibraryCommand,
    },

    /// Remove a tier-1 relation edge.
    ///
    /// Removes an edge authored by `link` (SL-048 §5.4). Symmetric on the same write
    /// seam; idempotent — unlinking an absent edge is a no-op.
    Unlink {
        /// The source entity's canonical ref (e.g. `SL-048`) or memory ref (`mem_<uid>`, `mem.<key>`).
        source: String,
        /// The relation label to remove, e.g. `governed_by`.
        label: String,
        /// The role of the `references` edge to remove (SL-149) — the removal matches
        /// the full `(label, role, target)` triple.
        #[arg(long)]
        role: Option<String>,
        /// The target ref the edge points at.
        target: String,
        /// Explicit project root (default: auto-detect from CWD).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Append a hard prerequisite.
    ///
    /// `needs SL-060 SL-047` (SL-060 §5.4). Generic cross-kind: SRC and TGT resolve
    /// via the same canonical-ref seam as `link`. SRC must be a dep/seq-authoring
    /// kind (slice or a backlog kind); TGT must resolve AND be work-like (slice or
    /// backlog) — a free-text or non-work-like target is refused at author time.
    /// Idempotent.
    Needs {
        /// The source entity's canonical ref, e.g. `SL-060`.
        source: String,
        /// The prerequisite target's canonical ref, e.g. `SL-047`.
        target: String,
        /// Explicit project root (default: auto-detect from CWD).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Append a soft-sequence edge.
    ///
    /// `after SL-060 SL-047 [--rank N]` (SL-060 §5.4). Generic cross-kind with the
    /// same author-time target gate as `needs`. Records `{ to, rank }` (rank
    /// default 0). Idempotent.
    After {
        /// The source entity's canonical ref, e.g. `SL-060`.
        source: String,
        /// The predecessor target's canonical ref, e.g. `SL-047`.
        /// Required unless --prune is set (PHASE-03 pre-wire).
        #[arg(required_unless_present = "prune")]
        target: Option<String>,
        /// Per-edge manual tie-break rank. On append: sets the new edge's rank
        /// (default 0). On --remove: upper bound — only edges with rank ≤ N are
        /// removed. Ignored with --prune.
        #[arg(long, default_value_t = 0)]
        rank: i32,
        /// Remove matching after edges instead of appending.
        #[arg(long, conflicts_with = "prune")]
        remove: bool,
        /// Drop every dangling after edge from the source entity.
        #[arg(long, conflicts_with = "remove")]
        prune: bool,
        /// Explicit project root (default: auto-detect from CWD).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Read-only project orientation dashboard.
    ///
    /// Active work, blocked items, boot staleness, recent commits. 10–20 lines
    /// human output; structured JSON.
    Status {
        /// Output format (table | json).
        #[arg(long, value_parser = Format::from_str, default_value_t = Format::Table)]
        format: Format,

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

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

    /// Record that NEW supersedes OLD.
    ///
    /// `supersede ADR-012 ADR-004` (SL-062 §5.4). ADR-first — one parse-once /
    /// hold-both / write-once transaction writes `NEW.supersedes += OLD`,
    /// `OLD.superseded_by += NEW` (the single sanctioned reverse carve-out, ADR-004
    /// §5), and flips `OLD.status → superseded`. Refuses a self-edge, cross-kind
    /// refs, a non-ADR kind, and an OLD already superseded by a different ADR.
    /// Idempotent — a re-run with all three surfaces present is a no-op.
    Supersede {
        /// The superseding entity's canonical ref, e.g. `ADR-012`.
        new: String,
        /// The superseded entity's canonical ref, e.g. `ADR-004`.
        old: String,
        /// Explicit project root (default: auto-detect from CWD).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },

    /// Set or clear the [estimate] facet
    Estimate {
        #[command(subcommand)]
        action: EstimateAction,
    },
    /// Set or clear the [value] facet
    Value {
        #[command(subcommand)]
        action: ValueAction,
    },
    /// Set or clear the [facet] on a risk item
    Risk {
        #[command(subcommand)]
        action: RiskAction,
    },

    /// Capture a pairwise value comparison into an append-only session file.
    Compare(CompareArgs),

    /// Resolve and inspect the LLM prompt cascade.
    Prompt {
        #[command(subcommand)]
        command: crate::commands::prompt::PromptCommand,
    },
}

// ── help rendering ───────────────────────────────────────────────────────────

/// A navigational grouping of top-level commands (SL-150). Header-only: `members`
/// are command names matched against the live clap tree. `suppress_verbs` keeps the
/// family's commands header-only in the boot map (infra is operational / skill-driven,
/// not boot-time authoring routing — D7); the flag rides the struct so the suppression
/// is compile-linked to the family, not a separate stringly-typed key list (F-4).
struct Family {
    key: &'static str,
    members: &'static [&'static str],
    suppress_verbs: bool,
}

/// The 8-family taxonomy (SL-150 §5.2). The ONLY hand-maintained classification of
/// the top-level command surface; the drift-guard test asserts it partitions the
/// visible clap subcommands exactly (INV-1/INV-2). Families render in this declared
/// order; members within a family render in member-array order (INV-4).
static FAMILIES: &[Family] = &[
    Family {
        key: "change",
        suppress_verbs: false,
        members: &[
            "slice",
            "revision",
            "rfc",
            "rec",
            "review",
            "reconcile",
            "coverage",
        ],
    },
    Family {
        key: "governance",
        suppress_verbs: false,
        members: &["adr", "policy", "standard", "spec"],
    },
    Family {
        key: "knowledge",
        suppress_verbs: false,
        members: &["memory", "knowledge", "backlog"],
    },
    Family {
        key: "relations",
        suppress_verbs: false,
        members: &["link", "unlink", "needs", "after", "supersede"],
    },
    Family {
        key: "facets",
        suppress_verbs: false,
        members: &["estimate", "value", "compare", "risk", "tag"],
    },
    Family {
        key: "reports",
        suppress_verbs: false,
        members: &[
            "status", "next", "blockers", "survey", "explain", "findings",
        ],
    },
    Family {
        key: "explore",
        suppress_verbs: false,
        members: &[
            "search",
            "inspect",
            "relation",
            "concept-map",
            "graph",
            "map",
            "onboard",
            "library",
        ],
    },
    Family {
        key: "infra",
        suppress_verbs: true,
        members: &[
            "install",
            "boot",
            "serve",
            "config",
            "validate",
            "publication",
            "doctor",
            "check",
            "reseat",
            "export",
            "prompt",
            "reservation",
            "worktree",
            "dispatch",
            "catalog",
        ],
    },
];

/// Verbs every entity kind shares; subtracted to leave the distinctive set (SL-150).
/// `status` is deliberately NOT in the spine — not universal, lifecycle-bearing, so it
/// surfaces as distinctive where present.
const SPINE: &[&str] = &["new", "list", "show", "paths"];

/// One row in the top-level help table.
struct HelpEntry {
    name: String,
    about: String,
}

/// Render the top-level command list as a comfy-table, replacing clap's built-in
/// help output. Called from `main()` when `--help` is requested at the top level.
///
/// SL-150: commands are grouped by [`FAMILIES`] (declared order; members in member-array
/// order — INV-4) and rendered from ONE underlying table (shared column widths) via
/// [`crate::listing::render_grouped`], which injects a full-width family-heading band at
/// each group boundary. No column header row — families are the structure (A2). A member
/// that does not resolve to a visible command is skipped (the drift test guards against
/// that ever happening in practice).
pub(crate) fn render_top_level_help(color: bool, term_width: Option<u16>) -> String {
    use crate::listing::{self, Column, ColumnPaint, RenderOpts};

    let cmd = <crate::Cli as CommandFactory>::command();
    let about_of = |name: &str| -> Option<String> {
        cmd.get_subcommands()
            .find(|sub| !sub.is_hide_set() && sub.get_name() == name)
            .map(|sub| sub.get_about().map_or(String::new(), ToString::to_string))
    };

    let groups: Vec<(&str, Vec<HelpEntry>)> = FAMILIES
        .iter()
        .map(|fam| {
            let entries: Vec<HelpEntry> = fam
                .members
                .iter()
                .filter_map(|name| {
                    about_of(name).map(|about| HelpEntry {
                        name: (*name).to_string(),
                        about,
                    })
                })
                .collect();
            (fam.key, entries)
        })
        .collect();

    let cols: &[&Column<HelpEntry>] = &[
        &Column {
            name: "command",
            header: "command",
            cell: |e| e.name.clone(),
            paint: ColumnPaint::None,
        },
        &Column {
            name: "description",
            header: "description",
            cell: |e| e.about.clone(),
            paint: ColumnPaint::Alternate([listing::TITLE_EVEN, listing::TITLE_ODD]),
        },
    ];

    let opts = RenderOpts { color, term_width };
    listing::render_grouped(&groups, cols, opts)
}

/// Render the dense boot-map projection (SL-150 §5.4) — a plain-text, PUSH-tier
/// command surface for the boot snapshot. PURE: a function of the compiled clap
/// tree + the [`FAMILIES`]/[`SPINE`] taxonomy only — no clock/rng/disk/tty, so
/// two runs are byte-identical (INV-3).
///
/// Layout:
/// - a spine legend line once at the top (the [`SPINE`] verbs);
/// - per family (FAMILIES order), a header line `{key}  {member member …}` —
///   all members bare, member-array order (INV-4);
/// - a sub-line for a command IFF its distinctive set (subcommand verbs − SPINE,
///   in clap derive order — INV-4) is non-empty AND its family's `suppress_verbs`
///   is false. Leaves (no subcommands) and infra families get a header only (D7).
///
/// Names (family keys and sub-line command names) share one left-padded field
/// width so the surface scans as a column.
pub(crate) fn render_boot_map() -> String {
    use std::fmt::Write as _;

    let cmd = <crate::Cli as CommandFactory>::command();

    // Distinctive verbs for one command: its visible subcommand names, minus the
    // SPINE, preserving clap derive order. Empty for leaves / spine-only commands.
    let distinctive = |name: &str| -> Vec<String> {
        cmd.get_subcommands()
            .find(|sub| !sub.is_hide_set() && sub.get_name() == name)
            .map(|sub| {
                sub.get_subcommands()
                    .filter(|g| !g.is_hide_set() && g.get_name() != "help")
                    .map(|g| g.get_name().to_string())
                    .filter(|verb| !SPINE.contains(&verb.as_str()))
                    .collect()
            })
            .unwrap_or_default()
    };

    // Shared name-field width: the longest family key, plus a two-space gutter.
    let pad = FAMILIES.iter().map(|f| f.key.len()).max().unwrap_or(0) + 2;

    let mut out = String::new();
    out.push_str("SPINE: ");
    out.push_str(&SPINE.join(" "));
    out.push_str(" (+status where lifecycle) \u{2014} entity kinds\n\n");

    for fam in FAMILIES {
        _ = writeln!(out, "{:<pad$}{}", fam.key, fam.members.join(" "));
        if fam.suppress_verbs {
            continue;
        }
        for member in fam.members {
            let verbs = distinctive(member);
            if verbs.is_empty() {
                continue;
            }
            // sub-line: two-space indent + the same padded name field + verbs.
            _ = writeln!(out, "  {:<pad$}{}", member, verbs.join(" "));
        }
    }
    out
}

/// One row in the `--commands` subcommand-grouped help table.
struct VerbEntry {
    command: String,
    verb: String,
    description: String,
}

/// Truncate a description to its first sentence for the summary table.
/// Splits on `. ` where the next character is uppercase or a backtick —
/// avoids false splits on abbreviations ("e.g.", "i.e.", "§5.3").
/// If no such break exists, returns the full text unchanged.
fn first_sentence(about: &str) -> String {
    let mut pos = 0;
    while let Some(candidate) = about[pos..].find(". ") {
        let abs = pos + candidate;
        // Skip known abbreviations: "e.g. " and "i.e. "
        if about[..abs].ends_with("e.g") || about[..abs].ends_with("i.e") {
            pos = abs + 1; // advance past this period, keep looking
            continue;
        }
        // Check the character after ". " — must start a new sentence
        if let Some(next_char) = about[abs + 2..].chars().next()
            && (next_char.is_ascii_uppercase() || next_char == '`')
        {
            // Return up to and including the period (drop the space)
            return about[..=abs].to_string();
        }
        pos = abs + 1; // advance past this period, keep looking
    }
    about.to_string()
}

/// Render the `--help --commands` table: three-column (`command | verb | description`)
/// with each top-level command's subcommands grouped beneath it. The command name
/// appears only on the first subcommand row; continuation rows leave it blank.
/// Leaf commands (no subcommands) get a single row with an em-dash in the verb column.
/// Descriptions are truncated to the first sentence for scanability — full text
/// is available via `doctrine <command> <verb> --help`.
pub(crate) fn render_commands_table(color: bool, term_width: Option<u16>) -> String {
    use crate::listing::{self, Column, ColumnPaint, RenderOpts};

    let cmd = <crate::Cli as CommandFactory>::command();
    let mut entries: Vec<VerbEntry> = Vec::new();

    for sub in cmd
        .get_subcommands()
        .filter(|s| !s.is_hide_set() && s.get_name() != "help")
    {
        let parent = sub.get_name().to_string();
        let grandchildren: Vec<_> = sub
            .get_subcommands()
            .filter(|g| !g.is_hide_set() && g.get_name() != "help")
            .collect();

        if grandchildren.is_empty() {
            // Leaf command — single row, em-dash placeholder in verb column.
            let about = sub
                .get_about()
                .map_or(String::new(), |a| first_sentence(&a.to_string()));
            entries.push(VerbEntry {
                command: parent,
                verb: "\u{2014}".to_string(),
                description: about,
            });
        } else {
            for (i, gc) in grandchildren.into_iter().enumerate() {
                let verb = gc.get_name().to_string();
                let desc = gc
                    .get_about()
                    .map_or(String::new(), |a| first_sentence(&a.to_string()));
                entries.push(VerbEntry {
                    command: if i == 0 {
                        parent.clone()
                    } else {
                        String::new()
                    },
                    verb,
                    description: desc,
                });
            }
        }
    }

    if entries.is_empty() {
        return String::new();
    }

    let cols: &[&Column<VerbEntry>] = &[
        &Column {
            name: "command",
            header: "command",
            cell: |e| e.command.clone(),
            paint: ColumnPaint::None,
        },
        &Column {
            name: "verb",
            header: "verb",
            cell: |e| e.verb.clone(),
            paint: ColumnPaint::None,
        },
        &Column {
            name: "description",
            header: "description",
            cell: |e| e.description.clone(),
            paint: ColumnPaint::Alternate([listing::TITLE_EVEN, listing::TITLE_ODD]),
        },
    ];

    let mut out = listing::render_columns(&entries, cols, RenderOpts { color, term_width });
    out.push_str("\nFor arguments & options: doctrine <command> <verb> --help\n");
    out
}

/// One argument's clap invocation string — the left ("name") column of the
/// focused-help options section (SL-208 PHASE-01). Composed from clap's own
/// per-arg getters so the short/long/value-name contract is preserved rather than
/// re-invented: `-p, --path <PATH>` for a value option, `--worker` for a flag,
/// `<FORK>` / `[FORK]` for a required / optional positional. The value placeholder
/// uses the arg's explicit value name when set, else its upcased id.
fn arg_invocation(arg: &clap::Arg) -> String {
    use std::fmt::Write as _;

    let mut inv = String::new();
    if let Some(short) = arg.get_short() {
        _ = write!(inv, "-{short}");
    }
    if let Some(long) = arg.get_long() {
        if !inv.is_empty() {
            inv.push_str(", ");
        }
        _ = write!(inv, "--{long}");
    }

    let takes_value = arg
        .get_num_args()
        .map_or_else(|| arg.is_positional(), |range| range.takes_values());
    if takes_value {
        let value = arg.get_value_names().and_then(<[_]>::first).map_or_else(
            || arg.get_id().to_string().to_uppercase(),
            ToString::to_string,
        );
        let optional_positional = arg.is_positional() && !arg.is_required_set();
        let (open, close) = if optional_positional {
            ('[', ']')
        } else {
            ('<', '>')
        };
        if inv.is_empty() {
            _ = write!(inv, "{open}{value}{close}");
        } else {
            _ = write!(inv, " {open}{value}{close}");
        }
    }
    inv
}

/// The clap-format info annotations appended to an arg's help column (SL-208
/// PHASE-02, G3) — the RIGHT-column suffix clap's own help emits after the help
/// text, in clap's exact order and spacing: `[env: NAME]`, then `[default: v …]`,
/// then `[possible values: a, b, …]`. Each group is gated by clap's per-arg hide
/// flags, mirroring the default help template so a cloned subcommand's options
/// carry the same info contract as clap's built-in render (verified byte-for-byte
/// against `--color`). Returns an empty string when the arg has no annotations;
/// the leading space is included so the caller appends verbatim.
fn arg_annotations(arg: &clap::Arg) -> String {
    use std::fmt::Write as _;

    let mut out = String::new();

    // `[env: NAME]` — the bound environment variable, unless hidden.
    if let Some(env) = arg.get_env()
        && !arg.is_hide_env_set()
    {
        _ = write!(out, " [env: {}]", env.to_string_lossy());
    }

    // `[default: v1 v2]` — space-joined default values, unless hidden. Gated on
    // the arg taking a value: clap suppresses defaults for valueless flags (a
    // `SetTrue` flag carries an internal `"false"` default clap never prints).
    let takes_value = arg
        .get_num_args()
        .map_or_else(|| arg.is_positional(), |range| range.takes_values());
    if takes_value && !arg.is_hide_default_value_set() {
        let defaults = arg.get_default_values();
        if !defaults.is_empty() {
            let joined = defaults
                .iter()
                .map(|v| v.to_string_lossy())
                .collect::<Vec<_>>()
                .join(" ");
            _ = write!(out, " [default: {joined}]");
        }
    }

    // `[possible values: a, b, c]` — comma-space-joined names, skipping hidden
    // variants, unless the whole set is hidden.
    if !arg.is_hide_possible_values_set() {
        let names: Vec<String> = arg
            .get_possible_values()
            .iter()
            .filter(|p| !p.is_hide_set())
            .map(|p| p.get_name().to_string())
            .collect();
        if !names.is_empty() {
            _ = write!(out, " [possible values: {}]", names.join(", "));
        }
    }

    out
}

/// Render the borderless two-column `Options:` section for a focused subcommand
/// help (SL-208 PHASE-01). The left column is each visible argument's clap
/// invocation ([`arg_invocation`]), right-padded to the widest name plus a
/// two-space gutter; the right column is clap's per-arg help plus its info
/// annotations ([`arg_annotations`] — G3: `[env:]`/`[default:]`/`[possible
/// values:]`, matching clap's order and spacing). With `term_width: Some(w)` the
/// help wraps via [`textwrap::fill`] to the residual width, continuation lines
/// indented under the help column; `None` emits help verbatim (no line breaks).
/// This is thin key/value padding — NO box-drawing, deliberately distinct from
/// the `│`-separated [`crate::listing::render_table`] grid, so it does not reuse
/// (nor modify) that machinery. Colour is resolved upstream (the caller sets
/// `ColorChoice::Never` on the root before rendering, so clap emits no ANSI); the
/// `_color` slot is retained for signature symmetry with the other help
/// renderers, and the per-arg help is unstyled derive text.
pub(crate) fn render_options_section(
    cmd: &clap::Command,
    _color: bool,
    term_width: Option<u16>,
) -> String {
    use std::fmt::Write as _;

    let args: Vec<&clap::Arg> = cmd.get_arguments().filter(|a| !a.is_hide_set()).collect();
    if args.is_empty() {
        return String::new();
    }

    let names: Vec<String> = args.iter().map(|a| arg_invocation(a)).collect();
    let widest = names.iter().map(|n| n.chars().count()).max().unwrap_or(0);
    let name_col = widest + 2;
    let indent = " ".repeat(name_col + 2);

    let mut out = String::from("Options:\n");
    for (arg, name) in args.iter().zip(&names) {
        let mut help = arg
            .get_help()
            .or_else(|| arg.get_long_help())
            .map_or_else(String::new, ToString::to_string);
        // G3 — append clap's `[env:]`/`[default:]`/`[possible values:]` info
        // annotations to the help STRING before wrapping, so they flow with the
        // help column rather than being dropped.
        help.push_str(&arg_annotations(arg));
        let pad = " ".repeat(name_col.saturating_sub(name.chars().count()));

        match term_width {
            Some(w) => {
                let residual = usize::from(w).saturating_sub(name_col + 2).max(1);
                let wrapped = textwrap::fill(&help, residual);
                let mut lines = wrapped.split('\n');
                let first = lines.next().unwrap_or("");
                _ = writeln!(out, "  {name}{pad}{first}");
                for line in lines {
                    _ = writeln!(out, "{indent}{line}");
                }
            }
            None => {
                _ = writeln!(out, "  {name}{pad}{help}");
            }
        }
    }
    out
}

/// Render focused `--help` for a subcommand `path` (SL-208 PHASE-01) — the
/// replacement for clap's built-in per-subcommand help, matching the top-level
/// help's cozy-table style ([`render_top_level_help`]). Walks the clap tree from
/// the [`crate::Cli`] root via [`clap::Command::find_subcommand_mut`] for each
/// path segment (intermediate `help` tokens stripped, so
/// `["worktree","help","provision"]` resolves worktree → provision); an
/// unresolved segment yields an `unknown command: <seg>` line. Emits, in order:
/// the target's about (first paragraph), its `Usage:` line (ANSI-stripped under
/// `color: false` — F-2/VT-7), a `Commands:` cozy-table IFF it has visible
/// sub-subcommands, and always the borderless `Options:` section for its visible
/// args. PURE: a function of the compiled clap tree + inputs only.
///
/// SL-208 PHASE-02 restores clap's full info contract that the naive clone drops:
/// G1 — the `Usage:` line carries the full invocation path (`doctrine slice
/// selector add`) via a pinned `bin_name`; G2 — ancestor global options (e.g.
/// `--color`) are re-attached to the cloned target; G3 — per-arg annotations flow
/// through [`arg_annotations`].
pub(crate) fn render_subcommand_help(
    path: &[&str],
    color: bool,
    term_width: Option<u16>,
) -> String {
    let root = <crate::Cli as CommandFactory>::command();

    // Strip intermediate `help` tokens so a `help`-flavoured path still walks the
    // real command chain. Walk the UNBUILT tree (derive attaches subcommands before
    // build) via `find_subcommand` — a full `root.build()` would recurse the whole
    // tree and trip clap's deep debug-asserts on unrelated commands.
    let segments: Vec<&str> = path.iter().copied().filter(|&seg| seg != "help").collect();

    // Walk to the target, accumulating every global arg from the root and each
    // intermediate ancestor (G2 — cloning the unbuilt target drops ancestor
    // globals like `--color`; we re-attach them below).
    let mut globals: Vec<clap::Arg> = Vec::new();
    let mut resolved: &clap::Command = &root;
    for seg in &segments {
        for arg in resolved.get_arguments() {
            if arg.is_global_set() {
                globals.push(arg.clone());
            }
        }
        match resolved.find_subcommand(seg) {
            Some(next) => resolved = next,
            None => return format!("unknown command: {seg}\n"),
        }
    }

    // Own the target so we can pin bin_name / ColorChoice / re-attach globals and
    // call the `&mut` `render_usage`, whose shallow `_build_self` stays local to
    // this command (no deep recursion, no debug-assert panic).
    let mut cmd = resolved.clone();

    // G1 — the `Usage:` line carries the full invocation path, not the bare leaf.
    // `_build_self` honours an already-set bin_name, so `render_usage` prints it.
    if !segments.is_empty() {
        cmd = cmd.bin_name(format!("doctrine {}", segments.join(" ")));
    }

    // G2 — re-attach ancestor globals the clone dropped, skipping any the target
    // already defines (dedup by id or long).
    for global in &globals {
        let dup = cmd.get_arguments().any(|a| {
            a.get_id() == global.get_id()
                || (global.get_long().is_some() && a.get_long() == global.get_long())
        });
        if !dup {
            cmd = cmd.arg(global.clone());
        }
    }

    // Pin `ColorChoice::Never` (ANSI-free under `!color`, VT-3/VT-7).
    if !color {
        cmd = cmd.color(clap::ColorChoice::Never);
    }
    let cmd = &mut cmd;

    let mut out = String::new();

    // About — first paragraph only. (Clap emits no ANSI here because the root was
    // built with `ColorChoice::Never` under `!color` — VT-3.)
    if let Some(about) = cmd.get_about() {
        let about = about.to_string();
        let first = about.split("\n\n").next().unwrap_or(&about).trim_end();
        if !first.is_empty() {
            out.push_str(first);
            out.push_str("\n\n");
        }
    }

    // Usage — clap-generated; ANSI-free under `!color` via the root ColorChoice (VT-7).
    let usage = cmd.render_usage().to_string();
    out.push_str(usage.trim_end());
    out.push('\n');

    // Commands table — only when the command has visible sub-subcommands.
    let visible = |sub: &&clap::Command| !sub.is_hide_set() && sub.get_name() != "help";
    if cmd.get_subcommands().any(|s| visible(&s)) {
        let rows: Vec<Vec<String>> = cmd
            .get_subcommands()
            .filter(visible)
            .map(|s| {
                vec![
                    s.get_name().to_string(),
                    s.get_about().map_or_else(String::new, ToString::to_string),
                ]
            })
            .collect();
        out.push_str("\nCommands:\n");
        out.push_str(&crate::listing::render_table(&rows, term_width));
    }

    // Options section — always, when the command has visible args.
    let options = render_options_section(cmd, color, term_width);
    if !options.is_empty() {
        out.push('\n');
        out.push_str(&options);
    }

    out
}

// ── ExportCommand ───────────────────────────────────────────────────────────

#[derive(Subcommand)]
pub(crate) enum ExportCommand {
    /// Emit the corpus as a single lazyspec Brief (JSON) on stdout (SL-026).
    Lazyspec {
        /// Explicit project root (default: auto-detect from CWD).
        #[arg(short = 'p', long)]
        path: Option<PathBuf>,
    },
}

// ── dispatch ────────────────────────────────────────────────────────────────

pub(crate) fn dispatch(cmd: Command, color: bool) -> Result<()> {
    match cmd {
        Command::Install {
            path,
            agent,
            skill,
            domain,
            only_memory,
            global,
            dry_run,
            yes,
            dev,
        } => crate::install::run(
            path,
            &crate::install::InstallArgs {
                agents: &agent,
                skills: &skill,
                domains: &domain,
                only_memory,
                global,
                dry_run,
                yes,
                dev,
            },
        ),
        Command::ConceptMap { command } => crate::concept_map::dispatch(command, color),
        Command::Slice { command } => crate::slice::dispatch(command, color),
        Command::Memory {
            command:
                crate::memory::MemoryCommand::Sync {
                    command,
                    dry_run: sync_dry_run,
                    yes: sync_yes,
                    path: sync_path,
                },
        } => match command {
            None => crate::corpus::run_sync(sync_path, sync_dry_run, sync_yes),
            Some(crate::memory::SyncCommand::Install { path, dry_run, yes }) => {
                crate::corpus::run_sync_install(path, dry_run, yes)
            }
        },
        Command::Memory { command } => crate::memory::dispatch(command, color),
        Command::Review { command } => crate::review::dispatch(command, color),
        Command::Rec { command } => crate::rec::dispatch(command, color),
        Command::Search(args) => crate::search::run(
            args,
            crate::listing::RenderOpts {
                color,
                term_width: crate::tty::stdout_terminal_width(),
            },
        ),
        Command::Revision { command } => crate::revision::dispatch(command, color),
        Command::Reconcile {
            req,
            slice,
            r#move,
            to,
            note,
            path,
        } => crate::reconcile::run(
            path,
            &crate::reconcile::ReconcileArgs {
                req,
                slice,
                r#move,
                to,
                note,
            },
        ),
        Command::Coverage { command } => crate::commands::coverage::dispatch(command, color),
        Command::Check { command } => crate::commands::check::dispatch(command),
        Command::Inspect {
            id,
            format,
            json,
            transitive,
            direction,
            labels,
            max_depth,
            path,
        } => crate::commands::inspect::run_inspect(
            path,
            &crate::commands::inspect::InspectArgs {
                id: &id,
                format,
                json,
                transitive,
                direction: direction.to_transitive(),
                labels,
                max_depth,
            },
        ),
        Command::Survey {
            all,
            hide_blocked,
            format,
            json,
            path,
            limit,
            offset,
            page,
        } => {
            let resolved_offset = crate::priority::resolve_page_offset(page, limit, offset)?;
            crate::priority::run_survey(
                path,
                all,
                hide_blocked,
                format,
                json,
                crate::listing::RenderOpts {
                    color,
                    term_width: crate::tty::stdout_terminal_width(),
                },
                limit,
                resolved_offset,
            )
        }
        Command::Next {
            format,
            json,
            path,
            columns,
            limit,
            offset,
            page,
            verbose,
        } => {
            let resolved_offset = crate::priority::resolve_page_offset(page, limit, offset)?;
            crate::priority::run_next(
                path,
                format,
                json,
                crate::listing::RenderOpts {
                    color,
                    term_width: crate::tty::stdout_terminal_width(),
                },
                columns.as_ref(),
                limit,
                resolved_offset,
                verbose,
            )
        }
        Command::Blockers {
            id,
            transitive,
            format,
            json,
            path,
        } => crate::priority::run_blockers(
            path,
            &id,
            transitive,
            format,
            json,
            crate::listing::RenderOpts {
                color,
                term_width: crate::tty::stdout_terminal_width(),
            },
        ),
        Command::Explain {
            id,
            format,
            json,
            path,
        } => crate::priority::run_explain(
            path,
            &id,
            format,
            json,
            crate::listing::RenderOpts {
                color,
                term_width: crate::tty::stdout_terminal_width(),
            },
        ),
        Command::Findings { format, json, path } => crate::priority::run_findings(
            path,
            format,
            json,
            crate::listing::RenderOpts {
                color,
                term_width: crate::tty::stdout_terminal_width(),
            },
        ),
        Command::Graph {
            focus,
            depth,
            kind,
            label,
            include_memory,
            format,
            path,
        } => crate::commands::graph::run_graph(
            path,
            focus,
            depth,
            kind,
            label,
            include_memory,
            format,
        ),
        Command::Adr { command } => crate::adr::dispatch(command, color),
        Command::Policy { command } => crate::policy::dispatch(command, color),
        Command::Standard { command } => crate::standard::dispatch(command, color),
        Command::Rfc { command } => crate::rfc::dispatch(command, color),
        Command::Spec { command } => crate::spec::dispatch(command, color),
        Command::Export { command } => match command {
            ExportCommand::Lazyspec { path } => {
                let root = crate::root::find(path, &crate::root::default_markers())?;
                let now = crate::clock::now_timestamp()?;
                let version = env!("CARGO_PKG_VERSION");
                let json = crate::lazyspec::run_export_lazyspec(&root, &now, version)?;
                writeln!(std::io::stdout(), "{json}")?;
                Ok(())
            }
        },
        Command::Backlog { command } => crate::backlog::dispatch(command, color),
        Command::Knowledge { command } => crate::knowledge::dispatch(command, color),
        Command::Tag { command } => crate::commands::tag::dispatch(command),
        Command::Reservation { command } => crate::commands::reservation::dispatch(command),
        Command::Serve { args } => crate::commands::serve::run_serve(args),
        Command::Boot {
            command,
            check,
            emit,
            json,
            path,
        } => {
            let emit_mode = emit.then_some(if json {
                crate::boot::EmitMode::Json
            } else {
                crate::boot::EmitMode::Raw
            });
            crate::boot::dispatch(command, check, emit_mode, path, color, render_boot_map)
        }
        Command::Catalog { command } => crate::catalog::dispatch(command, color),
        // SL-228 PHASE-04 (D1/D3): the create-fork path is the Class-2 recorder for the
        // `Spawn` funnel row, but `worktree` must not import `dispatch` (the command-tier
        // back-cycle SL-204 removed). So THIS arm — and only this arm — is routed through
        // the `dispatch::` tier, which calls `worktree::run_create_fork` and lands the row
        // after the act. Every other worktree verb dispatches unchanged.
        Command::Worktree {
            command: crate::worktree::WorktreeCommand::CreateFork,
        } => crate::dispatch::run_create_fork_and_record(),
        // SL-228 PHASE-08 (T10 / D-P8-10): the funnel's landing authority is INJECTED
        // here, the one place that already depends on `crate::dispatch`. `worktree` is
        // command tier and `dispatch → worktree` already exists, so no `worktree`
        // signature may name `dispatch` — the proof is computed above and handed down as
        // a bare closure. Read-only and FAIL-SOFT: an unreadable record yields `None`
        // (fall through to the shared `git cherry` oracle), an AMBIGUOUS record yields
        // `Some(false)` (render `unknown` — never pass patch-id archaeology off as an
        // answer to a question the record already muddied).
        Command::Worktree { command } => {
            crate::worktree::dispatch(command, &|root, slice, fork| {
                use crate::dispatch::funnel::LandingVerdict;
                match crate::dispatch::funnel::resolve_landing(
                    root,
                    &crate::dispatch::dispatch_ref(slice),
                    slice,
                    fork,
                ) {
                    Ok(LandingVerdict::Landed) => Some(true),
                    Ok(LandingVerdict::Ambiguous) => Some(false),
                    Ok(LandingVerdict::NotProven | LandingVerdict::NoRow) | Err(_) => None,
                }
            })
        }
        Command::Dispatch { command } => crate::dispatch::dispatch(command, color),
        Command::Validate { path } => crate::commands::validate::run_validate(path),
        Command::Doctor {
            path,
            json,
            verbose,
            with_terminal_slices,
        } => crate::commands::doctor::run_doctor(path, json, verbose, with_terminal_slices),
        Command::Reseat {
            reference,
            to,
            path,
        } => crate::integrity::run_reseat(path, &reference, to),
        Command::Relation { command } => match command {
            crate::commands::relation::RelationCommand::List {
                include_memory,
                label,
                target,
                source_kind,
                unresolved,
                format,
                json,
                columns,
                path,
            } => crate::commands::relation::run_relation_list(
                path,
                include_memory,
                label,
                target,
                source_kind,
                unresolved,
                format,
                json,
                columns.as_deref(),
            ),
            crate::commands::relation::RelationCommand::Census {
                include_memory,
                format,
                json,
                columns,
                path,
            } => crate::commands::relation::run_relation_census(
                path,
                include_memory,
                format,
                json,
                columns.as_deref(),
            ),
        },
        Command::Link {
            source,
            label,
            role,
            degree,
            descriptor,
            target,
            path,
        } => crate::commands::relation::run_link(
            path,
            &source,
            &label,
            role.as_deref(),
            degree.as_deref(),
            descriptor.as_deref(),
            &target,
        ),
        Command::Config { command } => {
            let root = crate::root::find(None, &crate::root::default_markers())?;
            match command {
                ConfigCommand::Show(ref args) => {
                    crate::commands::config::run_config_show(&root, args)
                }
                ConfigCommand::Set(ref args) => {
                    crate::commands::config::run_config_set(&root, args)
                }
                ConfigCommand::Get(ref args) => {
                    crate::commands::config::run_config_get(&root, args)
                }
                ConfigCommand::Unset(ref args) => {
                    crate::commands::config::run_config_unset(&root, args)
                }
                ConfigCommand::Validate => crate::commands::config::run_config_validate(&root),
            }
        }
        Command::Publication { command } => match command {
            PublicationCommand::Validate => {
                crate::commands::publication::run_publication_validate()
            }
        },
        Command::Library { command } => command.run(),
        Command::Unlink {
            source,
            label,
            role,
            target,
            path,
        } => crate::commands::relation::run_unlink(path, &source, &label, role.as_deref(), &target),
        Command::Needs {
            source,
            target,
            path,
        } => crate::commands::dep_seq::run_needs_edge(path, &source, &target),
        Command::After {
            source,
            target,
            rank,
            remove,
            prune,
            path,
        } => {
            if prune {
                crate::commands::dep_seq::run_after_prune(path, &source)
            } else if remove {
                crate::commands::dep_seq::run_after_remove(
                    path,
                    &source,
                    target.as_deref().unwrap_or(""),
                    rank,
                )
            } else {
                crate::commands::dep_seq::run_after_edge(
                    path,
                    &source,
                    target.as_deref().unwrap_or(""),
                    rank,
                )
            }
        }
        Command::Status { format, json, path } => crate::status::run(path, format, json),
        Command::Estimate { action } => match action {
            EstimateAction::Set(args) => crate::commands::facet::run_estimate_set(&args),
            EstimateAction::Pin(args) => crate::commands::facet::run_estimate_pin(&args),
            EstimateAction::Clear(args) => crate::commands::facet::run_estimate_clear(&args),
        },
        Command::Value { action } => match action {
            ValueAction::Set(args) => crate::commands::facet::run_value_set(&args),
            ValueAction::Pin(args) => crate::commands::facet::run_value_pin(&args),
            ValueAction::Clear(args) => crate::commands::facet::run_value_clear(&args),
        },
        Command::Risk { action } => match action {
            RiskAction::Set(args) => crate::commands::facet::run_risk_set(&args),
            RiskAction::Clear(args) => crate::commands::facet::run_risk_clear(&args),
        },
        Command::Compare(args) => crate::commands::compare::run_compare(args),
        Command::Supersede { new, old, path } => {
            crate::commands::supersede::run_supersede(path, &new, &old)
        }
        Command::Prompt { command } => crate::commands::prompt::dispatch(command, render_boot_map),
        Command::Map { command } => crate::commands::map::dispatch(command),
        Command::Onboard => crate::commands::map::run_onboard(),
    }
}

#[cfg(test)]
#[expect(
    clippy::unwrap_used,
    clippy::expect_used,
    reason = "test code: fail-fast on internal invariant violations"
)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    /// Visible top-level command names: `!is_hide_set` and ≠ `help` — the
    /// classification denominator (mirrors the render filters, INV-1 EDGE).
    fn visible_commands() -> Vec<String> {
        let cmd = <crate::Cli as CommandFactory>::command();
        cmd.get_subcommands()
            .filter(|s| !s.is_hide_set() && s.get_name() != "help")
            .map(|s| s.get_name().to_string())
            .collect()
    }

    /// VT-1 / EX-2 — the FAMILIES ⟷ clap-tree drift guard (design §9). Three
    /// assertions; set equality alone is insufficient (a command in two families
    /// dedups in the union and would pass), so this builds a name→family collision
    /// map. INV-1 (total partition, no orphan), INV-2 (no phantom), no duplicate.
    #[test]
    fn families_partition_the_visible_command_tree() {
        let visible: std::collections::BTreeSet<String> = visible_commands().into_iter().collect();

        // (a) no duplicate member: a second insert for a name is a collision.
        let mut owner: BTreeMap<&str, &str> = BTreeMap::new();
        for fam in FAMILIES {
            for &member in fam.members {
                if let Some(prev) = owner.insert(member, fam.key) {
                    panic!(
                        "command `{member}` is in two families (`{prev}` and `{}`)",
                        fam.key
                    );
                }
            }
        }

        // (b) no phantom: every member resolves to a real visible command.
        for (&member, &family) in &owner {
            assert!(
                visible.contains(member),
                "FAMILIES member `{member}` (family `{family}`) is not a visible command"
            );
        }

        // (c) no orphan: every visible command is in some family (INV-1).
        for name in &visible {
            assert!(
                owner.contains_key(name.as_str()),
                "visible command `{name}` is not classified into any family"
            );
        }

        // Census: 46 visible top-level commands (44 at SL-150 A1 + `check` SL-163 + `doctor` SL-168)
        // + `findings` (SL-194 PHASE-01) + `onboard` (SL-201 PHASE-01) + `compare` (SL-210 PHASE-02)
        // + `publication` (SL-223 PHASE-02) + `graph` (SL-226 PHASE-04)
        // + `library` (SL-227 PHASE-02).
        assert_eq!(visible.len(), 53, "expected 53 visible top-level commands");
    }

    /// R-a — narrow-width WRAP case (design watchout): at a width that forces the
    /// description column to wrap, band injection must still map each continuation
    /// line to the right family (a continuation has a blank first column, so
    /// `is_table_row_start` is false and no spurious band is emitted mid-row). Assert
    /// exactly 8 family headings survive wrapping, and every `  {key}` heading is
    /// immediately preceded by a blank line (never mid-row).
    #[test]
    fn narrow_width_wrap_keeps_eight_bands_and_no_mid_row_heading() {
        let out = render_top_level_help(false, Some(40));
        let lines: Vec<&str> = out.lines().collect();
        let keys: std::collections::BTreeSet<&str> = [
            "change",
            "governance",
            "knowledge",
            "relations",
            "facets",
            "reports",
            "explore",
            "infra",
        ]
        .into_iter()
        .collect();
        let mut headings = 0;
        for (i, line) in lines.iter().enumerate() {
            if let Some(rest) = line.strip_prefix("  ")
                && keys.contains(rest)
            {
                headings += 1;
                assert!(
                    i > 0 && lines[i - 1].is_empty(),
                    "wrapped output put family band `{rest}` mid-row (no blank above)"
                );
            }
        }
        assert_eq!(headings, 8, "all 8 family bands must survive wrapping");
        // Wrapping actually happened: some line exceeds none and a continuation
        // (blank first column, no separator-leading token) exists.
        assert!(
            lines.iter().any(|l| {
                l.starts_with(' ') && !l.trim_start().is_empty() && {
                    let head = l.split('\u{2502}').next().unwrap_or(l);
                    head.chars().all(char::is_whitespace)
                }
            }),
            "the 40-col width must actually wrap at least one description"
        );
    }

    /// VA-1 — colour-ON smoke (design §9): the family-heading band paints its
    /// background SGR escape and pads edge-to-edge to `term_width`. NOT a byte
    /// golden — asserts escape-code presence + full-width pad, not exact bytes.
    #[test]
    fn colour_on_help_paints_full_width_family_bands() {
        let out = render_top_level_help(true, Some(80));
        // A band carries an SGR background escape (`\x1b[…m`).
        assert!(
            out.contains('\u{1b}'),
            "colour-on help must emit ANSI escapes"
        );
        // The first family band header is present and painted.
        assert!(
            out.contains("change"),
            "first family heading `change` must appear"
        );
        // Full-width pad: at least one painted line reaches the 80-col width once
        // ANSI escapes are stripped (the band fills edge-to-edge).
        let widest = out
            .lines()
            .map(|l| crate::listing::strip_ansi(l).chars().count())
            .max()
            .unwrap_or(0);
        assert!(
            widest >= 80,
            "a band line must pad to term_width (80); widest visible was {widest}"
        );
    }
}