cbcl-core 0.3.1

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

#![forbid(unsafe_code)]

use alloc::collections::BTreeMap;
use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

use crate::causal_kernel::{self as kernel, Decision, FanIn, Lookup};
use crate::message::CausedBy;
use crate::store::{ContentHash, MessageStore, ThreadId};

/// Reserved keyword strings recognised by `verify_causal` as having
/// dedicated semantics. Currently the singleton `{"begin"}`, mirroring
/// `LeanCbcl/Verify.lean::CausalProtocol.begin` as a typed constructor.
/// Extending this set requires adding a corresponding constructor to the
/// Lean `CausalProtocol` inductive — otherwise `verify_causal` and the
/// Lean `verify` will silently disagree at the new keyword's call sites.
/// The accompanying tripwire test in this module asserts the singleton
/// invariant; updating it without an ADR is a review-time signal.
pub const BEGIN_KEYWORD: &str = "begin";

/// Index separator for names synthesised by `(repeat k …)` macro-expansion
/// (SPEC-015 REQ-704, CON-701).
///
/// `'#'` is *outside* the parser's legal symbol alphabet: in
/// `cbcl-parser::parser::is_symbol_char` the accepted characters are ASCII
/// alphanumerics plus `_ - . / ! ? + * < > = @`, and `'#'` instead
/// introduces the boolean literals `#t`/`#f`. A user-declared performative
/// name therefore can never contain `'#'`, so a synthesised copy name like
/// `x#2` cannot collide with any declared performative — impossible by
/// construction, not by convention (the hazard SPEC-014 ADR-604 avoided).
pub const REPEAT_SEPARATOR: char = '#';

/// Resolve a (possibly synthesised) protocol step name to its base
/// performative name (SPEC-015 REQ-704).
///
/// `x#2` → `x`; nested-repeat names strip every index: `x#1#3` → `x`;
/// a plain user name is returned unchanged. Because `#` is outside the
/// user symbol alphabet ([`REPEAT_SEPARATOR`]), this resolution is exact:
/// everything before the first separator is the declared base name.
///
/// This is how each expanded copy *inherits the base performative's
/// definition and role annotation*: R5 definedness and the R6 annotation
/// table look a copy up under its base name, while R3 core-name protection
/// continues to apply to the base name (copies are never declared
/// performatives).
pub fn repeat_base_name(name: &str) -> &str {
    match name.find(REPEAT_SEPARATOR) {
        Some(idx) => &name[..idx],
        None => name,
    }
}

// ================================================================
// Causal Protocol Data Model (REQ-200)
// ================================================================

/// Reference to one or more performatives in a protocol declaration (REQ-201).
///
/// - `Single` — a bare symbol (one performative).
/// - `Any` — `(any ...)` disjunction (choice / alternatives).
/// - `All` — `(all ...)` conjunction (fan-in / fan-out).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum NodeRef {
    Single(String),
    Any(BTreeSet<String>),
    All(BTreeSet<String>),
}

impl NodeRef {
    /// Return all performative names referenced by this node-ref.
    pub fn performatives(&self) -> impl Iterator<Item = &str> {
        match self {
            NodeRef::Single(s) => {
                let v: Vec<&str> = alloc::vec![s.as_str()];
                v.into_iter()
            }
            NodeRef::Any(set) | NodeRef::All(set) => {
                let v: Vec<&str> = set.iter().map(|s| s.as_str()).collect();
                v.into_iter()
            }
        }
    }
}

/// A step in the causal protocol graph (REQ-200).
///
/// Aggregates all declared predecessor and successor relationships
/// for a single performative name.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StepDecl {
    pub performative: String,
    pub predecessors: Vec<NodeRef>,
    pub successors: Vec<NodeRef>,
}

/// Parsed causal protocol declaration (REQ-200, REQ-201).
///
/// Built from `(protocol (then ...)+)` S-expression syntax.
/// Stores the dependency graph as a map from performative name to step declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CausalProtocol {
    pub steps: BTreeMap<String, StepDecl>,
}

/// Protocol-level violation found during R5 verification (REQ-204–207).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ProtocolViolation {
    /// A cycle was found in the dependency graph (REQ-204).
    Cycle { participants: Vec<String> },
    /// A step is unreachable from `begin` (REQ-205).
    Unreachable { step: String },
    /// A performative is referenced but not defined (REQ-206).
    UndefinedPerformative { name: String },
    /// Duplicate step declaration for the same performative (REQ-207).
    DuplicateStep { name: String },
}

impl fmt::Display for ProtocolViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cycle { participants } => {
                write!(f, "cycle detected: {}", participants.join(" → "))
            }
            Self::Unreachable { step } => {
                write!(f, "step '{}' is unreachable from begin", step)
            }
            Self::UndefinedPerformative { name } => {
                write!(f, "performative '{}' is not defined", name)
            }
            Self::DuplicateStep { name } => {
                write!(f, "duplicate step declaration for '{}'", name)
            }
        }
    }
}

fn has_duplicate(refs: &[NodeRef]) -> bool {
    for i in 0..refs.len() {
        for j in (i + 1)..refs.len() {
            if refs[i] == refs[j] {
                return true;
            }
        }
    }
    false
}

impl CausalProtocol {
    /// Collect all performative names referenced in successor/predecessor node-refs,
    /// excluding `begin`.
    fn all_referenced_performatives(&self) -> BTreeSet<String> {
        let mut names = BTreeSet::new();
        for (name, step) in &self.steps {
            if name != BEGIN_KEYWORD {
                names.insert(name.clone());
            }
            for nr in step.predecessors.iter().chain(step.successors.iter()) {
                for p in nr.performatives() {
                    if p != BEGIN_KEYWORD {
                        names.insert(p.into());
                    }
                }
            }
        }
        names
    }

    /// Build adjacency list (successor graph) from steps.
    fn successor_graph(&self) -> BTreeMap<&str, BTreeSet<&str>> {
        let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
        for (name, step) in &self.steps {
            graph.entry(name.as_str()).or_default();
            for nr in &step.successors {
                for s in nr.performatives() {
                    graph.entry(name.as_str()).or_default().insert(s);
                    graph.entry(s).or_default();
                }
            }
        }
        graph
    }

    /// Check acyclicity of the protocol dependency graph (REQ-204).
    ///
    /// Uses DFS with white/gray/black colouring to detect back edges.
    /// Returns violations for each cycle found.
    pub fn check_acyclicity(&self) -> Vec<ProtocolViolation> {
        let graph = self.successor_graph();

        // 0 = white (unvisited), 1 = gray (in progress), 2 = black (done)
        let mut color: BTreeMap<&str, u8> = BTreeMap::new();
        let mut path: Vec<&str> = Vec::new();
        let mut violations = Vec::new();

        for &node in graph.keys() {
            if *color.get(node).unwrap_or(&0) == 0 {
                Self::dfs_cycle(node, &graph, &mut color, &mut path, &mut violations);
            }
        }
        violations
    }

