doctrine 0.19.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
// SPDX-License-Identifier: GPL-3.0-only
//! `doctrine compare` — the pairwise comparison capture verb (SL-210
//! PHASE-02; capture surface reworked for schema v2 in SL-213 PHASE-01). The
//! impure command shell over the pure wire model in `crate::comparison`: it
//! resolves refs to kinds, checks admissibility, mints the impure edge (uuid
//! v7 session/row uids + today's date), and writes a merge-clean
//! session-of-one file under `.doctrine/comparisons/`.
//!
//! v2 capture (SL-213 design S1): the response is a mutually-exclusive group
//! `--prefer | --equal | --incomparable` (exactly one); `--supersedes <uid>`
//! is validated against the loaded corpus (unknown uid = hard error — the
//! only moment a human is present); the frame derives the domain silently
//! (`prefer-first` ⇒ `priority`), via the wire tier's single table.
//!
//! Layering (ADR-001): a `command`-tier shell. Impurity (clock/uuid/disk) lives
//! here; the pure model never sees a path or a clock.
//!
//! Clap shape (EX-4): the design's PRE-AUTHORISED fallback — capture is the
//! `record` subcommand (`compare record <A> <B> …`), beside `list` / `withdraw`.
//! The primary shape (bare capture args coexisting with subcommands via
//! `args_conflicts_with_subcommands` + `subcommand_negates_reqs`) was tried
//! first and genuinely fought clap: `subcommand_negates_reqs` does NOT relax
//! REQUIRED positionals (`<A>`/`<B>`) that share an argument slot with a
//! subcommand name, so `compare list` demanded the capture positionals. The
//! subcommand group is cosmetic, not structural. `list` / `withdraw` are stubbed
//! here and land in PHASE-03 — their arg shapes are fixed now.

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

use anyhow::Context;
use clap::{Args, Subcommand, ValueEnum};

use crate::comparison::{
    self, COMPARISONS_DIR, ComparisonSession, FRAME_EQUAL_EFFORT, FRAME_PREFER_FIRST, Judgement,
    RaterKind, ResolutionStatus, Response, RowForm, RowSummary, SessionHeader, Tombstone,
    load_sessions,
};
use crate::priority::config::PriorityConfig;
use crate::priority::elicit::{
    CandidateKind, DecisionContext, ElicitInputs, ElicitQueue, EntryPayload, FrontierItem,
    ItemCosting, Participant, QueueEntry, QueueState, assemble,
};
use crate::priority::graph::{self, PriorityGraph};
use crate::priority::view::ReasonKind;

/// `doctrine compare <SUBCOMMAND>` — the comparison-ledger verb group.
#[derive(Args)]
pub(crate) struct CompareArgs {
    #[command(subcommand)]
    pub(crate) action: CompareAction,
}

/// The comparison subcommands. `record` captures; `list` / `withdraw` are
/// PHASE-03 stubs (their arg shapes are fixed now so the read-side phase only
/// fills the run paths).
#[derive(Subcommand)]
pub(crate) enum CompareAction {
    /// Capture a pairwise value comparison as a session-of-one file.
    Record(RecordArgs),
    /// List captured comparison judgements (SL-210 PHASE-03).
    List(ListArgs),
    /// Withdraw a judgement row by uid (SL-210 PHASE-03).
    Withdraw(WithdrawArgs),
    /// Surface the ranked elicitation queue — the next comparisons/anchor
    /// reviews worth asking (SL-217 PHASE-03; read-only, D18).
    Elicit(ElicitArgs),
}

/// `compare record <A> <B> <response> [flags]` — the full capture surface.
/// The response is a mutually-exclusive group (SL-213 S1): exactly one of
/// `--prefer` / `--equal` / `--incomparable`. `domain` derives from the frame
/// (never typed); `form` is fixed at `order` (no flag mints it; `--magnitude`
/// awaits RFC-019 OQ-6).
#[derive(Args)]
#[command(group = clap::ArgGroup::new("response").required(true).multiple(false))]
pub(crate) struct RecordArgs {
    /// First entity — full canonical ref (e.g. `SL-204`).
    pub(crate) a: String,
    /// Second entity — full canonical ref (e.g. `IMP-118`).
    pub(crate) b: String,
    /// Preferred side: the literal `a` / `b`, or the full ref of one side.
    #[arg(long, group = "response")]
    pub(crate) prefer: Option<String>,
    /// The two sides carry exactly equal value (compiles to a class merge).
    #[arg(long, group = "response")]
    pub(crate) equal: bool,
    /// Considered "these don't compare" — recorded as asked, zero constraint.
    #[arg(long, group = "response")]
    pub(crate) incomparable: bool,
    /// Supersede a prior judgement row by uid (explicit revision — the target
    /// must exist in the ledger).
    #[arg(long)]
    pub(crate) supersedes: Option<String>,
    /// Comparison frame (closed vocab; default `equal-effort`). `prefer-first`
    /// asks "under a binding capacity cutoff, which do you keep?" and records
    /// a priority-domain row — not value-bearing.
    #[arg(long, value_enum, default_value_t = FrameArg::EqualEffort)]
    pub(crate) frame: FrameArg,
    /// Who rendered the judgement (default `agent`).
    #[arg(long, value_enum, default_value_t = RaterArg::Agent)]
    pub(crate) rater: RaterArg,
    /// Optional rater identity (free text).
    #[arg(long)]
    pub(crate) by: Option<String>,
    /// Optional value lens (the IDE-035 seam).
    #[arg(long)]
    pub(crate) lens: Option<String>,
    /// Optional free-text note.
    #[arg(long)]
    pub(crate) note: Option<String>,
    /// Optional audience tag — the session-header field (OQ-1/T4).
    #[arg(long)]
    pub(crate) audience: Option<String>,
    /// Explicit project root (default: auto-detect).
    #[arg(short = 'p', long)]
    pub(crate) path: Option<PathBuf>,
}

/// `compare list [<ID>] [--active-only]` — arg shape for PHASE-03, status
/// column + `--active-only` filter SL-213 PHASE-06 (design §4 S2).
#[derive(Args)]
pub(crate) struct ListArgs {
    /// Optional participation filter — a canonical ref; rows where `a` or `b`
    /// equals it.
    pub(crate) id: Option<String>,
    /// Show only `ResolutionStatus::Active` rows — quarantined and
    /// no-constraint rows ARE active (they still show; they are visibly
    /// non-constraining, design D13/S2).
    #[arg(long)]
    pub(crate) active_only: bool,
    /// Explicit project root (default: auto-detect).
    #[arg(short = 'p', long)]
    pub(crate) path: Option<PathBuf>,
}

/// `compare withdraw <ROW-UID> [--note]` — arg shape for PHASE-03.
#[derive(Args)]
pub(crate) struct WithdrawArgs {
    /// The judgement row uid to withdraw (full uid — never a prefix).
    pub(crate) uid: String,
    /// Optional note recording the reason for withdrawal.
    #[arg(long)]
    pub(crate) note: Option<String>,
    /// Explicit project root (default: auto-detect).
    #[arg(short = 'p', long)]
    pub(crate) path: Option<PathBuf>,
}

/// `compare elicit [--depth K] [--limit N] [--kind …] [--json]` — surface the
/// ranked elicitation queue (design §3). Read-only end to end (D18): every entry
/// carries the exact answer command; no TTY interaction, no writes.
#[derive(Args)]
pub(crate) struct ElicitArgs {
    /// Frontier band depth to probe (top-K). Overrides `[priority.elicit] depth`
    /// (default `ELICIT_DEPTH`); clamped to ≥ 1.
    #[arg(long)]
    pub(crate) depth: Option<usize>,
    /// Cap the number of entries DISPLAYED (default `ELICIT_LIMIT`). The full
    /// pool is still ranked — the cap is display-only.
    #[arg(long)]
    pub(crate) limit: Option<usize>,
    /// Show only entries of this kind (filter applied POST-ranking).
    #[arg(long, value_enum)]
    pub(crate) kind: Option<KindArg>,
    /// Emit the schema-v1 JSON envelope instead of the human render.
    #[arg(long)]
    pub(crate) json: bool,
    /// Explicit project root (default: auto-detect).
    #[arg(short = 'p', long)]
    pub(crate) path: Option<PathBuf>,
}

/// Clap adapter for the candidate-kind filter — keeps clap out of the pure
/// `priority::elicit` tier. Ties back to [`CandidateKind`] (no magic strings).
#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum KindArg {
    Comparison,
    AnchorReview,
}

impl KindArg {
    fn matches(self, kind: CandidateKind) -> bool {
        matches!(
            (self, kind),
            (KindArg::Comparison, CandidateKind::Comparison)
                | (KindArg::AnchorReview, CandidateKind::AnchorReview)
        )
    }
}

/// Clap adapter for the closed frame vocab — keeps clap out of the pure
/// `comparison` engine tier (ADR-001). The kebab-cased variant names are the
/// CLI tokens; [`Self::as_frame`] ties them back to the engine constants (no
/// magic strings, STD-001).
#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum FrameArg {
    EqualEffort,
    PreferFirst,
}

impl FrameArg {
    fn as_frame(self) -> &'static str {
        match self {
            Self::EqualEffort => FRAME_EQUAL_EFFORT,
            Self::PreferFirst => FRAME_PREFER_FIRST,
        }
    }
}

/// Clap adapter for the rater kind — the shell boundary that keeps clap out of
/// the pure model's [`RaterKind`].
#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum RaterArg {
    Human,
    Agent,
}

impl RaterArg {
    fn to_kind(self) -> RaterKind {
        match self {
            Self::Human => RaterKind::Human,
            Self::Agent => RaterKind::Agent,
        }
    }
}

