doctrine 0.5.1

Project tooling CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
// SPDX-License-Identifier: GPL-3.0-only
//! The cross-kind relation graph engine (design §5.1/§5.2).
//!
//! Sits at the engine layer (ADR-001): it imports the relation vocabulary leaf
//! ([`crate::relation`]) and every edge-authoring kind module, dispatching a
//! data-driven [`outbound_for`] over `integrity::KINDS` — kind is *data*, not a
//! trait (`mem.pattern.entity.kind-is-data-not-trait`). No kind module imports
//! back, so there is no cycle (the whole reason the vocabulary lives in the leaf).
//!
//! PHASE-02 landed the outbound extraction dispatch ([`outbound_for`]). PHASE-03
//! extended this file with the all-kind scan ([`build_relation_graph`]), the
//! `Projection<EntityKey>`, the reference overlays, and the [`inspect`] query
//! (design §5.4). PHASE-04 wires the `inspect <ID>` CLI command ([`run`]) — the
//! render + `--json` surface — so the scan and `inspect` are now live (the
//! PHASE-03 `not(test)` `dead_code` expect retired itself here, as designed).

use std::collections::BTreeMap;
use std::path::Path;

use cordage::{Arity, CyclePolicy, EdgeAttrs, Graph, GraphBuilder, OverlayConfig, OverlayId};

use crate::catalog::hydrate::{CatalogEdgeLabel, CatalogKey, EdgeTarget};
use crate::dep_seq;
use crate::entity;
use crate::integrity;
use crate::listing::{self, Format};
use crate::projection::Projection;
use crate::relation::{RELATION_RULES, RelationEdge, RelationLabel, TargetSpec};

// Re-exports from catalog::scan — the single source of truth (SL-071 D7).
// Aliases, not wrappers — one body, one source.
pub(crate) use crate::catalog::scan::{EntityKey, ScannedEntity, outbound_for, scan_entities};

/// One entity's `needs`/`after` dep/seq edges plus its `promoted` flag, dispatched to
/// the owning kind's reader by canonical prefix — the kind-agnostic READ gate that lets
/// slice (and any future authoring kind) dep/seq edges reach the priority blocker/next
/// view (design D7/§5.2/§5.4). The shape mirrors [`outbound_for`]: one data-driven match
/// over the corpus-wide `kind.prefix` discriminant, each arm reading only its own kind's
/// dep/seq via that kind's existing path — never a second parse.
///
/// - **backlog** — routed through backlog's single `dep_seq_for` reader (ONE parse: it
///   already reads `resolution` for `promoted`), its `Vec<(String, i32)>` `after`
///   adapted into the leaf [`dep_seq::AfterEdge`] shape (design F3).
/// - **slice** — the leaf [`dep_seq::read`] over the slice's own toml; `promoted` is
///   always `false` (only a backlog item carries the typed promoted projection).
/// - **every non-authoring kind** — SHORT-CIRCUITS to an empty [`dep_seq::DepSeq`] with
///   `false`, BEFORE any path construction or disk touch (design F5). This is
///   load-bearing: the priority read loop now visits ALL kinds, not just the five
///   backlog ones, so a non-authoring kind must contribute zero edges with NO read.
pub(crate) fn dep_seq_for(
    root: &Path,
    kind: &entity::Kind,
    id: u32,
) -> anyhow::Result<(dep_seq::DepSeq, bool)> {
    match kind.prefix {
        // Slice authors dep/seq directly (PHASE-03); the leaf reads its own toml. Stem
        // is `"slice"` (the same id-path shape `integrity::KINDS` carries for SL).
        "SL" => {
            let name = format!("{id:03}");
            let path = root
                .join(kind.dir)
                .join(&name)
                .join(format!("slice-{name}.toml"));
            Ok((dep_seq::read(&path)?, false))
        }
        // REV (SL-066, G2) — mirrors the SL arm: a Revision authors its own
        // `needs`/`after` (the IDE-010 payoff — a REV may `needs` a spike), so the
        // leaf reads its `revision-NNN.toml` directly. Without this arm REV-as-source
        // edges short-circuit to the empty fallthrough and never reach the blocker/
        // `next` view. `promoted` is always `false` (a backlog-only projection).
        "REV" => {
            let name = format!("{id:03}");
            let path = root
                .join(kind.dir)
                .join(&name)
                .join(format!("revision-{name}.toml"));
            Ok((dep_seq::read(&path)?, false))
        }
        // The five backlog kinds route to backlog's own one-parse reader, which carries
        // the `promoted` projection. Adapt its `(to, rank)` pairs to the leaf AfterEdge.
        other => {
            if let Some(item_kind) = crate::backlog::kind_from_prefix(other) {
                let bl = crate::backlog::dep_seq_for(root, item_kind, id)?;
                let after = bl
                    .after
                    .into_iter()
                    .map(|(to, rank)| dep_seq::AfterEdge { to, rank })
                    .collect();
                Ok((
                    dep_seq::DepSeq {
                        needs: bl.needs,
                        after,
                    },
                    bl.promoted,
                ))
            } else {
                // Every non-authoring kind: zero dep/seq, no disk read. The kind is
                // tested HERE — before any path is built or any toml is touched (F5).
                Ok((dep_seq::DepSeq::default(), false))
            }
        }
    }
}

// ---------------------------------------------------------------------------
// PHASE-03 — the all-kind scan, the reference overlays, and the inspect query.
// ---------------------------------------------------------------------------

/// The single existence gate for the keyed read surfaces (SL-050 F6). A well-formed
/// ref to a never-minted id (e.g. `SL-999`) is indistinguishable from a real isolated
/// node at the render layer — this turns it into a clean error instead. The oracle is
/// the `Projection<EntityKey>` each keyed surface already holds: it contains EXACTLY
/// the minted keys, so `resolve(key).is_none()` ⇔ the entity was never minted (no
/// entity dir). One helper, one message, every keyed surface (`inspect`/`render`/
/// `explain`/`blockers`/`actionability_block`) routes through it — no second
/// existence path to drift.
///
/// # Errors
///
/// `"{KIND-NNN}: no such entity"` when `key` is absent from `projection`.
pub(crate) fn require_minted(
    projection: &Projection<EntityKey>,
    key: EntityKey,
) -> anyhow::Result<()> {
    if projection.resolve(key).is_none() {
        anyhow::bail!("{}: no such entity", key.canonical());
    }
    Ok(())
}

/// The overlay-identity map: one cordage overlay per OVERLAY-BACKED relation label,
/// keyed both ways. The overlay-backed set is *derived* from [`RELATION_RULES`]
/// (R2-M4) — every distinct label whose `TargetSpec != Unvalidated`. The two
/// target-unvalidated labels — `Drift` and `DecisionRef` (ADR-010 Decision 2) — get
/// NO overlay (their targets never resolve to a node), so `overlay_for` returns
/// `None` for them and their edges always dangle.
///
/// Label is overlay identity (OQ2-B): the same label authored from different source
/// kinds (e.g. `Supersedes` from both slice and governance, `GovernedBy` from SL·PRD·
/// SPEC) shares ONE overlay — the iteration de-dupes on the label key.
struct OverlayMap {
    by_label: BTreeMap<RelationLabel, OverlayId>,
    by_overlay: BTreeMap<OverlayId, RelationLabel>,
}

impl OverlayMap {
    /// Allocate one `Reject`/`Unbounded` overlay per overlay-backed label (I1:
    /// `Reject` removes no edges, `Unbounded` exempts arity eviction — `in_edges`
    /// then enumerates exactly the authored unique inbound set).
    ///
    /// Table-derived (R2-M4): iterate [`RELATION_RULES`] and allocate one overlay per
    /// DISTINCT label whose `TargetSpec != Unvalidated`. The `by_label` `BTreeMap`
    /// de-dupes a label that appears in several rows (e.g. `Supersedes` from SL and
    /// gov) to one overlay. NO hardcoded label const — the table is the single source,
    /// so a new resolvable label gets an overlay automatically (VT-1 pins the set ==
    /// the resolvable graph labels). Behaviour-preserving: the corpus authors no
    /// `governed_by`/`consumes` edges yet, so the allocated set grows by those two
    /// labels but produces byte-identical `inspect` / `*-show` output (EX-2).
    fn build(builder: &mut GraphBuilder) -> Self {
        let mut by_label = BTreeMap::new();
        let mut by_overlay = BTreeMap::new();
        for rule in RELATION_RULES {
            if matches!(rule.target, TargetSpec::Unvalidated) {
                continue;
            }
            // De-dupe: a label spanning several source rows shares ONE overlay.
            if by_label.contains_key(&rule.label) {
                continue;
            }
            let ov = builder.overlay(OverlayConfig::new(CyclePolicy::Reject, Arity::Unbounded));
            by_label.insert(rule.label, ov);
            by_overlay.insert(ov, rule.label);
        }
        Self {
            by_label,
            by_overlay,
        }
    }

    /// The overlay backing `label`, or `None` for the target-unvalidated labels
    /// (`Drift`/`DecisionRef`) that carry no overlay. `label_of` is unneeded —
    /// `inspect` iterates `by_overlay` directly (overlay → label), so the reverse
    /// map is read as a field, not through an accessor.
    fn overlay_for(&self, label: RelationLabel) -> Option<OverlayId> {
        self.by_label.get(&label).copied()
    }
}

/// The assembled relation graph: the cordage `Graph`, the `EntityKey ↔ NodeId`
/// projection, the overlay-identity map, and the per-source danglers collected
/// during the edge pass. `inspect` reads inbound from the graph, outbound fresh
/// from `outbound_for`, and returns only the queried entity's danglers.
struct RelationGraph {
    graph: Graph,
    projection: Projection<EntityKey>,
    overlays: OverlayMap,
    /// Danglers keyed by source entity — the unresolved / free-text / no-overlay
    /// outbound targets, so `inspect` returns only the queried entity's set.
    danglers: BTreeMap<EntityKey, Vec<(RelationLabel, String)>>,
}

