Skip to main content

cbcl_core/
protocol.rs

1//! Causal protocol types and verification result lattice (REQ-200, REQ-302, REQ-303).
2//!
3//! The verification result forms a flat lattice with Unknown (⊥) at the bottom
4//! and Valid / Violation as incomparable top elements. Meet implements conjunction
5//! for `(all ...)` fan-in; join implements disjunction for `(any ...)`.
6
7#![forbid(unsafe_code)]
8
9use alloc::collections::BTreeMap;
10use alloc::collections::BTreeSet;
11use alloc::string::String;
12use alloc::vec::Vec;
13use core::fmt;
14
15use crate::causal_kernel::{self as kernel, Decision, FanIn, Lookup};
16use crate::message::CausedBy;
17use crate::store::{ContentHash, MessageStore, ThreadId};
18
19/// Reserved keyword strings recognised by `verify_causal` as having
20/// dedicated semantics. Currently the singleton `{"begin"}`, mirroring
21/// `LeanCbcl/Verify.lean::CausalProtocol.begin` as a typed constructor.
22/// Extending this set requires adding a corresponding constructor to the
23/// Lean `CausalProtocol` inductive — otherwise `verify_causal` and the
24/// Lean `verify` will silently disagree at the new keyword's call sites.
25/// The accompanying tripwire test in this module asserts the singleton
26/// invariant; updating it without an ADR is a review-time signal.
27pub const BEGIN_KEYWORD: &str = "begin";
28
29/// Index separator for names synthesised by `(repeat k …)` macro-expansion
30/// (SPEC-015 REQ-704, CON-701).
31///
32/// `'#'` is *outside* the parser's legal symbol alphabet: in
33/// `cbcl-parser::parser::is_symbol_char` the accepted characters are ASCII
34/// alphanumerics plus `_ - . / ! ? + * < > = @`, and `'#'` instead
35/// introduces the boolean literals `#t`/`#f`. A user-declared performative
36/// name therefore can never contain `'#'`, so a synthesised copy name like
37/// `x#2` cannot collide with any declared performative — impossible by
38/// construction, not by convention (the hazard SPEC-014 ADR-604 avoided).
39pub const REPEAT_SEPARATOR: char = '#';
40
41/// Resolve a (possibly synthesised) protocol step name to its base
42/// performative name (SPEC-015 REQ-704).
43///
44/// `x#2` → `x`; nested-repeat names strip every index: `x#1#3` → `x`;
45/// a plain user name is returned unchanged. Because `#` is outside the
46/// user symbol alphabet ([`REPEAT_SEPARATOR`]), this resolution is exact:
47/// everything before the first separator is the declared base name.
48///
49/// This is how each expanded copy *inherits the base performative's
50/// definition and role annotation*: R5 definedness and the R6 annotation
51/// table look a copy up under its base name, while R3 core-name protection
52/// continues to apply to the base name (copies are never declared
53/// performatives).
54pub fn repeat_base_name(name: &str) -> &str {
55    match name.find(REPEAT_SEPARATOR) {
56        Some(idx) => &name[..idx],
57        None => name,
58    }
59}
60
61// ================================================================
62// Causal Protocol Data Model (REQ-200)
63// ================================================================
64
65/// Reference to one or more performatives in a protocol declaration (REQ-201).
66///
67/// - `Single` — a bare symbol (one performative).
68/// - `Any` — `(any ...)` disjunction (choice / alternatives).
69/// - `All` — `(all ...)` conjunction (fan-in / fan-out).
70#[derive(Debug, Clone, PartialEq, Eq)]
71#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
72pub enum NodeRef {
73    Single(String),
74    Any(BTreeSet<String>),
75    All(BTreeSet<String>),
76}
77
78impl NodeRef {
79    /// Return all performative names referenced by this node-ref.
80    pub fn performatives(&self) -> impl Iterator<Item = &str> {
81        match self {
82            NodeRef::Single(s) => {
83                let v: Vec<&str> = alloc::vec![s.as_str()];
84                v.into_iter()
85            }
86            NodeRef::Any(set) | NodeRef::All(set) => {
87                let v: Vec<&str> = set.iter().map(|s| s.as_str()).collect();
88                v.into_iter()
89            }
90        }
91    }
92}
93
94/// A step in the causal protocol graph (REQ-200).
95///
96/// Aggregates all declared predecessor and successor relationships
97/// for a single performative name.
98#[derive(Debug, Clone, PartialEq, Eq)]
99#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
100pub struct StepDecl {
101    pub performative: String,
102    pub predecessors: Vec<NodeRef>,
103    pub successors: Vec<NodeRef>,
104}
105
106/// Parsed causal protocol declaration (REQ-200, REQ-201).
107///
108/// Built from `(protocol (then ...)+)` S-expression syntax.
109/// Stores the dependency graph as a map from performative name to step declaration.
110#[derive(Debug, Clone, PartialEq, Eq)]
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112pub struct CausalProtocol {
113    pub steps: BTreeMap<String, StepDecl>,
114}
115
116/// Protocol-level violation found during R5 verification (REQ-204–207).
117#[derive(Debug, Clone, PartialEq, Eq)]
118#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
119pub enum ProtocolViolation {
120    /// A cycle was found in the dependency graph (REQ-204).
121    Cycle { participants: Vec<String> },
122    /// A step is unreachable from `begin` (REQ-205).
123    Unreachable { step: String },
124    /// A performative is referenced but not defined (REQ-206).
125    UndefinedPerformative { name: String },
126    /// Duplicate step declaration for the same performative (REQ-207).
127    DuplicateStep { name: String },
128}
129
130impl fmt::Display for ProtocolViolation {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        match self {
133            Self::Cycle { participants } => {
134                write!(f, "cycle detected: {}", participants.join(" → "))
135            }
136            Self::Unreachable { step } => {
137                write!(f, "step '{}' is unreachable from begin", step)
138            }
139            Self::UndefinedPerformative { name } => {
140                write!(f, "performative '{}' is not defined", name)
141            }
142            Self::DuplicateStep { name } => {
143                write!(f, "duplicate step declaration for '{}'", name)
144            }
145        }
146    }
147}
148
149fn has_duplicate(refs: &[NodeRef]) -> bool {
150    for i in 0..refs.len() {
151        for j in (i + 1)..refs.len() {
152            if refs[i] == refs[j] {
153                return true;
154            }
155        }
156    }
157    false
158}
159
160impl CausalProtocol {
161    /// Collect all performative names referenced in successor/predecessor node-refs,
162    /// excluding `begin`.
163    fn all_referenced_performatives(&self) -> BTreeSet<String> {
164        let mut names = BTreeSet::new();
165        for (name, step) in &self.steps {
166            if name != BEGIN_KEYWORD {
167                names.insert(name.clone());
168            }
169            for nr in step.predecessors.iter().chain(step.successors.iter()) {
170                for p in nr.performatives() {
171                    if p != BEGIN_KEYWORD {
172                        names.insert(p.into());
173                    }
174                }
175            }
176        }
177        names
178    }
179
180    /// Build adjacency list (successor graph) from steps.
181    fn successor_graph(&self) -> BTreeMap<&str, BTreeSet<&str>> {
182        let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
183        for (name, step) in &self.steps {
184            graph.entry(name.as_str()).or_default();
185            for nr in &step.successors {
186                for s in nr.performatives() {
187                    graph.entry(name.as_str()).or_default().insert(s);
188                    graph.entry(s).or_default();
189                }
190            }
191        }
192        graph
193    }
194
195    /// Check acyclicity of the protocol dependency graph (REQ-204).
196    ///
197    /// Uses DFS with white/gray/black colouring to detect back edges.
198    /// Returns violations for each cycle found.
199    pub fn check_acyclicity(&self) -> Vec<ProtocolViolation> {
200        let graph = self.successor_graph();
201
202        // 0 = white (unvisited), 1 = gray (in progress), 2 = black (done)
203        let mut color: BTreeMap<&str, u8> = BTreeMap::new();
204        let mut path: Vec<&str> = Vec::new();
205        let mut violations = Vec::new();
206
207        for &node in graph.keys() {
208            if *color.get(node).unwrap_or(&0) == 0 {
209                Self::dfs_cycle(node, &graph, &mut color, &mut path, &mut violations);
210            }
211        }
212        violations
213    }
214
215    fn dfs_cycle<'a>(
216        node: &'a str,
217        graph: &BTreeMap<&'a str, BTreeSet<&'a str>>,
218        color: &mut BTreeMap<&'a str, u8>,
219        path: &mut Vec<&'a str>,
220        violations: &mut Vec<ProtocolViolation>,
221    ) {
222        color.insert(node, 1); // gray
223        path.push(node);
224
225        if let Some(neighbors) = graph.get(node) {
226            for &next in neighbors {
227                match color.get(next).unwrap_or(&0) {
228                    0 => Self::dfs_cycle(next, graph, color, path, violations),
229                    1 => {
230                        // Back edge: extract cycle from path
231                        if let Some(pos) = path.iter().position(|&n| n == next) {
232                            let cycle: Vec<String> =
233                                path[pos..].iter().map(|s| String::from(*s)).collect();
234                            violations.push(ProtocolViolation::Cycle {
235                                participants: cycle,
236                            });
237                        }
238                    }
239                    _ => {} // black, already fully explored
240                }
241            }
242        }
243
244        path.pop();
245        color.insert(node, 2); // black
246    }
247
248    /// Check that all steps are reachable from `begin` (REQ-205).
249    ///
250    /// Uses BFS from `begin` over the successor graph.
251    pub fn check_reachability(&self) -> Vec<ProtocolViolation> {
252        let graph = self.successor_graph();
253        let mut visited: BTreeSet<&str> = BTreeSet::new();
254        let mut queue: Vec<&str> = Vec::new();
255
256        if graph.contains_key(BEGIN_KEYWORD) {
257            queue.push(BEGIN_KEYWORD);
258            visited.insert(BEGIN_KEYWORD);
259        }
260
261        while let Some(current) = queue.pop() {
262            if let Some(neighbors) = graph.get(current) {
263                for &next in neighbors {
264                    if visited.insert(next) {
265                        queue.push(next);
266                    }
267                }
268            }
269        }
270
271        let mut violations = Vec::new();
272        for name in self.steps.keys() {
273            if name != BEGIN_KEYWORD && !visited.contains(name.as_str()) {
274                violations.push(ProtocolViolation::Unreachable { step: name.clone() });
275            }
276        }
277        violations
278    }
279
280    /// Check that all referenced performatives are defined (REQ-206).
281    ///
282    /// `defined_performatives` should include all performatives from the dialect's
283    /// `extend` clauses and installed ancestors. `begin` is always valid.
284    pub fn check_performative_definedness(
285        &self,
286        defined_performatives: &[&str],
287    ) -> Vec<ProtocolViolation> {
288        let defined: BTreeSet<&str> = defined_performatives.iter().copied().collect();
289        let referenced = self.all_referenced_performatives();
290
291        // A `(repeat k …)` copy such as `x#2` is defined iff its base
292        // performative `x` is (SPEC-015 REQ-704: per-copy inheritance).
293        // Flag each undefined *base* name once, not once per copy.
294        let mut flagged: BTreeSet<&str> = BTreeSet::new();
295        let mut violations = Vec::new();
296        for name in &referenced {
297            let base = repeat_base_name(name);
298            if !defined.contains(base) && flagged.insert(base) {
299                violations.push(ProtocolViolation::UndefinedPerformative {
300                    name: String::from(base),
301                });
302            }
303        }
304        violations
305    }
306
307    /// Number of protocol steps that count against R2's declared expansion
308    /// budget at install (SPEC-015 REQ-704): every named step — including
309    /// `(repeat k …)` copies, which are already materialised in `steps` by
310    /// the time a `CausalProtocol` exists — except the `begin` root, which
311    /// is a keyword, not an expansion product. A hand-unrolled equivalent
312    /// protocol counts identically, which is what keeps `k` honest.
313    pub fn expansion_size(&self) -> u32 {
314        let n = self
315            .steps
316            .keys()
317            .filter(|name| name.as_str() != BEGIN_KEYWORD)
318            .count();
319        u32::try_from(n).unwrap_or(u32::MAX)
320    }
321
322    /// Check that no performative has duplicate step declarations (REQ-207).
323    ///
324    /// `CausalProtocol::steps` is keyed by performative name, so step *names*
325    /// cannot collide structurally. The remaining hazard is the `(then …)`
326    /// parser, which accumulates predecessor `NodeRef` entries across
327    /// clauses by `push`: every clause that targets the same performative
328    /// pushes another entry. Distinct-alternative declarations like
329    /// `(then begin a) (then b a)` are *intentional* — `verify_causal`
330    /// reads the resulting `[Single("begin"), Single("b")]` as
331    /// `begin ∨ b` for the predecessor of `a` (see
332    /// `allowed_single_predecessors`), so this shape must pass R5.
333    /// What R5 does forbid is *literal* duplication, e.g. the same
334    /// `(then begin a)` clause written twice, which collapses to
335    /// `[Single("begin"), Single("begin")]` and signals an authoring
336    /// error rather than an alternative. Use `has_duplicate` so only
337    /// equal `NodeRef` entries are rejected. Successor duplicates are
338    /// still flagged as a defence-in-depth check against
339    /// programmatically-constructed protocols whose two sides have
340    /// drifted out of sync.
341    pub fn check_step_uniqueness(&self) -> Vec<ProtocolViolation> {
342        let mut violations = Vec::new();
343        for (name, step) in &self.steps {
344            if has_duplicate(&step.predecessors) || has_duplicate(&step.successors) {
345                violations.push(ProtocolViolation::DuplicateStep { name: name.clone() });
346            }
347        }
348        violations
349    }
350
351    /// Run all R5 protocol checks (REQ-208).
352    ///
353    /// Checks: step uniqueness (REQ-207), acyclicity (REQ-204),
354    /// reachability (REQ-205), and performative definedness (REQ-206).
355    pub fn verify_r5_protocol(&self, defined_performatives: &[&str]) -> Vec<ProtocolViolation> {
356        let mut violations = Vec::new();
357        violations.extend(self.check_step_uniqueness());
358        violations.extend(self.check_acyclicity());
359        violations.extend(self.check_reachability());
360        violations.extend(self.check_performative_definedness(defined_performatives));
361        violations
362    }
363}
364
365/// Causal verification failure details (CON-202, SPEC-002).
366#[derive(Debug, Clone, PartialEq, Eq)]
367#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
368pub enum CausalViolation {
369    /// Predecessor hash not found in the message store.
370    UnknownPredecessor { caused_by: String },
371    /// Predecessor found but has wrong performative type.
372    InvalidPredecessor {
373        caused_by: String,
374        expected: Vec<String>,
375        found: String,
376    },
377    /// Message requires `:caused-by` but none was provided.
378    MissingCausedBy,
379    /// Fan-in `(all ...)` has missing predecessor types.
380    IncompleteFanIn { missing_types: Vec<String> },
381    /// Predecessor found but not declared in the protocol.
382    ExtraneousPredecessor { caused_by: String, found: String },
383    /// Fan-in without an `(all ...)` declaration for this performative.
384    FanInWithoutAllDecl { performative: String },
385    /// Role-layer conformance failure (SPEC-014 REQ-612/613/615/618).
386    RoleConformance { reason: String },
387}
388
389impl fmt::Display for CausalViolation {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        match self {
392            Self::UnknownPredecessor { caused_by } => {
393                write!(f, "unknown predecessor: {caused_by}")
394            }
395            Self::InvalidPredecessor {
396                caused_by,
397                expected,
398                found,
399            } => {
400                write!(
401                    f,
402                    "invalid predecessor {caused_by}: expected one of [{}], found {found}",
403                    expected.join(", ")
404                )
405            }
406            Self::MissingCausedBy => write!(f, "missing :caused-by"),
407            Self::IncompleteFanIn { missing_types } => {
408                write!(
409                    f,
410                    "incomplete fan-in: missing types [{}]",
411                    missing_types.join(", ")
412                )
413            }
414            Self::ExtraneousPredecessor { caused_by, found } => {
415                write!(f, "extraneous predecessor {caused_by}: found {found}")
416            }
417            Self::FanInWithoutAllDecl { performative } => {
418                write!(f, "fan-in without (all ...) declaration for {performative}")
419            }
420            Self::RoleConformance { reason } => {
421                write!(f, "role conformance: {reason}")
422            }
423        }
424    }
425}
426
427/// Three-valued verification result lattice (REQ-302, CON-301).
428///
429/// ```text
430///      Valid          Violation
431///        \              /
432///         \            /
433///          ⊥ (Unknown)
434/// ```
435///
436/// Unknown is ⊥. Valid and Violation are incomparable top elements.
437#[derive(Debug, Clone, PartialEq, Eq)]
438#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
439pub enum VerificationResult {
440    /// ⊥ — predecessor not in store; undecidable with current state.
441    Unknown,
442    /// Predecessor found, type matches protocol declaration.
443    Valid,
444    /// Predecessor found, type mismatch or malformed hash.
445    Violation(CausalViolation),
446}
447
448impl VerificationResult {
449    /// Strong Kleene conjunction for `(all ...)` fan-in (REQ-303).
450    /// Greatest lower bound in the truth order: Violation < Unknown < Valid.
451    /// Algebraic laws apply to verdict classes, excluding diagnostic payloads.
452    ///
453    /// Truth table:
454    /// - Violation ⊓ _ = Violation  (absorbing)
455    /// - _ ⊓ Violation = Violation  (absorbing)
456    /// - Unknown ⊓ _ = Unknown      (when other ≠ Violation)
457    /// - Valid ⊓ Valid = Valid
458    pub fn meet(self, other: VerificationResult) -> VerificationResult {
459        match (&self, &other) {
460            (VerificationResult::Violation(_), _) => self,
461            (_, VerificationResult::Violation(_)) => other,
462            (VerificationResult::Unknown, _) | (_, VerificationResult::Unknown) => {
463                VerificationResult::Unknown
464            }
465            (VerificationResult::Valid, VerificationResult::Valid) => VerificationResult::Valid,
466        }
467    }
468
469    /// Strong Kleene disjunction for `(any ...)` (REQ-303).
470    /// Least upper bound in the truth order: Violation < Unknown < Valid.
471    /// Algebraic laws apply to verdict classes, excluding diagnostic payloads.
472    ///
473    /// Truth table:
474    /// - Valid ⊔ _ = Valid           (absorbing)
475    /// - _ ⊔ Valid = Valid           (absorbing)
476    /// - Violation ⊔ Unknown = Unknown
477    /// - Violation ⊔ Violation = Violation (preserves the left diagnostic)
478    /// - Unknown ⊔ Unknown = Unknown
479    pub fn join(self, other: VerificationResult) -> VerificationResult {
480        match (&self, &other) {
481            (VerificationResult::Valid, _) | (_, VerificationResult::Valid) => {
482                VerificationResult::Valid
483            }
484            (VerificationResult::Unknown, _) | (_, VerificationResult::Unknown) => {
485                VerificationResult::Unknown
486            }
487            (VerificationResult::Violation(_), VerificationResult::Violation(_)) => self,
488        }
489    }
490
491    /// Kuper's threshold test — has the lattice crossed {Valid, Violation}? (CON-301).
492    pub fn is_resolved(&self) -> bool {
493        !matches!(self, VerificationResult::Unknown)
494    }
495
496    /// Stability test — identical to `is_resolved()` (CON-301).
497    ///
498    /// Once resolved, the result is permanent under store growth (monotonicity).
499    pub fn is_stable(&self) -> bool {
500        self.is_resolved()
501    }
502}
503
504impl PartialOrd for VerificationResult {
505    /// Knowledge partial order: Unknown < Valid, Unknown < Violation,
506    /// Valid and Violation are incomparable.
507    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
508        use core::cmp::Ordering;
509        match (self, other) {
510            // Equal cases
511            (VerificationResult::Unknown, VerificationResult::Unknown) => Some(Ordering::Equal),
512            (VerificationResult::Valid, VerificationResult::Valid) => Some(Ordering::Equal),
513            (VerificationResult::Violation(_), VerificationResult::Violation(_)) => {
514                Some(Ordering::Equal)
515            }
516            // Unknown < Valid, Unknown < Violation
517            (VerificationResult::Unknown, _) => Some(Ordering::Less),
518            (_, VerificationResult::Unknown) => Some(Ordering::Greater),
519            // Valid and Violation are incomparable
520            (VerificationResult::Valid, VerificationResult::Violation(_))
521            | (VerificationResult::Violation(_), VerificationResult::Valid) => None,
522        }
523    }
524}
525
526// ================================================================
527// Causal Verification (REQ-203, REQ-304, ADR-008)
528// ================================================================
529
530/// Resolve the performative type of a `:caused-by` reference: from the
531/// full message when the store holds one, else from a redacted envelope's
532/// *authenticated* header, else from an opened envelope's *authenticated*
533/// Performative opening (SPEC-015 REQ-702; SPEC-017 REQ-813).
534///
535/// This is the safety-level seam of redacted delivery: presence,
536/// predecessor type, and resolution read exactly the fields an envelope
537/// carries (hash, type, endpoints, signature), so a widened recipient
538/// holding only the envelope — redacted *or* opened — reaches the same
539/// safety verdict it would with the full predecessor. An opened envelope's
540/// type comes from its Performative opening, verified against the signed
541/// typed root the address commits to; its endpoints (from/to openings) are
542/// available for role-conformance the same way, at zero payload disclosure.
543/// A full message, when present, wins — the two name the same content root,
544/// so they are the same message.
545///
546/// The completion-level occupant fan-in (`projection::verify_causal_for_role`,
547/// REQ-618) deliberately does *not* use this seam: fan-in membership
548/// ("present and Valid") still demands full messages (REQ-703). An opened
549/// envelope, which seals leaf 5, therefore satisfies the safety checks here
550/// but never the completion check there — the SPEC-015 boundary, preserved.
551pub(crate) fn predecessor_type<'a, S: MessageStore>(
552    store: &'a S,
553    hash: &ContentHash,
554    thread: &ThreadId,
555) -> Option<&'a str> {
556    if let Some(predecessor_msg) = store.lookup_in_thread(hash, thread) {
557        // Type through wrappers: the agent stores whole (possibly signed)
558        // messages, so a wrapped predecessor must type as its innermost
559        // Simple (SPEC-014; pre-existing Simple behaviour unchanged).
560        return Some(
561            predecessor_msg
562                .innermost_simple()
563                .and_then(|m| m.performative())
564                .map(|p| p.name())
565                .unwrap_or(""),
566        );
567    }
568    if let Some(e) = store.envelope_in_thread(hash, thread) {
569        return Some(e.performative());
570    }
571    store
572        .opened_in_thread(hash, thread)
573        .and_then(|e| e.performative())
574}
575
576/// Collect performative names allowed as single-message predecessors.
577///
578/// Gathers names from `Single` and `Any` node-refs (not `All`, which is for fan-in).
579pub(crate) fn allowed_single_predecessors(step: &StepDecl) -> Vec<String> {
580    let mut types = Vec::new();
581    for nr in &step.predecessors {
582        match nr {
583            NodeRef::Single(s) => types.push(s.clone()),
584            NodeRef::Any(set) => types.extend(set.iter().cloned()),
585            NodeRef::All(_) => {} // fan-in handled separately
586        }
587    }
588    types
589}
590
591/// Verify causal consistency of a message against its protocol (REQ-203, REQ-304).
592///
593/// Three-valued result: `Unknown` when a predecessor hash is not yet in the store,
594/// `Valid` when all predecessors resolve and match the protocol, `Violation` when
595/// a predecessor exists but has the wrong type or the causal link is malformed.
596///
597/// Thread-scoped: `:caused-by` hashes resolve only within the same `:thread` (ADR-008).
598/// Stateless and valid-sticky. Wrong evidence dominates missing evidence in fan-in.
599/// The admission monitor applies a separate resolved-first guard before this verifier.
600/// Decisions use `causal_kernel`; lookups, membership, coverage and diagnostics
601/// remain adapters whose Rust-to-Lean correspondence is a separate obligation.
602pub fn verify_causal<S: MessageStore>(
603    msg_performative: &str,
604    caused_by: Option<&CausedBy>,
605    store: &S,
606    protocol: &CausalProtocol,
607    thread: &ThreadId,
608) -> VerificationResult {
609    if crate::repeat::has_repeat(protocol) {
610        return crate::repeat::verify(msg_performative, caused_by, store, protocol, thread, None);
611    }
612    let step = match protocol.steps.get(msg_performative) {
613        Some(s) => s,
614        // Legacy unconstrained route; strict admission excludes it.
615        None => return VerificationResult::Valid,
616    };
617    let has_predecessors = !step.predecessors.is_empty();
618
619    match caused_by {
620        None => match kernel::absent(has_predecessors) {
621            Decision::Valid => VerificationResult::Valid,
622            Decision::MissingCausedBy => {
623                VerificationResult::Violation(CausalViolation::MissingCausedBy)
624            }
625            _ => unreachable!("absent decision"),
626        },
627        Some(CausedBy::Begin) => {
628            let begin_allowed = step.predecessors.iter().any(|nr| match nr {
629                NodeRef::Single(s) => s == BEGIN_KEYWORD,
630                NodeRef::Any(set) => set.contains(BEGIN_KEYWORD),
631                NodeRef::All(_) => false,
632            });
633            match kernel::literal_begin(begin_allowed) {
634                Decision::Valid => VerificationResult::Valid,
635                Decision::InvalidPredecessor => {
636                    VerificationResult::Violation(CausalViolation::InvalidPredecessor {
637                        caused_by: BEGIN_KEYWORD.into(),
638                        expected: allowed_single_predecessors(step),
639                        found: BEGIN_KEYWORD.into(),
640                    })
641                }
642                _ => unreachable!("literal-begin decision"),
643            }
644        }
645        Some(CausedBy::Single(hash_str)) => {
646            let content_hash = ContentHash(hash_str.clone());
647            let pred_perf = predecessor_type(store, &content_hash, thread);
648            // Preserve the missing-lookup fast path and diagnostics ordering.
649            let allowed = if pred_perf.is_some() {
650                allowed_single_predecessors(step)
651            } else {
652                Vec::new()
653            };
654            let lookup = match pred_perf {
655                None => Lookup::Missing,
656                Some(p) if allowed.iter().any(|a| a == p) => Lookup::Allowed,
657                Some(_) => Lookup::Wrong,
658            };
659            match kernel::single(has_predecessors, lookup) {
660                Decision::Valid => VerificationResult::Valid,
661                Decision::Unknown => VerificationResult::Unknown,
662                Decision::ExtraneousPredecessor => {
663                    VerificationResult::Violation(CausalViolation::ExtraneousPredecessor {
664                        caused_by: hash_str.clone(),
665                        found: pred_perf.expect("wrong lookup has a type").into(),
666                    })
667                }
668                Decision::InvalidPredecessor => {
669                    VerificationResult::Violation(CausalViolation::InvalidPredecessor {
670                        caused_by: hash_str.clone(),
671                        expected: allowed,
672                        found: pred_perf.expect("wrong lookup has a type").into(),
673                    })
674                }
675                _ => unreachable!("single decision"),
676            }
677        }
678        Some(CausedBy::Multiple(hashes)) => {
679            // Preserve FIRST-All selection, including empty and later clauses.
680            let all_decl = step.predecessors.iter().find_map(|nr| match nr {
681                NodeRef::All(set) => Some(set),
682                _ => None,
683            });
684            let mut state = FanIn::Clear;
685            let mut found_types = BTreeSet::new();
686            let mut first_error = None;
687            let mut missing = Vec::new();
688            if let Some(all_set) = all_decl {
689                for hash_str in hashes {
690                    let content_hash = ContentHash(hash_str.clone());
691                    let lookup = match predecessor_type(store, &content_hash, thread) {
692                        None => Lookup::Missing,
693                        Some(pred_perf) if all_set.contains(pred_perf) => {
694                            found_types.insert(String::from(pred_perf));
695                            Lookup::Allowed
696                        }
697                        Some(pred_perf) => {
698                            if first_error.is_none() {
699                                first_error = Some(CausalViolation::InvalidPredecessor {
700                                    caused_by: hash_str.clone(),
701                                    expected: all_set.iter().cloned().collect(),
702                                    found: pred_perf.into(),
703                                });
704                            }
705                            Lookup::Wrong
706                        }
707                    };
708                    state = kernel::observe(state, lookup);
709                }
710                if matches!(state, FanIn::Clear) {
711                    missing = all_set
712                        .iter()
713                        .filter(|t| !found_types.contains(*t))
714                        .cloned()
715                        .collect();
716                }
717            }
718            match kernel::finish(all_decl.is_some(), state, missing.is_empty()) {
719                Decision::Valid => VerificationResult::Valid,
720                Decision::Unknown => VerificationResult::Unknown,
721                Decision::InvalidPredecessor => VerificationResult::Violation(
722                    first_error.expect("wrong fan-in has a diagnostic"),
723                ),
724                Decision::IncompleteFanIn => {
725                    VerificationResult::Violation(CausalViolation::IncompleteFanIn {
726                        missing_types: missing,
727                    })
728                }
729                Decision::FanInWithoutAllDecl => {
730                    VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl {
731                        performative: msg_performative.into(),
732                    })
733                }
734                _ => unreachable!("fan-in decision"),
735            }
736        }
737    }
738}
739
740#[cfg(test)]
741mod tests {
742    use super::*;
743
744    // ================================================================
745    // SPEC-005 NFR-512 / Verify.lean parity tripwire
746    // ================================================================
747
748    /// Tripwire: the reserved-keyword vocabulary recognised by
749    /// `verify_causal` is the singleton `{BEGIN_KEYWORD}`. Adding a second
750    /// reserved keyword (e.g. `"end"`, `"fork"`) without extending
751    /// `LeanCbcl/Verify.lean::CausalProtocol` to match would silently
752    /// break the Lean ↔ Rust parity that REQ-512..514 depend on. If this
753    /// test starts failing, the right response is an ADR amendment to
754    /// SPEC-005 §"Open Questions" §1, not a quick patch.
755    #[test]
756    fn test_reserved_keyword_vocabulary_is_singleton() {
757        assert_eq!(BEGIN_KEYWORD, "begin");
758    }
759
760    fn violation() -> VerificationResult {
761        VerificationResult::Violation(CausalViolation::MissingCausedBy)
762    }
763
764    fn violation2() -> VerificationResult {
765        VerificationResult::Violation(CausalViolation::UnknownPredecessor {
766            caused_by: "f1220test".into(),
767        })
768    }
769
770    // ================================================================
771    // TEST-302: Three-Valued Result Construction and Ordering
772    // ================================================================
773
774    #[test]
775    fn test_construction_unknown() {
776        let r = VerificationResult::Unknown;
777        assert!(!r.is_resolved());
778        assert!(!r.is_stable());
779    }
780
781    #[test]
782    fn test_construction_valid() {
783        let r = VerificationResult::Valid;
784        assert!(r.is_resolved());
785        assert!(r.is_stable());
786    }
787
788    #[test]
789    fn test_construction_violation() {
790        let r = violation();
791        assert!(r.is_resolved());
792        assert!(r.is_stable());
793    }
794
795    #[test]
796    fn test_partial_ord_unknown_lt_valid() {
797        assert!(VerificationResult::Unknown < VerificationResult::Valid);
798    }
799
800    #[test]
801    fn test_partial_ord_unknown_lt_violation() {
802        assert!(VerificationResult::Unknown < violation());
803    }
804
805    #[test]
806    fn test_partial_ord_valid_violation_incomparable() {
807        let v = VerificationResult::Valid;
808        let viol = violation();
809        assert!(v.partial_cmp(&viol).is_none());
810        assert!(viol.partial_cmp(&v).is_none());
811    }
812
813    #[test]
814    fn test_partial_ord_reflexive() {
815        assert_eq!(
816            VerificationResult::Unknown.partial_cmp(&VerificationResult::Unknown),
817            Some(core::cmp::Ordering::Equal)
818        );
819        assert_eq!(
820            VerificationResult::Valid.partial_cmp(&VerificationResult::Valid),
821            Some(core::cmp::Ordering::Equal)
822        );
823        assert_eq!(
824            violation().partial_cmp(&violation()),
825            Some(core::cmp::Ordering::Equal)
826        );
827    }
828
829    // ================================================================
830    // TEST-303: Meet (conjunction) 3×3 truth table
831    // ================================================================
832
833    #[test]
834    fn test_meet_unknown_unknown() {
835        assert_eq!(
836            VerificationResult::Unknown.meet(VerificationResult::Unknown),
837            VerificationResult::Unknown
838        );
839    }
840
841    #[test]
842    fn test_meet_unknown_valid() {
843        assert_eq!(
844            VerificationResult::Unknown.meet(VerificationResult::Valid),
845            VerificationResult::Unknown
846        );
847    }
848
849    #[test]
850    fn test_meet_unknown_violation() {
851        let result = VerificationResult::Unknown.meet(violation());
852        assert!(matches!(result, VerificationResult::Violation(_)));
853    }
854
855    #[test]
856    fn test_meet_valid_unknown() {
857        assert_eq!(
858            VerificationResult::Valid.meet(VerificationResult::Unknown),
859            VerificationResult::Unknown
860        );
861    }
862
863    #[test]
864    fn test_meet_valid_valid() {
865        assert_eq!(
866            VerificationResult::Valid.meet(VerificationResult::Valid),
867            VerificationResult::Valid
868        );
869    }
870
871    #[test]
872    fn test_meet_valid_violation() {
873        let result = VerificationResult::Valid.meet(violation());
874        assert!(matches!(result, VerificationResult::Violation(_)));
875    }
876
877    #[test]
878    fn test_meet_violation_unknown() {
879        let result = violation().meet(VerificationResult::Unknown);
880        assert!(matches!(result, VerificationResult::Violation(_)));
881    }
882
883    #[test]
884    fn test_meet_violation_valid() {
885        let result = violation().meet(VerificationResult::Valid);
886        assert!(matches!(result, VerificationResult::Violation(_)));
887    }
888
889    #[test]
890    fn test_meet_violation_violation() {
891        let result = violation().meet(violation2());
892        assert!(matches!(result, VerificationResult::Violation(_)));
893    }
894
895    // ================================================================
896    // TEST-303: Join (disjunction) 3×3 truth table
897    // ================================================================
898
899    #[test]
900    fn test_join_unknown_unknown() {
901        assert_eq!(
902            VerificationResult::Unknown.join(VerificationResult::Unknown),
903            VerificationResult::Unknown
904        );
905    }
906
907    #[test]
908    fn test_join_unknown_valid() {
909        assert_eq!(
910            VerificationResult::Unknown.join(VerificationResult::Valid),
911            VerificationResult::Valid
912        );
913    }
914
915    #[test]
916    fn test_join_unknown_violation() {
917        let result = VerificationResult::Unknown.join(violation());
918        assert_eq!(result, VerificationResult::Unknown);
919    }
920
921    #[test]
922    fn test_join_valid_unknown() {
923        assert_eq!(
924            VerificationResult::Valid.join(VerificationResult::Unknown),
925            VerificationResult::Valid
926        );
927    }
928
929    #[test]
930    fn test_join_valid_valid() {
931        assert_eq!(
932            VerificationResult::Valid.join(VerificationResult::Valid),
933            VerificationResult::Valid
934        );
935    }
936
937    #[test]
938    fn test_join_valid_violation() {
939        assert_eq!(
940            VerificationResult::Valid.join(violation()),
941            VerificationResult::Valid
942        );
943    }
944
945    #[test]
946    fn test_join_violation_unknown() {
947        let result = violation().join(VerificationResult::Unknown);
948        assert_eq!(result, VerificationResult::Unknown);
949    }
950
951    #[test]
952    fn test_join_violation_valid() {
953        assert_eq!(
954            violation().join(VerificationResult::Valid),
955            VerificationResult::Valid
956        );
957    }
958
959    #[test]
960    fn test_join_violation_violation() {
961        let result = violation().join(violation2());
962        assert!(matches!(result, VerificationResult::Violation(_)));
963    }
964
965    // ================================================================
966    // CausalViolation construction and Display
967    // ================================================================
968
969    #[test]
970    fn test_causal_violation_display() {
971        let v = CausalViolation::MissingCausedBy;
972        assert_eq!(v.to_string(), "missing :caused-by");
973
974        let v = CausalViolation::UnknownPredecessor {
975            caused_by: "f1220abc".into(),
976        };
977        assert_eq!(v.to_string(), "unknown predecessor: f1220abc");
978    }
979
980    #[test]
981    fn test_causal_violation_variants_exist() {
982        let _ = CausalViolation::UnknownPredecessor {
983            caused_by: "h".into(),
984        };
985        let _ = CausalViolation::InvalidPredecessor {
986            caused_by: "h".into(),
987            expected: vec!["a".into()],
988            found: "b".into(),
989        };
990        let _ = CausalViolation::MissingCausedBy;
991        let _ = CausalViolation::IncompleteFanIn {
992            missing_types: vec!["a".into()],
993        };
994        let _ = CausalViolation::ExtraneousPredecessor {
995            caused_by: "h".into(),
996            found: "x".into(),
997        };
998        let _ = CausalViolation::FanInWithoutAllDecl {
999            performative: "p".into(),
1000        };
1001    }
1002
1003    // ================================================================
1004    // Meet preserves left violation detail
1005    // ================================================================
1006
1007    #[test]
1008    fn test_meet_preserves_first_violation() {
1009        let v1 = violation();
1010        let v2 = violation2();
1011        // When both are violations, meet returns the left one
1012        let result = v1.meet(v2);
1013        assert_eq!(
1014            result,
1015            VerificationResult::Violation(CausalViolation::MissingCausedBy)
1016        );
1017    }
1018
1019    // ================================================================
1020    // Join preserves first violation detail when both alternatives are violations
1021    // ================================================================
1022
1023    #[test]
1024    fn test_join_preserves_first_violation() {
1025        let v1 = violation();
1026        let result = v1.join(violation2());
1027        assert_eq!(
1028            result,
1029            VerificationResult::Violation(CausalViolation::MissingCausedBy)
1030        );
1031    }
1032
1033    // ================================================================
1034    // Protocol Validation Tests
1035    // ================================================================
1036
1037    /// Helper: build a simple linear protocol: begin → a → b → c
1038    fn linear_protocol() -> CausalProtocol {
1039        let mut steps = BTreeMap::new();
1040        steps.insert(
1041            "begin".into(),
1042            StepDecl {
1043                performative: "begin".into(),
1044                predecessors: vec![],
1045                successors: vec![NodeRef::Single("a".into())],
1046            },
1047        );
1048        steps.insert(
1049            "a".into(),
1050            StepDecl {
1051                performative: "a".into(),
1052                predecessors: vec![NodeRef::Single("begin".into())],
1053                successors: vec![NodeRef::Single("b".into())],
1054            },
1055        );
1056        steps.insert(
1057            "b".into(),
1058            StepDecl {
1059                performative: "b".into(),
1060                predecessors: vec![NodeRef::Single("a".into())],
1061                successors: vec![NodeRef::Single("c".into())],
1062            },
1063        );
1064        steps.insert(
1065            "c".into(),
1066            StepDecl {
1067                performative: "c".into(),
1068                predecessors: vec![NodeRef::Single("b".into())],
1069                successors: vec![],
1070            },
1071        );
1072        CausalProtocol { steps }
1073    }
1074
1075    // ---- TEST-204: Acyclicity ----
1076
1077    #[test]
1078    fn test_acyclicity_linear_chain_passes() {
1079        // begin → a → b → c — no cycles
1080        let proto = linear_protocol();
1081        assert!(proto.check_acyclicity().is_empty());
1082    }
1083
1084    #[test]
1085    fn test_acyclicity_direct_cycle_rejected() {
1086        // a → b, b → a (direct cycle)
1087        let mut steps = BTreeMap::new();
1088        steps.insert(
1089            "a".into(),
1090            StepDecl {
1091                performative: "a".into(),
1092                predecessors: vec![NodeRef::Single("b".into())],
1093                successors: vec![NodeRef::Single("b".into())],
1094            },
1095        );
1096        steps.insert(
1097            "b".into(),
1098            StepDecl {
1099                performative: "b".into(),
1100                predecessors: vec![NodeRef::Single("a".into())],
1101                successors: vec![NodeRef::Single("a".into())],
1102            },
1103        );
1104        let proto = CausalProtocol { steps };
1105        let violations = proto.check_acyclicity();
1106        assert!(!violations.is_empty());
1107        assert!(violations
1108            .iter()
1109            .any(|v| matches!(v, ProtocolViolation::Cycle { .. })));
1110    }
1111
1112    #[test]
1113    fn test_acyclicity_transitive_cycle_rejected() {
1114        // a → b → c → a (transitive cycle)
1115        let mut steps = BTreeMap::new();
1116        steps.insert(
1117            "a".into(),
1118            StepDecl {
1119                performative: "a".into(),
1120                predecessors: vec![NodeRef::Single("c".into())],
1121                successors: vec![NodeRef::Single("b".into())],
1122            },
1123        );
1124        steps.insert(
1125            "b".into(),
1126            StepDecl {
1127                performative: "b".into(),
1128                predecessors: vec![NodeRef::Single("a".into())],
1129                successors: vec![NodeRef::Single("c".into())],
1130            },
1131        );
1132        steps.insert(
1133            "c".into(),
1134            StepDecl {
1135                performative: "c".into(),
1136                predecessors: vec![NodeRef::Single("b".into())],
1137                successors: vec![NodeRef::Single("a".into())],
1138            },
1139        );
1140        let proto = CausalProtocol { steps };
1141        let violations = proto.check_acyclicity();
1142        assert!(!violations.is_empty());
1143    }
1144
1145    // ---- TEST-205: Reachability ----
1146
1147    #[test]
1148    fn test_reachability_linear_chain_passes() {
1149        let proto = linear_protocol();
1150        assert!(proto.check_reachability().is_empty());
1151    }
1152
1153    #[test]
1154    fn test_reachability_both_from_begin_passes() {
1155        // begin → a, begin → b (both directly reachable)
1156        let mut steps = BTreeMap::new();
1157        steps.insert(
1158            "begin".into(),
1159            StepDecl {
1160                performative: "begin".into(),
1161                predecessors: vec![],
1162                successors: vec![NodeRef::Single("a".into()), NodeRef::Single("b".into())],
1163            },
1164        );
1165        steps.insert(
1166            "a".into(),
1167            StepDecl {
1168                performative: "a".into(),
1169                predecessors: vec![NodeRef::Single("begin".into())],
1170                successors: vec![],
1171            },
1172        );
1173        steps.insert(
1174            "b".into(),
1175            StepDecl {
1176                performative: "b".into(),
1177                predecessors: vec![NodeRef::Single("begin".into())],
1178                successors: vec![],
1179            },
1180        );
1181        let proto = CausalProtocol { steps };
1182        assert!(proto.check_reachability().is_empty());
1183    }
1184
1185    #[test]
1186    fn test_reachability_unreachable_step_rejected() {
1187        // begin → a, but c has no connection to begin
1188        let mut steps = BTreeMap::new();
1189        steps.insert(
1190            "begin".into(),
1191            StepDecl {
1192                performative: "begin".into(),
1193                predecessors: vec![],
1194                successors: vec![NodeRef::Single("a".into())],
1195            },
1196        );
1197        steps.insert(
1198            "a".into(),
1199            StepDecl {
1200                performative: "a".into(),
1201                predecessors: vec![NodeRef::Single("begin".into())],
1202                successors: vec![],
1203            },
1204        );
1205        steps.insert(
1206            "c".into(),
1207            StepDecl {
1208                performative: "c".into(),
1209                predecessors: vec![NodeRef::Single("x".into())],
1210                successors: vec![],
1211            },
1212        );
1213        let proto = CausalProtocol { steps };
1214        let violations = proto.check_reachability();
1215        assert_eq!(violations.len(), 1);
1216        assert!(matches!(
1217            &violations[0],
1218            ProtocolViolation::Unreachable { step } if step == "c"
1219        ));
1220    }
1221
1222    // ---- TEST-206: Performative Definedness ----
1223
1224    #[test]
1225    fn test_definedness_all_defined_passes() {
1226        let proto = linear_protocol();
1227        let violations = proto.check_performative_definedness(&["a", "b", "c"]);
1228        assert!(violations.is_empty());
1229    }
1230
1231    #[test]
1232    fn test_definedness_undefined_rejected() {
1233        let proto = linear_protocol();
1234        // Only "a" is defined, "b" and "c" are not
1235        let violations = proto.check_performative_definedness(&["a"]);
1236        assert_eq!(violations.len(), 2);
1237        let names: Vec<&str> = violations
1238            .iter()
1239            .filter_map(|v| match v {
1240                ProtocolViolation::UndefinedPerformative { name } => Some(name.as_str()),
1241                _ => None,
1242            })
1243            .collect();
1244        assert!(names.contains(&"b"));
1245        assert!(names.contains(&"c"));
1246    }
1247
1248    // ---- TEST-207: Step Uniqueness ----
1249
1250    #[test]
1251    fn test_step_uniqueness_clean_protocol_passes() {
1252        let proto = linear_protocol();
1253        assert!(proto.check_step_uniqueness().is_empty());
1254    }
1255
1256    #[test]
1257    fn test_step_uniqueness_detects_duplicate_successor() {
1258        // Equivalent to `(then begin a) (then begin a)` — duplicate edge.
1259        let mut steps = BTreeMap::new();
1260        steps.insert(
1261            "begin".into(),
1262            StepDecl {
1263                performative: "begin".into(),
1264                predecessors: vec![],
1265                successors: vec![NodeRef::Single("a".into()), NodeRef::Single("a".into())],
1266            },
1267        );
1268        steps.insert(
1269            "a".into(),
1270            StepDecl {
1271                performative: "a".into(),
1272                predecessors: vec![
1273                    NodeRef::Single("begin".into()),
1274                    NodeRef::Single("begin".into()),
1275                ],
1276                successors: vec![],
1277            },
1278        );
1279        let proto = CausalProtocol { steps };
1280        let violations = proto.check_step_uniqueness();
1281        let names: BTreeSet<&str> = violations
1282            .iter()
1283            .filter_map(|v| match v {
1284                ProtocolViolation::DuplicateStep { name } => Some(name.as_str()),
1285                _ => None,
1286            })
1287            .collect();
1288        assert!(names.contains("begin"));
1289        assert!(names.contains("a"));
1290    }
1291
1292    #[test]
1293    fn test_step_uniqueness_accepts_distinct_alternatives() {
1294        // `(then begin a) (then b a)` — two clauses target `a` with
1295        // *different* predecessors. `verify_causal` treats the resulting
1296        // `[Single("begin"), Single("b")]` as the alternation `begin ∨ b`
1297        // (see `allowed_single_predecessors`), so this protocol shape is
1298        // valid and must pass R5. Only literal duplicates among the
1299        // predecessor entries should be flagged.
1300        let mut steps = BTreeMap::new();
1301        steps.insert(
1302            "a".into(),
1303            StepDecl {
1304                performative: "a".into(),
1305                predecessors: vec![NodeRef::Single("begin".into()), NodeRef::Single("b".into())],
1306                successors: vec![],
1307            },
1308        );
1309        let proto = CausalProtocol { steps };
1310        assert!(proto.check_step_uniqueness().is_empty());
1311    }
1312
1313    #[test]
1314    fn test_step_uniqueness_rejects_literal_duplicate_predecessor() {
1315        // Same `NodeRef` entered twice — e.g. `(then begin a)` written
1316        // twice — collapses to `[Single("begin"), Single("begin")]` and
1317        // is an authoring error, not an alternation. Must be flagged.
1318        let mut steps = BTreeMap::new();
1319        steps.insert(
1320            "a".into(),
1321            StepDecl {
1322                performative: "a".into(),
1323                predecessors: vec![
1324                    NodeRef::Single("begin".into()),
1325                    NodeRef::Single("begin".into()),
1326                ],
1327                successors: vec![],
1328            },
1329        );
1330        let proto = CausalProtocol { steps };
1331        assert!(proto
1332            .check_step_uniqueness()
1333            .iter()
1334            .any(|v| matches!(v, ProtocolViolation::DuplicateStep { name } if name == "a")));
1335    }
1336
1337    #[test]
1338    fn test_step_uniqueness_rejects_literal_duplicate_successor() {
1339        // Defence-in-depth (see protocol.rs `has_duplicate` rationale at the
1340        // method docstring): the successor side of `(then …)` is symmetric
1341        // with the predecessor side; a literal `NodeRef` repeated in the
1342        // successors list is an authoring error, not an alternation, and
1343        // must be flagged. This covers the symmetric case to
1344        // `test_step_uniqueness_rejects_literal_duplicate_predecessor`.
1345        let mut steps = BTreeMap::new();
1346        steps.insert(
1347            "a".into(),
1348            StepDecl {
1349                performative: "a".into(),
1350                predecessors: vec![NodeRef::Single("begin".into())],
1351                successors: vec![NodeRef::Single("b".into()), NodeRef::Single("b".into())],
1352            },
1353        );
1354        let proto = CausalProtocol { steps };
1355        assert!(proto
1356            .check_step_uniqueness()
1357            .iter()
1358            .any(|v| matches!(v, ProtocolViolation::DuplicateStep { name } if name == "a")));
1359    }
1360
1361    #[test]
1362    fn test_step_uniqueness_accepts_all_fan_in() {
1363        // `(then (all begin x) a)` — single predecessor entry, legitimate fan-in.
1364        let mut steps = BTreeMap::new();
1365        let mut all_set = BTreeSet::new();
1366        all_set.insert("begin".into());
1367        all_set.insert("x".into());
1368        steps.insert(
1369            "a".into(),
1370            StepDecl {
1371                performative: "a".into(),
1372                predecessors: vec![NodeRef::All(all_set)],
1373                successors: vec![],
1374            },
1375        );
1376        let proto = CausalProtocol { steps };
1377        assert!(proto.check_step_uniqueness().is_empty());
1378    }
1379
1380    // ---- TEST-208: verify_r5_protocol composite ----
1381
1382    #[test]
1383    fn test_verify_r5_protocol_valid() {
1384        let proto = linear_protocol();
1385        let violations = proto.verify_r5_protocol(&["a", "b", "c"]);
1386        assert!(violations.is_empty());
1387    }
1388
1389    #[test]
1390    fn test_verify_r5_protocol_catches_undefined() {
1391        let proto = linear_protocol();
1392        let violations = proto.verify_r5_protocol(&["a"]);
1393        assert!(violations
1394            .iter()
1395            .any(|v| matches!(v, ProtocolViolation::UndefinedPerformative { .. })));
1396    }
1397
1398    #[test]
1399    fn test_verify_r5_protocol_catches_unreachable() {
1400        let mut steps = BTreeMap::new();
1401        steps.insert(
1402            "begin".into(),
1403            StepDecl {
1404                performative: "begin".into(),
1405                predecessors: vec![],
1406                successors: vec![NodeRef::Single("a".into())],
1407            },
1408        );
1409        steps.insert(
1410            "a".into(),
1411            StepDecl {
1412                performative: "a".into(),
1413                predecessors: vec![NodeRef::Single("begin".into())],
1414                successors: vec![],
1415            },
1416        );
1417        steps.insert(
1418            "orphan".into(),
1419            StepDecl {
1420                performative: "orphan".into(),
1421                predecessors: vec![],
1422                successors: vec![],
1423            },
1424        );
1425        let proto = CausalProtocol { steps };
1426        let violations = proto.verify_r5_protocol(&["a", "orphan"]);
1427        assert!(violations
1428            .iter()
1429            .any(|v| matches!(v, ProtocolViolation::Unreachable { step } if step == "orphan")));
1430    }
1431
1432    // ---- ProtocolViolation Display ----
1433
1434    #[test]
1435    fn test_protocol_violation_display() {
1436        let v = ProtocolViolation::Cycle {
1437            participants: vec!["a".into(), "b".into()],
1438        };
1439        assert_eq!(v.to_string(), "cycle detected: a → b");
1440
1441        let v = ProtocolViolation::Unreachable {
1442            step: "orphan".into(),
1443        };
1444        assert!(v.to_string().contains("unreachable"));
1445
1446        let v = ProtocolViolation::UndefinedPerformative { name: "foo".into() };
1447        assert!(v.to_string().contains("not defined"));
1448
1449        let v = ProtocolViolation::DuplicateStep { name: "bar".into() };
1450        assert!(v.to_string().contains("duplicate"));
1451    }
1452
1453    // ---- Empty protocol ----
1454
1455    #[test]
1456    fn test_empty_protocol_passes_all_checks() {
1457        let proto = CausalProtocol {
1458            steps: BTreeMap::new(),
1459        };
1460        assert!(proto.check_acyclicity().is_empty());
1461        assert!(proto.check_reachability().is_empty());
1462        assert!(proto.check_performative_definedness(&[]).is_empty());
1463        assert!(proto.check_step_uniqueness().is_empty());
1464        assert!(proto.verify_r5_protocol(&[]).is_empty());
1465    }
1466
1467    // ================================================================
1468    // TEST-203 / TEST-304: verify_causal
1469    // ================================================================
1470
1471    use crate::message::{Message, Performative};
1472    use crate::sexpr::{Atom, SExpr};
1473    use crate::store::{ContentHash, MessageStore, ThreadId, ThreadedMessageStore};
1474
1475    fn chash(s: &str) -> ContentHash {
1476        ContentHash(s.into())
1477    }
1478
1479    fn tid(s: &str) -> ThreadId {
1480        ThreadId(s.into())
1481    }
1482
1483    fn make_msg(perf: &str, caused_by: Option<CausedBy>) -> Message {
1484        Message::Simple {
1485            performative: Performative::Custom(perf.into()),
1486            recipient: None,
1487            content: SExpr::Atom(Atom::Str("x".into())),
1488            params: alloc::vec![],
1489            thread: None,
1490            sender: None,
1491            caused_by,
1492        }
1493    }
1494
1495    /// Protocol: begin → a → b → c
1496    fn verification_protocol() -> CausalProtocol {
1497        let mut steps = BTreeMap::new();
1498        steps.insert(
1499            "begin".into(),
1500            StepDecl {
1501                performative: "begin".into(),
1502                predecessors: vec![],
1503                successors: vec![NodeRef::Single("a".into())],
1504            },
1505        );
1506        steps.insert(
1507            "a".into(),
1508            StepDecl {
1509                performative: "a".into(),
1510                predecessors: vec![NodeRef::Single("begin".into())],
1511                successors: vec![NodeRef::Single("b".into())],
1512            },
1513        );
1514        steps.insert(
1515            "b".into(),
1516            StepDecl {
1517                performative: "b".into(),
1518                predecessors: vec![NodeRef::Single("a".into())],
1519                successors: vec![NodeRef::Single("c".into())],
1520            },
1521        );
1522        steps.insert(
1523            "c".into(),
1524            StepDecl {
1525                performative: "c".into(),
1526                predecessors: vec![NodeRef::Single("b".into())],
1527                successors: vec![],
1528            },
1529        );
1530        CausalProtocol { steps }
1531    }
1532
1533    /// Protocol with fan-in: begin → x, begin → y, (all x y) → z
1534    fn fan_in_protocol() -> CausalProtocol {
1535        let mut steps = BTreeMap::new();
1536        steps.insert(
1537            "begin".into(),
1538            StepDecl {
1539                performative: "begin".into(),
1540                predecessors: vec![],
1541                successors: vec![NodeRef::Single("x".into()), NodeRef::Single("y".into())],
1542            },
1543        );
1544        steps.insert(
1545            "x".into(),
1546            StepDecl {
1547                performative: "x".into(),
1548                predecessors: vec![NodeRef::Single("begin".into())],
1549                successors: vec![],
1550            },
1551        );
1552        steps.insert(
1553            "y".into(),
1554            StepDecl {
1555                performative: "y".into(),
1556                predecessors: vec![NodeRef::Single("begin".into())],
1557                successors: vec![],
1558            },
1559        );
1560        let mut all_set = BTreeSet::new();
1561        all_set.insert("x".into());
1562        all_set.insert("y".into());
1563        steps.insert(
1564            "z".into(),
1565            StepDecl {
1566                performative: "z".into(),
1567                predecessors: vec![NodeRef::All(all_set)],
1568                successors: vec![],
1569            },
1570        );
1571        CausalProtocol { steps }
1572    }
1573
1574    // ---- Begin caused-by ----
1575
1576    #[test]
1577    fn verify_begin_valid() {
1578        let proto = verification_protocol();
1579        let store = ThreadedMessageStore::new();
1580        let t = tid("t1");
1581        let result = verify_causal("a", Some(&CausedBy::Begin), &store, &proto, &t);
1582        assert_eq!(result, VerificationResult::Valid);
1583    }
1584
1585    #[test]
1586    fn verify_begin_invalid_not_successor_of_begin() {
1587        let proto = verification_protocol();
1588        let store = ThreadedMessageStore::new();
1589        let t = tid("t1");
1590        // "c" requires predecessor "b", not "begin"
1591        let result = verify_causal("c", Some(&CausedBy::Begin), &store, &proto, &t);
1592        assert!(matches!(
1593            result,
1594            VerificationResult::Violation(CausalViolation::InvalidPredecessor { .. })
1595        ));
1596    }
1597
1598    // ---- Single caused-by ----
1599
1600    #[test]
1601    fn verify_single_valid() {
1602        let proto = verification_protocol();
1603        let mut store = ThreadedMessageStore::new();
1604        let t = tid("t1");
1605        // Put an "a" message in the store
1606        store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
1607        // "b" requires predecessor "a" — h1 is "a" → Valid
1608        let result = verify_causal(
1609            "b",
1610            Some(&CausedBy::Single("h1".into())),
1611            &store,
1612            &proto,
1613            &t,
1614        );
1615        assert_eq!(result, VerificationResult::Valid);
1616    }
1617
1618    #[test]
1619    fn verify_single_unknown_predecessor_not_in_store() {
1620        let proto = verification_protocol();
1621        let store = ThreadedMessageStore::new();
1622        let t = tid("t1");
1623        let result = verify_causal(
1624            "b",
1625            Some(&CausedBy::Single("missing".into())),
1626            &store,
1627            &proto,
1628            &t,
1629        );
1630        assert_eq!(result, VerificationResult::Unknown);
1631    }
1632
1633    #[test]
1634    fn verify_single_wrong_type() {
1635        let proto = verification_protocol();
1636        let mut store = ThreadedMessageStore::new();
1637        let t = tid("t1");
1638        // Put a "c" message in the store
1639        store.append(chash("h1"), t.clone(), make_msg("c", Some(CausedBy::Begin)));
1640        // "b" requires predecessor "a", but h1 is "c" → Violation
1641        let result = verify_causal(
1642            "b",
1643            Some(&CausedBy::Single("h1".into())),
1644            &store,
1645            &proto,
1646            &t,
1647        );
1648        assert!(matches!(
1649            result,
1650            VerificationResult::Violation(CausalViolation::InvalidPredecessor {
1651                found,
1652                ..
1653            }) if found == "c"
1654        ));
1655    }
1656
1657    // ---- Thread isolation (ADR-008) ----
1658
1659    #[test]
1660    fn verify_single_wrong_thread_is_unknown() {
1661        let proto = verification_protocol();
1662        let mut store = ThreadedMessageStore::new();
1663        // Message in thread t1
1664        store.append(chash("h1"), tid("t1"), make_msg("a", Some(CausedBy::Begin)));
1665        // Verify in thread t2 — h1 is not visible → Unknown
1666        let result = verify_causal(
1667            "b",
1668            Some(&CausedBy::Single("h1".into())),
1669            &store,
1670            &proto,
1671            &tid("t2"),
1672        );
1673        assert_eq!(result, VerificationResult::Unknown);
1674    }
1675
1676    // ---- Missing caused-by ----
1677
1678    #[test]
1679    fn verify_missing_caused_by_violation() {
1680        let proto = verification_protocol();
1681        let store = ThreadedMessageStore::new();
1682        let t = tid("t1");
1683        // "b" has predecessors → requires caused-by
1684        let result = verify_causal("b", None, &store, &proto, &t);
1685        assert!(matches!(
1686            result,
1687            VerificationResult::Violation(CausalViolation::MissingCausedBy)
1688        ));
1689    }
1690
1691    #[test]
1692    fn verify_missing_caused_by_ok_when_no_predecessors() {
1693        // "begin" has no predecessors → no caused-by required
1694        let proto = verification_protocol();
1695        let store = ThreadedMessageStore::new();
1696        let t = tid("t1");
1697        let result = verify_causal("begin", None, &store, &proto, &t);
1698        assert_eq!(result, VerificationResult::Valid);
1699    }
1700
1701    // ---- Performative not in protocol ----
1702
1703    #[test]
1704    fn verify_unknown_performative_is_valid() {
1705        let proto = verification_protocol();
1706        let store = ThreadedMessageStore::new();
1707        let t = tid("t1");
1708        let result = verify_causal(
1709            "not-in-protocol",
1710            Some(&CausedBy::Begin),
1711            &store,
1712            &proto,
1713            &t,
1714        );
1715        assert_eq!(result, VerificationResult::Valid);
1716    }
1717
1718    // ---- Fan-in: Multiple caused-by with (all ...) ----
1719
1720    #[test]
1721    fn verify_fan_in_all_valid() {
1722        let proto = fan_in_protocol();
1723        let mut store = ThreadedMessageStore::new();
1724        let t = tid("t1");
1725        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1726        store.append(chash("hy"), t.clone(), make_msg("y", Some(CausedBy::Begin)));
1727        let result = verify_causal(
1728            "z",
1729            Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hy".into()])),
1730            &store,
1731            &proto,
1732            &t,
1733        );
1734        assert_eq!(result, VerificationResult::Valid);
1735    }
1736
1737    #[test]
1738    fn verify_fan_in_one_unknown() {
1739        let proto = fan_in_protocol();
1740        let mut store = ThreadedMessageStore::new();
1741        let t = tid("t1");
1742        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1743        // hy not in store → Unknown (meet absorbs)
1744        let result = verify_causal(
1745            "z",
1746            Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hy".into()])),
1747            &store,
1748            &proto,
1749            &t,
1750        );
1751        assert_eq!(result, VerificationResult::Unknown);
1752    }
1753
1754    #[test]
1755    fn verify_fan_in_wrong_type() {
1756        let proto = fan_in_protocol();
1757        let mut store = ThreadedMessageStore::new();
1758        let t = tid("t1");
1759        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1760        // "wrong" is not in the (all x y) set
1761        store.append(
1762            chash("hw"),
1763            t.clone(),
1764            make_msg("wrong", Some(CausedBy::Begin)),
1765        );
1766        let result = verify_causal(
1767            "z",
1768            Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hw".into()])),
1769            &store,
1770            &proto,
1771            &t,
1772        );
1773        assert!(matches!(
1774            result,
1775            VerificationResult::Violation(CausalViolation::InvalidPredecessor { .. })
1776        ));
1777    }
1778
1779    #[test]
1780    fn verify_fan_in_incomplete() {
1781        let proto = fan_in_protocol();
1782        let mut store = ThreadedMessageStore::new();
1783        let t = tid("t1");
1784        // Only one "x" message, but (all x y) requires both x and y types
1785        store.append(
1786            chash("hx1"),
1787            t.clone(),
1788            make_msg("x", Some(CausedBy::Begin)),
1789        );
1790        store.append(
1791            chash("hx2"),
1792            t.clone(),
1793            make_msg("x", Some(CausedBy::Begin)),
1794        );
1795        let result = verify_causal(
1796            "z",
1797            Some(&CausedBy::Multiple(alloc::vec!["hx1".into(), "hx2".into()])),
1798            &store,
1799            &proto,
1800            &t,
1801        );
1802        assert!(matches!(
1803            result,
1804            VerificationResult::Violation(CausalViolation::IncompleteFanIn { .. })
1805        ));
1806    }
1807
1808    #[test]
1809    fn verify_fan_in_without_all_decl() {
1810        let proto = verification_protocol();
1811        let store = ThreadedMessageStore::new();
1812        let t = tid("t1");
1813        // "b" has Single("a") predecessor, not All — fan-in not declared
1814        let result = verify_causal(
1815            "b",
1816            Some(&CausedBy::Multiple(alloc::vec!["h1".into(), "h2".into()])),
1817            &store,
1818            &proto,
1819            &t,
1820        );
1821        assert!(matches!(
1822            result,
1823            VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl { .. })
1824        ));
1825    }
1826
1827    // ---- Monotonicity: Unknown → Valid after store growth ----
1828
1829    #[test]
1830    fn verify_monotone_unknown_to_valid() {
1831        let proto = verification_protocol();
1832        let mut store = ThreadedMessageStore::new();
1833        let t = tid("t1");
1834
1835        // First check: predecessor not in store → Unknown
1836        let r1 = verify_causal(
1837            "b",
1838            Some(&CausedBy::Single("h1".into())),
1839            &store,
1840            &proto,
1841            &t,
1842        );
1843        assert_eq!(r1, VerificationResult::Unknown);
1844
1845        // Store grows: add the predecessor
1846        store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
1847
1848        // Re-check: now Valid
1849        let r2 = verify_causal(
1850            "b",
1851            Some(&CausedBy::Single("h1".into())),
1852            &store,
1853            &proto,
1854            &t,
1855        );
1856        assert_eq!(r2, VerificationResult::Valid);
1857    }
1858
1859    #[test]
1860    fn verify_monotone_unknown_to_violation() {
1861        let proto = verification_protocol();
1862        let mut store = ThreadedMessageStore::new();
1863        let t = tid("t1");
1864
1865        // First check: predecessor not in store → Unknown
1866        let r1 = verify_causal(
1867            "b",
1868            Some(&CausedBy::Single("h1".into())),
1869            &store,
1870            &proto,
1871            &t,
1872        );
1873        assert_eq!(r1, VerificationResult::Unknown);
1874
1875        // Store grows: add predecessor with wrong type
1876        store.append(chash("h1"), t.clone(), make_msg("c", Some(CausedBy::Begin)));
1877
1878        // Re-check: now Violation
1879        let r2 = verify_causal(
1880            "b",
1881            Some(&CausedBy::Single("h1".into())),
1882            &store,
1883            &proto,
1884            &t,
1885        );
1886        assert!(matches!(r2, VerificationResult::Violation(_)));
1887    }
1888
1889    // ---- Any predecessor (disjunction) ----
1890
1891    #[test]
1892    fn verify_any_predecessor_either_type_valid() {
1893        let mut steps = BTreeMap::new();
1894        let mut any_set = BTreeSet::new();
1895        any_set.insert("x".into());
1896        any_set.insert("y".into());
1897        steps.insert(
1898            "z".into(),
1899            StepDecl {
1900                performative: "z".into(),
1901                predecessors: vec![NodeRef::Any(any_set)],
1902                successors: vec![],
1903            },
1904        );
1905        let proto = CausalProtocol { steps };
1906        let mut store = ThreadedMessageStore::new();
1907        let t = tid("t1");
1908
1909        // Predecessor is "x" — matches (any x y) → Valid
1910        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1911        let r = verify_causal(
1912            "z",
1913            Some(&CausedBy::Single("hx".into())),
1914            &store,
1915            &proto,
1916            &t,
1917        );
1918        assert_eq!(r, VerificationResult::Valid);
1919
1920        // Predecessor is "y" — also matches
1921        store.append(chash("hy"), t.clone(), make_msg("y", Some(CausedBy::Begin)));
1922        let r = verify_causal(
1923            "z",
1924            Some(&CausedBy::Single("hy".into())),
1925            &store,
1926            &proto,
1927            &t,
1928        );
1929        assert_eq!(r, VerificationResult::Valid);
1930    }
1931
1932    // ---- Extraneous predecessor ----
1933
1934    #[test]
1935    fn verify_extraneous_predecessor() {
1936        let mut steps = BTreeMap::new();
1937        steps.insert(
1938            "root".into(),
1939            StepDecl {
1940                performative: "root".into(),
1941                predecessors: vec![],
1942                successors: vec![],
1943            },
1944        );
1945        let proto = CausalProtocol { steps };
1946        let mut store = ThreadedMessageStore::new();
1947        let t = tid("t1");
1948        store.append(chash("h1"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1949        // "root" has no predecessors, but we provide one → ExtraneousPredecessor
1950        let result = verify_causal(
1951            "root",
1952            Some(&CausedBy::Single("h1".into())),
1953            &store,
1954            &proto,
1955            &t,
1956        );
1957        assert!(matches!(
1958            result,
1959            VerificationResult::Violation(CausalViolation::ExtraneousPredecessor { .. })
1960        ));
1961    }
1962
1963    // ---- Statelessness: same inputs → same outputs ----
1964
1965    #[test]
1966    fn verify_is_stateless() {
1967        let proto = verification_protocol();
1968        let mut store = ThreadedMessageStore::new();
1969        let t = tid("t1");
1970        store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
1971
1972        let r1 = verify_causal(
1973            "b",
1974            Some(&CausedBy::Single("h1".into())),
1975            &store,
1976            &proto,
1977            &t,
1978        );
1979        let r2 = verify_causal(
1980            "b",
1981            Some(&CausedBy::Single("h1".into())),
1982            &store,
1983            &proto,
1984            &t,
1985        );
1986        assert_eq!(r1, r2);
1987    }
1988
1989    // ================================================================
1990    // SPEC-015 REQ-702: safety-level verification over envelopes
1991    // ================================================================
1992
1993    use crate::attest::{sign_attestation_v2, AttestationHeader};
1994    use crate::envelope::RedactedEnvelope;
1995    use crate::keyid::KeyId;
1996    use crate::r4::Signer;
1997
1998    /// Data-dependent test signer (as in `attest.rs`): sig = SHA-256(secret
1999    /// ‖ data), so tampering with any authenticated field kills it.
2000    struct TestSigner {
2001        secret: &'static [u8],
2002    }
2003
2004    impl Signer for TestSigner {
2005        fn sign(&self, data: &[u8]) -> Vec<u8> {
2006            use sha2::{Digest, Sha256};
2007            let mut h = Sha256::new();
2008            h.update(self.secret);
2009            h.update(data);
2010            h.finalize().to_vec()
2011        }
2012        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
2013            self.sign(data) == sig
2014        }
2015    }
2016
2017    const SIGNER: TestSigner = TestSigner { secret: b"alice" };
2018
2019    fn signed_env(hash: &str, perf: &str, thread_name: &str) -> RedactedEnvelope {
2020        let mut to = BTreeSet::new();
2021        to.insert(KeyId::parse("@bob").unwrap());
2022        let header = AttestationHeader {
2023            content_hash: hash.into(),
2024            performative: perf.into(),
2025            from: KeyId::parse("@alice").unwrap(),
2026            to,
2027            thread: thread_name.into(),
2028            caused_by: Some(CausedBy::Begin),
2029        };
2030        let signature = sign_attestation_v2(&SIGNER, &header).unwrap();
2031        RedactedEnvelope { header, signature }
2032    }
2033
2034    /// REQ-702: a `:caused-by` reference resolves through an envelope —
2035    /// Unknown before it arrives, then the same safety verdict a full
2036    /// predecessor would give (here Valid), read from the authenticated
2037    /// performative type.
2038    #[test]
2039    fn single_reference_resolves_through_an_envelope() {
2040        let proto = verification_protocol();
2041        let mut store = ThreadedMessageStore::new();
2042        let t = tid("t1");
2043        let msg_b = ("b", Some(CausedBy::Single("h1".into())));
2044
2045        // Nothing yet: Unknown.
2046        assert_eq!(
2047            verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
2048            VerificationResult::Unknown
2049        );
2050
2051        // Envelope of the predecessor `a` arrives: resolves Valid.
2052        store
2053            .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
2054            .unwrap();
2055        assert_eq!(
2056            verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
2057            VerificationResult::Valid
2058        );
2059
2060        // Same verdict as with the full predecessor.
2061        let mut full_store = ThreadedMessageStore::new();
2062        full_store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
2063        assert_eq!(
2064            verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
2065            verify_causal(msg_b.0, msg_b.1.as_ref(), &full_store, &proto, &t),
2066        );
2067    }
2068
2069    /// REQ-702: predecessor *type* checks read the envelope's
2070    /// authenticated performative — a wrong-typed envelope resolves to
2071    /// the same typed Violation a wrong-typed full message would.
2072    #[test]
2073    fn envelope_with_wrong_type_is_the_typed_violation() {
2074        let proto = verification_protocol();
2075        let mut store = ThreadedMessageStore::new();
2076        let t = tid("t1");
2077        store
2078            .append_envelope(signed_env("h1", "c", "t1"), &SIGNER)
2079            .unwrap();
2080        assert_eq!(
2081            verify_causal(
2082                "b",
2083                Some(&CausedBy::Single("h1".into())),
2084                &store,
2085                &proto,
2086                &t
2087            ),
2088            VerificationResult::Violation(CausalViolation::InvalidPredecessor {
2089                caused_by: "h1".into(),
2090                expected: vec!["a".into()],
2091                found: "c".into(),
2092            })
2093        );
2094    }
2095
2096    /// REQ-702: an envelope satisfies references only in its
2097    /// authenticated thread — it is invisible from any other thread.
2098    #[test]
2099    fn envelope_is_scoped_to_its_authenticated_thread() {
2100        let proto = verification_protocol();
2101        let mut store = ThreadedMessageStore::new();
2102        store
2103            .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
2104            .unwrap();
2105        assert_eq!(
2106            verify_causal(
2107                "b",
2108                Some(&CausedBy::Single("h1".into())),
2109                &store,
2110                &proto,
2111                &tid("t2")
2112            ),
2113            VerificationResult::Unknown
2114        );
2115    }
2116
2117    /// A full message and its envelope name the same content hash; when
2118    /// both are present the full message is read (they agree by content
2119    /// addressing, so this is a preference, not a semantic difference).
2120    #[test]
2121    fn full_message_shadows_its_own_envelope() {
2122        let proto = verification_protocol();
2123        let mut store = ThreadedMessageStore::new();
2124        let t = tid("t1");
2125        store
2126            .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
2127            .unwrap();
2128        store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
2129        assert_eq!(
2130            verify_causal(
2131                "b",
2132                Some(&CausedBy::Single("h1".into())),
2133                &store,
2134                &proto,
2135                &t
2136            ),
2137            VerificationResult::Valid
2138        );
2139    }
2140
2141    /// REQ-702 over the R5 fan-in *type* check: envelope members resolve
2142    /// the `(all …)` type completeness (safety level). The completion
2143    /// boundary (REQ-703) is enforced one layer up, in the role layer's
2144    /// occupant fan-in — see `projection.rs`.
2145    #[test]
2146    fn fan_in_type_check_resolves_through_envelopes() {
2147        let proto = fan_in_protocol();
2148        let mut store = ThreadedMessageStore::new();
2149        let t = tid("t1");
2150        // x arrives in full; y only as an envelope.
2151        store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
2152        let z = CausedBy::Multiple(vec!["hx".into(), "hy".into()]);
2153        assert_eq!(
2154            verify_causal("z", Some(&z), &store, &proto, &t),
2155            VerificationResult::Unknown
2156        );
2157        store
2158            .append_envelope(signed_env("hy", "y", "t1"), &SIGNER)
2159            .unwrap();
2160        assert_eq!(
2161            verify_causal("z", Some(&z), &store, &proto, &t),
2162            VerificationResult::Valid
2163        );
2164    }
2165
2166    // ================================================================
2167    // SPEC-017 REQ-813 Stage 3: safety-level verification over OPENED
2168    // envelopes (native field-openings against the signed typed root)
2169    // ================================================================
2170
2171    use crate::envelope::{build_opened, OpenedEnvelope, HEADER_FIELDS};
2172    use crate::keyid::SignatureSuite;
2173    use crate::message::Recipients;
2174
2175    /// A predecessor message typed `perf`, sender `@alice`, thread
2176    /// `thread_name`, and its opened envelope (header fields, payload sealed)
2177    /// plus the typed root that a citing `:caused-by` must name.
2178    fn opened_pred(perf: &str, thread_name: &str) -> (OpenedEnvelope, String) {
2179        let mut to = BTreeSet::new();
2180        to.insert("@bob".to_string());
2181        let m = Message::Simple {
2182            performative: Performative::Custom(perf.into()),
2183            recipient: Some(Recipients::Set(to)),
2184            content: SExpr::Atom(Atom::Str("secret-payload".into())),
2185            params: alloc::vec![],
2186            thread: Some(thread_name.into()),
2187            sender: Some("@alice".into()),
2188            caused_by: Some(CausedBy::Begin),
2189        };
2190        let root = crate::typed_addr::typed_root(&m);
2191        let env = build_opened(&m, &HEADER_FIELDS, &SignatureSuite::Ed25519, &SIGNER).unwrap();
2192        (env, root)
2193    }
2194
2195    /// REQ-813: a `:caused-by` reference resolves through an opened
2196    /// envelope — Unknown before it arrives, then the same safety verdict a
2197    /// full predecessor gives (Valid), read from the authenticated
2198    /// Performative opening, at zero payload disclosure.
2199    #[test]
2200    fn single_reference_resolves_through_an_opened_envelope() {
2201        let proto = verification_protocol();
2202        let mut store = ThreadedMessageStore::new();
2203        let t = tid("t1");
2204        let (env, root) = opened_pred("a", "t1");
2205        let cb = CausedBy::Single(root);
2206
2207        assert_eq!(
2208            verify_causal("b", Some(&cb), &store, &proto, &t),
2209            VerificationResult::Unknown
2210        );
2211        store.append_opened(env, &SIGNER).unwrap();
2212        assert_eq!(
2213            verify_causal("b", Some(&cb), &store, &proto, &t),
2214            VerificationResult::Valid
2215        );
2216    }
2217
2218    /// REQ-813: a wrong-typed opened envelope resolves to the same typed
2219    /// Violation a wrong-typed full message would (predecessor-type check
2220    /// reads the authenticated Performative opening).
2221    #[test]
2222    fn opened_envelope_with_wrong_type_is_the_typed_violation() {
2223        let proto = verification_protocol();
2224        let mut store = ThreadedMessageStore::new();
2225        let t = tid("t1");
2226        let (env, root) = opened_pred("c", "t1"); // 'b' requires 'a', not 'c'
2227        store.append_opened(env, &SIGNER).unwrap();
2228        assert_eq!(
2229            verify_causal(
2230                "b",
2231                Some(&CausedBy::Single(root.clone())),
2232                &store,
2233                &proto,
2234                &t
2235            ),
2236            VerificationResult::Violation(CausalViolation::InvalidPredecessor {
2237                caused_by: root,
2238                expected: vec!["a".into()],
2239                found: "c".into(),
2240            })
2241        );
2242    }
2243
2244    /// REQ-813: an opened envelope satisfies references only in its
2245    /// authenticated thread (its Thread opening) — invisible elsewhere.
2246    #[test]
2247    fn opened_envelope_is_scoped_to_its_authenticated_thread() {
2248        let proto = verification_protocol();
2249        let mut store = ThreadedMessageStore::new();
2250        let (env, root) = opened_pred("a", "t1");
2251        store.append_opened(env, &SIGNER).unwrap();
2252        assert_eq!(
2253            verify_causal(
2254                "b",
2255                Some(&CausedBy::Single(root)),
2256                &store,
2257                &proto,
2258                &tid("t2")
2259            ),
2260            VerificationResult::Unknown
2261        );
2262    }
2263
2264    /// REQ-813 over the R5 fan-in *type* check: opened-envelope members
2265    /// resolve the `(all …)` type completeness (safety level). The
2266    /// completion boundary (REQ-703) is enforced one layer up in the role
2267    /// layer's occupant fan-in (`projection.rs`), which never consults the
2268    /// opened shelf — an opened envelope seals leaf 5 and so can satisfy
2269    /// safety here but never completion there.
2270    #[test]
2271    fn fan_in_type_check_resolves_through_opened_envelopes() {
2272        let proto = fan_in_protocol();
2273        let mut store = ThreadedMessageStore::new();
2274        let t = tid("t1");
2275        let (env_x, root_x) = opened_pred("x", "t1");
2276        let (env_y, root_y) = opened_pred("y", "t1");
2277        let z = CausedBy::Multiple(vec![root_x.clone(), root_y.clone()]);
2278
2279        store.append_opened(env_x, &SIGNER).unwrap();
2280        assert_eq!(
2281            verify_causal("z", Some(&z), &store, &proto, &t),
2282            VerificationResult::Unknown,
2283            "one member still missing"
2284        );
2285        store.append_opened(env_y, &SIGNER).unwrap();
2286        assert_eq!(
2287            verify_causal("z", Some(&z), &store, &proto, &t),
2288            VerificationResult::Valid
2289        );
2290    }
2291}