/// Dispatch `doctrine compare` — capture (`record`) or a PHASE-03 stub.
pub(crate) fn run_compare(args: CompareArgs) -> anyhow::Result<()> {
    match args.action {
        CompareAction::Record(record) => run_capture(&record),
        CompareAction::List(list) => run_list(&list),
        CompareAction::Withdraw(withdraw) => run_withdraw(&withdraw),
        CompareAction::Elicit(elicit) => run_elicit(&elicit),
    }
}

/// Resolve one participant ref to `(canonical id, kind prefix)`. Enforces the
/// full canonical form (design D4 — bare ids are cross-kind-ambiguous) and that
/// the entity exists (dangling evidence refused), riding the facet resolver so
/// there is no parallel corpus scan.
fn resolve_participant(root: &Path, raw: &str) -> anyhow::Result<(String, &'static str)> {
    // D4: full `SL-123` form only — rejects a bare `123`.
    let (kref, _id) = crate::integrity::parse_canonical_ref(raw)?;
    // Existence — a well-formed but absent ref is refused here.
    let (_path, canonical) = crate::commands::facet::resolve_entity_path_and_canonical(root, raw)?;
    Ok((canonical, kref.kind.prefix))
}

/// Resolve the response group to a wire [`Response`]. `--prefer` accepts the
/// literal `a` / `b`, or the full ref of either side; anything else is
/// refused. Clap enforces exactly-one-of, so the fallthrough is `--prefer`.
fn resolve_response(
    args: &RecordArgs,
    canonical_a: &str,
    canonical_b: &str,
) -> anyhow::Result<Response> {
    if args.equal {
        return Ok(Response::Equal);
    }
    if args.incomparable {
        return Ok(Response::Incomparable);
    }
    let prefer = args
        .prefer
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("one of --prefer / --equal / --incomparable is required"))?;
    match prefer {
        "a" => Ok(Response::PreferA),
        "b" => Ok(Response::PreferB),
        other if other == canonical_a => Ok(Response::PreferA),
        other if other == canonical_b => Ok(Response::PreferB),
        other => anyhow::bail!(
            "--prefer `{other}` must be `a`, `b`, or one of the two refs ({canonical_a} / {canonical_b})"
        ),
    }
}

/// Validate `--supersedes` against the loaded corpus (SL-213 S1): the target
/// must be an existing judgement row's uid — capture is the only moment a
/// human is present, so an unknown uid is a hard error, not a load-time
/// warning. Resolution happens here in the shell; the pure tiers never trust
/// an unresolved ref.
fn validate_supersedes(root: &Path, target: &str) -> anyhow::Result<()> {
    let sessions = load_sessions(root)?;
    let known = sessions
        .iter()
        .any(|s| s.judgements.iter().any(|j| j.uid == target));
    if !known {
        anyhow::bail!(
            "--supersedes `{target}` names no judgement row — supersession targets an existing row uid (see `compare list`)"
        );
    }
    Ok(())
}

/// The capture flow: resolve → admissibility → build → validate → mint (impure
/// edge) → write a fresh session-of-one file (clobber-refusing).
fn run_capture(args: &RecordArgs) -> anyhow::Result<()> {
    use std::io::Write;

    let root = crate::root::find(args.path.clone(), &crate::root::default_markers())?;

    // Resolve both refs (existence + kind). Order: refs before admissibility so
    // a dangling ref is the first refusal.
    let (canonical_a, kind_a) = resolve_participant(&root, &args.a)?;
    let (canonical_b, kind_b) = resolve_participant(&root, &args.b)?;

    // Pair admissibility over the resolved kinds (record pairs / RSK
    // participants refused, with the human-readable reason). The priority
    // domain reuses the value-domain admit set (design D2).
    comparison::admissible_value_pair(kind_a, kind_b).map_err(|reason| anyhow::anyhow!(reason))?;

    let response = resolve_response(args, &canonical_a, &canonical_b)?;

    // The frame implies the domain (S1) — the wire table is the single source.
    let frame = args.frame.as_frame();
    let domain = comparison::domain_for_frame(frame)
        .ok_or_else(|| anyhow::anyhow!("frame `{frame}` maps to no domain"))?;

    // Supersession target resolved against the corpus before any write.
    if let Some(target) = args.supersedes.as_deref() {
        validate_supersedes(&root, target)?;
    }

    // Impure edge: v7 uids (hyphenated, per the schema) + today's date.
    let session_uid = uuid::Uuid::now_v7().to_string();
    let row_uid = uuid::Uuid::now_v7().to_string();
    let date = crate::clock::today();

    let judgement = Judgement {
        uid: row_uid,
        seq: 0,
        a: canonical_a,
        b: canonical_b,
        response,
        domain: domain.to_string(),
        frame: frame.to_string(),
        form: RowForm::Order,
        magnitude: None,
        supersedes: args.supersedes.clone(),
        lens: args.lens.clone(),
        rater: args.rater.to_kind(),
        by: args.by.clone(),
        note: args.note.clone(),
        date: date.clone(),
    };
    comparison::validate_judgement(&judgement)?;

    let session = comparison::session_of_one(
        SessionHeader {
            uid: session_uid.clone(),
            date: date.clone(),
            audience: args.audience.clone(),
        },
        judgement,
    );
    let text = comparison::to_toml(&session)?;

    // Write a fresh file — clobber-refusing, dir created lazily. The v7 session
    // uid keys the filename, so distinct invocations never collide (append-only,
    // design D2).
    let path = write_session_file(&root, &date, &session_uid, &text)?;

    writeln!(
        std::io::stdout(),
        "compare: captured {} — session {}",
        path.display(),
        session_uid
    )?;
    Ok(())
}

/// Write a fresh session file `<date>-<uid>.toml` under
/// `.doctrine/comparisons/` — clobber-refusing (`create-new`), directory made
/// lazily. The single disk seam shared by capture and withdrawal (design D2 —
/// append-only, exactly one new file per act; never rewrites an existing path).
fn write_session_file(
    root: &Path,
    date: &str,
    session_uid: &str,
    text: &str,
) -> anyhow::Result<PathBuf> {
    use std::io::Write;
    let dir = root.join(".doctrine").join(COMPARISONS_DIR);
    std::fs::create_dir_all(&dir)
        .with_context(|| format!("create comparisons dir {}", dir.display()))?;
    let path = dir.join(format!("{date}-{session_uid}.toml"));
    let mut file = crate::fsutil::create_new_file(&path)
        .with_context(|| format!("write comparison session {}", path.display()))?;
    file.write_all(text.as_bytes())
        .with_context(|| format!("write comparison session {}", path.display()))?;
    Ok(path)
}

/// Render one joined row for `list` (SL-213 PHASE-06, design §4 S2): the FULL
/// row uid (never a prefix — uuid-v7 prefixes share a timestamp bucket and
/// collide, and this line feeds `withdraw`, RV-262 F-6), the joined
/// [`RowState`] display token, the pair with the preferred side marked `*`,
/// frame, rater (+identity when present), date, note when present, and a
/// `[withdrawn]` marker when the row is `ResolutionStatus::Tombstoned`
/// (retained verbatim alongside the new `status=tombstoned` token —
/// pre-existing golden text, extend-don't-replace).
fn render_row(row: &RowSummary) -> String {
    // Minimal v2 adaptation (SL-213 PHASE-01 EX-4): the `*` marks a preferred
    // side; `=` / `~` render equal / incomparable.
    let pair = match row.response {
        Response::PreferA => format!("{}* vs {}", row.a, row.b),
        Response::PreferB => format!("{} vs {}*", row.a, row.b),
        Response::Equal => format!("{} = {}", row.a, row.b),
        Response::Incomparable => format!("{} ~ {}", row.a, row.b),
    };
    let by = row
        .by
        .as_deref()
        .map(|b| format!(":{b}"))
        .unwrap_or_default();
    let note = row
        .note
        .as_deref()
        .map(|n| format!("  note: {n}"))
        .unwrap_or_default();
    let withdrawn = matches!(row.state.resolution, ResolutionStatus::Tombstoned);
    let tomb = if withdrawn { "  [withdrawn]" } else { "" };
    format!(
        "{uid}  status={status}  {pair}  frame={frame}  rater={rater}{by}  {date}{note}{tomb}",
        uid = row.uid,
        status = row.state.display_token(),
        frame = row.frame,
        rater = row.rater_token,
        date = row.date,
    )
}

/// Filter + render the pipeline's joined rows for `list` (design §4 S2, D13:
/// "the pipeline computes it anyway"). `filter` keeps rows where either side
/// matches the participation ref; `active_only` keeps `ResolutionStatus::
/// Active` rows only — quarantined and no-constraint rows ARE active (design
/// A2), so they still show under `--active-only`. Ordering comes for free
/// from `resolve`'s own total-key sort (`(date, session_uid, seq)`) that
/// `RowSummary`s are already in.
fn list_lines(rows: &[RowSummary], filter: Option<&str>, active_only: bool) -> Vec<String> {
    rows.iter()
        .filter(|r| filter.is_none_or(|id| r.a == id || r.b == id))
        .filter(|r| !active_only || matches!(r.state.resolution, ResolutionStatus::Active))
        .map(render_row)
        .collect()
}

/// `compare list [<ID>] [--active-only]` — read the ledger back through the
/// SAME resolve → compile pipeline `explain`/`findings` consume (SL-213
/// PHASE-06, design D13): every row joins its [`ResolutionStatus`] with its
/// (Active-only) `CompilationStatus` into ONE display token. A missing
/// comparisons directory is an empty listing, not an error.
fn run_list(args: &ListArgs) -> anyhow::Result<()> {
    use std::io::Write;
    let root = crate::root::find(args.path.clone(), &crate::root::default_markers())?;
    let pipeline = crate::priority::graph::load_comparison_pipeline_for_root(&root)?;
    let lines = list_lines(&pipeline.rows, args.id.as_deref(), args.active_only);

    let mut out = std::io::stdout();
    if lines.is_empty() {
        writeln!(out, "compare: no judgements recorded")?;
        return Ok(());
    }
    for line in lines {
        writeln!(out, "{line}")?;
    }
    Ok(())
}