    fn dfs_cycle<'a>(
        node: &'a str,
        graph: &BTreeMap<&'a str, BTreeSet<&'a str>>,
        color: &mut BTreeMap<&'a str, u8>,
        path: &mut Vec<&'a str>,
        violations: &mut Vec<ProtocolViolation>,
    ) {
        color.insert(node, 1); // gray
        path.push(node);

        if let Some(neighbors) = graph.get(node) {
            for &next in neighbors {
                match color.get(next).unwrap_or(&0) {
                    0 => Self::dfs_cycle(next, graph, color, path, violations),
                    1 => {
                        // Back edge: extract cycle from path
                        if let Some(pos) = path.iter().position(|&n| n == next) {
                            let cycle: Vec<String> =
                                path[pos..].iter().map(|s| String::from(*s)).collect();
                            violations.push(ProtocolViolation::Cycle {
                                participants: cycle,
                            });
                        }
                    }
                    _ => {} // black, already fully explored
                }
            }
        }

        path.pop();
        color.insert(node, 2); // black
    }

    /// Check that all steps are reachable from `begin` (REQ-205).
    ///
    /// Uses BFS from `begin` over the successor graph.
    pub fn check_reachability(&self) -> Vec<ProtocolViolation> {
        let graph = self.successor_graph();
        let mut visited: BTreeSet<&str> = BTreeSet::new();
        let mut queue: Vec<&str> = Vec::new();

        if graph.contains_key(BEGIN_KEYWORD) {
            queue.push(BEGIN_KEYWORD);
            visited.insert(BEGIN_KEYWORD);
        }

        while let Some(current) = queue.pop() {
            if let Some(neighbors) = graph.get(current) {
                for &next in neighbors {
                    if visited.insert(next) {
                        queue.push(next);
                    }
                }
            }
        }

        let mut violations = Vec::new();
        for name in self.steps.keys() {
            if name != BEGIN_KEYWORD && !visited.contains(name.as_str()) {
                violations.push(ProtocolViolation::Unreachable { step: name.clone() });
            }
        }
        violations
    }

    /// Check that all referenced performatives are defined (REQ-206).
    ///
    /// `defined_performatives` should include all performatives from the dialect's
    /// `extend` clauses and installed ancestors. `begin` is always valid.
    pub fn check_performative_definedness(
        &self,
        defined_performatives: &[&str],
    ) -> Vec<ProtocolViolation> {
        let defined: BTreeSet<&str> = defined_performatives.iter().copied().collect();
        let referenced = self.all_referenced_performatives();

        // A `(repeat k …)` copy such as `x#2` is defined iff its base
        // performative `x` is (SPEC-015 REQ-704: per-copy inheritance).
        // Flag each undefined *base* name once, not once per copy.
        let mut flagged: BTreeSet<&str> = BTreeSet::new();
        let mut violations = Vec::new();
        for name in &referenced {
            let base = repeat_base_name(name);
            if !defined.contains(base) && flagged.insert(base) {
                violations.push(ProtocolViolation::UndefinedPerformative {
                    name: String::from(base),
                });
            }
        }
        violations
    }

    /// Number of protocol steps that count against R2's declared expansion
    /// budget at install (SPEC-015 REQ-704): every named step — including
    /// `(repeat k …)` copies, which are already materialised in `steps` by
    /// the time a `CausalProtocol` exists — except the `begin` root, which
    /// is a keyword, not an expansion product. A hand-unrolled equivalent
    /// protocol counts identically, which is what keeps `k` honest.
    pub fn expansion_size(&self) -> u32 {
        let n = self
            .steps
            .keys()
            .filter(|name| name.as_str() != BEGIN_KEYWORD)
            .count();
        u32::try_from(n).unwrap_or(u32::MAX)
    }

    /// Check that no performative has duplicate step declarations (REQ-207).
    ///
    /// `CausalProtocol::steps` is keyed by performative name, so step *names*
    /// cannot collide structurally. The remaining hazard is the `(then …)`
    /// parser, which accumulates predecessor `NodeRef` entries across
    /// clauses by `push`: every clause that targets the same performative
    /// pushes another entry. Distinct-alternative declarations like
    /// `(then begin a) (then b a)` are *intentional* — `verify_causal`
    /// reads the resulting `[Single("begin"), Single("b")]` as
    /// `begin ∨ b` for the predecessor of `a` (see
    /// `allowed_single_predecessors`), so this shape must pass R5.
    /// What R5 does forbid is *literal* duplication, e.g. the same
    /// `(then begin a)` clause written twice, which collapses to
    /// `[Single("begin"), Single("begin")]` and signals an authoring
    /// error rather than an alternative. Use `has_duplicate` so only
    /// equal `NodeRef` entries are rejected. Successor duplicates are
    /// still flagged as a defence-in-depth check against
    /// programmatically-constructed protocols whose two sides have
    /// drifted out of sync.
    pub fn check_step_uniqueness(&self) -> Vec<ProtocolViolation> {
        let mut violations = Vec::new();
        for (name, step) in &self.steps {
            if has_duplicate(&step.predecessors) || has_duplicate(&step.successors) {
                violations.push(ProtocolViolation::DuplicateStep { name: name.clone() });
            }
        }
        violations
    }

    /// Run all R5 protocol checks (REQ-208).
    ///
    /// Checks: step uniqueness (REQ-207), acyclicity (REQ-204),
    /// reachability (REQ-205), and performative definedness (REQ-206).
    pub fn verify_r5_protocol(&self, defined_performatives: &[&str]) -> Vec<ProtocolViolation> {
        let mut violations = Vec::new();
        violations.extend(self.check_step_uniqueness());
        violations.extend(self.check_acyclicity());
        violations.extend(self.check_reachability());
        violations.extend(self.check_performative_definedness(defined_performatives));
        violations
    }
}

/// Causal verification failure details (CON-202, SPEC-002).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CausalViolation {
    /// Predecessor hash not found in the message store.
    UnknownPredecessor { caused_by: String },
    /// Predecessor found but has wrong performative type.
    InvalidPredecessor {
        caused_by: String,
        expected: Vec<String>,
        found: String,
    },
    /// Message requires `:caused-by` but none was provided.
    MissingCausedBy,
    /// Fan-in `(all ...)` has missing predecessor types.
    IncompleteFanIn { missing_types: Vec<String> },
    /// Predecessor found but not declared in the protocol.
    ExtraneousPredecessor { caused_by: String, found: String },
    /// Fan-in without an `(all ...)` declaration for this performative.
    FanInWithoutAllDecl { performative: String },
    /// Role-layer conformance failure (SPEC-014 REQ-612/613/615/618).
    RoleConformance { reason: String },
}

impl fmt::Display for CausalViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownPredecessor { caused_by } => {
                write!(f, "unknown predecessor: {caused_by}")
            }
            Self::InvalidPredecessor {
                caused_by,
                expected,
                found,
            } => {
                write!(
                    f,
                    "invalid predecessor {caused_by}: expected one of [{}], found {found}",
                    expected.join(", ")
                )
            }
            Self::MissingCausedBy => write!(f, "missing :caused-by"),
            Self::IncompleteFanIn { missing_types } => {
                write!(
                    f,
                    "incomplete fan-in: missing types [{}]",
                    missing_types.join(", ")
                )
            }
            Self::ExtraneousPredecessor { caused_by, found } => {
                write!(f, "extraneous predecessor {caused_by}: found {found}")
            }
            Self::FanInWithoutAllDecl { performative } => {
                write!(f, "fan-in without (all ...) declaration for {performative}")
            }
            Self::RoleConformance { reason } => {
                write!(f, "role conformance: {reason}")
            }
        }
    }
}

/// Three-valued verification result lattice (REQ-302, CON-301).
///
/// ```text
///      Valid          Violation
///        \              /
///         \            /
///          ⊥ (Unknown)
/// ```
///
/// Unknown is ⊥. Valid and Violation are incomparable top elements.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum VerificationResult {
    /// ⊥ — predecessor not in store; undecidable with current state.
    Unknown,
    /// Predecessor found, type matches protocol declaration.
    Valid,
    /// Predecessor found, type mismatch or malformed hash.
    Violation(CausalViolation),
}

impl VerificationResult {
    /// Strong Kleene conjunction for `(all ...)` fan-in (REQ-303).
    /// Greatest lower bound in the truth order: Violation < Unknown < Valid.
    /// Algebraic laws apply to verdict classes, excluding diagnostic payloads.
    ///
    /// Truth table:
    /// - Violation ⊓ _ = Violation  (absorbing)
    /// - _ ⊓ Violation = Violation  (absorbing)
    /// - Unknown ⊓ _ = Unknown      (when other ≠ Violation)
    /// - Valid ⊓ Valid = Valid
    pub fn meet(self, other: VerificationResult) -> VerificationResult {
        match (&self, &other) {
            (VerificationResult::Violation(_), _) => self,
            (_, VerificationResult::Violation(_)) => other,
            (VerificationResult::Unknown, _) | (_, VerificationResult::Unknown) => {
                VerificationResult::Unknown
            }
            (VerificationResult::Valid, VerificationResult::Valid) => VerificationResult::Valid,
        }
    }