/// Build the cross-kind reference-overlay graph from a PRE-SCANNED entity slice (the
/// SL-050 F2 shared-scan seam — a SEPARATE cordage `Graph` from `backlog_order`/
/// `priority`: they share the `Projection` *type*, never a graph instance or a scan).
/// Takes only the slice — it touches no disk beyond the scan it is handed (the F2
/// seam: the single corpus walk lives at the command layer). The mint/edge order is the
/// scan order the caller supplies (KINDS table / id ascending), so the mint order — and
/// thus the byte-identical `inspect` output (VT-4) — is preserved exactly.
///
/// 1. Mint nodes: one `intern` per scanned entity, in scan order.
/// 2. Emit edges: per minted entity, per outbound edge, parse + resolve the target; a
///    resolvable target whose label has an overlay ⇒ `builder.edge`,
///    `EdgeAttrs::new(0, 0)` (C3 — two authored rows with the same `(label,src,dst)`
///    collapse to one in cordage's `BTreeSet<Edge>`); anything else (unresolved,
///    parse-error / free-text, or a no-overlay label like `Drift`/`DecisionRef`,
///    INCLUDING a resolvable target under a no-overlay label) ⇒ a dangler.
/// 3. `builder.build()` — NO `OrderSpec` over reference overlays (I2: direct-only,
///    composition-free; no union-cycle pass touches them).
fn build_relation_graph_from(scanned: &[ScannedEntity]) -> anyhow::Result<RelationGraph> {
    let mut builder = GraphBuilder::new();
    let overlays = OverlayMap::build(&mut builder);
    let mut projection: Projection<EntityKey> = Projection::new();

    // Pass 1 — mint every entity's node (scan order: KINDS table, ids ascending).
    for entity in scanned {
        projection.intern(&mut builder, entity.key);
    }

    // Pass 2 — emit edges (resolve only, never intern) and collect danglers.
    let mut danglers: BTreeMap<EntityKey, Vec<(RelationLabel, String)>> = BTreeMap::new();
    for entity in scanned {
        // Present by construction (pass 1 interned every key from the same scan);
        // loud in debug if that ever desyncs, a benign skip in release (the path
        // stays panic-free).
        let Some(src) = projection.resolve(entity.key) else {
            debug_assert!(
                false,
                "build_relation_graph: pass-2 key not interned in pass 1"
            );
            continue;
        };
        for edge in &entity.outbound {
            if let Some(dst) = resolve_target(&projection, edge)
                && let Some(ov) = overlays.overlay_for(edge.label)
            {
                builder.edge(ov, src, dst, EdgeAttrs::new(0, 0));
            } else {
                danglers
                    .entry(entity.key)
                    .or_default()
                    .push((edge.label, edge.target.clone()));
            }
        }
    }

    let graph = builder.build().map_err(|e| {
        anyhow::anyhow!(
            "relation_graph: cordage rejected well-formed adapter input (internal bug): {e:?}"
        )
    })?;

    Ok(RelationGraph {
        graph,
        projection,
        overlays,
        danglers,
    })
}

/// Resolve an authored edge's `target` to a minted node, or `None`. A target that
/// fails to parse as a canonical ref (free-text — `Drift`/`DecisionRef`), or parses
/// to an id that was never minted (no entity dir), resolves to `None` → a dangler.
fn resolve_target(
    projection: &Projection<EntityKey>,
    edge: &RelationEdge,
) -> Option<cordage::NodeId> {
    let (kref, tid) = integrity::parse_canonical_ref(&edge.target).ok()?;
    projection.resolve(EntityKey {
        prefix: kref.kind.prefix,
        id: tid,
    })
}

// ---------------------------------------------------------------------------
// PHASE-05 — the corpus-edge `validate` walk + supersession cross-check (design
// §5.5, R2-M5 / R2-m2). Report-only: returns finding strings, NEVER rewrites (the
// reseat precedent). Consumed by `integrity::run_validate`.
// ---------------------------------------------------------------------------

/// The `validate` relation-edge walk (design §5.5, R2-M5): scan every entity's
/// authored `[[relation]]` block and report two finding classes — never rewriting:
///
/// 1. **Danglers** — a validated (`Kinds`/`SameKind`/`AnyNumbered`) target that no
///    longer resolves to an entity (a deleted target). `Unvalidated` labels
///    (`drift`/`decision_ref`) are EXCLUDED: their free-text targets dangle BY DESIGN
///    (ADR-010 D2), so they are not findings.
/// 2. **`IllegalRows`** — hand-edited `[[relation]]` rows whose `(source, label)` is
///    off-table (an unknown label, or a label illegal for that source). `read_block`
///    surfaces these; `outbound_for`/`tier1_edges` drop them, so the raw block is
///    re-read here. A mis-ordered hand-edited typed table is caught by the WRITE
///    seam's F1 defence (`append_edge`), not this read walk — this walk reports the
///    row-legality findings the read seam yields.
///
/// Rides the established seams: `scan_entities` for the outbound edges (already legal,
/// resolved-or-not) and `integrity::ensure_ref_resolves` as the dangler oracle (parse +
/// dir-probe — the same existence check `link` uses forward). The raw block re-read for
/// `IllegalRows` uses `integrity::KINDS` (dir + stem) — no new path authority.
pub(crate) fn validate_relations(root: &Path) -> anyhow::Result<Vec<String>> {
    let mut findings = Vec::new();

    // (1) danglers — consume Catalog.edges for target-resolution failures
    // (SL-071 PHASE-05). Catalog classifies every edge target via
    // `parse_canonical_ref`; UnresolvedRef means the target parsed as a
    // canonical ref but the entity was absent from the scan.
    let catalog = crate::catalog::hydrate::scan_catalog(root)?;
    // Index entity keys → Kind for label-validation lookups.
    let entity_kinds: BTreeMap<EntityKey, &'static entity::Kind> = catalog
        .entities
        .iter()
        .filter_map(|e| {
            if let CatalogKey::Numbered(key) = &e.key {
                e.kind.map(|k| (*key, k))
            } else {
                None
            }
        })
        .collect();

    for edge in &catalog.edges {
        // Only report UnresolvedRef targets — UnvalidatedText targets dangle
        // by design (free-text / unknown-prefix targets), and Resolved targets
        // are fine.
        if let EdgeTarget::UnresolvedRef { raw } = &edge.target {
            // Only report danglers for validated labels — Unvalidated labels
            // (TargetSpec::Unvalidated in RELATION_RULES) dangle by design
            // (their targets are free-form by contract).
            // Edge source always exists in entity_kinds — edges are built from
            // entities in the same Catalog. A None here is a bug — guarded by
            // the invariant that every CatalogEdge.source is drawn from the
            // same Catalog whose entities built entity_kinds.
            let CatalogKey::Numbered(source_key) = &edge.source else {
                continue;
            };
            let CatalogEdgeLabel::Validated(label) = &edge.label else {
                // Raw label on a numbered edge is catalog corruption.
                findings.push(format!(
                    "internal: numbered edge {} has Raw label {:?}",
                    source_key.canonical(),
                    edge.label.name()
                ));
                continue;
            };
            let Some(kind) = entity_kinds.get(source_key) else {
                findings.push(format!(
                    "internal: edge source {} not in entity-kind map",
                    source_key.canonical()
                ));
                continue;
            };
            let validated = crate::relation::lookup(kind, *label)
                .is_some_and(|r| !matches!(r.target, TargetSpec::Unvalidated));
            if validated {
                findings.push(format!(
                    "{}: `{}` target `{}` does not resolve (dangling [[relation]] edge)",
                    edge.source.canonical(),
                    edge.label.name(),
                    raw
                ));
            }
        }
    }

    // (2) IllegalRows — hand-edited off-table `(source, label)` rows. Re-read the raw
    // `[[relation]]` block per entity (scan_entities drops the illegal rows).
    for kref in integrity::KINDS {
        let mut ids = entity::scan_ids(&root.join(kref.kind.dir))?;
        ids.sort_unstable();
        for id in ids {
            let name = format!("{id:03}");
            let toml_path = root
                .join(kref.kind.dir)
                .join(&name)
                .join(format!("{}-{name}.toml", kref.stem));
            let text = std::fs::read_to_string(&toml_path)
                .map_err(|e| anyhow::anyhow!("read {} for validate: {e}", toml_path.display()))?;
            let doc = crate::relation::RelationDoc::parse(&text)?;
            let (_edges, illegal) = crate::relation::read_block(kref.kind, &doc);
            for row in illegal {
                let why = match row.reason {
                    crate::relation::IllegalReason::UnknownLabel => "unknown label",
                    crate::relation::IllegalReason::IllegalForSource => "label illegal for source",
                };
                findings.push(format!(
                    "{}: [[relation]] row `{}` -> `{}` is illegal ({why})",
                    listing::canonical_id(kref.kind.prefix, id),
                    row.label,
                    row.target
                ));
            }
        }
    }

    findings.extend(validate_supersession(root)?);
    Ok(findings)
}

/// The supersession cross-check (design §5.5, R2-m2 / OD-3 / ADR-010 D4): report where
/// a governance entity's STORED `superseded_by` disagrees with the reciprocal DERIVED
/// from `supersedes` in-edges. Pure read, report-only — MAY surface pre-existing
/// hand-authored drift, which is the intended point (C3); NEVER rewrites.
///
/// The stored side is read via the typed governance seam
/// (`governance::supersession_pair` → `doc.relationships.superseded_by`) — the generic
/// `read_block`/`outbound_for` path deliberately excludes `superseded_by`. The derived
/// side is built per gov kind: X's derived `superseded_by` = every same-kind Y whose
/// stored `supersedes` lists X. Disagreement EITHER WAY (stored-not-derived /
/// derived-not-stored) is a finding.
fn validate_supersession(root: &Path) -> anyhow::Result<Vec<String>> {
    use std::collections::{BTreeMap, BTreeSet};

    // Per governance kind, drive its own ADR/POL/STD namespace.
    let gov_kinds: &[&crate::governance::GovKind] = &[
        &crate::adr::ADR_KIND,
        &crate::policy::POLICY_KIND,
        &crate::standard::STANDARD_KIND,
    ];

    let mut findings = Vec::new();
    for g in gov_kinds {
        let prefix = g.kind.prefix;
        let mut ids = entity::scan_ids(&root.join(g.kind.dir))?;
        ids.sort_unstable();

        // Read every entity's (supersedes, superseded_by) once.
        let mut stored: BTreeMap<u32, (Vec<String>, Vec<String>)> = BTreeMap::new();
        for id in &ids {
            stored.insert(*id, crate::governance::supersession_pair(g, root, *id)?);
        }

        // Derived reciprocal: for each Y listing X in `supersedes`, X is superseded_by Y.
        let mut derived: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
        for (y, (sup, _)) in &stored {
            let y_ref = listing::canonical_id(prefix, *y);
            for x_ref in sup {
                derived
                    .entry(x_ref.clone())
                    .or_default()
                    .insert(y_ref.clone());
            }
        }

        // Compare stored superseded_by against the derived set, both ways.
        for (x, (_sup, stored_by)) in &stored {
            let x_ref = listing::canonical_id(prefix, *x);
            let stored_set: BTreeSet<String> = stored_by.iter().cloned().collect();
            let derived_set = derived.get(&x_ref).cloned().unwrap_or_default();
            for missing in derived_set.difference(&stored_set) {
                findings.push(format!(
                    "{x_ref}: `{missing}` supersedes it (derived) but `{x_ref}` does not list \
                     it in `superseded_by` (supersession drift)"
                ));
            }
            for extra in stored_set.difference(&derived_set) {
                findings.push(format!(
                    "{x_ref}: lists `{extra}` in `superseded_by` but `{extra}` does not \
                     `supersede` it (supersession drift)"
                ));
            }
        }
    }
    Ok(findings)
}

/// One entity's direct relation view (design §5.2): its authored outbound relations
/// grouped by label, the derived inbound relations grouped by label, and its
/// unresolved/free-text outbound danglers. Direct-only, one-hop, composition-free
/// (I2). Inbound is recomputed every query from `in_edges` — nothing stores a
/// reverse field (ADR-004 §3 / REQ-074).
#[derive(Debug)]
pub(crate) struct InspectView {
    pub(crate) id: String,
    pub(crate) outbound: Vec<(RelationLabel, Vec<String>)>,
    pub(crate) inbound: Vec<(RelationLabel, Vec<String>)>,
    pub(crate) danglers: Vec<(RelationLabel, String)>,
}