/// `compare withdraw <ROW-UID> [--note]` — append-only withdrawal. Scans the
/// ledger to confirm the uid names a live judgement row (unknown / tombstone-row
/// / already-withdrawn each refused), then writes a NEW session-of-one file
/// carrying only the tombstone — never editing an existing file (design D2, the
/// same create-new seam as capture).
fn run_withdraw(args: &WithdrawArgs) -> anyhow::Result<()> {
    use std::io::Write;
    let root = crate::root::find(args.path.clone(), &crate::root::default_markers())?;
    let sessions = load_sessions(&root)?;

    // The uid must name a live judgement row.
    let Some(target_session) = sessions
        .iter()
        .find(|s| s.judgements.iter().any(|j| j.uid == args.uid))
    else {
        // Distinguish a tombstone-row uid from a wholly-unknown uid.
        let is_tombstone = sessions
            .iter()
            .any(|s| s.tombstones.iter().any(|t| t.uid == args.uid));
        if is_tombstone {
            anyhow::bail!(
                "{} is a tombstone, not a judgement — withdraw targets judgement rows",
                args.uid
            );
        }
        anyhow::bail!("unknown row uid `{}` — no judgement carries it", args.uid);
    };

    // Idempotency: refuse a second withdrawal of the same row.
    let already = sessions
        .iter()
        .any(|s| s.tombstones.iter().any(|t| t.target == args.uid));
    if already {
        anyhow::bail!("{} is already withdrawn", args.uid);
    }

    // Impure edge: fresh session/tombstone uids + today.
    let session_uid = uuid::Uuid::now_v7().to_string();
    let tombstone_uid = uuid::Uuid::now_v7().to_string();
    let date = crate::clock::today();

    // Ride the target file's wire discriminators, so the tombstone matches the
    // ledger version it withdraws from (no hand-set version magic).
    let session = ComparisonSession {
        schema: target_session.schema.clone(),
        version: target_session.version,
        session: SessionHeader {
            uid: session_uid.clone(),
            date: date.clone(),
            audience: None,
        },
        judgements: Vec::new(),
        tombstones: vec![Tombstone {
            uid: tombstone_uid,
            seq: 0,
            target: args.uid.clone(),
            date: date.clone(),
            note: args.note.clone(),
        }],
    };
    let text = comparison::to_toml(&session)?;
    let path = write_session_file(&root, &date, &session_uid, &text)?;

    writeln!(
        std::io::stdout(),
        "compare: withdrew {} — tombstone {}",
        args.uid,
        path.display()
    )?;
    Ok(())
}

/// `compare elicit` — assemble the ranked queue over the SAME resolve→compile
/// pipeline the read surfaces consume, then render (design §3). Read-only (D18):
/// no session or authored write on any path. The `PriorityGraph` supplies the
/// frontier ranking + per-item costing (D6); the comparison `Pipeline` supplies
/// the active evidence + anchors + projection the assembler recompiles over.
fn run_elicit(args: &ElicitArgs) -> anyhow::Result<()> {
    let root = crate::root::find(args.path.clone(), &crate::root::default_markers())?;
    let cfg = crate::priority::config::load(&root);
    let graph = graph::build(&root)?;
    let pipeline = graph::load_comparison_pipeline_for_root(&root)?;
    let depth = args.depth.unwrap_or(cfg.elicit.depth).max(1);

    let inputs = build_elicit_inputs(&graph, &pipeline, &cfg, depth);
    let queue = assemble(&inputs, DecisionContext::Sequencing { depth });

    let ctx = RenderCtx::new(&graph, &pipeline, &cfg);
    if args.json {
        render_elicit_json(&queue, depth, args, &ctx)
    } else {
        render_elicit_human(&queue, args, &ctx)
    }
}

/// Compose the pure [`ElicitInputs`] from the built graph + loaded pipeline
/// (design §2 shell seam). The frontier is the top-`depth` band by final score
/// (id-lex tiebreak — determinism); costing is the D6 `(multiplier, est_cost,
/// bare_estimate)` per entity; active evidence + anchors + projection come
/// straight off the pipeline. Borrows the pipeline's owned `active_judgements`,
/// so the returned inputs live no longer than `pipeline`.
fn build_elicit_inputs<'a>(
    graph: &PriorityGraph,
    pipeline: &'a comparison::Pipeline,
    cfg: &PriorityConfig,
    depth: usize,
) -> ElicitInputs<'a> {
    // Frontier: final score DESC, canonical-id ASC — the deterministic top-K band.
    let mut ranked: Vec<(&_, f64)> = graph.score.iter().map(|(k, &s)| (k, s)).collect();
    ranked.sort_by(|(ka, sa), (kb, sb)| sb.total_cmp(sa).then_with(|| ka.cmp(kb)));
    let frontier: Vec<FrontierItem> = ranked
        .iter()
        .take(depth)
        .filter_map(|(key, _)| {
            graph.attrs.get(key).map(|attr| FrontierItem {
                id: key.canonical(),
                kind: attr.kind.prefix.to_string(),
            })
        })
        .collect();

    // Costing: D6 multiplier + β-skewed est_cost + bare flag, for every scored entity.
    let mut costing: std::collections::BTreeMap<String, ItemCosting> =
        std::collections::BTreeMap::new();
    for key in graph.attrs.keys() {
        if let Some((multiplier, est_cost, bare_estimate)) = graph.item_costing(key, cfg) {
            costing.insert(
                key.canonical(),
                ItemCosting {
                    multiplier,
                    est_cost,
                    bare_estimate,
                },
            );
        }
    }

    ElicitInputs {
        active: pipeline.active_judgements.iter().collect(),
        anchors: pipeline.anchors.clone(),
        frontier,
        costing,
        projection: pipeline.projection.clone(),
        rank_decay: cfg.elicit.rank_decay,
        confirm_boost: cfg.elicit.confirm_boost,
    }
}

/// The display slice after the POST-ranking `--kind` filter + `--limit` display
/// cap (the full pool is ranked; only the view is capped, design §3).
fn displayed<'q>(queue: &'q ElicitQueue, args: &ElicitArgs) -> Vec<&'q QueueEntry> {
    let limit = args.limit.unwrap_or(crate::priority::config::ELICIT_LIMIT);
    queue
        .entries
        .iter()
        .filter(|e| args.kind.is_none_or(|k| k.matches(e.kind)))
        .take(limit)
        .collect()
}

/// The bare-estimate mask glyph (D17) — the ⚠ marker on a projected-but-bare
/// participant (STD-001: one definition for the human render).
const MASK_MARK: &str = "";

/// The D15 state token + footer detail (design §3 / D15 — the precise stall /
/// stable / m=0 wording). Takes the whole queue so `Stable` can scope its claim
/// by the `excluded_value_insensitive` (`m = 0`, D6) count.
fn state_footer(queue: &ElicitQueue) -> (&'static str, String) {
    match &queue.state {
        QueueState::Candidates => (
            "candidates",
            "candidates outstanding — comparisons / anchor-reviews worth asking".to_string(),
        ),
        QueueState::Stalled { depth } => (
            "stalled",
            format!(
                "stalled at depth {depth}: greedy one-step yield exhausted — NOT a stability \
                 claim (a bridge question may remain)"
            ),
        ),
        QueueState::Stable { depth } => {
            // D15: the claim is INTERNAL order among the CURRENT top-K members —
            // never prefix-membership (D5). Scoped further when m=0 exclusions
            // exist (D6): those pairs are value-insensitive, outside the claim.
            let base = format!(
                "stable: value_dim order among the current top-{depth} frontier members is \
                 stable over the joint set (internal order, current members — not membership)"
            );
            let scope = match queue.excluded_value_insensitive {
                0 => String::new(),
                n => format!("; {n} pair(s) value-insensitive (zero weight), outside the claim"),
            };
            ("stable", format!("{base}{scope}"))
        }
    }
}

/// Human render (design §3): per entry the rank/kind spine, ask line,
/// participants with fetched context (title/status/S3 value shape/estimate-or-
/// bare ⚠), reasons prose, and the exact answer command; then the D15 footer.
fn render_elicit_human(
    queue: &ElicitQueue,
    args: &ElicitArgs,
    ctx: &RenderCtx<'_>,
) -> anyhow::Result<()> {
    use std::io::Write;
    let mut out = std::io::stdout();
    let shown = displayed(queue, args);
    if shown.is_empty() {
        writeln!(out, "elicit: no candidates")?;
    }
    for (i, entry) in shown.iter().enumerate() {
        write!(out, "{}", entry_human(i + 1, entry, ctx))?;
    }
    let (_, detail) = state_footer(queue);
    writeln!(out, "state: {detail}")?;
    Ok(())
}

/// One entry's human block (design §3): spine line, ask line, participants with
/// fetched context, reasons prose, and the exact answer command. Returns the
/// framed multi-line string (trailing newline) — the render loop concatenates.
fn entry_human(rank: usize, entry: &QueueEntry, ctx: &RenderCtx<'_>) -> String {
    let kind = match entry.kind {
        CandidateKind::Comparison => "comparison",
        CandidateKind::AnchorReview => "anchor-review",
    };
    let mut parts = vec![format!(
        "{rank}. [{kind}] score {:.3}  yield {:+}  impact {:.3}\n",
        entry.score, entry.guaranteed_yield, entry.guaranteed_impact
    )];
    match &entry.payload {
        EntryPayload::Comparison { a, b, .. } => {
            parts.push(format!("   ask: {} vs {}\n", a.id, b.id));
            parts.push(participant_human(ctx, a));
            parts.push(participant_human(ctx, b));
        }
        EntryPayload::AnchorReview { subject, .. } => {
            let anchor = subject
                .anchor
                .map_or_else(|| "".to_string(), |v| format!("{v}"));
            parts.push(format!(
                "   review: anchor on {} (value {anchor})\n",
                subject.id
            ));
        }
    }
    let reasons: Vec<&str> = entry.reasons.iter().map(|r| r.text.as_str()).collect();
    if !reasons.is_empty() {
        parts.push(format!("   reasons: {}\n", reasons.join("; ")));
    }
    parts.push(format!("   answer: {}\n", answer_command(entry)));
    parts.concat()
}