    /// Strong Kleene disjunction for `(any ...)` (REQ-303).
    /// Least upper bound in the truth order: Violation < Unknown < Valid.
    /// Algebraic laws apply to verdict classes, excluding diagnostic payloads.
    ///
    /// Truth table:
    /// - Valid ⊔ _ = Valid           (absorbing)
    /// - _ ⊔ Valid = Valid           (absorbing)
    /// - Violation ⊔ Unknown = Unknown
    /// - Violation ⊔ Violation = Violation (preserves the left diagnostic)
    /// - Unknown ⊔ Unknown = Unknown
    pub fn join(self, other: VerificationResult) -> VerificationResult {
        match (&self, &other) {
            (VerificationResult::Valid, _) | (_, VerificationResult::Valid) => {
                VerificationResult::Valid
            }
            (VerificationResult::Unknown, _) | (_, VerificationResult::Unknown) => {
                VerificationResult::Unknown
            }
            (VerificationResult::Violation(_), VerificationResult::Violation(_)) => self,
        }
    }

    /// Kuper's threshold test — has the lattice crossed {Valid, Violation}? (CON-301).
    pub fn is_resolved(&self) -> bool {
        !matches!(self, VerificationResult::Unknown)
    }

    /// Stability test — identical to `is_resolved()` (CON-301).
    ///
    /// Once resolved, the result is permanent under store growth (monotonicity).
    pub fn is_stable(&self) -> bool {
        self.is_resolved()
    }
}

impl PartialOrd for VerificationResult {
    /// Knowledge partial order: Unknown < Valid, Unknown < Violation,
    /// Valid and Violation are incomparable.
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        use core::cmp::Ordering;
        match (self, other) {
            // Equal cases
            (VerificationResult::Unknown, VerificationResult::Unknown) => Some(Ordering::Equal),
            (VerificationResult::Valid, VerificationResult::Valid) => Some(Ordering::Equal),
            (VerificationResult::Violation(_), VerificationResult::Violation(_)) => {
                Some(Ordering::Equal)
            }
            // Unknown < Valid, Unknown < Violation
            (VerificationResult::Unknown, _) => Some(Ordering::Less),
            (_, VerificationResult::Unknown) => Some(Ordering::Greater),
            // Valid and Violation are incomparable
            (VerificationResult::Valid, VerificationResult::Violation(_))
            | (VerificationResult::Violation(_), VerificationResult::Valid) => None,
        }
    }
}

// ================================================================
// Causal Verification (REQ-203, REQ-304, ADR-008)
// ================================================================

/// Resolve the performative type of a `:caused-by` reference: from the
/// full message when the store holds one, else from a redacted envelope's
/// *authenticated* header, else from an opened envelope's *authenticated*
/// Performative opening (SPEC-015 REQ-702; SPEC-017 REQ-813).
///
/// This is the safety-level seam of redacted delivery: presence,
/// predecessor type, and resolution read exactly the fields an envelope
/// carries (hash, type, endpoints, signature), so a widened recipient
/// holding only the envelope — redacted *or* opened — reaches the same
/// safety verdict it would with the full predecessor. An opened envelope's
/// type comes from its Performative opening, verified against the signed
/// typed root the address commits to; its endpoints (from/to openings) are
/// available for role-conformance the same way, at zero payload disclosure.
/// A full message, when present, wins — the two name the same content root,
/// so they are the same message.
///
/// The completion-level occupant fan-in (`projection::verify_causal_for_role`,
/// REQ-618) deliberately does *not* use this seam: fan-in membership
/// ("present and Valid") still demands full messages (REQ-703). An opened
/// envelope, which seals leaf 5, therefore satisfies the safety checks here
/// but never the completion check there — the SPEC-015 boundary, preserved.
pub(crate) fn predecessor_type<'a, S: MessageStore>(
    store: &'a S,
    hash: &ContentHash,
    thread: &ThreadId,
) -> Option<&'a str> {
    if let Some(predecessor_msg) = store.lookup_in_thread(hash, thread) {
        // Type through wrappers: the agent stores whole (possibly signed)
        // messages, so a wrapped predecessor must type as its innermost
        // Simple (SPEC-014; pre-existing Simple behaviour unchanged).
        return Some(
            predecessor_msg
                .innermost_simple()
                .and_then(|m| m.performative())
                .map(|p| p.name())
                .unwrap_or(""),
        );
    }
    if let Some(e) = store.envelope_in_thread(hash, thread) {
        return Some(e.performative());
    }
    store
        .opened_in_thread(hash, thread)
        .and_then(|e| e.performative())
}

/// Collect performative names allowed as single-message predecessors.
///
/// Gathers names from `Single` and `Any` node-refs (not `All`, which is for fan-in).
pub(crate) fn allowed_single_predecessors(step: &StepDecl) -> Vec<String> {
    let mut types = Vec::new();
    for nr in &step.predecessors {
        match nr {
            NodeRef::Single(s) => types.push(s.clone()),
            NodeRef::Any(set) => types.extend(set.iter().cloned()),
            NodeRef::All(_) => {} // fan-in handled separately
        }
    }
    types
}