/// `inspect <ID>` — the cross-kind relation view of one entity (design §5.2/§5.4).
///
/// Parses `id` via `integrity::parse_canonical_ref` (an unknown prefix / malformed
/// ref → a clean `anyhow` error, never a panic), builds the relation graph once,
/// and returns the entity's direct relations:
/// - **outbound**: the entity's own `outbound_for` edges, grouped by label,
///   targets in authored order within a label.
/// - **inbound**: per overlay, `graph.in_edges(ov, node)` → source `EntityKey` →
///   canonical ref, grouped under `label_of(ov)`. The `Supersedes`-overlay inbound
///   is the derived reciprocal "superseded by" (ADR-004 §3) — carried under the
///   `Supersedes` label here; PHASE-04 render flips the word. NO stored
///   `superseded_by` field is read (C8/R3/VT-4).
/// - **danglers**: the queried entity's unresolved / free-text / no-overlay
///   outbound targets.
///
/// A well-formed ref to a non-existent id (never minted) is an ERROR — `"{KIND-NNN}:
/// no such entity"` (SL-050 F6): an unminted id is indistinguishable from a real
/// isolated node at the render layer, so the existence gate makes it a clean failure.
/// The `require_minted` bail also keeps `outbound_for` (which reads the entity's own
/// toml) off a missing file — the gate subsumes the old missing-file guard. NEVER
/// reads `graph.provenance()` (C7 — a benign symmetric-`related` 2-cycle yields a
/// `Reject` `CycleDiagnostic` that must not leak into the view).
///
/// The own-scan convenience wrapper over [`inspect_from`] for callers that do NOT
/// already hold a corpus scan — the unit suite below. The command layer (`main.rs`)
/// holds the single F2 scan and calls `inspect_from`/`render_from` directly, so in a
/// non-test build this wrapper has no caller.
#[cfg_attr(
    not(test),
    expect(
        dead_code,
        reason = "own-scan convenience wrapper for the unit suite; the F2 command layer \
                  calls inspect_from with the shared scan, so it is test-only"
    )
)]
pub(crate) fn inspect(root: &Path, id: &str) -> anyhow::Result<InspectView> {
    inspect_from(&scan_entities(root, &mut vec![])?, root, id)
}

/// `inspect` over a PRE-SCANNED entity slice (the SL-050 F2 shared-scan seam). `inspect`
/// is now the thin `scan_entities(root)?` + delegate wrapper; this carries the body.
/// `root` is RETAINED for the queried entity's OWN per-entity re-reads — its outbound
/// `outbound_for` (its own toml) and `render_human`'s interaction-type read — which are
/// per-entity, not corpus, so they are not part of `scan_entities` and stay as-is.
pub(crate) fn inspect_from(
    scanned: &[ScannedEntity],
    root: &Path,
    id: &str,
) -> anyhow::Result<InspectView> {
    let (kref, qid) = integrity::parse_canonical_ref(id)?;
    let query_key = EntityKey {
        prefix: kref.kind.prefix,
        id: qid,
    };

    let rg = build_relation_graph_from(scanned)?;

    // Existence gate (F6): a well-formed ref to a never-minted id is an error, not an
    // empty-section view — the `Projection` holds exactly the minted keys. This also
    // keeps `outbound_for` (which reads the entity's own toml below) off a missing file.
    require_minted(&rg.projection, query_key)?;
    // Present by construction now the gate has passed.
    let Some(node) = rg.projection.resolve(query_key) else {
        debug_assert!(false, "inspect_from: gate passed but key not resolvable");
        anyhow::bail!("{}: no such entity", query_key.canonical());
    };

    // outbound — the entity's own authored edges, grouped by label (targets in
    // authored order within a label).
    let mut outbound_by_label: BTreeMap<RelationLabel, Vec<String>> = BTreeMap::new();
    for edge in outbound_for(root, kref.kind, qid)? {
        outbound_by_label
            .entry(edge.label)
            .or_default()
            .push(edge.target);
    }
    let outbound: Vec<(RelationLabel, Vec<String>)> = outbound_by_label.into_iter().collect();

    // inbound — derived from in_edges per overlay (no stored reverse field read).
    let mut inbound_by_label: BTreeMap<RelationLabel, Vec<String>> = BTreeMap::new();
    for (&overlay, &label) in &rg.overlays.by_overlay {
        let mut srcs: Vec<EntityKey> = rg
            .graph
            .in_edges(overlay, node)
            .filter_map(|(src_node, _attrs)| rg.projection.key_of(src_node))
            .collect::<Vec<EntityKey>>();
        if !srcs.is_empty() {
            // in_edges orders by the (src,rank,age) adjacency key, but src NodeId
            // order is mint order, not ref order — sort by EntityKey::Ord
            // (prefix lexicographic, id numeric) for a deterministic,
            // permutation-invariant render correct past id 999 (RSK-007).
            srcs.sort();
            inbound_by_label
                .entry(label)
                .or_default()
                .extend(srcs.into_iter().map(EntityKey::canonical));
        }
    }
    let inbound: Vec<(RelationLabel, Vec<String>)> = inbound_by_label.into_iter().collect();

    // danglers — only the queried entity's set (empty if none).
    let danglers = rg.danglers.get(&query_key).cloned().unwrap_or_default();

    Ok(InspectView {
        id: query_key.canonical(),
        outbound,
        inbound,
        danglers,
    })
}

// ---------------------------------------------------------------------------
// PHASE-04 — the `inspect <ID>` command: render (human + --json) and the shell.
// ---------------------------------------------------------------------------

/// Render the relation view of `id` to a string from a PRE-SCANNED entity slice (the
/// command-layer seam, SL-047 §5.4 + SL-050 F2): `main.rs`'s `inspect` handler builds
/// the single corpus scan ONCE, calls this for the relation portion, then APPENDS the
/// priority actionability block BELOW it (the composition lives at the command layer,
/// which alone may depend on both `relation_graph` and `priority`; ADR-001 forbids
/// `relation_graph` from calling up into `priority`). The relation portion stays
/// byte-identical — the appended block is additive (EX-2 / VT-2 behaviour-preserving).
/// No trailing newline on JSON (the golden contract); the human surface ends in `\n`.
///
/// Delegates through [`inspect_from`], so it inherits the F6 existence gate (a
/// never-minted id errors before any render). `root` is retained for the queried
/// entity's own per-entity re-reads (`inspect_from`'s outbound + `render_human`'s
/// interaction types).
pub(crate) fn render_from(
    scanned: &[ScannedEntity],
    root: &Path,
    id: &str,
    format: Format,
) -> anyhow::Result<String> {
    let view = inspect_from(scanned, root, id)?;
    match format {
        // The queried entity's per-edge interaction `type` is re-read from the
        // SOURCE here (C2 / §5.3) — a human-render annotation only; never carried
        // in `InspectView`.
        Format::Table => render_human(root, &view),
        Format::Json => render_json(&view),
    }
}

/// Render one entity's relation view for human reading (default). Fixed
/// deterministic section order — **outbound, then inbound, then danglers** (EX-2);
/// each section omitted when empty (the `show`-surface convention — governance /
/// spec `format_show` omit empty relationship blocks; VT-3). Within a section,
/// labels are already ordered (the `RelationLabel` `Ord`), targets in the view's
/// order. House style: `Vec<String>` parts each carrying their own newline, joined
/// by `concat` (the `governance::format_show` / `backlog::format_show` precedent —
/// avoids the `push_str(&format!)` lint).
///
/// Two presentation flips, both by SECTION (never by reading a stored field):
/// - inbound `Supersedes` renders the word **"superseded by"** (the derived
///   reciprocal — ADR-004 §3); outbound `Supersedes` stays **"supersedes"**.
/// - the queried entity's OUTBOUND `Interactions` targets are annotated with their
///   per-edge free-text `type`, re-read from the source `interactions.toml` via the
///   spec reader (C2 / EX-4) — `SPEC-002 (calls)`.
fn render_human(root: &Path, view: &InspectView) -> anyhow::Result<String> {
    // Re-read the queried entity's interaction types from source (C2) — only a tech
    // spec authors any; every other kind yields an empty map, so the annotation is a
    // no-op there. `parse_canonical_ref` already classified the id in `inspect`; the
    // queried id is `view.id`.
    let interaction_types = match integrity::parse_canonical_ref(&view.id) {
        Ok((kref, qid)) if kref.kind.prefix == "SPEC" => crate::spec::interaction_types(root, qid)?,
        _ => BTreeMap::new(),
    };

    let mut parts: Vec<String> = Vec::new();
    parts.push(format!("{} — relations\n", view.id));

    render_outbound(&mut parts, view, &interaction_types);
    render_inbound(&mut parts, view);
    render_danglers(&mut parts, view);

    // An entity with no relations at all renders the header plus an explicit note,
    // so an empty view is never a bare one-liner (VT-3 — empty sections render
    // cleanly).
    if view.outbound.is_empty() && view.inbound.is_empty() && view.danglers.is_empty() {
        parts.push("\n(no relations)\n".to_string());
    }
    Ok(parts.concat())
}

/// Append the outbound section (omitted when empty). The queried tech spec's
/// `Interactions` targets carry their re-read free-text `type` annotation (C2).
fn render_outbound(
    parts: &mut Vec<String>,
    view: &InspectView,
    interaction_types: &BTreeMap<String, String>,
) {
    if view.outbound.is_empty() {
        return;
    }
    parts.push("\noutbound:\n".to_string());
    for (label, targets) in &view.outbound {
        let rendered: Vec<String> = if *label == RelationLabel::Interactions {
            targets
                .iter()
                .map(|t| match interaction_types.get(t) {
                    Some(ty) => format!("{t} ({ty})"),
                    None => t.clone(),
                })
                .collect()
        } else {
            targets.clone()
        };
        parts.push(format!("  {}: {}\n", label.name(), rendered.join(", ")));
    }
}

/// Append the inbound section (omitted when empty). The `Supersedes` overlay's
/// inbound is the derived reciprocal — rendered as the word "superseded by"
/// (ADR-004 §3); the flip is by SECTION, not by reading any stored field.
fn render_inbound(parts: &mut Vec<String>, view: &InspectView) {
    if view.inbound.is_empty() {
        return;
    }
    parts.push("\ninbound:\n".to_string());
    for (label, srcs) in &view.inbound {
        // Table-driven inbound render text (design §5.5 X5 / R2-M3): the `supersedes` →
        // "superseded by" special-case collapses into `relation::inbound_name`, which
        // also renders `governed_by` → "governs", `consumes` → "consumed_by". Legacy
        // labels carry `inbound_name == name()`, so shipped goldens are unchanged. The
        // `--json` inbound keeps the raw label (`render_json`), per R2-M3.
        let word = crate::relation::inbound_name(*label);
        parts.push(format!("  {word}: {}\n", srcs.join(", ")));
    }
}

/// Append the danglers section (omitted when empty) — the queried entity's
/// unresolved / free-text / no-overlay outbound targets, grouped by label.
fn render_danglers(parts: &mut Vec<String>, view: &InspectView) {
    if view.danglers.is_empty() {
        return;
    }
    parts.push("\ndanglers:\n".to_string());
    for (label, target) in &view.danglers {
        parts.push(format!("  {}: {target}\n", label.name()));
    }
}