/// One participant's human context lines (design §3): id + title + status, then
/// the S3 value shape and the estimate cell; a trailing ⚠-mask line when the
/// engine flagged the participant (bare estimate masks the projection, D17).
fn participant_human(ctx: &RenderCtx<'_>, p: &Participant) -> String {
    let (title, status) = ctx.context(&p.id).unwrap_or(("", None));
    let status = status.unwrap_or("");
    let value = ctx
        .value_fragment(&p.id)
        .unwrap_or_else(|| "value —".to_string());
    let est = ctx.estimate_display(&p.id);
    let mut parts = vec![format!(
        "{} \"{title}\" ({status})\n     {value}  ·  {est}\n",
        p.id
    )];
    if !p.annotations.is_empty() {
        parts.push(format!("     {MASK_MARK} {}\n", p.annotations.join("; ")));
    }
    parts.concat()
}

/// The exact answer command a curator runs to record the judgement (design §3 —
/// no TTY, the command IS the capture leg). Comparison → the `compare record`
/// call over the pair; anchor-review → the revise/uphold resolving actions
/// (mirrors the JSON `exits`).
fn answer_command(entry: &QueueEntry) -> String {
    match &entry.payload {
        EntryPayload::Comparison { a, b, .. } => format!(
            "doctrine compare record {} {} --prefer a   (| --prefer b | --equal | --incomparable)",
            a.id, b.id
        ),
        EntryPayload::AnchorReview { subject, .. } => format!(
            "doctrine value set {} <v>   (revise)   |   supersede/withdraw the cited rows (uphold)",
            subject.id
        ),
    }
}

/// The join context the elicit render needs beyond the pure [`ElicitQueue`]:
/// per-participant value source + estimate come from a shell join
/// (`Participant.id → PriorityGraph / Pipeline`), since `assemble` keeps
/// participants LEAN (design D16). Built once per render from the same graph +
/// pipeline `run_elicit` already loaded (no second scan).
struct RenderCtx<'a> {
    graph: &'a PriorityGraph,
    pipeline: &'a comparison::Pipeline,
    cfg: &'a PriorityConfig,
    keys: std::collections::BTreeMap<String, crate::relation_graph::EntityKey>,
}

impl<'a> RenderCtx<'a> {
    fn new(
        graph: &'a PriorityGraph,
        pipeline: &'a comparison::Pipeline,
        cfg: &'a PriorityConfig,
    ) -> Self {
        let keys = graph.attrs.keys().map(|k| (k.canonical(), *k)).collect();
        Self {
            graph,
            pipeline,
            cfg,
            keys,
        }
    }

    /// The structural value block for a participant (design §3 / D16):
    /// `{provenance, point}` from the SINGLE value-source precedence
    /// (`surface::value_source_reason` — authored > projected > gauge), plus the
    /// STRUCTURAL bounds (`surface::class_bounds_structural`, open/closed/unbounded
    /// retained — the human `explain` path flattens, this surface must not, web
    /// review). `None` when the entity has no citable value source (an
    /// un-constrained bare item — the numeric default floor is not a source,
    /// surface.rs S3).
    fn value_block(&self, canonical: &str) -> Option<serde_json::Value> {
        let key = *self.keys.get(canonical)?;
        let (provenance, point) =
            match crate::priority::surface::value_source_reason(self.graph, key, self.pipeline)? {
                ReasonKind::ValueAuthored { value, .. } => ("authored", value),
                ReasonKind::ValueProjected { value, .. } => ("projected", value),
                ReasonKind::ValueGauge { value, .. } => ("gauge", value),
                _ => return None,
            };
        let bounds = crate::priority::surface::class_bounds_structural(
            &self.pipeline.constraint_set,
            canonical,
        );
        Some(value_block_json(provenance, point, bounds))
    }

    /// The participant's scalar cost estimate (`est_cost`, D7) — `None` when the
    /// estimate is BARE (no authored facet); the bare case is disclosed instead
    /// by the `projection masked by bare estimate` annotation on the participant
    /// (D17), never by a synthesized number here.
    fn estimate(&self, canonical: &str) -> Option<f64> {
        let key = *self.keys.get(canonical)?;
        let (_, est_cost, bare) = self.graph.item_costing(&key, self.cfg)?;
        (!bare).then_some(est_cost)
    }

    /// Fetched display context for the human render (design §3): the entity's
    /// title + status. `None` for an id absent from the graph (defensive — a
    /// participant is always a scored entity).
    fn context(&self, canonical: &str) -> Option<(&str, Option<&str>)> {
        let key = self.keys.get(canonical)?;
        let attr = self.graph.attrs.get(key)?;
        Some((attr.title.as_str(), attr.status.as_deref()))
    }

    /// The human S3 value-source fragment — reuses `render::value_source_fragment`
    /// verbatim (the SINGLE value-shape template, shared with `explain`). `None`
    /// when the entity has no citable value source.
    fn value_fragment(&self, canonical: &str) -> Option<String> {
        let key = *self.keys.get(canonical)?;
        let reason = crate::priority::surface::value_source_reason(self.graph, key, self.pipeline)?;
        crate::priority::render::value_source_fragment(&reason)
    }

    /// The human estimate cell: the scalar `est_cost`, or a dash when bare (the
    /// ⚠ mask itself rides the participant annotations, D17 — not re-derived here).
    fn estimate_display(&self, canonical: &str) -> String {
        match self
            .keys
            .get(canonical)
            .and_then(|k| self.graph.item_costing(k, self.cfg))
        {
            Some((_, est, false)) => format!("est {est:.2}"),
            _ => "est —".to_string(),
        }
    }

    /// One lean participant (design D16): id + value/estimate block + the
    /// engine's annotations (the bare-estimate mask rides these).
    fn participant_json(&self, p: &Participant) -> serde_json::Value {
        serde_json::json!({
            "id": p.id,
            "value": self.value_block(&p.id),
            "estimate": self.estimate(&p.id),
            "annotations": p.annotations,
        })
    }
}

/// JSON schema-v1 envelope (design §3 / D16). Byte-stable (`BTree` key order
/// from `serde_json::Value`); NO trailing newline (the golden contract, mirrors
/// `render.rs::finish`).
fn render_elicit_json(
    queue: &ElicitQueue,
    depth: usize,
    args: &ElicitArgs,
    ctx: &RenderCtx<'_>,
) -> anyhow::Result<()> {
    use std::io::Write;
    let text = serde_json::to_string_pretty(&elicit_envelope(queue, depth, args, ctx))?;
    write!(std::io::stdout(), "{text}")?;
    Ok(())
}

/// The schema-v1 envelope value (pure — the byte-stability + golden anchor).
fn elicit_envelope(
    queue: &ElicitQueue,
    depth: usize,
    args: &ElicitArgs,
    ctx: &RenderCtx<'_>,
) -> serde_json::Value {
    let (state_token, state_detail) = state_footer(queue);
    let entries: Vec<serde_json::Value> = displayed(queue, args)
        .iter()
        .enumerate()
        .map(|(i, e)| entry_json(i + 1, e, ctx))
        .collect();
    serde_json::json!({
        "schema": "doctrine.elicit-queue",
        "version": 1,
        "context": { "kind": "sequencing", "depth": depth },
        "state": state_token,
        "state_detail": state_detail,
        "excluded_value_insensitive": queue.excluded_value_insensitive,
        "entries": entries,
    })
}

/// One entry's JSON (spine + kind payload + kind-specific ask). Reason/ask codes
/// ride the engine's structured shapes verbatim (D16 findings-parity).
fn entry_json(rank: usize, entry: &QueueEntry, ctx: &RenderCtx<'_>) -> serde_json::Value {
    let kind = match entry.kind {
        CandidateKind::Comparison => "comparison",
        CandidateKind::AnchorReview => "anchor-review",
    };
    let reasons: Vec<serde_json::Value> = entry
        .reasons
        .iter()
        .map(|r| serde_json::json!({ "code": r.code, "text": r.text }))
        .collect();
    let payload = match &entry.payload {
        EntryPayload::Comparison { a, b, ask } => serde_json::json!({
            "participants": [ctx.participant_json(a), ctx.participant_json(b)],
            "ask": comparison_ask_json(ask),
        }),
        EntryPayload::AnchorReview { subject, ask } => serde_json::json!({
            "subject": {
                "id": subject.id,
                "anchor": subject.anchor,
                "conflict_pairs": subject.conflict_pairs,
                "quarantined_rows": subject.quarantined_rows,
            },
            "ask": anchor_ask_json(ask, subject),
        }),
    };
    let mut obj = serde_json::json!({
        "rank": rank,
        "kind": kind,
        "guaranteed_yield": entry.guaranteed_yield,
        "guaranteed_impact": entry.guaranteed_impact,
        "score": entry.score,
        "yield_basis": match entry.yield_basis {
            crate::priority::elicit::YieldBasis::OrderBearingAnswers => "order-bearing-answers",
            crate::priority::elicit::YieldBasis::CanonicalResolvingActions => {
                "canonical-resolving-actions"
            }
        },
        "reasons": reasons,
    });
    if let (Some(map), serde_json::Value::Object(pmap)) = (obj.as_object_mut(), payload) {
        for (k, v) in pmap {
            map.insert(k, v);
        }
    }
    obj
}

/// The comparison ask block (design §3): the canonical equal-effort/value frame
/// (D1 — comparison entries carry no other frame), the answer tokens, and each
/// token's disclosed yield. No `yield_note`/`exits` (those are anchor-only).
fn comparison_ask_json(ask: &crate::priority::elicit::AskSpec) -> serde_json::Value {
    serde_json::json!({
        "frame": FRAME_EQUAL_EFFORT,
        "domain": comparison::DOMAIN_VALUE,
        "answers": ask.answers,
        "yield_by_answer": ask.yield_by_answer,
    })
}