/// Verify causal consistency of a message against its protocol (REQ-203, REQ-304).
///
/// Three-valued result: `Unknown` when a predecessor hash is not yet in the store,
/// `Valid` when all predecessors resolve and match the protocol, `Violation` when
/// a predecessor exists but has the wrong type or the causal link is malformed.
///
/// Thread-scoped: `:caused-by` hashes resolve only within the same `:thread` (ADR-008).
/// Stateless and valid-sticky. Wrong evidence dominates missing evidence in fan-in.
/// The admission monitor applies a separate resolved-first guard before this verifier.
/// Decisions use `causal_kernel`; lookups, membership, coverage and diagnostics
/// remain adapters whose Rust-to-Lean correspondence is a separate obligation.
pub fn verify_causal<S: MessageStore>(
    msg_performative: &str,
    caused_by: Option<&CausedBy>,
    store: &S,
    protocol: &CausalProtocol,
    thread: &ThreadId,
) -> VerificationResult {
    if crate::repeat::has_repeat(protocol) {
        return crate::repeat::verify(msg_performative, caused_by, store, protocol, thread, None);
    }
    let step = match protocol.steps.get(msg_performative) {
        Some(s) => s,
        // Legacy unconstrained route; strict admission excludes it.
        None => return VerificationResult::Valid,
    };
    let has_predecessors = !step.predecessors.is_empty();

    match caused_by {
        None => match kernel::absent(has_predecessors) {
            Decision::Valid => VerificationResult::Valid,
            Decision::MissingCausedBy => {
                VerificationResult::Violation(CausalViolation::MissingCausedBy)
            }
            _ => unreachable!("absent decision"),
        },
        Some(CausedBy::Begin) => {
            let begin_allowed = step.predecessors.iter().any(|nr| match nr {
                NodeRef::Single(s) => s == BEGIN_KEYWORD,
                NodeRef::Any(set) => set.contains(BEGIN_KEYWORD),
                NodeRef::All(_) => false,
            });
            match kernel::literal_begin(begin_allowed) {
                Decision::Valid => VerificationResult::Valid,
                Decision::InvalidPredecessor => {
                    VerificationResult::Violation(CausalViolation::InvalidPredecessor {
                        caused_by: BEGIN_KEYWORD.into(),
                        expected: allowed_single_predecessors(step),
                        found: BEGIN_KEYWORD.into(),
                    })
                }
                _ => unreachable!("literal-begin decision"),
            }
        }
        Some(CausedBy::Single(hash_str)) => {
            let content_hash = ContentHash(hash_str.clone());
            let pred_perf = predecessor_type(store, &content_hash, thread);
            // Preserve the missing-lookup fast path and diagnostics ordering.
            let allowed = if pred_perf.is_some() {
                allowed_single_predecessors(step)
            } else {
                Vec::new()
            };
            let lookup = match pred_perf {
                None => Lookup::Missing,
                Some(p) if allowed.iter().any(|a| a == p) => Lookup::Allowed,
                Some(_) => Lookup::Wrong,
            };
            match kernel::single(has_predecessors, lookup) {
                Decision::Valid => VerificationResult::Valid,
                Decision::Unknown => VerificationResult::Unknown,
                Decision::ExtraneousPredecessor => {
                    VerificationResult::Violation(CausalViolation::ExtraneousPredecessor {
                        caused_by: hash_str.clone(),
                        found: pred_perf.expect("wrong lookup has a type").into(),
                    })
                }
                Decision::InvalidPredecessor => {
                    VerificationResult::Violation(CausalViolation::InvalidPredecessor {
                        caused_by: hash_str.clone(),
                        expected: allowed,
                        found: pred_perf.expect("wrong lookup has a type").into(),
                    })
                }
                _ => unreachable!("single decision"),
            }
        }
        Some(CausedBy::Multiple(hashes)) => {
            // Preserve FIRST-All selection, including empty and later clauses.
            let all_decl = step.predecessors.iter().find_map(|nr| match nr {
                NodeRef::All(set) => Some(set),
                _ => None,
            });
            let mut state = FanIn::Clear;
            let mut found_types = BTreeSet::new();
            let mut first_error = None;
            let mut missing = Vec::new();
            if let Some(all_set) = all_decl {
                for hash_str in hashes {
                    let content_hash = ContentHash(hash_str.clone());
                    let lookup = match predecessor_type(store, &content_hash, thread) {
                        None => Lookup::Missing,
                        Some(pred_perf) if all_set.contains(pred_perf) => {
                            found_types.insert(String::from(pred_perf));
                            Lookup::Allowed
                        }
                        Some(pred_perf) => {
                            if first_error.is_none() {
                                first_error = Some(CausalViolation::InvalidPredecessor {
                                    caused_by: hash_str.clone(),
                                    expected: all_set.iter().cloned().collect(),
                                    found: pred_perf.into(),
                                });
                            }
                            Lookup::Wrong
                        }
                    };
                    state = kernel::observe(state, lookup);
                }
                if matches!(state, FanIn::Clear) {
                    missing = all_set
                        .iter()
                        .filter(|t| !found_types.contains(*t))
                        .cloned()
                        .collect();
                }
            }
            match kernel::finish(all_decl.is_some(), state, missing.is_empty()) {
                Decision::Valid => VerificationResult::Valid,
                Decision::Unknown => VerificationResult::Unknown,
                Decision::InvalidPredecessor => VerificationResult::Violation(
                    first_error.expect("wrong fan-in has a diagnostic"),
                ),
                Decision::IncompleteFanIn => {
                    VerificationResult::Violation(CausalViolation::IncompleteFanIn {
                        missing_types: missing,
                    })
                }
                Decision::FanInWithoutAllDecl => {
                    VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl {
                        performative: msg_performative.into(),
                    })
                }
                _ => unreachable!("fan-in decision"),
            }
        }
    }
}

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

    // ================================================================
    // SPEC-005 NFR-512 / Verify.lean parity tripwire
    // ================================================================

    /// Tripwire: the reserved-keyword vocabulary recognised by
    /// `verify_causal` is the singleton `{BEGIN_KEYWORD}`. Adding a second
    /// reserved keyword (e.g. `"end"`, `"fork"`) without extending
    /// `LeanCbcl/Verify.lean::CausalProtocol` to match would silently
    /// break the Lean ↔ Rust parity that REQ-512..514 depend on. If this
    /// test starts failing, the right response is an ADR amendment to
    /// SPEC-005 §"Open Questions" §1, not a quick patch.
    #[test]
    fn test_reserved_keyword_vocabulary_is_singleton() {
        assert_eq!(BEGIN_KEYWORD, "begin");
    }

    fn violation() -> VerificationResult {
        VerificationResult::Violation(CausalViolation::MissingCausedBy)
    }

    fn violation2() -> VerificationResult {
        VerificationResult::Violation(CausalViolation::UnknownPredecessor {
            caused_by: "f1220test".into(),
        })
    }

    // ================================================================
    // TEST-302: Three-Valued Result Construction and Ordering
    // ================================================================

    #[test]
    fn test_construction_unknown() {
        let r = VerificationResult::Unknown;
        assert!(!r.is_resolved());
        assert!(!r.is_stable());
    }

    #[test]
    fn test_construction_valid() {
        let r = VerificationResult::Valid;
        assert!(r.is_resolved());
        assert!(r.is_stable());
    }

    #[test]
    fn test_construction_violation() {
        let r = violation();
        assert!(r.is_resolved());
        assert!(r.is_stable());
    }

    #[test]
    fn test_partial_ord_unknown_lt_valid() {
        assert!(VerificationResult::Unknown < VerificationResult::Valid);
    }

    #[test]
    fn test_partial_ord_unknown_lt_violation() {
        assert!(VerificationResult::Unknown < violation());
    }

    #[test]
    fn test_partial_ord_valid_violation_incomparable() {
        let v = VerificationResult::Valid;
        let viol = violation();
        assert!(v.partial_cmp(&viol).is_none());
        assert!(viol.partial_cmp(&v).is_none());
    }

    #[test]
    fn test_partial_ord_reflexive() {
        assert_eq!(
            VerificationResult::Unknown.partial_cmp(&VerificationResult::Unknown),
            Some(core::cmp::Ordering::Equal)
        );
        assert_eq!(
            VerificationResult::Valid.partial_cmp(&VerificationResult::Valid),
            Some(core::cmp::Ordering::Equal)
        );
        assert_eq!(
            violation().partial_cmp(&violation()),
            Some(core::cmp::Ordering::Equal)
        );
    }

    // ================================================================
    // TEST-303: Meet (conjunction) 3×3 truth table
    // ================================================================

    #[test]
    fn test_meet_unknown_unknown() {
        assert_eq!(
            VerificationResult::Unknown.meet(VerificationResult::Unknown),
            VerificationResult::Unknown
        );
    }

    #[test]
    fn test_meet_unknown_valid() {
        assert_eq!(
            VerificationResult::Unknown.meet(VerificationResult::Valid),
            VerificationResult::Unknown
        );
    }

    #[test]
    fn test_meet_unknown_violation() {
        let result = VerificationResult::Unknown.meet(violation());
        assert!(matches!(result, VerificationResult::Violation(_)));
    }

    #[test]
    fn test_meet_valid_unknown() {
        assert_eq!(
            VerificationResult::Valid.meet(VerificationResult::Unknown),
            VerificationResult::Unknown
        );
    }

    #[test]
    fn test_meet_valid_valid() {
        assert_eq!(
            VerificationResult::Valid.meet(VerificationResult::Valid),
            VerificationResult::Valid
        );
    }

    #[test]
    fn test_meet_valid_violation() {
        let result = VerificationResult::Valid.meet(violation());
        assert!(matches!(result, VerificationResult::Violation(_)));
    }

    #[test]
    fn test_meet_violation_unknown() {
        let result = violation().meet(VerificationResult::Unknown);
        assert!(matches!(result, VerificationResult::Violation(_)));
    }

    #[test]
    fn test_meet_violation_valid() {
        let result = violation().meet(VerificationResult::Valid);
        assert!(matches!(result, VerificationResult::Violation(_)));
    }

    #[test]
    fn test_meet_violation_violation() {
        let result = violation().meet(violation2());
        assert!(matches!(result, VerificationResult::Violation(_)));
    }

    // ================================================================
    // TEST-303: Join (disjunction) 3×3 truth table
    // ================================================================

    #[test]
    fn test_join_unknown_unknown() {
        assert_eq!(
            VerificationResult::Unknown.join(VerificationResult::Unknown),
            VerificationResult::Unknown
        );
    }

    #[test]
    fn test_join_unknown_valid() {
        assert_eq!(
            VerificationResult::Unknown.join(VerificationResult::Valid),
            VerificationResult::Valid
        );
    }

    #[test]
    fn test_join_unknown_violation() {
        let result = VerificationResult::Unknown.join(violation());
        assert_eq!(result, VerificationResult::Unknown);
    }

    #[test]
    fn test_join_valid_unknown() {
        assert_eq!(
            VerificationResult::Valid.join(VerificationResult::Unknown),
            VerificationResult::Valid
        );
    }

    #[test]
    fn test_join_valid_valid() {
        assert_eq!(
            VerificationResult::Valid.join(VerificationResult::Valid),
            VerificationResult::Valid
        );
    }

    #[test]
    fn test_join_valid_violation() {
        assert_eq!(
            VerificationResult::Valid.join(violation()),
            VerificationResult::Valid
        );
    }

    #[test]
    fn test_join_violation_unknown() {
        let result = violation().join(VerificationResult::Unknown);
        assert_eq!(result, VerificationResult::Unknown);
    }

    #[test]
    fn test_join_violation_valid() {
        assert_eq!(
            violation().join(VerificationResult::Valid),
            VerificationResult::Valid
        );
    }

    #[test]
    fn test_join_violation_violation() {
        let result = violation().join(violation2());
        assert!(matches!(result, VerificationResult::Violation(_)));
    }

    // ================================================================
    // CausalViolation construction and Display
    // ================================================================

    #[test]
    fn test_causal_violation_display() {
        let v = CausalViolation::MissingCausedBy;
        assert_eq!(v.to_string(), "missing :caused-by");

        let v = CausalViolation::UnknownPredecessor {
            caused_by: "f1220abc".into(),
        };
        assert_eq!(v.to_string(), "unknown predecessor: f1220abc");
    }

    #[test]
    fn test_causal_violation_variants_exist() {
        let _ = CausalViolation::UnknownPredecessor {
            caused_by: "h".into(),
        };
        let _ = CausalViolation::InvalidPredecessor {
            caused_by: "h".into(),
            expected: vec!["a".into()],
            found: "b".into(),
        };
        let _ = CausalViolation::MissingCausedBy;
        let _ = CausalViolation::IncompleteFanIn {
            missing_types: vec!["a".into()],
        };
        let _ = CausalViolation::ExtraneousPredecessor {
            caused_by: "h".into(),
            found: "x".into(),
        };
        let _ = CausalViolation::FanInWithoutAllDecl {
            performative: "p".into(),
        };
    }

    // ================================================================
    // Meet preserves left violation detail
    // ================================================================

    #[test]
    fn test_meet_preserves_first_violation() {
        let v1 = violation();
        let v2 = violation2();
        // When both are violations, meet returns the left one
        let result = v1.meet(v2);
        assert_eq!(
            result,
            VerificationResult::Violation(CausalViolation::MissingCausedBy)
        );
    }

    // ================================================================
    // Join preserves first violation detail when both alternatives are violations
    // ================================================================

    #[test]
    fn test_join_preserves_first_violation() {
        let v1 = violation();
        let result = v1.join(violation2());
        assert_eq!(
            result,
            VerificationResult::Violation(CausalViolation::MissingCausedBy)
        );
    }

    // ================================================================
    // Protocol Validation Tests
    // ================================================================

    /// Helper: build a simple linear protocol: begin → a → b → c
    fn linear_protocol() -> CausalProtocol {
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: vec![],
                successors: vec![NodeRef::Single("a".into())],
            },
        );
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![NodeRef::Single("b".into())],
            },
        );
        steps.insert(
            "b".into(),
            StepDecl {
                performative: "b".into(),
                predecessors: vec![NodeRef::Single("a".into())],
                successors: vec![NodeRef::Single("c".into())],
            },
        );
        steps.insert(
            "c".into(),
            StepDecl {
                performative: "c".into(),
                predecessors: vec![NodeRef::Single("b".into())],
                successors: vec![],
            },
        );
        CausalProtocol { steps }
    }

    // ---- TEST-204: Acyclicity ----

    #[test]
    fn test_acyclicity_linear_chain_passes() {
        // begin → a → b → c — no cycles
        let proto = linear_protocol();
        assert!(proto.check_acyclicity().is_empty());
    }

    #[test]
    fn test_acyclicity_direct_cycle_rejected() {
        // a → b, b → a (direct cycle)
        let mut steps = BTreeMap::new();
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("b".into())],
                successors: vec![NodeRef::Single("b".into())],
            },
        );
        steps.insert(
            "b".into(),
            StepDecl {
                performative: "b".into(),
                predecessors: vec![NodeRef::Single("a".into())],
                successors: vec![NodeRef::Single("a".into())],
            },
        );
        let proto = CausalProtocol { steps };
        let violations = proto.check_acyclicity();
        assert!(!violations.is_empty());
        assert!(violations
            .iter()
            .any(|v| matches!(v, ProtocolViolation::Cycle { .. })));
    }

    #[test]
    fn test_acyclicity_transitive_cycle_rejected() {
        // a → b → c → a (transitive cycle)
        let mut steps = BTreeMap::new();
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("c".into())],
                successors: vec![NodeRef::Single("b".into())],
            },
        );
        steps.insert(
            "b".into(),
            StepDecl {
                performative: "b".into(),
                predecessors: vec![NodeRef::Single("a".into())],
                successors: vec![NodeRef::Single("c".into())],
            },
        );
        steps.insert(
            "c".into(),
            StepDecl {
                performative: "c".into(),
                predecessors: vec![NodeRef::Single("b".into())],
                successors: vec![NodeRef::Single("a".into())],
            },
        );
        let proto = CausalProtocol { steps };
        let violations = proto.check_acyclicity();
        assert!(!violations.is_empty());
    }

    // ---- TEST-205: Reachability ----

    #[test]
    fn test_reachability_linear_chain_passes() {
        let proto = linear_protocol();
        assert!(proto.check_reachability().is_empty());
    }

    #[test]
    fn test_reachability_both_from_begin_passes() {
        // begin → a, begin → b (both directly reachable)
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: vec![],
                successors: vec![NodeRef::Single("a".into()), NodeRef::Single("b".into())],
            },
        );
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![],
            },
        );
        steps.insert(
            "b".into(),
            StepDecl {
                performative: "b".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        assert!(proto.check_reachability().is_empty());
    }

    #[test]
    fn test_reachability_unreachable_step_rejected() {
        // begin → a, but c has no connection to begin
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: vec![],
                successors: vec![NodeRef::Single("a".into())],
            },
        );
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![],
            },
        );
        steps.insert(
            "c".into(),
            StepDecl {
                performative: "c".into(),
                predecessors: vec![NodeRef::Single("x".into())],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        let violations = proto.check_reachability();
        assert_eq!(violations.len(), 1);
        assert!(matches!(
            &violations[0],
            ProtocolViolation::Unreachable { step } if step == "c"
        ));
    }

    // ---- TEST-206: Performative Definedness ----

    #[test]
    fn test_definedness_all_defined_passes() {
        let proto = linear_protocol();
        let violations = proto.check_performative_definedness(&["a", "b", "c"]);
        assert!(violations.is_empty());
    }

    #[test]
    fn test_definedness_undefined_rejected() {
        let proto = linear_protocol();
        // Only "a" is defined, "b" and "c" are not
        let violations = proto.check_performative_definedness(&["a"]);
        assert_eq!(violations.len(), 2);
        let names: Vec<&str> = violations
            .iter()
            .filter_map(|v| match v {
                ProtocolViolation::UndefinedPerformative { name } => Some(name.as_str()),
                _ => None,
            })
            .collect();
        assert!(names.contains(&"b"));
        assert!(names.contains(&"c"));
    }

    // ---- TEST-207: Step Uniqueness ----

    #[test]
    fn test_step_uniqueness_clean_protocol_passes() {
        let proto = linear_protocol();
        assert!(proto.check_step_uniqueness().is_empty());
    }

    #[test]
    fn test_step_uniqueness_detects_duplicate_successor() {
        // Equivalent to `(then begin a) (then begin a)` — duplicate edge.
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: vec![],
                successors: vec![NodeRef::Single("a".into()), NodeRef::Single("a".into())],
            },
        );
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![
                    NodeRef::Single("begin".into()),
                    NodeRef::Single("begin".into()),
                ],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        let violations = proto.check_step_uniqueness();
        let names: BTreeSet<&str> = violations
            .iter()
            .filter_map(|v| match v {
                ProtocolViolation::DuplicateStep { name } => Some(name.as_str()),
                _ => None,
            })
            .collect();
        assert!(names.contains("begin"));
        assert!(names.contains("a"));
    }

    #[test]
    fn test_step_uniqueness_accepts_distinct_alternatives() {
        // `(then begin a) (then b a)` — two clauses target `a` with
        // *different* predecessors. `verify_causal` treats the resulting
        // `[Single("begin"), Single("b")]` as the alternation `begin ∨ b`
        // (see `allowed_single_predecessors`), so this protocol shape is
        // valid and must pass R5. Only literal duplicates among the
        // predecessor entries should be flagged.
        let mut steps = BTreeMap::new();
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("begin".into()), NodeRef::Single("b".into())],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        assert!(proto.check_step_uniqueness().is_empty());
    }

    #[test]
    fn test_step_uniqueness_rejects_literal_duplicate_predecessor() {
        // Same `NodeRef` entered twice — e.g. `(then begin a)` written
        // twice — collapses to `[Single("begin"), Single("begin")]` and
        // is an authoring error, not an alternation. Must be flagged.
        let mut steps = BTreeMap::new();
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![
                    NodeRef::Single("begin".into()),
                    NodeRef::Single("begin".into()),
                ],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        assert!(proto
            .check_step_uniqueness()
            .iter()
            .any(|v| matches!(v, ProtocolViolation::DuplicateStep { name } if name == "a")));
    }

    #[test]
    fn test_step_uniqueness_rejects_literal_duplicate_successor() {
        // Defence-in-depth (see protocol.rs `has_duplicate` rationale at the
        // method docstring): the successor side of `(then …)` is symmetric
        // with the predecessor side; a literal `NodeRef` repeated in the
        // successors list is an authoring error, not an alternation, and
        // must be flagged. This covers the symmetric case to
        // `test_step_uniqueness_rejects_literal_duplicate_predecessor`.
        let mut steps = BTreeMap::new();
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![NodeRef::Single("b".into()), NodeRef::Single("b".into())],
            },
        );
        let proto = CausalProtocol { steps };
        assert!(proto
            .check_step_uniqueness()
            .iter()
            .any(|v| matches!(v, ProtocolViolation::DuplicateStep { name } if name == "a")));
    }

    #[test]
    fn test_step_uniqueness_accepts_all_fan_in() {
        // `(then (all begin x) a)` — single predecessor entry, legitimate fan-in.
        let mut steps = BTreeMap::new();
        let mut all_set = BTreeSet::new();
        all_set.insert("begin".into());
        all_set.insert("x".into());
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::All(all_set)],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        assert!(proto.check_step_uniqueness().is_empty());
    }

    // ---- TEST-208: verify_r5_protocol composite ----

    #[test]
    fn test_verify_r5_protocol_valid() {
        let proto = linear_protocol();
        let violations = proto.verify_r5_protocol(&["a", "b", "c"]);
        assert!(violations.is_empty());
    }

    #[test]
    fn test_verify_r5_protocol_catches_undefined() {
        let proto = linear_protocol();
        let violations = proto.verify_r5_protocol(&["a"]);
        assert!(violations
            .iter()
            .any(|v| matches!(v, ProtocolViolation::UndefinedPerformative { .. })));
    }

    #[test]
    fn test_verify_r5_protocol_catches_unreachable() {
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: vec![],
                successors: vec![NodeRef::Single("a".into())],
            },
        );
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![],
            },
        );
        steps.insert(
            "orphan".into(),
            StepDecl {
                performative: "orphan".into(),
                predecessors: vec![],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        let violations = proto.verify_r5_protocol(&["a", "orphan"]);
        assert!(violations
            .iter()
            .any(|v| matches!(v, ProtocolViolation::Unreachable { step } if step == "orphan")));
    }

    // ---- ProtocolViolation Display ----

    #[test]
    fn test_protocol_violation_display() {
        let v = ProtocolViolation::Cycle {
            participants: vec!["a".into(), "b".into()],
        };
        assert_eq!(v.to_string(), "cycle detected: a → b");

        let v = ProtocolViolation::Unreachable {
            step: "orphan".into(),
        };
        assert!(v.to_string().contains("unreachable"));

        let v = ProtocolViolation::UndefinedPerformative { name: "foo".into() };
        assert!(v.to_string().contains("not defined"));

        let v = ProtocolViolation::DuplicateStep { name: "bar".into() };
        assert!(v.to_string().contains("duplicate"));
    }

    // ---- Empty protocol ----

    #[test]
    fn test_empty_protocol_passes_all_checks() {
        let proto = CausalProtocol {
            steps: BTreeMap::new(),
        };
        assert!(proto.check_acyclicity().is_empty());
        assert!(proto.check_reachability().is_empty());
        assert!(proto.check_performative_definedness(&[]).is_empty());
        assert!(proto.check_step_uniqueness().is_empty());
        assert!(proto.verify_r5_protocol(&[]).is_empty());
    }

    // ================================================================
    // TEST-203 / TEST-304: verify_causal
    // ================================================================

    use crate::message::{Message, Performative};
    use crate::sexpr::{Atom, SExpr};
    use crate::store::{ContentHash, MessageStore, ThreadId, ThreadedMessageStore};

    fn chash(s: &str) -> ContentHash {
        ContentHash(s.into())
    }

    fn tid(s: &str) -> ThreadId {
        ThreadId(s.into())
    }

    fn make_msg(perf: &str, caused_by: Option<CausedBy>) -> Message {
        Message::Simple {
            performative: Performative::Custom(perf.into()),
            recipient: None,
            content: SExpr::Atom(Atom::Str("x".into())),
            params: alloc::vec![],
            thread: None,
            sender: None,
            caused_by,
        }
    }

    /// Protocol: begin → a → b → c
    fn verification_protocol() -> CausalProtocol {
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: vec![],
                successors: vec![NodeRef::Single("a".into())],
            },
        );
        steps.insert(
            "a".into(),
            StepDecl {
                performative: "a".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![NodeRef::Single("b".into())],
            },
        );
        steps.insert(
            "b".into(),
            StepDecl {
                performative: "b".into(),
                predecessors: vec![NodeRef::Single("a".into())],
                successors: vec![NodeRef::Single("c".into())],
            },
        );
        steps.insert(
            "c".into(),
            StepDecl {
                performative: "c".into(),
                predecessors: vec![NodeRef::Single("b".into())],
                successors: vec![],
            },
        );
        CausalProtocol { steps }
    }

    /// Protocol with fan-in: begin → x, begin → y, (all x y) → z
    fn fan_in_protocol() -> CausalProtocol {
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: vec![],
                successors: vec![NodeRef::Single("x".into()), NodeRef::Single("y".into())],
            },
        );
        steps.insert(
            "x".into(),
            StepDecl {
                performative: "x".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![],
            },
        );
        steps.insert(
            "y".into(),
            StepDecl {
                performative: "y".into(),
                predecessors: vec![NodeRef::Single("begin".into())],
                successors: vec![],
            },
        );
        let mut all_set = BTreeSet::new();
        all_set.insert("x".into());
        all_set.insert("y".into());
        steps.insert(
            "z".into(),
            StepDecl {
                performative: "z".into(),
                predecessors: vec![NodeRef::All(all_set)],
                successors: vec![],
            },
        );
        CausalProtocol { steps }
    }

    // ---- Begin caused-by ----

    #[test]
    fn verify_begin_valid() {
        let proto = verification_protocol();
        let store = ThreadedMessageStore::new();
        let t = tid("t1");
        let result = verify_causal("a", Some(&CausedBy::Begin), &store, &proto, &t);
        assert_eq!(result, VerificationResult::Valid);
    }

    #[test]
    fn verify_begin_invalid_not_successor_of_begin() {
        let proto = verification_protocol();
        let store = ThreadedMessageStore::new();
        let t = tid("t1");
        // "c" requires predecessor "b", not "begin"
        let result = verify_causal("c", Some(&CausedBy::Begin), &store, &proto, &t);
        assert!(matches!(
            result,
            VerificationResult::Violation(CausalViolation::InvalidPredecessor { .. })
        ));
    }

    // ---- Single caused-by ----

    #[test]
    fn verify_single_valid() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        // Put an "a" message in the store
        store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
        // "b" requires predecessor "a" — h1 is "a" → Valid
        let result = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        assert_eq!(result, VerificationResult::Valid);
    }

    #[test]
    fn verify_single_unknown_predecessor_not_in_store() {
        let proto = verification_protocol();
        let store = ThreadedMessageStore::new();
        let t = tid("t1");
        let result = verify_causal(
            "b",
            Some(&CausedBy::Single("missing".into())),
            &store,
            &proto,
            &t,
        );
        assert_eq!(result, VerificationResult::Unknown);
    }

    #[test]
    fn verify_single_wrong_type() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        // Put a "c" message in the store
        store.append(chash("h1"), t.clone(), make_msg("c", Some(CausedBy::Begin)));
        // "b" requires predecessor "a", but h1 is "c" → Violation
        let result = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        assert!(matches!(
            result,
            VerificationResult::Violation(CausalViolation::InvalidPredecessor {
                found,
                ..
            }) if found == "c"
        ));
    }

    // ---- Thread isolation (ADR-008) ----

    #[test]
    fn verify_single_wrong_thread_is_unknown() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        // Message in thread t1
        store.append(chash("h1"), tid("t1"), make_msg("a", Some(CausedBy::Begin)));
        // Verify in thread t2 — h1 is not visible → Unknown
        let result = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &tid("t2"),
        );
        assert_eq!(result, VerificationResult::Unknown);
    }

    // ---- Missing caused-by ----

    #[test]
    fn verify_missing_caused_by_violation() {
        let proto = verification_protocol();
        let store = ThreadedMessageStore::new();
        let t = tid("t1");
        // "b" has predecessors → requires caused-by
        let result = verify_causal("b", None, &store, &proto, &t);
        assert!(matches!(
            result,
            VerificationResult::Violation(CausalViolation::MissingCausedBy)
        ));
    }

    #[test]
    fn verify_missing_caused_by_ok_when_no_predecessors() {
        // "begin" has no predecessors → no caused-by required
        let proto = verification_protocol();
        let store = ThreadedMessageStore::new();
        let t = tid("t1");
        let result = verify_causal("begin", None, &store, &proto, &t);
        assert_eq!(result, VerificationResult::Valid);
    }

    // ---- Performative not in protocol ----

    #[test]
    fn verify_unknown_performative_is_valid() {
        let proto = verification_protocol();
        let store = ThreadedMessageStore::new();
        let t = tid("t1");
        let result = verify_causal(
            "not-in-protocol",
            Some(&CausedBy::Begin),
            &store,
            &proto,
            &t,
        );
        assert_eq!(result, VerificationResult::Valid);
    }

    // ---- Fan-in: Multiple caused-by with (all ...) ----

    #[test]
    fn verify_fan_in_all_valid() {
        let proto = fan_in_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
        store.append(chash("hy"), t.clone(), make_msg("y", Some(CausedBy::Begin)));
        let result = verify_causal(
            "z",
            Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hy".into()])),
            &store,
            &proto,
            &t,
        );
        assert_eq!(result, VerificationResult::Valid);
    }

    #[test]
    fn verify_fan_in_one_unknown() {
        let proto = fan_in_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
        // hy not in store → Unknown (meet absorbs)
        let result = verify_causal(
            "z",
            Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hy".into()])),
            &store,
            &proto,
            &t,
        );
        assert_eq!(result, VerificationResult::Unknown);
    }

    #[test]
    fn verify_fan_in_wrong_type() {
        let proto = fan_in_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
        // "wrong" is not in the (all x y) set
        store.append(
            chash("hw"),
            t.clone(),
            make_msg("wrong", Some(CausedBy::Begin)),
        );
        let result = verify_causal(
            "z",
            Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hw".into()])),
            &store,
            &proto,
            &t,
        );
        assert!(matches!(
            result,
            VerificationResult::Violation(CausalViolation::InvalidPredecessor { .. })
        ));
    }

    #[test]
    fn verify_fan_in_incomplete() {
        let proto = fan_in_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        // Only one "x" message, but (all x y) requires both x and y types
        store.append(
            chash("hx1"),
            t.clone(),
            make_msg("x", Some(CausedBy::Begin)),
        );
        store.append(
            chash("hx2"),
            t.clone(),
            make_msg("x", Some(CausedBy::Begin)),
        );
        let result = verify_causal(
            "z",
            Some(&CausedBy::Multiple(alloc::vec!["hx1".into(), "hx2".into()])),
            &store,
            &proto,
            &t,
        );
        assert!(matches!(
            result,
            VerificationResult::Violation(CausalViolation::IncompleteFanIn { .. })
        ));
    }

    #[test]
    fn verify_fan_in_without_all_decl() {
        let proto = verification_protocol();
        let store = ThreadedMessageStore::new();
        let t = tid("t1");
        // "b" has Single("a") predecessor, not All — fan-in not declared
        let result = verify_causal(
            "b",
            Some(&CausedBy::Multiple(alloc::vec!["h1".into(), "h2".into()])),
            &store,
            &proto,
            &t,
        );
        assert!(matches!(
            result,
            VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl { .. })
        ));
    }

    // ---- Monotonicity: Unknown → Valid after store growth ----

    #[test]
    fn verify_monotone_unknown_to_valid() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");

        // First check: predecessor not in store → Unknown
        let r1 = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        assert_eq!(r1, VerificationResult::Unknown);

        // Store grows: add the predecessor
        store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));

        // Re-check: now Valid
        let r2 = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        assert_eq!(r2, VerificationResult::Valid);
    }

    #[test]
    fn verify_monotone_unknown_to_violation() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");

        // First check: predecessor not in store → Unknown
        let r1 = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        assert_eq!(r1, VerificationResult::Unknown);

        // Store grows: add predecessor with wrong type
        store.append(chash("h1"), t.clone(), make_msg("c", Some(CausedBy::Begin)));

        // Re-check: now Violation
        let r2 = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        assert!(matches!(r2, VerificationResult::Violation(_)));
    }

    // ---- Any predecessor (disjunction) ----

    #[test]
    fn verify_any_predecessor_either_type_valid() {
        let mut steps = BTreeMap::new();
        let mut any_set = BTreeSet::new();
        any_set.insert("x".into());
        any_set.insert("y".into());
        steps.insert(
            "z".into(),
            StepDecl {
                performative: "z".into(),
                predecessors: vec![NodeRef::Any(any_set)],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");

        // Predecessor is "x" — matches (any x y) → Valid
        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
        let r = verify_causal(
            "z",
            Some(&CausedBy::Single("hx".into())),
            &store,
            &proto,
            &t,
        );
        assert_eq!(r, VerificationResult::Valid);

        // Predecessor is "y" — also matches
        store.append(chash("hy"), t.clone(), make_msg("y", Some(CausedBy::Begin)));
        let r = verify_causal(
            "z",
            Some(&CausedBy::Single("hy".into())),
            &store,
            &proto,
            &t,
        );
        assert_eq!(r, VerificationResult::Valid);
    }

    // ---- Extraneous predecessor ----

    #[test]
    fn verify_extraneous_predecessor() {
        let mut steps = BTreeMap::new();
        steps.insert(
            "root".into(),
            StepDecl {
                performative: "root".into(),
                predecessors: vec![],
                successors: vec![],
            },
        );
        let proto = CausalProtocol { steps };
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        store.append(chash("h1"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
        // "root" has no predecessors, but we provide one → ExtraneousPredecessor
        let result = verify_causal(
            "root",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        assert!(matches!(
            result,
            VerificationResult::Violation(CausalViolation::ExtraneousPredecessor { .. })
        ));
    }

    // ---- Statelessness: same inputs → same outputs ----

    #[test]
    fn verify_is_stateless() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));

        let r1 = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        let r2 = verify_causal(
            "b",
            Some(&CausedBy::Single("h1".into())),
            &store,
            &proto,
            &t,
        );
        assert_eq!(r1, r2);
    }

    // ================================================================
    // SPEC-015 REQ-702: safety-level verification over envelopes
    // ================================================================

    use crate::attest::{sign_attestation_v2, AttestationHeader};
    use crate::envelope::RedactedEnvelope;
    use crate::keyid::KeyId;
    use crate::r4::Signer;

    /// Data-dependent test signer (as in `attest.rs`): sig = SHA-256(secret
    /// ‖ data), so tampering with any authenticated field kills it.
    struct TestSigner {
        secret: &'static [u8],
    }

    impl Signer for TestSigner {
        fn sign(&self, data: &[u8]) -> Vec<u8> {
            use sha2::{Digest, Sha256};
            let mut h = Sha256::new();
            h.update(self.secret);
            h.update(data);
            h.finalize().to_vec()
        }
        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
            self.sign(data) == sig
        }
    }

    const SIGNER: TestSigner = TestSigner { secret: b"alice" };

    fn signed_env(hash: &str, perf: &str, thread_name: &str) -> RedactedEnvelope {
        let mut to = BTreeSet::new();
        to.insert(KeyId::parse("@bob").unwrap());
        let header = AttestationHeader {
            content_hash: hash.into(),
            performative: perf.into(),
            from: KeyId::parse("@alice").unwrap(),
            to,
            thread: thread_name.into(),
            caused_by: Some(CausedBy::Begin),
        };
        let signature = sign_attestation_v2(&SIGNER, &header).unwrap();
        RedactedEnvelope { header, signature }
    }

    /// REQ-702: a `:caused-by` reference resolves through an envelope —
    /// Unknown before it arrives, then the same safety verdict a full
    /// predecessor would give (here Valid), read from the authenticated
    /// performative type.
    #[test]
    fn single_reference_resolves_through_an_envelope() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        let msg_b = ("b", Some(CausedBy::Single("h1".into())));

        // Nothing yet: Unknown.
        assert_eq!(
            verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
            VerificationResult::Unknown
        );

        // Envelope of the predecessor `a` arrives: resolves Valid.
        store
            .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
            .unwrap();
        assert_eq!(
            verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
            VerificationResult::Valid
        );

        // Same verdict as with the full predecessor.
        let mut full_store = ThreadedMessageStore::new();
        full_store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
        assert_eq!(
            verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
            verify_causal(msg_b.0, msg_b.1.as_ref(), &full_store, &proto, &t),
        );
    }

    /// REQ-702: predecessor *type* checks read the envelope's
    /// authenticated performative — a wrong-typed envelope resolves to
    /// the same typed Violation a wrong-typed full message would.
    #[test]
    fn envelope_with_wrong_type_is_the_typed_violation() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        store
            .append_envelope(signed_env("h1", "c", "t1"), &SIGNER)
            .unwrap();
        assert_eq!(
            verify_causal(
                "b",
                Some(&CausedBy::Single("h1".into())),
                &store,
                &proto,
                &t
            ),
            VerificationResult::Violation(CausalViolation::InvalidPredecessor {
                caused_by: "h1".into(),
                expected: vec!["a".into()],
                found: "c".into(),
            })
        );
    }

    /// REQ-702: an envelope satisfies references only in its
    /// authenticated thread — it is invisible from any other thread.
    #[test]
    fn envelope_is_scoped_to_its_authenticated_thread() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        store
            .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
            .unwrap();
        assert_eq!(
            verify_causal(
                "b",
                Some(&CausedBy::Single("h1".into())),
                &store,
                &proto,
                &tid("t2")
            ),
            VerificationResult::Unknown
        );
    }

    /// A full message and its envelope name the same content hash; when
    /// both are present the full message is read (they agree by content
    /// addressing, so this is a preference, not a semantic difference).
    #[test]
    fn full_message_shadows_its_own_envelope() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        store
            .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
            .unwrap();
        store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
        assert_eq!(
            verify_causal(
                "b",
                Some(&CausedBy::Single("h1".into())),
                &store,
                &proto,
                &t
            ),
            VerificationResult::Valid
        );
    }

    /// REQ-702 over the R5 fan-in *type* check: envelope members resolve
    /// the `(all …)` type completeness (safety level). The completion
    /// boundary (REQ-703) is enforced one layer up, in the role layer's
    /// occupant fan-in — see `projection.rs`.
    #[test]
    fn fan_in_type_check_resolves_through_envelopes() {
        let proto = fan_in_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        // x arrives in full; y only as an envelope.
        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
        let z = CausedBy::Multiple(vec!["hx".into(), "hy".into()]);
        assert_eq!(
            verify_causal("z", Some(&z), &store, &proto, &t),
            VerificationResult::Unknown
        );
        store
            .append_envelope(signed_env("hy", "y", "t1"), &SIGNER)
            .unwrap();
        assert_eq!(
            verify_causal("z", Some(&z), &store, &proto, &t),
            VerificationResult::Valid
        );
    }

    // ================================================================
    // SPEC-017 REQ-813 Stage 3: safety-level verification over OPENED
    // envelopes (native field-openings against the signed typed root)
    // ================================================================

    use crate::envelope::{build_opened, OpenedEnvelope, HEADER_FIELDS};
    use crate::keyid::SignatureSuite;
    use crate::message::Recipients;

    /// A predecessor message typed `perf`, sender `@alice`, thread
    /// `thread_name`, and its opened envelope (header fields, payload sealed)
    /// plus the typed root that a citing `:caused-by` must name.
    fn opened_pred(perf: &str, thread_name: &str) -> (OpenedEnvelope, String) {
        let mut to = BTreeSet::new();
        to.insert("@bob".to_string());
        let m = Message::Simple {
            performative: Performative::Custom(perf.into()),
            recipient: Some(Recipients::Set(to)),
            content: SExpr::Atom(Atom::Str("secret-payload".into())),
            params: alloc::vec![],
            thread: Some(thread_name.into()),
            sender: Some("@alice".into()),
            caused_by: Some(CausedBy::Begin),
        };
        let root = crate::typed_addr::typed_root(&m);
        let env = build_opened(&m, &HEADER_FIELDS, &SignatureSuite::Ed25519, &SIGNER).unwrap();
        (env, root)
    }

    /// REQ-813: a `:caused-by` reference resolves through an opened
    /// envelope — Unknown before it arrives, then the same safety verdict a
    /// full predecessor gives (Valid), read from the authenticated
    /// Performative opening, at zero payload disclosure.
    #[test]
    fn single_reference_resolves_through_an_opened_envelope() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        let (env, root) = opened_pred("a", "t1");
        let cb = CausedBy::Single(root);

        assert_eq!(
            verify_causal("b", Some(&cb), &store, &proto, &t),
            VerificationResult::Unknown
        );
        store.append_opened(env, &SIGNER).unwrap();
        assert_eq!(
            verify_causal("b", Some(&cb), &store, &proto, &t),
            VerificationResult::Valid
        );
    }

    /// REQ-813: a wrong-typed opened envelope resolves to the same typed
    /// Violation a wrong-typed full message would (predecessor-type check
    /// reads the authenticated Performative opening).
    #[test]
    fn opened_envelope_with_wrong_type_is_the_typed_violation() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        let (env, root) = opened_pred("c", "t1"); // 'b' requires 'a', not 'c'
        store.append_opened(env, &SIGNER).unwrap();
        assert_eq!(
            verify_causal(
                "b",
                Some(&CausedBy::Single(root.clone())),
                &store,
                &proto,
                &t
            ),
            VerificationResult::Violation(CausalViolation::InvalidPredecessor {
                caused_by: root,
                expected: vec!["a".into()],
                found: "c".into(),
            })
        );
    }

    /// REQ-813: an opened envelope satisfies references only in its
    /// authenticated thread (its Thread opening) — invisible elsewhere.
    #[test]
    fn opened_envelope_is_scoped_to_its_authenticated_thread() {
        let proto = verification_protocol();
        let mut store = ThreadedMessageStore::new();
        let (env, root) = opened_pred("a", "t1");
        store.append_opened(env, &SIGNER).unwrap();
        assert_eq!(
            verify_causal(
                "b",
                Some(&CausedBy::Single(root)),
                &store,
                &proto,
                &tid("t2")
            ),
            VerificationResult::Unknown
        );
    }

    /// REQ-813 over the R5 fan-in *type* check: opened-envelope members
    /// resolve the `(all …)` type completeness (safety level). The
    /// completion boundary (REQ-703) is enforced one layer up in the role
    /// layer's occupant fan-in (`projection.rs`), which never consults the
    /// opened shelf — an opened envelope seals leaf 5 and so can satisfy
    /// safety here but never completion there.
    #[test]
    fn fan_in_type_check_resolves_through_opened_envelopes() {
        let proto = fan_in_protocol();
        let mut store = ThreadedMessageStore::new();
        let t = tid("t1");
        let (env_x, root_x) = opened_pred("x", "t1");
        let (env_y, root_y) = opened_pred("y", "t1");
        let z = CausedBy::Multiple(vec![root_x.clone(), root_y.clone()]);

        store.append_opened(env_x, &SIGNER).unwrap();
        assert_eq!(
            verify_causal("z", Some(&z), &store, &proto, &t),
            VerificationResult::Unknown,
            "one member still missing"
        );
        store.append_opened(env_y, &SIGNER).unwrap();
        assert_eq!(
            verify_causal("z", Some(&z), &store, &proto, &t),
            VerificationResult::Valid
        );
    }
}