/// Render the `--json` view: the serialized `InspectView`, every surface asserted
/// (`id`, `outbound`, `inbound`, `danglers` — VT-2). Built MANUALLY with
/// `serde_json::json!` (the `spec::show_json` precedent — the repo derives no
/// `Serialize` on domain enums; `RelationLabel` renders via `.name()`). Each label
/// group is `{ "label": <name>, "targets": [...] }`; each dangler is
/// `{ "label": <name>, "target": <ref> }`. The interaction `type` is a human-render
/// extra ONLY (design §5.2) — it is NOT in the JSON. The envelope is the 4
/// `InspectView` fields (`id`/`outbound`/`inbound`/`danglers`) under a `"kind":
/// "inspect"` discriminant (the `spec::show_json` envelope precedent), so an agent
/// reads the same shape `InspectView` carries. No trailing newline (the black-box
/// golden contract — `write!`, not `writeln!`).
fn render_json(view: &InspectView) -> anyhow::Result<String> {
    serde_json::to_string_pretty(&inspect_value(view))
        .map_err(|e| anyhow::anyhow!("failed to serialize inspect JSON: {e}"))
}

/// The `inspect` `--json` envelope as a [`serde_json::Value`] (the 4 `InspectView`
/// surfaces under a `"kind": "inspect"` discriminant). Factored out so the command
/// layer can INJECT the priority `actionability` block as an additive key (SL-047
/// §5.4 / SL-046 D1) without `relation_graph` depending on `priority` (ADR-001) — the
/// relation surfaces stay byte-identical; only a new key is added.
pub(crate) fn inspect_value(view: &InspectView) -> serde_json::Value {
    let group = |label: RelationLabel, targets: &[String]| serde_json::json!({ "label": label.name(), "targets": targets });
    let outbound: Vec<serde_json::Value> =
        view.outbound.iter().map(|(l, t)| group(*l, t)).collect();
    let inbound: Vec<serde_json::Value> = view.inbound.iter().map(|(l, t)| group(*l, t)).collect();
    let danglers: Vec<serde_json::Value> = view
        .danglers
        .iter()
        .map(|(l, t)| serde_json::json!({ "label": l.name(), "target": t }))
        .collect();
    serde_json::json!({
        "kind": "inspect",
        "id": view.id,
        "outbound": outbound,
        "inbound": inbound,
        "danglers": danglers,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::integrity::KINDS;
    use crate::relation::RelationLabel;
    use std::fs;

    /// Write `parent/dir/<name>` with `body`, creating parents.
    fn write(root: &Path, rel: &str, body: &str) {
        let path = root.join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, body).unwrap();
    }

    /// Find the `KindRef` for a prefix (the dispatch input the scan supplies).
    fn kind_for(prefix: &str) -> &'static entity::Kind {
        KINDS.iter().find(|k| k.kind.prefix == prefix).unwrap().kind
    }

    /// (label, target) pairs for ergonomic assertions.
    fn pairs(edges: &[RelationEdge]) -> Vec<(RelationLabel, &str)> {
        edges.iter().map(|e| (e.label, e.target.as_str())).collect()
    }

    /// A throwaway corpus root under an RAII temp dir (auto-removed on drop), matching
    /// the spec.rs tests' `tempfile::tempdir()` convention — no hand-rolled
    /// pid/nanos uniqueness, no leaked dirs. Callers bind the `TempDir` and read
    /// `.path()` so the dir outlives the test body.
    fn tmp() -> tempfile::TempDir {
        tempfile::tempdir().unwrap()
    }

    // -- VT-1 outbound correctness per kind + outbound_for dispatch ----------

    #[test]
    fn slice_outbound_specs_requirements_supersedes() {
        let dir = tmp();
        let root = dir.path();
        write(
            &root,
            ".doctrine/slice/001/slice-001.toml",
            // SL-048 PHASE-04: tier-1 axes migrated to `[[relation]]` rows.
            "id = 1\nslug = \"a\"\ntitle = \"A\"\nstatus = \"proposed\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [[relation]]\nlabel = \"specs\"\ntarget = \"PRD-010\"\n\
             [[relation]]\nlabel = \"requirements\"\ntarget = \"REQ-001\"\n\
             [[relation]]\nlabel = \"requirements\"\ntarget = \"REQ-002\"\n\
             [[relation]]\nlabel = \"supersedes\"\ntarget = \"SL-000\"\n",
        );
        write(&root, ".doctrine/slice/001/slice-001.md", "scope\n");
        let edges = outbound_for(&root, kind_for("SL"), 1).unwrap();
        assert_eq!(
            pairs(&edges),
            vec![
                (RelationLabel::Specs, "PRD-010"),
                (RelationLabel::Requirements, "REQ-001"),
                (RelationLabel::Requirements, "REQ-002"),
                (RelationLabel::Supersedes, "SL-000"),
            ]
        );
    }

    #[test]
    fn governance_outbound_supersedes_related_only() {
        let dir = tmp();
        let root = dir.path();
        // ADR with every axis populated — only supersedes + related must emit.
        write(
            &root,
            ".doctrine/adr/002/adr-002.toml",
            // SL-095 PHASE-02: `supersedes` is now a `[[relation]]` row.
            "id = 2\nslug = \"a\"\ntitle = \"A\"\nstatus = \"accepted\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [relationships]\nsuperseded_by = [\"ADR-009\"]\n\
             tags = [\"layering\"]\n\
             [[relation]]\nlabel = \"supersedes\"\ntarget = \"ADR-001\"\n\
             [[relation]]\nlabel = \"related\"\ntarget = \"ADR-004\"\n",
        );
        write(&root, ".doctrine/adr/002/adr-002.md", "body\n");
        let edges = outbound_for(&root, kind_for("ADR"), 2).unwrap();
        assert_eq!(
            pairs(&edges),
            vec![
                (RelationLabel::Supersedes, "ADR-001"),
                (RelationLabel::Related, "ADR-004"),
            ],
            "governance emits supersedes + related ONLY (no superseded_by, no tags)"
        );
    }

    #[test]
    fn spec_outbound_lineage_members_interactions() {
        let dir = tmp();
        let root = dir.path();
        write(
            &root,
            ".doctrine/spec/tech/001/spec-001.toml",
            "id = 1\nslug = \"s\"\ntitle = \"S\"\nstatus = \"draft\"\nkind = \"tech\"\n\
             descends_from = \"PRD-005\"\nparent = \"SPEC-000\"\n",
        );
        write(&root, ".doctrine/spec/tech/001/spec-001.md", "b\n");
        write(
            &root,
            ".doctrine/spec/tech/001/members.toml",
            "[[member]]\nrequirement = \"REQ-009\"\nlabel = \"FR\"\norder = 1\n",
        );
        write(
            &root,
            ".doctrine/spec/tech/001/interactions.toml",
            "[[edge]]\ntarget = \"SPEC-002\"\ntype = \"calls\"\nnotes = \"sync\"\n",
        );
        let edges = outbound_for(&root, kind_for("SPEC"), 1).unwrap();
        assert_eq!(
            pairs(&edges),
            vec![
                (RelationLabel::DescendsFrom, "PRD-005"),
                (RelationLabel::Parent, "SPEC-000"),
                (RelationLabel::Members, "REQ-009"),
                (RelationLabel::Interactions, "SPEC-002"),
            ]
        );
    }

    #[test]
    fn product_spec_lineage_options_absent_emit_nothing() {
        let dir = tmp();
        let root = dir.path();
        // A product spec has no descends_from/parent and no interactions.toml.
        write(
            &root,
            ".doctrine/spec/product/003/spec-003.toml",
            "id = 3\nslug = \"p\"\ntitle = \"P\"\nstatus = \"draft\"\nkind = \"product\"\n",
        );
        write(&root, ".doctrine/spec/product/003/spec-003.md", "b\n");
        write(&root, ".doctrine/spec/product/003/members.toml", "");
        let edges = outbound_for(&root, kind_for("PRD"), 3).unwrap();
        assert!(
            edges.is_empty(),
            "absent Options + empty members emit nothing"
        );
    }

    #[test]
    fn backlog_outbound_slices_specs_drift_only() {
        let dir = tmp();
        let root = dir.path();
        // Every axis populated — only slices/specs/drift must emit (not
        // needs/after/triggers).
        write(
            &root,
            ".doctrine/backlog/issue/001/backlog-001.toml",
            // SL-048 PHASE-04: slices/specs/drift migrated to `[[relation]]`; the typed
            // `needs` axis stays in a `[relationships]` table preceding the arrays (F1).
            "id = 1\nslug = \"i\"\ntitle = \"I\"\nkind = \"issue\"\nstatus = \"open\"\n\
             resolution = \"\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [relationships]\nneeds = [\"ISS-002\"]\n\
             [[relation]]\nlabel = \"slices\"\ntarget = \"SL-020\"\n\
             [[relation]]\nlabel = \"specs\"\ntarget = \"PRD-009\"\n\
             [[relation]]\nlabel = \"drift\"\ntarget = \"some-free-text\"\n",
        );
        write(&root, ".doctrine/backlog/issue/001/backlog-001.md", "b\n");
        let edges = outbound_for(&root, kind_for("ISS"), 1).unwrap();
        // SL-048 PHASE-04 (X1): `read_block` emits in canonical RELATION_RULES order —
        // specs (pos 0) precedes slices (pos 10) precedes drift (pos 14). The former
        // hardcoded accessor order (slices, specs, drift) is replaced; no render golden
        // depends on the raw accessor order (inspect regroups by enum Ord, which is the
        // same specs<slices<drift; format_show/show_json keep their own literal order).
        assert_eq!(
            pairs(&edges),
            vec![
                (RelationLabel::Specs, "PRD-009"),
                (RelationLabel::Slices, "SL-020"),
                (RelationLabel::Drift, "some-free-text"),
            ],
            "backlog emits slices/specs/drift ONLY (no needs/after/triggers), canonical order"
        );
    }

    #[test]
    fn review_outbound_single_reviews_edge() {
        let dir = tmp();
        let root = dir.path();
        write(
            &root,
            ".doctrine/review/001/review-001.toml",
            "id = 1\nslug = \"r\"\ntitle = \"R\"\n\
             [review]\nfacet = \"reconciliation\"\nraiser = \"a\"\nresponder = \"b\"\n\
             [target]\nref = \"SL-046\"\n",
        );
        let edges = outbound_for(&root, kind_for("RV"), 1).unwrap();
        assert_eq!(pairs(&edges), vec![(RelationLabel::Reviews, "SL-046")]);
    }

    #[test]
    fn rec_outbound_owning_slice_and_decision_ref() {
        let dir = tmp();
        let root = dir.path();
        write(
            &root,
            ".doctrine/rec/001/rec-001.toml",
            "id = 1\nslug = \"r\"\ntitle = \"R\"\n\
             [rec]\nmove = \"accept\"\nowning_slice = \"SL-046\"\ndecision_ref = \"DEC-005-C\"\n",
        );
        let edges = outbound_for(&root, kind_for("REC"), 1).unwrap();
        assert_eq!(
            pairs(&edges),
            vec![
                (RelationLabel::OwningSlice, "SL-046"),
                (RelationLabel::DecisionRef, "DEC-005-C"),
            ]
        );
    }

    #[test]
    fn requirement_authors_no_outbound() {
        let dir = tmp();
        let root = dir.path();
        // REQ is an edge target only; the dispatch returns empty without touching disk.
        let edges = outbound_for(&root, kind_for("REQ"), 1).unwrap();
        assert!(edges.is_empty());
    }

    // -- SL-066 G3/G2: the REV arms land WITH the KINDS row -------------------

    #[test]
    fn revision_outbound_arm_reads_change_rows() {
        // G3: a REV row in KINDS routes to `revision::relation_edges` BEFORE the
        // `debug_assert!(false)` fallthrough. The accessor reads the `[[change]]`
        // payload (PHASE-03), projecting each row to one `Revises` edge — a REV with
        // no rows authors none.
        let dir = tmp();
        let root = dir.path();
        // No `[[change]]` rows → no outbound edges.
        write(
            &root,
            ".doctrine/revision/001/revision-001.toml",
            "id = 1\nslug = \"r\"\ntitle = \"R\"\nstatus = \"proposed\"\napproval = \"none\"\n",
        );
        let empty = outbound_for(&root, kind_for("REV"), 1).unwrap();
        assert!(
            empty.is_empty(),
            "a REV with no change rows authors no outbound"
        );

        // A `[[change]]` row projects to one `revises` edge to its target.
        write(
            &root,
            ".doctrine/revision/002/revision-002.toml",
            "id = 2\nslug = \"r\"\ntitle = \"R\"\nstatus = \"proposed\"\napproval = \"none\"\n\
             [[change]]\ntarget = \"ADR-006\"\naction = \"modify\"\nprimary = true\n",
        );
        let edges = outbound_for(&root, kind_for("REV"), 2).unwrap();
        assert_eq!(edges.len(), 1, "one change row → one revises edge");
        assert_eq!(edges[0].label, RelationLabel::Revises);
        assert_eq!(edges[0].target, "ADR-006");
    }

    #[test]
    fn revision_dep_seq_arm_reads_its_own_toml() {
        // G2: REV-as-source `needs`/`after` route to the leaf `dep_seq::read` over
        // `revision-NNN.toml` (mirrors the SL arm), not the empty short-circuit.
        let dir = tmp();
        let root = dir.path();
        write(
            &root,
            ".doctrine/revision/001/revision-001.toml",
            "id = 1\nslug = \"r\"\ntitle = \"R\"\nstatus = \"proposed\"\napproval = \"none\"\n\
             [relationships]\nneeds = [\"SL-046\"]\nafter = []\n",
        );
        let (ds, promoted) = dep_seq_for(&root, kind_for("REV"), 1).unwrap();
        assert_eq!(ds.needs, vec!["SL-046"], "REV needs reach the blocker view");
        assert!(!promoted, "REV carries no backlog-only promoted projection");
    }

    // -- SL-059 VT-1: outbound_for total-dispatch for the four knowledge kinds --

    #[test]
    fn knowledge_kinds_author_outbound_edges() {
        let dir = tmp();
        let root = dir.path();
        // Seed an assumption record with [[relation]] rows
        write(
            &root,
            ".doctrine/knowledge/assumption/001/record-001.toml",
            "schema = \"doctrine.knowledge\"\nversion = 1\n\n\
             id = 1\nslug = \"a\"\ntitle = \"A\"\n\
             record_kind = \"assumption\"\nstatus = \"held\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             tags = []\n\n\
             [facet]\n\
             claim = \"\"\nconfidence = \"\"\nbasis = \"\"\n\
             validation_plan = \"\"\nvalidated_by = \"\"\nvalidated_on = \"\"\n\
             invalidated_by = \"\"\ninvalidated_on = \"\"\n\n\
             [evidence]\n\
             supports = []\ncontradicts = []\nnotes = []\n\
             [[relation]]\nlabel = \"shapes\"\ntarget = \"SL-001\"\n\
             [[relation]]\nlabel = \"spawns\"\ntarget = \"ISS-001\"\n\
             [[relation]]\nlabel = \"governed_by\"\ntarget = \"ADR-001\"\n",
        );
        write(
            &root,
            ".doctrine/knowledge/assumption/001/record-001.md",
            "body\n",
        );
        let edges = outbound_for(&root, kind_for("ASM"), 1).unwrap();
        assert_eq!(edges.len(), 3);
        // Verify each edge exists with correct target
        assert!(
            edges
                .iter()
                .any(|e| e.label == RelationLabel::Shapes && e.target == "SL-001")
        );
        assert!(
            edges
                .iter()
                .any(|e| e.label == RelationLabel::Spawns && e.target == "ISS-001")
        );
        assert!(
            edges
                .iter()
                .any(|e| e.label == RelationLabel::GovernedBy && e.target == "ADR-001")
        );
    }

    // -- SL-059 VT-2: scan-side totality (F-A7, the L7 partner) ---------------

    #[test]
    fn knowledge_rows_present_but_no_record_tree_leaves_the_graph_unchanged() {
        let dir = tmp();
        let root = dir.path();
        // A fixture with an ordinary entity but NO knowledge trees. The four KINDS
        // rows are present, so `scan_entities` visits the (absent) record dirs — it
        // is benign only because `entity::scan_ids` returns Ok(vec![]) on a missing
        // dir. The scan returns exactly the pre-existing entity; the four record
        // kinds contribute nothing. Regression tripwire if `scan_ids` is made strict.
        write(
            &root,
            ".doctrine/requirement/001/requirement-001.toml",
            "id = 1\nslug = \"r\"\ntitle = \"R\"\nstatus = \"active\"\n",
        );
        write(&root, ".doctrine/requirement/001/requirement-001.md", "b\n");
        let scanned = scan_entities(&root, &mut vec![]).unwrap();
        let keys: Vec<_> = scanned.iter().map(|e| e.key.canonical()).collect();
        assert_eq!(keys, vec!["REQ-001"], "no record kind contributes a node");
    }

    // -- VT-2 exclusion proof (REC decision_ref carried, not dropped) --------

    #[test]
    fn rec_decision_ref_carried_as_free_text_not_dropped() {
        let dir = tmp();
        let root = dir.path();
        write(
            &root,
            ".doctrine/rec/002/rec-002.toml",
            "id = 2\nslug = \"r\"\ntitle = \"R\"\n\
             [rec]\nmove = \"accept\"\ndecision_ref = \"DEC-001-A\"\n",
        );
        let edges = outbound_for(&root, kind_for("REC"), 2).unwrap();
        // decision_ref survives even with no owning_slice — carried, will dangle.
        assert_eq!(
            pairs(&edges),
            vec![(RelationLabel::DecisionRef, "DEC-001-A")]
        );
    }

    // -- SL-060 PHASE-04: dep_seq_for cross-kind dispatch --------------------

    #[test]
    fn dep_seq_for_slice_arm_reads_needs_after_promoted_false() {
        let dir = tmp();
        let root = dir.path();
        // A slice authoring both dep/seq axes — the slice arm reads its own toml via the
        // leaf; `promoted` is always false (only a backlog item carries that projection).
        write(
            &root,
            ".doctrine/slice/001/slice-001.toml",
            "id = 1\nslug = \"a\"\ntitle = \"A\"\nstatus = \"proposed\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [relationships]\nneeds = [\"SL-002\"]\n\
             after = [{ to = \"SL-003\", rank = 4 }]\n",
        );
        write(&root, ".doctrine/slice/001/slice-001.md", "scope\n");
        let (ds, promoted) = dep_seq_for(&root, kind_for("SL"), 1).unwrap();
        assert_eq!(ds.needs, vec!["SL-002"]);
        assert_eq!(
            ds.after,
            vec![dep_seq::AfterEdge {
                to: "SL-003".to_string(),
                rank: 4,
            }]
        );
        assert!(!promoted, "a slice is never promoted");
    }

    #[test]
    fn dep_seq_for_backlog_arm_one_parse_carries_promoted() {
        let dir = tmp();
        let root = dir.path();
        // A promoted backlog issue authoring dep/seq — the backlog arm routes to backlog's
        // single `dep_seq_for` (ONE parse), adapting its `(to, rank)` pairs to AfterEdge
        // and carrying `resolution == promoted` through.
        write(
            &root,
            ".doctrine/backlog/issue/001/backlog-001.toml",
            "id = 1\nslug = \"i\"\ntitle = \"I\"\nkind = \"issue\"\nstatus = \"resolved\"\n\
             resolution = \"promoted\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [relationships]\nneeds = [\"ISS-002\"]\n\
             after = [{ to = \"RSK-001\", rank = 2 }]\n",
        );
        write(&root, ".doctrine/backlog/issue/001/backlog-001.md", "b\n");
        let (ds, promoted) = dep_seq_for(&root, kind_for("ISS"), 1).unwrap();
        assert_eq!(ds.needs, vec!["ISS-002"]);
        assert_eq!(
            ds.after,
            vec![dep_seq::AfterEdge {
                to: "RSK-001".to_string(),
                rank: 2,
            }]
        );
        assert!(
            promoted,
            "resolution=promoted carried through the backlog arm"
        );
    }

    #[test]
    fn dep_seq_for_non_authoring_kind_short_circuits_before_any_read() {
        let dir = tmp();
        let root = dir.path();
        // VT-4 no-read probe (design F5): a non-authoring kind (ADR) whose on-disk toml is
        // ABSENT. The dispatch must return an empty DepSeq WITHOUT error — proving the kind
        // is tested BEFORE any path is built or any toml is touched. (If the arm read disk
        // first it would fail to open the missing ADR-001 toml.) `promoted` is false.
        let (ds, promoted) = dep_seq_for(&root, kind_for("ADR"), 1).unwrap();
        assert_eq!(
            ds,
            dep_seq::DepSeq::default(),
            "non-authoring kind yields empty dep/seq with no disk read"
        );
        assert!(!promoted);

        // Stronger probe: a GARBAGE toml on disk for a non-authoring kind is never opened —
        // a read arm would choke on the malformed TOML; the short-circuit ignores it.
        write(
            &root,
            ".doctrine/requirement/001/requirement-001.toml",
            "this is not valid toml at all = = =\n",
        );
        let (ds2, _promoted2) = dep_seq_for(&root, kind_for("REQ"), 1).unwrap();
        assert_eq!(
            ds2,
            dep_seq::DepSeq::default(),
            "garbage toml for a non-authoring kind is never read → still empty"
        );
    }

    // -- VT-3 interactions collapse to a single `Interactions` class ---------
    // (The per-edge free-text `type` round-trips from the SOURCE `Interaction`
    //  struct — asserted in spec.rs where the reader + struct are visible.)

    #[test]
    fn interactions_collapse_to_single_class_label() {
        let dir = tmp();
        let root = dir.path();
        write(
            &root,
            ".doctrine/spec/tech/004/spec-004.toml",
            "id = 4\nslug = \"s\"\ntitle = \"S\"\nstatus = \"draft\"\nkind = \"tech\"\n",
        );
        write(&root, ".doctrine/spec/tech/004/spec-004.md", "b\n");
        write(&root, ".doctrine/spec/tech/004/members.toml", "");
        write(
            &root,
            ".doctrine/spec/tech/004/interactions.toml",
            "[[edge]]\ntarget = \"SPEC-009\"\ntype = \"depends-on\"\nnotes = \"n\"\n\
             [[edge]]\ntarget = \"SPEC-010\"\ntype = \"calls\"\n",
        );
        // Two interactions with different free-text types share ONE label class; the
        // type is NOT encoded in the label (re-read at render — C2).
        let edges = outbound_for(&root, kind_for("SPEC"), 4).unwrap();
        assert_eq!(
            pairs(&edges),
            vec![
                (RelationLabel::Interactions, "SPEC-009"),
                (RelationLabel::Interactions, "SPEC-010"),
            ]
        );
    }

    // -- PHASE-03 inspect query ---------------------------------------------

    /// All inbound targets under `label` in a view (sorted-render order).
    fn inbound_for(view: &InspectView, label: RelationLabel) -> Vec<&str> {
        view.inbound
            .iter()
            .find(|(l, _)| *l == label)
            .map(|(_, v)| v.iter().map(String::as_str).collect())
            .unwrap_or_default()
    }

    /// All outbound targets under `label` in a view.
    fn outbound_targets(view: &InspectView, label: RelationLabel) -> Vec<&str> {
        view.outbound
            .iter()
            .find(|(l, _)| *l == label)
            .map(|(_, v)| v.iter().map(String::as_str).collect())
            .unwrap_or_default()
    }

    /// A minimal slice toml with the given relations, in the SL-048 migrated shape
    /// (`axes` → `[relationships]` typed leftovers then `[[relation]]` rows).
    fn slice_toml(id: u32, axes: &[(&str, &[&str])]) -> String {
        format!(
            "id = {id}\nslug = \"s\"\ntitle = \"S\"\nstatus = \"proposed\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n{}",
            crate::relation::rels_block(kind_for("SL"), axes)
        )
    }

    /// Seed a slice entity (toml + md) under `root`.
    fn seed_slice(root: &Path, id: u32, axes: &[(&str, &[&str])]) {
        write(
            root,
            &format!(".doctrine/slice/{id:03}/slice-{id:03}.toml"),
            &slice_toml(id, axes),
        );
        write(
            root,
            &format!(".doctrine/slice/{id:03}/slice-{id:03}.md"),
            "scope\n",
        );
    }

    /// Seed an ADR governance entity (SL-048 migrated shape — only `related` moves to
    /// `[[relation]]`; supersedes/superseded_by/tags stay typed, OD-3).
    fn seed_adr(root: &Path, id: u32, axes: &[(&str, &[&str])]) {
        write(
            root,
            &format!(".doctrine/adr/{id:03}/adr-{id:03}.toml"),
            &format!(
                "id = {id}\nslug = \"a\"\ntitle = \"A\"\nstatus = \"accepted\"\n\
                 created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n{}",
                crate::relation::rels_block(kind_for("ADR"), axes)
            ),
        );
        write(
            root,
            &format!(".doctrine/adr/{id:03}/adr-{id:03}.md"),
            "body\n",
        );
    }

    // VT-1 — derived inbound correctness over a seeded multi-kind corpus, incl.
    // the supersedes reciprocal. Structural proof: NO stored reverse field is read
    // (the predecessor authors no `superseded_by`; inbound is derived from the
    // successor's outbound `supersedes` via in_edges — ADR-004 §3 / REQ-074).
    #[test]
    fn inbound_derived_from_in_edges_including_supersedes_reciprocal() {
        let dir = tmp();
        let root = dir.path();
        // SL-002 supersedes SL-001 and requires REQ-005; SL-001 authors nothing.
        seed_slice(&root, 1, &[]);
        seed_slice(
            &root,
            2,
            &[("requirements", &["REQ-005"]), ("supersedes", &["SL-001"])],
        );
        // REQ-005 is an edge target only (no outbound).
        write(
            &root,
            ".doctrine/requirement/005/requirement-005.toml",
            "id = 5\nslug = \"r\"\ntitle = \"R\"\nstatus = \"active\"\n",
        );
        write(&root, ".doctrine/requirement/005/requirement-005.md", "r\n");

        // SL-001's only inbound is the derived "superseded by" from SL-002.
        let pred = inspect(&root, "SL-001").unwrap();
        assert_eq!(pred.id, "SL-001");
        assert!(pred.outbound.is_empty(), "predecessor authors no outbound");
        assert_eq!(
            inbound_for(&pred, RelationLabel::Supersedes),
            vec!["SL-002"],
            "supersedes-overlay inbound is the derived reciprocal (renders 'superseded by')"
        );

        // REQ-005's only inbound is the requirements edge from SL-002.
        let req = inspect(&root, "REQ-005").unwrap();
        assert_eq!(
            inbound_for(&req, RelationLabel::Requirements),
            vec!["SL-002"]
        );

        // SL-002 owns the outbound; it has no inbound.
        let succ = inspect(&root, "SL-002").unwrap();
        assert_eq!(
            outbound_targets(&succ, RelationLabel::Supersedes),
            vec!["SL-001"]
        );
        assert!(succ.inbound.is_empty(), "successor has no inbound");
    }

    // VT-2 / C3 — two authored rows sharing (label, src, dst) surface as ONE
    // inbound edge, no panic. Asserted at the projection boundary: the duplicate
    // collapses in cordage's BTreeSet<Edge> (EdgeAttrs(0,0)).
    #[test]
    fn duplicate_authored_ref_collapses_to_single_inbound_no_panic() {
        let dir = tmp();
        let root = dir.path();
        // SL-002 lists SL-001 twice under supersedes (an authoring duplicate).
        seed_slice(&root, 1, &[]);
        seed_slice(&root, 2, &[("supersedes", &["SL-001", "SL-001"])]);
        let view = inspect(&root, "SL-001").unwrap();
        assert_eq!(
            inbound_for(&view, RelationLabel::Supersedes),
            vec!["SL-002"],
            "two identical (label,src,dst) rows collapse to one inbound edge"
        );
    }

    // VT-3 / C5 — out-of-order planted entity dirs yield identical output: the
    // ascending sort after scan_ids makes mint + render permutation-invariant
    // (REQ-077). We seed the same corpus and assert the view is stable regardless
    // of how many supersedors target SL-001 (their canonical-ref render order is
    // independent of NodeId mint order).
    #[test]
    fn inbound_render_is_permutation_invariant() {
        let dir = tmp();
        let root = dir.path();
        // Three supersedors of SL-001, planted out of id order on disk; scan_ids is
        // read_dir order (unsorted), so the only thing making the render stable is
        // the ascending sort + the EntityKey sort in inspect.
        seed_slice(&root, 1, &[]);
        seed_slice(&root, 4, &[("supersedes", &["SL-001"])]);
        seed_slice(&root, 2, &[("supersedes", &["SL-001"])]);
        seed_slice(&root, 3, &[("supersedes", &["SL-001"])]);
        let view = inspect(&root, "SL-001").unwrap();
        assert_eq!(
            inbound_for(&view, RelationLabel::Supersedes),
            vec!["SL-002", "SL-003", "SL-004"],
            "inbound renders in ascending canonical-ref order, not filesystem order"
        );

        // RSK-007: same-prefix ids ≥ 1000 must sort numerically, not lexically.
        // Plant SL-998, SL-999, SL-1000, SL-1001 out-of-order as supersedors of
        // SL-001. Lexical sort would give ["SL-1000","SL-1001","SL-0998","SL-0999"].
        let dir2 = tmp();
        let root2 = dir2.path();
        seed_slice(&root2, 1, &[]);
        seed_slice(&root2, 1001, &[("supersedes", &["SL-001"])]);
        seed_slice(&root2, 998, &[("supersedes", &["SL-001"])]);
        seed_slice(&root2, 1000, &[("supersedes", &["SL-001"])]);
        seed_slice(&root2, 999, &[("supersedes", &["SL-001"])]);
        let view2 = inspect(&root2, "SL-001").unwrap();
        assert_eq!(
            inbound_for(&view2, RelationLabel::Supersedes),
            vec!["SL-998", "SL-999", "SL-1000", "SL-1001"],
            "inbound sort is numeric-within-prefix, not lexical (RSK-007)"
        );
    }

    // VT-4 / C8/R3 — a stored `superseded_by` with NO reciprocal `supersedes`
    // produces NO inbound. The reader projects only the outbound `supersedes`; the
    // stored reverse field is never read (ADR-004 §5 carve-out, but §3 derivation).
    #[test]
    fn stored_superseded_by_without_reciprocal_yields_no_inbound() {
        let dir = tmp();
        let root = dir.path();
        // ADR-002 carries a stored superseded_by = ADR-009 but NO entity authors
        // `supersedes = [ADR-002]`. ADR-009 exists but supersedes nothing.
        seed_adr(&root, 2, &[("superseded_by", &["ADR-009"])]);
        seed_adr(&root, 9, &[]);
        let view = inspect(&root, "ADR-002").unwrap();
        assert!(
            view.inbound.is_empty(),
            "a lone stored superseded_by produces no derived inbound"
        );
        // And ADR-009 has no inbound from ADR-002 either (no reciprocal supersedes).
        let nine = inspect(&root, "ADR-009").unwrap();
        assert!(nine.inbound.is_empty());
    }

    // VT-5 / R4 — free-text / dangling targets surface as danglers, never panic;
    // the NNN-slug symlink is skipped (scan_ids ignores non-dirs); an entity with
    // no relations yields empty sections, not an error.
    #[test]
    fn dangling_and_free_text_targets_surface_as_danglers() {
        let dir = tmp();
        let root = dir.path();
        // A backlog issue with a free-text drift, an unresolved slice ref, and a
        // resolvable slice ref. drift → dangler (no DRIFT kind); SL-099 → dangler
        // (no such entity); SL-001 → a real edge.
        seed_slice(&root, 1, &[]);
        write(
            &root,
            ".doctrine/backlog/issue/001/backlog-001.toml",
            // SL-048 PHASE-04: slices/drift migrated to `[[relation]]` rows.
            "id = 1\nslug = \"i\"\ntitle = \"I\"\nkind = \"issue\"\nstatus = \"open\"\n\
             resolution = \"\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [[relation]]\nlabel = \"slices\"\ntarget = \"SL-001\"\n\
             [[relation]]\nlabel = \"slices\"\ntarget = \"SL-099\"\n\
             [[relation]]\nlabel = \"drift\"\ntarget = \"some-free-text\"\n",
        );
        write(&root, ".doctrine/backlog/issue/001/backlog-001.md", "b\n");
        let view = inspect(&root, "ISS-001").unwrap();
        // The resolvable slice edge is NOT a dangler.
        assert_eq!(
            outbound_targets(&view, RelationLabel::Slices),
            vec!["SL-001", "SL-099"],
            "outbound lists every authored target regardless of resolution"
        );
        // Danglers: the unresolved SL-099 and the free-text drift.
        assert!(
            view.danglers
                .contains(&(RelationLabel::Slices, "SL-099".to_string())),
            "an unresolved canonical ref dangles"
        );
        assert!(
            view.danglers
                .contains(&(RelationLabel::Drift, "some-free-text".to_string())),
            "a free-text drift target dangles (no DRIFT kind / overlay)"
        );

        // VT-5 — NNN-slug symlink is skipped: plant one beside SL-001 and confirm
        // it neither mints a node nor breaks the scan.
        std::os::unix::fs::symlink("001", root.join(".doctrine/slice/a-slug")).unwrap();
        let still = inspect(&root, "ISS-001").unwrap();
        assert_eq!(
            outbound_targets(&still, RelationLabel::Slices),
            vec!["SL-001", "SL-099"]
        );

        // VT-5 — an entity with no relations: empty sections, not an error.
        let empty = inspect(&root, "SL-001").unwrap();
        // SL-001 is referenced by ISS-001's slices edge → it DOES have inbound;
        // a freshly-isolated no-relation entity proves the empty path instead.
        seed_slice(&root, 50, &[]);
        let lone = inspect(&root, "SL-050").unwrap();
        assert!(lone.outbound.is_empty());
        assert!(lone.inbound.is_empty());
        assert!(lone.danglers.is_empty());
        // (SL-001 has the inbound slices edge — sanity that inspect saw it.)
        assert_eq!(inbound_for(&empty, RelationLabel::Slices), vec!["ISS-001"]);
    }

    // SL-050 F6 — a well-formed ref to a never-minted id is now an ERROR (flips the old
    // empty-view half); the exact message is `KIND-NNN: no such entity`.
    #[test]
    fn nonexistent_id_is_no_such_entity_error() {
        let dir = tmp();
        let root = dir.path();
        seed_slice(&root, 1, &[]);
        // Well-formed ref, no such entity → the existence gate errors (not an empty view).
        let err = inspect(&root, "SL-999").unwrap_err();
        assert_eq!(
            err.to_string(),
            "SL-999: no such entity",
            "the exact existence-gate message"
        );
    }

    // An unknown prefix is a clean error (not a panic) — the parse-classification path,
    // unchanged by the F6 existence gate (it fails before the scan).
    #[test]
    fn unknown_prefix_clean_error() {
        let dir = tmp();
        let root = dir.path();
        seed_slice(&root, 1, &[]);
        let err = inspect(&root, "ZZZ-001").unwrap_err();
        assert!(
            err.to_string().contains("ZZZ"),
            "unknown prefix surfaces a clean error mentioning the prefix"
        );
    }

    // -- PHASE-03 VT-1: table-driven overlay coverage (R2-M4) ---------------

    /// VT-1 (R2-M4): the overlay-backed label set, the resolvable-graph label set, and
    /// the table's distinct non-`Unvalidated` labels are the SAME set. Asserted by the
    /// PROPERTY — both expectations are derived from `RELATION_RULES` (the single
    /// source), NOT from a deleted parallel const, so it cannot be a tautology against
    /// the implementation. A real `GraphBuilder` is driven so the assertion is over the
    /// actually-allocated overlays (`by_label` keys), not a re-derivation.
    #[test]
    fn overlay_set_equals_resolvable_graph_labels_table_driven() {
        use crate::relation::{RELATION_RULES, TargetSpec};
        use std::collections::BTreeSet;

        // Side A — every distinct label the table marks resolvable (TargetSpec !=
        // Unvalidated). Derived from the table, NOT a hardcoded list.
        let resolvable_from_table: BTreeSet<RelationLabel> = RELATION_RULES
            .iter()
            .filter(|r| !matches!(r.target, TargetSpec::Unvalidated))
            .map(|r| r.label)
            .collect();

        // Side B — the labels OverlayMap::build actually allocates an overlay for,
        // read off a real builder (the live allocation, not a re-derivation).
        let mut builder = GraphBuilder::new();
        let overlays = OverlayMap::build(&mut builder);
        let overlay_backed: BTreeSet<RelationLabel> = overlays.by_label.keys().copied().collect();

        assert_eq!(
            overlay_backed, resolvable_from_table,
            "the allocated overlay set must equal the table's resolvable (non-Unvalidated) labels"
        );

        // And the complement is EXACTLY the Unvalidated no-overlay pair — overlay_for
        // returns None for those and only those.
        let unvalidated: BTreeSet<RelationLabel> = RELATION_RULES
            .iter()
            .filter(|r| matches!(r.target, TargetSpec::Unvalidated))
            .map(|r| r.label)
            .collect();
        assert_eq!(
            unvalidated,
            BTreeSet::from([
                RelationLabel::Contextualizes,
                RelationLabel::Drift,
                RelationLabel::DecisionRef,
            ]),
            "the no-overlay set is exactly contextualizes + drift + decision_ref"
        );
        for label in [
            RelationLabel::Contextualizes,
            RelationLabel::Drift,
            RelationLabel::DecisionRef,
        ] {
            assert!(
                overlays.overlay_for(label).is_none(),
                "{label:?} (Unvalidated) must have no overlay"
            );
        }
        // The 17 = 20 distinct labels minus the 3 Unvalidated. The set, not just the
        // count, is the real assertion above; the count is a human-readable sanity tag.
        assert_eq!(overlay_backed.len(), 17, "overlay-backed label count is 17");
    }

    // -- PHASE-04 VT-4 / X3 arm (a): exact reader coverage (read_block live) ---

    /// The distinct labels `RELATION_RULES` legalises for a given source prefix.
    fn table_labels_for(prefix: &str) -> std::collections::BTreeSet<RelationLabel> {
        use crate::relation::RELATION_RULES;
        RELATION_RULES
            .iter()
            .filter(|r| r.sources.iter().any(|k| *k == prefix))
            .map(|r| r.label)
            .collect()
    }

    /// The distinct labels a kind's live `outbound_for` accessor ACTUALLY emits over a
    /// corpus where every legal axis is authored.
    fn emitted_labels(
        root: &Path,
        prefix: &str,
        id: u32,
    ) -> std::collections::BTreeSet<RelationLabel> {
        outbound_for(root, kind_for(prefix), id)
            .unwrap()
            .iter()
            .map(|e| e.label)
            .collect()
    }

    /// VT-4 (X3 arm (a), now `read_block` is LIVE): per source kind, the label set the
    /// shipped `relation_edges` accessor EMITS == the label set `RELATION_RULES`
    /// legalises for that source — no off-table emission, no table rule without a reader
    /// path. The exact set (not ⊆) is the assertion: a fully-populated fixture authors
    /// one edge of every legal axis (tier-1 via `[[relation]]`, tier-2/3 via its typed
    /// structure), and the emitted distinct-label set must equal the table's.
    #[test]
    fn reader_emitted_labels_equal_table_labels_per_source() {
        let dir = tmp();
        let root = dir.path();

        // --- SL: specs, requirements, supersedes, governed_by, related (all tier-1) ---
        write(
            &root,
            ".doctrine/slice/001/slice-001.toml",
            "id = 1\nslug = \"s\"\ntitle = \"S\"\nstatus = \"proposed\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [[relation]]\nlabel = \"specs\"\ntarget = \"PRD-010\"\n\
             [[relation]]\nlabel = \"requirements\"\ntarget = \"REQ-001\"\n\
             [[relation]]\nlabel = \"supersedes\"\ntarget = \"SL-002\"\n\
             [[relation]]\nlabel = \"governed_by\"\ntarget = \"ADR-001\"\n\
             [[relation]]\nlabel = \"related\"\ntarget = \"ADR-010\"\n",
        );
        write(&root, ".doctrine/slice/001/slice-001.md", "s\n");
        assert_eq!(
            emitted_labels(root, "SL", 1),
            table_labels_for("SL"),
            "slice reader emits exactly its table labels"
        );

        // --- ADR (governance): supersedes + related (both tier-1 after SL-095) ---
        write(
            &root,
            ".doctrine/adr/001/adr-001.toml",
            "id = 1\nslug = \"a\"\ntitle = \"A\"\nstatus = \"accepted\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [relationships]\nsuperseded_by = []\ntags = []\n\
             [[relation]]\nlabel = \"supersedes\"\ntarget = \"ADR-002\"\n\
             [[relation]]\nlabel = \"related\"\ntarget = \"ADR-003\"\n",
        );
        write(&root, ".doctrine/adr/001/adr-001.md", "a\n");
        assert_eq!(
            emitted_labels(root, "ADR", 1),
            table_labels_for("ADR"),
            "governance reader emits exactly supersedes + related"
        );

        // --- ISS (backlog): specs + slices + related + drift (all tier-1) ---
        write(
            &root,
            ".doctrine/backlog/issue/001/backlog-001.toml",
            "id = 1\nslug = \"i\"\ntitle = \"I\"\nkind = \"issue\"\nstatus = \"open\"\n\
             resolution = \"\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [[relation]]\nlabel = \"specs\"\ntarget = \"PRD-010\"\n\
             [[relation]]\nlabel = \"slices\"\ntarget = \"SL-001\"\n\
             [[relation]]\nlabel = \"related\"\ntarget = \"ADR-010\"\n\
             [[relation]]\nlabel = \"drift\"\ntarget = \"free-text\"\n",
        );
        write(&root, ".doctrine/backlog/issue/001/backlog-001.md", "i\n");
        assert_eq!(
            emitted_labels(root, "ISS", 1),
            table_labels_for("ISS"),
            "backlog reader emits exactly specs + slices + related + drift"
        );

        // --- SPEC (tech): governed_by (tier-1) + descends_from/parent (typed) +
        //     members (members.toml) + interactions (interactions.toml) ---
        write(
            &root,
            ".doctrine/spec/tech/001/spec-001.toml",
            "id = 1\nslug = \"sp\"\ntitle = \"SP\"\nstatus = \"draft\"\nkind = \"tech\"\n\
             descends_from = \"PRD-010\"\nparent = \"SPEC-002\"\n\
             [[relation]]\nlabel = \"governed_by\"\ntarget = \"ADR-001\"\n",
        );
        write(&root, ".doctrine/spec/tech/001/spec-001.md", "sp\n");
        write(
            &root,
            ".doctrine/spec/tech/001/members.toml",
            "[[member]]\nlabel = \"M\"\norder = 0\nrequirement = \"REQ-001\"\n",
        );
        write(
            &root,
            ".doctrine/spec/tech/001/interactions.toml",
            "[[edge]]\ntarget = \"SPEC-003\"\ntype = \"calls\"\nnotes = \"\"\n",
        );
        assert_eq!(
            emitted_labels(root, "SPEC", 1),
            table_labels_for("SPEC"),
            "tech spec reader emits governed_by + descends_from + parent + members + interactions"
        );

        // --- PRD (product): governed_by + consumes (tier-1) + members (members.toml) ---
        write(
            &root,
            ".doctrine/spec/product/001/spec-001.toml",
            "id = 1\nslug = \"pr\"\ntitle = \"PR\"\nstatus = \"draft\"\nkind = \"product\"\n\
             [[relation]]\nlabel = \"governed_by\"\ntarget = \"ADR-001\"\n\
             [[relation]]\nlabel = \"consumes\"\ntarget = \"PRD-002\"\n",
        );
        write(&root, ".doctrine/spec/product/001/spec-001.md", "pr\n");
        write(
            &root,
            ".doctrine/spec/product/001/members.toml",
            "[[member]]\nlabel = \"M\"\norder = 0\nrequirement = \"REQ-001\"\n",
        );
        assert_eq!(
            emitted_labels(root, "PRD", 1),
            table_labels_for("PRD"),
            "product spec reader emits governed_by + consumes + members"
        );

        // --- RV: reviews (the [target].ref) ---
        write(
            &root,
            ".doctrine/review/001/review-001.toml",
            "id = 1\nslug = \"r\"\ntitle = \"R\"\n\
             [review]\nfacet = \"reconciliation\"\nraiser = \"a\"\nresponder = \"b\"\n\
             [target]\nref = \"SL-001\"\n",
        );
        assert_eq!(
            emitted_labels(root, "RV", 1),
            table_labels_for("RV"),
            "review reader emits exactly reviews"
        );

        // --- REC: owning_slice + decision_ref ---
        write(
            &root,
            ".doctrine/rec/001/rec-001.toml",
            "id = 1\nslug = \"r\"\ntitle = \"R\"\n\
             [rec]\nmove = \"accept\"\nowning_slice = \"SL-001\"\ndecision_ref = \"DEC-001-A\"\n",
        );
        assert_eq!(
            emitted_labels(root, "REC", 1),
            table_labels_for("REC"),
            "rec reader emits exactly owning_slice + decision_ref"
        );

        // --- ASM (knowledge): shapes + spawns + governed_by ---
        write(
            &root,
            ".doctrine/knowledge/assumption/001/record-001.toml",
            "schema = \"doctrine.knowledge\"\nversion = 1\n\n\
             id = 1\nslug = \"a\"\ntitle = \"A\"\n\
             record_kind = \"assumption\"\nstatus = \"held\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             tags = []\n\n\
             [facet]\n\
             claim = \"\"\nconfidence = \"\"\nbasis = \"\"\n\
             validation_plan = \"\"\nvalidated_by = \"\"\nvalidated_on = \"\"\n\
             invalidated_by = \"\"\ninvalidated_on = \"\"\n\n\
             [evidence]\n\
             supports = []\ncontradicts = []\nnotes = []\n\
             [[relation]]\nlabel = \"shapes\"\ntarget = \"SL-001\"\n\
             [[relation]]\nlabel = \"spawns\"\ntarget = \"ISS-001\"\n\
             [[relation]]\nlabel = \"governed_by\"\ntarget = \"ADR-001\"\n",
        );
        write(
            &root,
            ".doctrine/knowledge/assumption/001/record-001.md",
            "body\n",
        );
        // RECORD kinds emit shapes + spawns + governed_by via [[relation]] rows;
        // Supersedes is LifecycleOnly (verb-writes to typed [relationships], not
        // authored in [[relation]]) — the typed parse lands in PHASE-03.
        // table_labels_for now includes Supersedes from RELATION_RULES, but
        // outbound_for won't emit it until the typed [relationships] block is
        // parsed, so we compare against the Writable subset.
        {
            let mut expected = table_labels_for("ASM");
            expected.remove(&RelationLabel::Supersedes);
            assert_eq!(
                emitted_labels(root, "ASM", 1),
                expected,
                "ASM: shapes + spawns + governed_by (supersedes is LifecycleOnly — typed parse in PHASE-03)"
            );
        }

        // --- DEC (knowledge): shapes + spawns + governed_by ---
        write(
            &root,
            ".doctrine/knowledge/decision/001/record-001.toml",
            "schema = \"doctrine.knowledge\"\nversion = 1\n\n\
             id = 1\nslug = \"d\"\ntitle = \"D\"\n\
             record_kind = \"decision\"\nstatus = \"proposed\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             tags = []\n\n\
             [facet]\n\
             context = \"\"\nchoice = \"\"\nalternatives = []\n\
             rationale = \"\"\nconsequences = []\n\
             decided_by = \"\"\ndecided_on = \"\"\n\n\
             [evidence]\n\
             supports = []\ncontradicts = []\nnotes = []\n\
             [[relation]]\nlabel = \"shapes\"\ntarget = \"SL-001\"\n\
             [[relation]]\nlabel = \"spawns\"\ntarget = \"ISS-001\"\n\
             [[relation]]\nlabel = \"governed_by\"\ntarget = \"ADR-001\"\n",
        );
        write(
            &root,
            ".doctrine/knowledge/decision/001/record-001.md",
            "body\n",
        );
        {
            let mut expected = table_labels_for("DEC");
            expected.remove(&RelationLabel::Supersedes);
            assert_eq!(
                emitted_labels(root, "DEC", 1),
                expected,
                "DEC: shapes + spawns + governed_by (supersedes is LifecycleOnly — typed parse in PHASE-03)"
            );
        }

        // --- QUE (knowledge): shapes + spawns + governed_by ---
        write(
            &root,
            ".doctrine/knowledge/question/001/record-001.toml",
            "schema = \"doctrine.knowledge\"\nversion = 1\n\n\
             id = 1\nslug = \"q\"\ntitle = \"Q\"\n\
             record_kind = \"question\"\nstatus = \"open\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             tags = []\n\n\
             [facet]\n\
             question = \"\"\nwhy_matters = \"\"\nanswer = \"\"\n\
             answered_by = \"\"\nanswered_on = \"\"\n\n\
             [evidence]\n\
             supports = []\ncontradicts = []\nnotes = []\n\
             [[relation]]\nlabel = \"shapes\"\ntarget = \"SL-001\"\n\
             [[relation]]\nlabel = \"spawns\"\ntarget = \"ISS-001\"\n\
             [[relation]]\nlabel = \"governed_by\"\ntarget = \"ADR-001\"\n",
        );
        write(
            &root,
            ".doctrine/knowledge/question/001/record-001.md",
            "body\n",
        );
        {
            let mut expected = table_labels_for("QUE");
            expected.remove(&RelationLabel::Supersedes);
            assert_eq!(
                emitted_labels(root, "QUE", 1),
                expected,
                "QUE: shapes + spawns + governed_by (supersedes is LifecycleOnly — typed parse in PHASE-03)"
            );
        }

        // --- CON (knowledge): shapes + spawns + governed_by ---
        write(
            &root,
            ".doctrine/knowledge/constraint/001/record-001.toml",
            "schema = \"doctrine.knowledge\"\nversion = 1\n\n\
             id = 1\nslug = \"c\"\ntitle = \"C\"\n\
             record_kind = \"constraint\"\nstatus = \"active\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             tags = []\n\n\
             [facet]\n\
             statement = \"\"\nsource = \"\"\napplies_to = []\n\
             waiver_reason = \"\"\nwaived_by = \"\"\nwaived_on = \"\"\n\n\
             [evidence]\n\
             supports = []\ncontradicts = []\nnotes = []\n\
             [[relation]]\nlabel = \"shapes\"\ntarget = \"SL-001\"\n\
             [[relation]]\nlabel = \"spawns\"\ntarget = \"ISS-001\"\n\
             [[relation]]\nlabel = \"governed_by\"\ntarget = \"ADR-001\"\n",
        );
        write(
            &root,
            ".doctrine/knowledge/constraint/001/record-001.md",
            "body\n",
        );
        {
            let mut expected = table_labels_for("CON");
            expected.remove(&RelationLabel::Supersedes);
            assert_eq!(
                emitted_labels(root, "CON", 1),
                expected,
                "CON: shapes + spawns + governed_by (supersedes is LifecycleOnly — typed parse in PHASE-03)"
            );
        }
    }

    // -- PHASE-05: corpus-edge validate + supersession cross-check ------------

    /// VT-3 (R2-M5/X2): a deleted target leaves a `[[relation]]` dangler that
    /// `validate_relations` reports; a hand-edited illegal `(source, label)` row is
    /// reported as an `IllegalRow`; a free-text `Unvalidated` target is NOT a finding
    /// (it dangles by design). Report-only — the corpus is never rewritten.
    #[test]
    fn validate_relations_reports_danglers_and_illegal_rows() {
        let dir = tmp();
        let root = dir.path();
        // SL-001 links requirements to REQ-005, which we DO seed (resolves), and to
        // REQ-999, which we do NOT (a dangler). The free-text `drift` case rides a
        // backlog issue below (`drift` is a backlog label, not a slice one).
        seed_slice(root, 1, &[("requirements", &["REQ-005", "REQ-999"])]);
        write(
            root,
            ".doctrine/requirement/005/requirement-005.toml",
            "id = 5\nslug = \"r\"\ntitle = \"R\"\nstatus = \"active\"\n",
        );
        write(root, ".doctrine/requirement/005/requirement-005.md", "r\n");
        // A backlog issue with a free-text `drift` (Unvalidated) target — must NOT be a
        // finding (it dangles by design), plus a resolvable `slices` edge to SL-001.
        write(
            root,
            ".doctrine/backlog/issue/001/backlog-001.toml",
            "schema = \"doctrine.backlog\"\nversion = 1\n\
             id = 1\nslug = \"i\"\ntitle = \"I\"\nkind = \"issue\"\nstatus = \"open\"\n\
             resolution = \"\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\ntags = []\n\
             [[relation]]\nlabel = \"drift\"\ntarget = \"loose talk\"\n\
             [[relation]]\nlabel = \"slices\"\ntarget = \"SL-001\"\n",
        );
        write(root, ".doctrine/backlog/issue/001/backlog-001.md", "i\n");
        // SL-002 carries a HAND-EDITED illegal row: a slice cannot author `descends_from`
        // (a spec-only label; `related` is now legal for slices since SL-095).
        write(
            root,
            ".doctrine/slice/002/slice-002.toml",
            "id = 2\nslug = \"s\"\ntitle = \"S\"\nstatus = \"proposed\"\n\
             created = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
             [[relation]]\nlabel = \"descends_from\"\ntarget = \"PRD-001\"\n",
        );
        write(root, ".doctrine/slice/002/slice-002.md", "s\n");

        let findings = validate_relations(root).unwrap();
        let joined = findings.join("\n");
        assert!(
            joined.contains("SL-001") && joined.contains("REQ-999") && joined.contains("dangling"),
            "the deleted REQ-999 target is reported as a dangler: {joined}"
        );
        assert!(
            !joined.contains("REQ-005"),
            "the resolvable REQ-005 target is NOT a finding: {joined}"
        );
        assert!(
            !joined.contains("loose talk"),
            "the Unvalidated drift target dangles by design — not a finding: {joined}"
        );
        assert!(
            joined.contains("SL-002") && joined.contains("illegal"),
            "the hand-edited illegal `descends_from` row is reported: {joined}"
        );
        // Report-only: the corpus file is byte-unchanged.
        let after =
            std::fs::read_to_string(root.join(".doctrine/slice/002/slice-002.toml")).unwrap();
        assert!(
            after.contains("label = \"descends_from\""),
            "validate never rewrites the corpus"
        );
    }

    /// VT-4 (R2-m2/OD-3): the supersession cross-check reads the STORED `superseded_by`
    /// via the typed governance seam and reports disagreement with the `supersedes`
    /// in-edge reciprocal — BOTH ways (a derived edge missing from the stored field, and
    /// a stored entry with no derived backing). A consistent pair yields NO finding.
    #[test]
    fn validate_supersession_reports_drift_both_ways() {
        let dir = tmp();
        let root = dir.path();
        // ADR-002 supersedes ADR-001 (derived: ADR-001 superseded_by ADR-002). ADR-001
        // stores NO superseded_by ⇒ a "derived-not-stored" finding. ADR-003 stores a
        // bogus superseded_by ADR-009 with no backing ⇒ a "stored-not-derived" finding.
        seed_adr(root, 1, &[]);
        seed_adr(root, 2, &[("supersedes", &["ADR-001"])]);
        seed_adr(root, 3, &[("superseded_by", &["ADR-009"])]);

        let findings = validate_supersession(root).unwrap();
        let joined = findings.join("\n");
        assert!(
            joined.contains("ADR-001") && joined.contains("ADR-002"),
            "ADR-002 supersedes ADR-001 but ADR-001 omits it from superseded_by: {joined}"
        );
        assert!(
            joined.contains("ADR-003") && joined.contains("ADR-009"),
            "ADR-003 lists ADR-009 in superseded_by with no backing supersedes: {joined}"
        );
    }

    /// A consistent supersession pair (the successor's `supersedes` AND the
    /// predecessor's `superseded_by` agree) produces no cross-check finding.
    #[test]
    fn validate_supersession_clean_on_consistent_pair() {
        let dir = tmp();
        let root = dir.path();
        seed_adr(root, 1, &[("superseded_by", &["ADR-002"])]);
        seed_adr(root, 2, &[("supersedes", &["ADR-001"])]);
        assert!(
            validate_supersession(root).unwrap().is_empty(),
            "a consistent supersedes/superseded_by pair is clean"
        );
    }
}