/// The anchor-review ask block (design §3, RV-269 F-3): answers + per-answer
/// yield + the conditional-yield `yield_note` + `exits` (suggested resolving
/// actions per answer token; uphold is not one executable command).
fn anchor_ask_json(
    ask: &crate::priority::elicit::AskSpec,
    subject: &crate::priority::elicit::AnchorSubject,
) -> serde_json::Value {
    serde_json::json!({
        "answers": ask.answers,
        "yield_by_answer": ask.yield_by_answer,
        "yield_note": ask.yield_note,
        "exits": anchor_exits_json(subject),
    })
}

/// The per-answer suggested resolving actions for an anchor-review entry
/// (design §3): `revise-anchor` re-authors the suspect value; `uphold-anchor`
/// retires the cited closure (supersede or withdraw each quarantined row) —
/// arrays of suggested commands, not a single executable, keyed by answer token
/// (STD-001: tokens shared with `elicit`).
fn anchor_exits_json(subject: &crate::priority::elicit::AnchorSubject) -> serde_json::Value {
    let revise = vec![format!("doctrine value set {} <v>", subject.id)];
    let mut uphold: Vec<String> = Vec::new();
    if let Some(first) = subject.quarantined_rows.first() {
        uphold.push(format!(
            "doctrine compare record <a> <b> <response> --supersedes {first}"
        ));
    }
    for uid in &subject.quarantined_rows {
        uphold.push(format!("doctrine compare withdraw {uid}"));
    }
    serde_json::json!({
        crate::priority::elicit::ANSWER_REVISE_ANCHOR: revise,
        crate::priority::elicit::ANSWER_UPHOLD_ANCHOR: uphold,
    })
}

/// A structural C6 bound as `{kind, value?}` (design §3): mirrors the `Bound`
/// enum so the open/closed distinction survives (`[null, 2.8]` would lose it —
/// web review).
fn bound_json(b: comparison::Bound) -> serde_json::Value {
    match b {
        comparison::Bound::Unbounded => serde_json::json!({ "kind": "unbounded" }),
        comparison::Bound::Open(v) => serde_json::json!({ "kind": "open", "value": v }),
        comparison::Bound::Closed(v) => serde_json::json!({ "kind": "closed", "value": v }),
    }
}

/// The participant value block (design §3): `{provenance, point}` always, plus
/// structural `bounds` when the entity sits in a compiled class.
fn value_block_json(
    provenance: &str,
    point: f64,
    bounds: Option<comparison::ValueBounds>,
) -> serde_json::Value {
    let mut v = serde_json::json!({ "provenance": provenance, "point": point });
    if let (Some(b), Some(map)) = (bounds, v.as_object_mut()) {
        map.insert(
            "bounds".to_string(),
            serde_json::json!({ "lower": bound_json(b.lower), "upper": bound_json(b.upper) }),
        );
    }
    v
}

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

#[cfg(test)]
#[expect(clippy::unwrap_used, reason = "test code")]
mod tests {
    use super::*;

    /// Create a tempdir `root::find` resolves as a project root (facet.rs house
    /// pattern).
    fn mk_project_root() -> (tempfile::TempDir, PathBuf) {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join(".project"), "").unwrap();
        std::fs::create_dir_all(tmp.path().join(".doctrine")).unwrap();
        std::fs::write(tmp.path().join(crate::dtoml::DOCTRINE_TOML), "").unwrap();
        let root = tmp.path().to_path_buf();
        (tmp, root)
    }

    /// Seed a minimal resolvable entity of `prefix` with `status`, returning its
    /// canonical id. Rides `entity::id_path` + `integrity::kind_by_prefix`, so it
    /// works for any numbered kind regardless of its tree/stem layout.
    fn seed_entity(root: &Path, prefix: &str, id: u32, status: &str) -> String {
        let padded = format!("{id:03}");
        let kref = crate::integrity::kind_by_prefix(prefix).expect("valid prefix");
        let toml_path = crate::entity::id_path(root, kref.kind, id, crate::entity::Ext::Toml);
        std::fs::create_dir_all(toml_path.parent().unwrap()).unwrap();
        std::fs::write(
            &toml_path,
            format!(
                "id = {id}\nslug = \"t{padded}\"\ntitle = \"Test {prefix}-{padded}\"\nstatus = \"{status}\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n"
            ),
        )
        .unwrap();
        crate::listing::canonical_id(prefix, id)
    }

    /// The `.toml` session files currently under `.doctrine/comparisons/`.
    fn session_files(root: &Path) -> Vec<PathBuf> {
        let dir = root.join(".doctrine").join(COMPARISONS_DIR);
        let Ok(entries) = std::fs::read_dir(&dir) else {
            return Vec::new();
        };
        let mut files: Vec<PathBuf> = entries
            .filter_map(|e| e.ok().map(|e| e.path()))
            .filter(|p| p.extension().is_some_and(|x| x == "toml"))
            .collect();
        files.sort();
        files
    }

    /// A bare `record` capture over two refs, defaults elsewhere.
    fn capture(root: &Path, a: &str, b: &str, prefer: &str) -> RecordArgs {
        RecordArgs {
            a: a.to_string(),
            b: b.to_string(),
            prefer: Some(prefer.to_string()),
            equal: false,
            incomparable: false,
            supersedes: None,
            frame: FrameArg::EqualEffort,
            rater: RaterArg::Agent,
            by: None,
            lens: None,
            note: None,
            audience: None,
            path: Some(root.to_path_buf()),
        }
    }

    #[test]
    fn compare_capture_writes_session_of_one() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");

        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();

        let files = session_files(&root);
        assert_eq!(files.len(), 1, "exactly one session file");
        let name = files[0].file_name().unwrap().to_string_lossy();
        assert!(
            name.ends_with(".toml") && name.contains('-'),
            "filename is <date>-<uid>.toml: {name}"
        );

        let session = comparison::parse(&std::fs::read_to_string(&files[0]).unwrap()).unwrap();
        assert_eq!(session.judgements.len(), 1);
        assert!(session.tombstones.is_empty());
        let j = &session.judgements[0];
        assert_eq!(j.seq, 0);
        assert_eq!(j.a, "SL-204");
        assert_eq!(j.b, "IMP-118");
        assert_eq!(j.response, Response::PreferA);
        assert_eq!(j.domain, comparison::DOMAIN_VALUE);
        assert_eq!(j.frame, FRAME_EQUAL_EFFORT);
        assert_eq!(j.form, RowForm::Order);
        assert_eq!(j.rater, RaterKind::Agent);
        assert_eq!(j.magnitude, None);
        assert_eq!(j.supersedes, None);
    }

    #[test]
    fn second_capture_never_touches_first_file() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");

        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();
        let first = session_files(&root);
        assert_eq!(first.len(), 1);
        let first_path = first[0].clone();
        let first_bytes = std::fs::read(&first_path).unwrap();

        run_capture(&capture(&root, "SL-204", "IMP-118", "b")).unwrap();
        let second = session_files(&root);
        assert_eq!(second.len(), 2, "a fresh file per invocation");
        assert!(first_path.exists(), "the first file survives");
        assert_eq!(
            std::fs::read(&first_path).unwrap(),
            first_bytes,
            "the first file is byte-identical after the second capture"
        );
    }

    #[test]
    fn compare_refuses_missing_ref() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        // SL-999 is well-formed but absent.
        let err = run_capture(&capture(&root, "SL-204", "SL-999", "a")).unwrap_err();
        assert!(!err.to_string().is_empty());
        assert!(session_files(&root).is_empty(), "no file on a dangling ref");
    }

    #[test]
    fn compare_refuses_record_pair() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "QUE", 1, "open");
        seed_entity(&root, "QUE", 2, "open");
        let err = run_capture(&capture(&root, "QUE-001", "QUE-002", "a")).unwrap_err();
        assert!(
            err.to_string().contains("not value-bearing"),
            "admissibility reason surfaced: {err}"
        );
        assert!(session_files(&root).is_empty(), "no file on a record pair");
    }

    #[test]
    fn compare_refuses_rsk_participant() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "RSK", 1, "open");
        let err = run_capture(&capture(&root, "SL-204", "RSK-001", "a")).unwrap_err();
        assert!(
            err.to_string().contains("excluded from value comparison"),
            "RSK admissibility reason surfaced: {err}"
        );
        assert!(
            session_files(&root).is_empty(),
            "no file on an RSK participant"
        );
    }

    #[test]
    fn compare_admits_terminal_status_participant() {
        let (_tmp, root) = mk_project_root();
        // A closed slice — existence only, no status gate (design).
        seed_entity(&root, "SL", 204, "closed");
        seed_entity(&root, "IMP", 118, "accepted");
        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();
        assert_eq!(
            session_files(&root).len(),
            1,
            "terminal-status participant admitted"
        );
    }

    #[test]
    fn flag_surface_lands_frame_rater_by() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");

        let args = RecordArgs {
            frame: FrameArg::PreferFirst,
            rater: RaterArg::Human,
            by: Some("david".to_string()),
            lens: Some("user-value".to_string()),
            note: Some("auth unblocks the pilot".to_string()),
            ..capture(&root, "SL-204", "IMP-118", "a")
        };
        run_capture(&args).unwrap();

        let files = session_files(&root);
        let session = comparison::parse(&std::fs::read_to_string(&files[0]).unwrap()).unwrap();
        let j = &session.judgements[0];
        assert_eq!(j.frame, FRAME_PREFER_FIRST);
        assert_eq!(j.rater, RaterKind::Human);
        assert_eq!(j.by.as_deref(), Some("david"));
        assert_eq!(j.lens.as_deref(), Some("user-value"));
        assert_eq!(j.note.as_deref(), Some("auth unblocks the pilot"));
    }

    #[test]
    fn prefer_literal_shorthand() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");

        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();
        run_capture(&capture(&root, "SL-204", "IMP-118", "b")).unwrap();

        let mut responses: Vec<Response> = session_files(&root)
            .iter()
            .map(|p| {
                comparison::parse(&std::fs::read_to_string(p).unwrap())
                    .unwrap()
                    .judgements[0]
                    .response
            })
            .collect();
        responses.sort_by_key(|r| format!("{r:?}"));
        assert_eq!(responses, vec![Response::PreferA, Response::PreferB]);
    }

    #[test]
    fn prefer_full_ref_resolves() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");
        run_capture(&capture(&root, "SL-204", "IMP-118", "IMP-118")).unwrap();
        let files = session_files(&root);
        let session = comparison::parse(&std::fs::read_to_string(&files[0]).unwrap()).unwrap();
        assert_eq!(session.judgements[0].response, Response::PreferB);
    }

    /// S1: `--equal` and `--incomparable` land their wire responses; the
    /// default frame keeps the value domain.
    #[test]
    fn equal_and_incomparable_capture() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");

        let equal = RecordArgs {
            prefer: None,
            equal: true,
            ..capture(&root, "SL-204", "IMP-118", "unused")
        };
        run_capture(&equal).unwrap();

        let incomparable = RecordArgs {
            prefer: None,
            incomparable: true,
            ..capture(&root, "SL-204", "IMP-118", "unused")
        };
        run_capture(&incomparable).unwrap();

        let mut responses: Vec<Response> = session_files(&root)
            .iter()
            .map(|p| {
                let s = comparison::parse(&std::fs::read_to_string(p).unwrap()).unwrap();
                assert_eq!(s.judgements[0].domain, comparison::DOMAIN_VALUE);
                s.judgements[0].response
            })
            .collect();
        responses.sort_by_key(|r| format!("{r:?}"));
        assert_eq!(responses, vec![Response::Equal, Response::Incomparable]);
    }

    /// S1: `--frame prefer-first` silently derives `domain = priority` —
    /// users never type a domain (VT-3).
    #[test]
    fn prefer_first_frame_derives_priority_domain() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");

        let args = RecordArgs {
            frame: FrameArg::PreferFirst,
            ..capture(&root, "SL-204", "IMP-118", "a")
        };
        run_capture(&args).unwrap();

        let files = session_files(&root);
        let session = comparison::parse(&std::fs::read_to_string(&files[0]).unwrap()).unwrap();
        let j = &session.judgements[0];
        assert_eq!(j.domain, comparison::DOMAIN_PRIORITY);
        assert_eq!(j.frame, FRAME_PREFER_FIRST);
    }

    /// S1: `--supersedes` with an unknown uid is a hard error before any
    /// write; a known judgement uid lands in the row (VT-3).
    #[test]
    fn supersedes_validated_against_corpus() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");

        // Unknown uid — refused, nothing written.
        let unknown = RecordArgs {
            supersedes: Some("not-a-real-uid".to_string()),
            ..capture(&root, "SL-204", "IMP-118", "a")
        };
        let err = run_capture(&unknown).unwrap_err();
        assert!(
            err.to_string().contains("names no judgement row"),
            "unknown supersedes target refused: {err}"
        );
        assert!(session_files(&root).is_empty(), "no file on a bad target");

        // Known uid — the edge lands in the new row.
        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();
        let target = only_judgement_uid(&root);
        let known = RecordArgs {
            supersedes: Some(target.clone()),
            ..capture(&root, "SL-204", "IMP-118", "b")
        };
        run_capture(&known).unwrap();

        let superseding: Vec<Option<String>> = session_files(&root)
            .iter()
            .map(|p| {
                comparison::parse(&std::fs::read_to_string(p).unwrap())
                    .unwrap()
                    .judgements[0]
                    .supersedes
                    .clone()
            })
            .collect();
        assert!(
            superseding.contains(&Some(target)),
            "the superseding row carries the target uid"
        );
    }

    #[test]
    fn prefer_bogus_value_refused() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");
        let err = run_capture(&capture(&root, "SL-204", "IMP-118", "SL-999")).unwrap_err();
        assert!(err.to_string().contains("--prefer"), "got: {err}");
        assert!(session_files(&root).is_empty(), "no file on a bad --prefer");
    }

    #[test]
    fn compare_refuses_bare_ref() {
        // D4: bare ids are refused before any resolution.
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");
        let err = run_capture(&capture(&root, "204", "IMP-118", "a")).unwrap_err();
        assert!(!err.to_string().is_empty());
        assert!(session_files(&root).is_empty(), "no file on a bare ref");
    }

    #[test]
    fn audience_lands_in_session_header() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");

        // Present → lands in [session].
        let with_aud = RecordArgs {
            audience: Some("stakeholder".to_string()),
            ..capture(&root, "SL-204", "IMP-118", "a")
        };
        run_capture(&with_aud).unwrap();
        let files = session_files(&root);
        let text = std::fs::read_to_string(&files[0]).unwrap();
        let session = comparison::parse(&text).unwrap();
        assert_eq!(session.session.audience.as_deref(), Some("stakeholder"));

        // Absent → absent field (no `audience` key).
        std::fs::remove_file(&files[0]).unwrap();
        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();
        let files = session_files(&root);
        let text = std::fs::read_to_string(&files[0]).unwrap();
        assert!(
            !text.contains("audience"),
            "no audience key when flag absent:\n{text}"
        );
        let session = comparison::parse(&text).unwrap();
        assert!(session.session.audience.is_none());
    }

    /// EX-4: the fallback clap shape parses `record` capture and the `list` /
    /// `withdraw` subcommands. A local Parser wraps the `compare` subcommand
    /// group so the shape is exercised in isolation from the top-level `Command`
    /// enum.
    #[test]
    fn clap_shape_accepts_record_and_subcommands() {
        use clap::Parser;
        #[derive(Parser)]
        struct Wrap {
            #[command(subcommand)]
            action: CompareAction,
        }

        // record capture — positionals + one response arm.
        let w = Wrap::try_parse_from(["x", "record", "SL-204", "IMP-118", "--prefer", "a"])
            .expect("record form parses");
        let CompareAction::Record(r) = w.action else {
            panic!("expected record");
        };
        assert_eq!(r.a, "SL-204");
        assert_eq!(r.prefer.as_deref(), Some("a"));

        // The other response arms parse alone.
        for arm in ["--equal", "--incomparable"] {
            Wrap::try_parse_from(["x", "record", "SL-204", "IMP-118", arm])
                .unwrap_or_else(|e| panic!("{arm} parses alone: {e}"));
        }

        // The response group is mutually exclusive and required (VT-3).
        assert!(
            Wrap::try_parse_from([
                "x", "record", "SL-204", "IMP-118", "--prefer", "a", "--equal"
            ])
            .is_err(),
            "two response arms refused"
        );
        assert!(
            Wrap::try_parse_from([
                "x",
                "record",
                "SL-204",
                "IMP-118",
                "--equal",
                "--incomparable"
            ])
            .is_err(),
            "two flag arms refused"
        );
        assert!(
            Wrap::try_parse_from(["x", "record", "SL-204", "IMP-118"]).is_err(),
            "a response arm is required"
        );

        // `list` subcommand — no positionals demanded.
        let w = Wrap::try_parse_from(["x", "list"]).expect("list subcommand parses");
        assert!(matches!(w.action, CompareAction::List(_)));

        // `withdraw <uid>` subcommand.
        let w = Wrap::try_parse_from(["x", "withdraw", "some-uid"])
            .expect("withdraw subcommand parses");
        assert!(matches!(w.action, CompareAction::Withdraw(_)));

        // `record` without its required positionals is refused.
        assert!(
            Wrap::try_parse_from(["x", "record"]).is_err(),
            "record demands its positionals"
        );
    }

    // ----- PHASE-03: list / withdraw --------------------------------------

    /// A judgement row with the given key fields; optionals absent, response
    /// pinned to prefer-a.
    fn mk_judgement(uid: &str, seq: u32, a: &str, b: &str) -> Judgement {
        Judgement {
            uid: uid.to_string(),
            seq,
            a: a.to_string(),
            b: b.to_string(),
            response: Response::PreferA,
            domain: comparison::DOMAIN_VALUE.to_string(),
            frame: FRAME_EQUAL_EFFORT.to_string(),
            form: RowForm::Order,
            magnitude: None,
            supersedes: None,
            lens: None,
            rater: RaterKind::Agent,
            by: None,
            note: None,
            date: "2026-07-10".to_string(),
        }
    }

    /// An in-memory session carrying the given judgements (no tombstones).
    fn mk_session(date: &str, uid: &str, judgements: Vec<Judgement>) -> ComparisonSession {
        ComparisonSession {
            schema: comparison::COMPARISON_SCHEMA.to_string(),
            version: comparison::COMPARISON_VERSION,
            session: SessionHeader {
                uid: uid.to_string(),
                date: date.to_string(),
                audience: None,
            },
            judgements,
            tombstones: Vec::new(),
        }
    }

    /// Build render-ready [`RowSummary`] rows over in-memory sessions (no
    /// disk) — the SAME pipeline `run_list` composes, minus the entity scan
    /// (empty `StatusMap`/`AnchorMap`; `list`'s own unit tests exercise
    /// ordering/filtering, not R6/anchors).
    fn rows_of(sessions: &[ComparisonSession]) -> Vec<RowSummary> {
        comparison::pipeline_from_sessions(
            sessions,
            &comparison::StatusMap::new(),
            &comparison::AnchorMap::new(),
            &comparison::ProjectionCfg {
                gauge_step: 0.25,
                default_value: 1.0,
            },
        )
        .unwrap()
        .rows
    }

    fn withdraw_args(root: &Path, uid: &str, note: Option<&str>) -> WithdrawArgs {
        WithdrawArgs {
            uid: uid.to_string(),
            note: note.map(str::to_string),
            path: Some(root.to_path_buf()),
        }
    }

    /// The single judgement uid currently in the ledger (tests capture exactly one).
    fn only_judgement_uid(root: &Path) -> String {
        load_sessions(root)
            .unwrap()
            .iter()
            .flat_map(|s| s.judgements.iter())
            .map(|j| j.uid.clone())
            .next()
            .expect("a judgement row exists")
    }

    /// The single tombstone uid currently in the ledger.
    fn only_tombstone_uid(root: &Path) -> String {
        load_sessions(root)
            .unwrap()
            .iter()
            .flat_map(|s| s.tombstones.iter())
            .map(|t| t.uid.clone())
            .next()
            .expect("a tombstone row exists")
    }

    /// `mk_judgement` with an explicit row date — the total-key order (design
    /// §2 R3: `(date, session_uid, seq)`) sorts on the JUDGEMENT row's own
    /// `date` field (`resolve.rs`'s tested behaviour), which a real capture
    /// always stamps identically to its session's date (one shared
    /// `clock::today()` call, `run_capture`) — this fixture keeps that
    /// invariant honest rather than decoupling the two dates.
    fn mk_judgement_dated(uid: &str, seq: u32, a: &str, b: &str, date: &str) -> Judgement {
        let mut j = mk_judgement(uid, seq, a, b);
        j.date = date.to_string();
        j
    }

    #[test]
    fn compare_list_orders_by_total_key() {
        // Cross-file ordering by (date, session_uid, seq) — independent of the
        // order sessions are supplied in. Rows fed late-then-early must render
        // early-then-late.
        let late = mk_session(
            "2026-07-10",
            "sess-b",
            vec![mk_judgement_dated(
                "row-late",
                0,
                "SL-204",
                "IMP-118",
                "2026-07-10",
            )],
        );
        let early = mk_session(
            "2026-07-08",
            "sess-a",
            vec![mk_judgement_dated(
                "row-early",
                0,
                "SL-204",
                "CHR-042",
                "2026-07-08",
            )],
        );
        // Same-date tie broken by session uid then seq.
        let same_date = mk_session(
            "2026-07-08",
            "sess-c",
            vec![
                mk_judgement_dated("row-seq1", 1, "IDE-001", "IMP-118", "2026-07-08"),
                mk_judgement_dated("row-seq0", 0, "IDE-001", "SL-204", "2026-07-08"),
            ],
        );

        let lines = list_lines(&rows_of(&[late, same_date, early]), None, false);
        let order: Vec<&str> = lines
            .iter()
            .map(|l| l.split_whitespace().next().unwrap())
            .collect();
        // (2026-07-08, sess-a) < (2026-07-08, sess-c, seq0) < (…, seq1) < (2026-07-10, sess-b)
        assert_eq!(order, ["row-early", "row-seq0", "row-seq1", "row-late"]);
    }

    #[test]
    fn compare_list_filters_by_participant() {
        let session = mk_session(
            "2026-07-10",
            "sess-1",
            vec![
                mk_judgement("keep", 0, "SL-204", "IMP-118"),
                mk_judgement("drop", 1, "SL-999", "CHR-042"),
            ],
        );
        let lines = list_lines(&rows_of(&[session]), Some("IMP-118"), false);
        assert_eq!(lines.len(), 1, "only the participating row survives");
        assert!(
            lines[0].contains("keep"),
            "kept the IMP-118 row: {}",
            lines[0]
        );
    }

    #[test]
    fn list_renders_full_row_uid() {
        // The listing feeds `withdraw`, so it must print the COMPLETE uid, never
        // a colliding prefix (RV-262 F-6).
        let uid = "0197f3a2-6c2f-7d4e-8f5a-2b3c4d5e6f7a";
        let session = mk_session(
            "2026-07-10",
            "sess-1",
            vec![mk_judgement(uid, 0, "SL-204", "IMP-118")],
        );
        let lines = list_lines(&rows_of(&[session]), None, false);
        assert_eq!(lines.len(), 1);
        assert!(
            lines[0].contains(uid),
            "full uid rendered, not a prefix: {}",
            lines[0]
        );
    }

    #[test]
    fn withdraw_appends_tombstone() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");
        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();

        let before = session_files(&root);
        assert_eq!(before.len(), 1);
        let orig_path = before[0].clone();
        let orig_bytes = std::fs::read(&orig_path).unwrap();
        let uid = only_judgement_uid(&root);

        run_withdraw(&withdraw_args(&root, &uid, Some("wrong way round"))).unwrap();

        // A NEW file appended; the original is byte-identical (append-only).
        let after = session_files(&root);
        assert_eq!(after.len(), 2, "a fresh tombstone file was appended");
        assert!(orig_path.exists());
        assert_eq!(
            std::fs::read(&orig_path).unwrap(),
            orig_bytes,
            "the judgement file is untouched by withdraw"
        );

        // The tombstone is a session-of-one targeting the row, seq 0, note kept.
        let sessions = load_sessions(&root).unwrap();
        let tomb = sessions
            .iter()
            .flat_map(|s| s.tombstones.iter())
            .find(|t| t.target == uid)
            .expect("tombstone targets the withdrawn row");
        assert_eq!(tomb.seq, 0);
        assert_eq!(tomb.note.as_deref(), Some("wrong way round"));

        // list now marks that row withdrawn (display-only interpretation).
        let lines = list_lines(&rows_of(&sessions), None, false);
        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains(&uid), "full uid present: {}", lines[0]);
        assert!(
            lines[0].contains("[withdrawn]"),
            "row rendered withdrawn: {}",
            lines[0]
        );
    }

    #[test]
    fn refuses_double_withdraw() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");
        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();
        let uid = only_judgement_uid(&root);

        run_withdraw(&withdraw_args(&root, &uid, None)).unwrap();
        let err = run_withdraw(&withdraw_args(&root, &uid, None)).unwrap_err();
        assert!(
            err.to_string().contains("already withdrawn"),
            "second withdraw refused: {err}"
        );
        // No third file — the refused withdraw writes nothing.
        assert_eq!(session_files(&root).len(), 2, "refusal writes no file");
    }

    #[test]
    fn withdraw_refuses_unknown_and_tombstone_row() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "SL", 204, "accepted");
        seed_entity(&root, "IMP", 118, "accepted");
        run_capture(&capture(&root, "SL-204", "IMP-118", "a")).unwrap();
        let uid = only_judgement_uid(&root);

        // Unknown uid — no judgement carries it.
        let err = run_withdraw(&withdraw_args(&root, "not-a-real-uid", None)).unwrap_err();
        assert!(
            err.to_string().contains("unknown row uid"),
            "unknown uid refused: {err}"
        );

        // A tombstone-row uid is not a judgement — refused.
        run_withdraw(&withdraw_args(&root, &uid, None)).unwrap();
        let tomb_uid = only_tombstone_uid(&root);
        let err = run_withdraw(&withdraw_args(&root, &tomb_uid, None)).unwrap_err();
        assert!(
            err.to_string().contains("tombstone"),
            "tombstone-row uid refused: {err}"
        );
    }

    #[test]
    fn list_empty_ledger_is_not_an_error() {
        let (_tmp, root) = mk_project_root();
        // No comparisons dir at all — an empty listing, not a failure.
        let sessions = load_sessions(&root).unwrap();
        assert!(sessions.is_empty());
        assert!(list_lines(&rows_of(&sessions), None, false).is_empty());
        run_list(&ListArgs {
            id: None,
            active_only: false,
            path: Some(root),
        })
        .unwrap();
    }

    // ── SL-217 PHASE-03: the elicit shell ────────────────────────────────────

    /// Seed a value-bearing slice (`.toml` + `.md`) the priority scan discovers —
    /// no value facet ⇒ `DEFAULT_VALUE`, so it earns a score and enters the
    /// frontier. Returns its canonical id.
    fn seed_scored_slice(root: &Path, id: u32) -> String {
        let p = format!("{id:03}");
        let dir = root.join(".doctrine").join("slice").join(&p);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(format!("slice-{p}.toml")),
            format!(
                "id = {id}\nslug = \"s{p}\"\ntitle = \"S\"\nstatus = \"proposed\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n"
            ),
        )
        .unwrap();
        std::fs::write(dir.join(format!("slice-{p}.md")), "scope\n").unwrap();
        crate::listing::canonical_id("SL", id)
    }

    /// `ElicitArgs` with everything defaulted (no filters, human render).
    fn elicit_args(root: &Path) -> ElicitArgs {
        ElicitArgs {
            depth: None,
            limit: None,
            kind: None,
            json: false,
            path: Some(root.to_path_buf()),
        }
    }

    /// T2: the shell composes deterministic, D6-costed [`ElicitInputs`] from the
    /// built graph + loaded pipeline. Pins the frontier ordering (id-lex tiebreak),
    /// the multiplier decomposition (`coeff.value × kind_weight × tag_term`), and
    /// the bare-estimate flag for an estimate-free value-bearing item.
    #[test]
    fn build_elicit_inputs_is_deterministic_and_d6_costed() {
        let (_tmp, root) = mk_project_root();
        let id1 = seed_scored_slice(&root, 1);
        let id2 = seed_scored_slice(&root, 2);
        let cfg = crate::priority::config::load(&root);
        let graph = graph::build(&root).unwrap();
        let pipeline = graph::load_comparison_pipeline_for_root(&root).unwrap();

        let a = build_elicit_inputs(&graph, &pipeline, &cfg, 8);
        let b = build_elicit_inputs(&graph, &pipeline, &cfg, 8);
        // Determinism: byte-identical inputs across repeated builds.
        assert_eq!(format!("{a:?}"), format!("{b:?}"));

        // Frontier holds both seeded items; equal score ⇒ id-lex order (SL-001 first).
        let ids: Vec<&String> = a.frontier.iter().map(|f| &f.id).collect();
        assert!(ids.contains(&&id1) && ids.contains(&&id2));
        assert_eq!(a.frontier.first().map(|f| &f.id), Some(&id1));

        // D6 costing: no tags ⇒ tag_term = 1, no estimate ⇒ bare + empty-corpus
        // cost anchor; multiplier collapses to coeff.value × kind_weight(SL).
        let c = a.costing.get(&id1).expect("id1 is costed");
        let expected_m = cfg.coefficients.value * cfg.kind_weight("SL");
        assert!(
            (c.multiplier - expected_m).abs() < 1e-9,
            "m={}",
            c.multiplier
        );
        assert!(c.bare_estimate, "no estimate facet ⇒ bare");
        assert!(c.est_cost > 0.0);
    }

    /// T2: `--depth` clamps the frontier band; a depth of 1 keeps only the top item.
    #[test]
    fn build_elicit_inputs_respects_depth_band() {
        let (_tmp, root) = mk_project_root();
        let id1 = seed_scored_slice(&root, 1);
        let _id2 = seed_scored_slice(&root, 2);
        let cfg = crate::priority::config::load(&root);
        let graph = graph::build(&root).unwrap();
        let pipeline = graph::load_comparison_pipeline_for_root(&root).unwrap();

        let inputs = build_elicit_inputs(&graph, &pipeline, &cfg, 1);
        assert_eq!(inputs.frontier.len(), 1);
        assert_eq!(inputs.frontier.first().map(|f| &f.id), Some(&id1));
    }

    /// T1/T2: the arm runs read-only end-to-end over an empty ledger and renders
    /// a state line without error (EX-1 read-only: no session file is written).
    #[test]
    fn elicit_over_empty_ledger_is_read_only_and_ok() {
        let (_tmp, root) = mk_project_root();
        seed_entity(&root, "IMP", 1, "open");
        run_elicit(&elicit_args(&root)).unwrap();
        assert!(
            session_files(&root).is_empty(),
            "elicit is read-only — no session file minted"
        );
    }

    // ── T3: JSON schema-v1 shapers (design §3 / D16) ────────────────────────

    /// A structural C6 bound serializes to `{kind, value?}` — open/closed carry
    /// the value, unbounded omits it (the web-review distinction `[null, 2.8]`
    /// would erase).
    #[test]
    fn bound_json_carries_open_closed_unbounded() {
        assert_eq!(
            bound_json(comparison::Bound::Open(2.5)),
            serde_json::json!({ "kind": "open", "value": 2.5 })
        );
        assert_eq!(
            bound_json(comparison::Bound::Closed(5.0)),
            serde_json::json!({ "kind": "closed", "value": 5.0 })
        );
        assert_eq!(
            bound_json(comparison::Bound::Unbounded),
            serde_json::json!({ "kind": "unbounded" })
        );
    }

    /// The participant value block carries `{provenance, point}` always, and
    /// STRUCTURAL `bounds` when the entity sits in a compiled class; a class-less
    /// value (authored floor, no interval) omits `bounds` entirely.
    #[test]
    fn value_block_json_shapes_projected_and_classless() {
        let projected = value_block_json(
            "projected",
            2.6,
            Some(comparison::ValueBounds {
                lower: comparison::Bound::Open(2.5),
                upper: comparison::Bound::Open(2.8),
            }),
        );
        assert_eq!(
            projected,
            serde_json::json!({
                "provenance": "projected",
                "point": 2.6,
                "bounds": {
                    "lower": { "kind": "open", "value": 2.5 },
                    "upper": { "kind": "open", "value": 2.8 },
                },
            })
        );

        let classless = value_block_json("authored", 4.0, None);
        assert_eq!(
            classless,
            serde_json::json!({ "provenance": "authored", "point": 4.0 })
        );
        assert!(
            classless.get("bounds").is_none(),
            "no compiled class ⇒ no bounds key"
        );
    }

    /// Anchor-review `exits` is keyed by the two answer tokens: revise re-authors
    /// the suspect value; uphold suggests superseding then withdrawing each cited
    /// row (arrays of suggested actions, not one executable — design §3).
    #[test]
    fn anchor_exits_json_keys_by_answer_token() {
        let subject = crate::priority::elicit::AnchorSubject {
            id: "IMP-274".to_string(),
            anchor: Some(5.0),
            conflict_pairs: vec![("IMP-198".to_string(), "IMP-274".to_string())],
            quarantined_rows: vec!["uid-1".to_string(), "uid-2".to_string()],
        };
        assert_eq!(
            anchor_exits_json(&subject),
            serde_json::json!({
                "revise-anchor": ["doctrine value set IMP-274 <v>"],
                "uphold-anchor": [
                    "doctrine compare record <a> <b> <response> --supersedes uid-1",
                    "doctrine compare withdraw uid-1",
                    "doctrine compare withdraw uid-2",
                ],
            })
        );
    }

    /// A suspect anchor with no cited rows yields a revise action and an empty
    /// uphold list (nothing to retire) — no panic on the empty closure.
    #[test]
    fn anchor_exits_json_empty_closure_has_no_uphold_actions() {
        let subject = crate::priority::elicit::AnchorSubject {
            id: "IMP-9".to_string(),
            anchor: None,
            conflict_pairs: vec![],
            quarantined_rows: vec![],
        };
        assert_eq!(
            anchor_exits_json(&subject),
            serde_json::json!({
                "revise-anchor": ["doctrine value set IMP-9 <v>"],
                "uphold-anchor": [],
            })
        );
    }

    /// The comparison ask block carries the canonical equal-effort/value frame
    /// and NO `yield_note`/`exits` (those are anchor-only — schema fidelity).
    #[test]
    fn comparison_ask_json_carries_frame_and_no_anchor_fields() {
        let ask = crate::priority::elicit::AskSpec {
            answers: vec!["prefer-a", "prefer-b", "equal", "incomparable"],
            yield_by_answer: [("prefer-a".to_string(), 3)].into_iter().collect(),
            yield_note: None,
        };
        let v = comparison_ask_json(&ask);
        assert_eq!(
            v.get("frame").and_then(|f| f.as_str()),
            Some("equal-effort")
        );
        assert_eq!(v.get("domain").and_then(|d| d.as_str()), Some("value"));
        assert!(
            v.get("yield_note").is_none(),
            "comparison ask omits yield_note"
        );
        assert!(v.get("exits").is_none(), "comparison ask omits exits");
    }

    // ── T4: human render footer + answer command (design §3 / D15) ──────────

    fn empty_queue(state: QueueState, excluded: usize) -> ElicitQueue {
        ElicitQueue {
            state,
            entries: vec![],
            excluded_value_insensitive: excluded,
        }
    }

    /// The D15 footer: stall names the depth and disclaims stability; stable
    /// claims value_dim order among the CURRENT top-K members (not membership),
    /// scoped by the m=0 exclusion count when present (D6).
    #[test]
    fn state_footer_names_depth_disclaims_and_scopes_m0() {
        let (cand_tok, cand) = state_footer(&empty_queue(QueueState::Candidates, 0));
        assert_eq!(cand_tok, "candidates");
        assert!(cand.contains("candidates outstanding"));

        let (stall_tok, stall) = state_footer(&empty_queue(QueueState::Stalled { depth: 8 }, 0));
        assert_eq!(stall_tok, "stalled");
        assert!(
            stall.contains("depth 8") && stall.contains("NOT a stability claim"),
            "stall names depth + disclaims: {stall}"
        );

        let (stable_tok, stable) = state_footer(&empty_queue(QueueState::Stable { depth: 5 }, 0));
        assert_eq!(stable_tok, "stable");
        assert!(
            stable.contains("top-5 frontier members") && stable.contains("not membership"),
            "stable is member-scoped: {stable}"
        );
        assert!(
            !stable.contains("value-insensitive"),
            "no m=0 clause when none excluded"
        );

        let (_, scoped) = state_footer(&empty_queue(QueueState::Stable { depth: 5 }, 3));
        assert!(
            scoped.contains("3 pair(s) value-insensitive (zero weight), outside the claim"),
            "m=0 exclusions scope + disclose: {scoped}"
        );
    }

    fn bare_participant(id: &str) -> Participant {
        Participant {
            id: id.to_string(),
            annotations: vec![],
        }
    }

    fn empty_ask() -> crate::priority::elicit::AskSpec {
        crate::priority::elicit::AskSpec {
            answers: vec![],
            yield_by_answer: std::collections::BTreeMap::new(),
            yield_note: None,
        }
    }

    fn spine(payload: EntryPayload, kind: CandidateKind) -> QueueEntry {
        QueueEntry {
            kind,
            guaranteed_yield: 1,
            guaranteed_impact: 0.5,
            score: 0.5,
            yield_basis: crate::priority::elicit::YieldBasis::OrderBearingAnswers,
            reasons: vec![],
            payload,
        }
    }

    /// The exact answer command: comparison → the `compare record` call over the
    /// pair; anchor-review → the revise/uphold resolving actions.
    #[test]
    fn answer_command_per_kind() {
        let cmp = spine(
            EntryPayload::Comparison {
                a: bare_participant("IMP-1"),
                b: bare_participant("IMP-2"),
                ask: empty_ask(),
            },
            CandidateKind::Comparison,
        );
        assert_eq!(
            answer_command(&cmp),
            "doctrine compare record IMP-1 IMP-2 --prefer a   \
             (| --prefer b | --equal | --incomparable)"
        );

        let anchor = spine(
            EntryPayload::AnchorReview {
                subject: crate::priority::elicit::AnchorSubject {
                    id: "IMP-3".to_string(),
                    anchor: Some(5.0),
                    conflict_pairs: vec![],
                    quarantined_rows: vec![],
                },
                ask: empty_ask(),
            },
            CandidateKind::AnchorReview,
        );
        assert!(
            answer_command(&anchor).starts_with("doctrine value set IMP-3 <v>"),
            "anchor revise action: {}",
            answer_command(&anchor)
        );
    }
}