Skip to main content

cbcl_core/
projection.rs

1//! Endpoint projection and role-local verification (SPEC-014
2//! REQ-609..620, 623, 626; CON-602).
3//!
4//! [`project`] derives a role's local protocol from a role-annotated
5//! dialect as a pure function: every agent holding the same dialect (and,
6//! for indexed roles, the same sealed cast) computes the same local
7//! protocols — the choreographer is replicated at every endpoint.
8//!
9//! [`verify_causal_for_role`] is the runtime monitor: the lattice meet of a
10//! role-conformance check with the *unchanged* R5 `verify_causal` run
11//! against the dialect-level protocol (ADR-604), plus the one check the
12//! role layer adds rather than reuses: the occupant-counted `(all …)`
13//! fan-in (REQ-618). Projection keeps raw `:caused-by` edges (REQ-610):
14//! under R6(vi) the bystander splice is vacuous, so no rewritten
15//! predecessor view exists.
16//!
17//! Root typing (REQ-623, ADR-603): traces name the thread root *by hash*
18//! (`:caused-by h₀`) while protocol clauses name `begin`; the composition
19//! maps a reference that resolves to the thread's `with-roles` wrapper to
20//! the `begin` predecessor type before delegating to R5.
21
22#![forbid(unsafe_code)]
23
24use crate::dialect::Dialect;
25use crate::message::{CausedBy, Message, WrapperType};
26use crate::protocol::{
27    verify_causal, CausalProtocol, CausalViolation, NodeRef, VerificationResult,
28};
29use crate::role::{parse_wrapper_cast, AgentKey, Cast, Endpoint, R6Violation, RoleAnnotation};
30use crate::sexpr::{Atom, SExpr};
31use crate::store::{ContentHash, MessageStore, ThreadId};
32use alloc::collections::{BTreeMap, BTreeSet};
33use alloc::format;
34use alloc::string::String;
35use alloc::vec::Vec;
36
37/// A step of a local protocol, from one endpoint's viewpoint (CON-602).
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub enum LocalStep {
41    /// The endpoint's role is the performative's sender.
42    Send,
43    /// The endpoint's role is among the performative's recipients.
44    Recv,
45}
46
47/// A role's local protocol: its Send/Recv steps plus the dialect-level
48/// causal protocol, predecessor clauses untouched (raw edges, REQ-610).
49#[derive(Debug, Clone, PartialEq, Eq)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51pub struct LocalProtocol {
52    /// Performative name → step kind; bystander performatives are erased
53    /// (absent).
54    pub steps: BTreeMap<String, LocalStep>,
55    /// ExpectEnvelope steps (SPEC-015 REQ-709): the performatives whose
56    /// *redacted envelopes* this endpoint awaits under a
57    /// `(:causal-locality derive)` dialect — a Recv-analogue carrying no
58    /// payload obligation, one per derived route naming this endpoint.
59    ///
60    /// A separate step set, not a [`LocalStep`] variant in `steps`: a
61    /// per-occupant endpoint of an indexed role can hold *both* Send (its
62    /// own instance) and ExpectEnvelope (its co-occupants' instances) for
63    /// one performative type, which a single-valued step map cannot
64    /// express. Send/Recv steps and payload delivery are untouched; empty
65    /// under `reject` (the v1 reading, bit-for-bit).
66    #[cfg_attr(feature = "serde", serde(default))]
67    pub expect_envelopes: BTreeSet<String>,
68    /// The dialect-level protocol the R5 composition verifies against
69    /// (ADR-604); shared verbatim across all endpoints.
70    pub protocol: Option<CausalProtocol>,
71}
72
73/// Endpoint projection (REQ-609): a pure function of the dialect and the
74/// endpoint. A performative whose `:from` is the endpoint's role becomes a
75/// [`LocalStep::Send`]; one whose `:to` contains it becomes a
76/// [`LocalStep::Recv`]; one in which the role is no endpoint is erased,
77/// with no predecessor reference rewritten (the splice is vacuous under
78/// R6(vi)).
79///
80/// `cast` is accepted for per-occupant instantiation (CON-602). The
81/// Send/Recv step set is identical across an indexed role's occupants;
82/// under a `(:causal-locality derive)` dialect the cast additionally
83/// drives the thread-open half of the envelope-route derivation (SPEC-015
84/// REQ-709), whose ExpectEnvelope steps *are* occupant-dependent.
85pub fn project(d: &Dialect, endpoint: &Endpoint, cast: Option<&Cast>) -> LocalProtocol {
86    let mut steps: BTreeMap<String, LocalStep> = BTreeMap::new();
87    for p in &d.performatives {
88        if let Some(ann) = &p.role {
89            if ann.from == endpoint.role {
90                steps.insert(p.name.clone(), LocalStep::Send);
91            } else if ann.to.contains(&endpoint.role) {
92                steps.insert(p.name.clone(), LocalStep::Recv);
93            }
94        }
95    }
96    // ExpectEnvelope steps (REQ-709): one per derived route naming this
97    // endpoint. Under the default `reject` this set is empty and the
98    // projection is the v1 function bit-for-bit.
99    let mut expect_envelopes: BTreeSet<String> = BTreeSet::new();
100    if let crate::role::CausalLocality::Derive(table) = &d.causal_locality {
101        // Install-time (dialect-level) routes: role-addressed.
102        for (perf, roles) in &table.0 {
103            if roles.contains(&endpoint.role) {
104                expect_envelopes.insert(perf.clone());
105            }
106        }
107        // Thread-open (per-occupant) routes: derived here as a pure
108        // function of dialect and sealed cast — the same table every
109        // agent computes (REQ-709) — and read for this endpoint's
110        // occupant.
111        if let (Some(cast), Some(occupant)) = (cast, &endpoint.occupant) {
112            let occ = crate::r6::derive_occupant_envelope_routes(d, cast);
113            for (perf, keys) in &occ.0 {
114                if keys.contains(occupant) {
115                    expect_envelopes.insert(perf.clone());
116                }
117            }
118        }
119    }
120    LocalProtocol {
121        steps,
122        expect_envelopes,
123        protocol: d.causal_protocol.clone(),
124    }
125}
126
127/// The key a message is *ratified* under: the key of an enclosing `signed`
128/// wrapper (REQ-612, ratification-by-signature). Deliberately does **not**
129/// fall back to the innermost `:sender` field — that field is a self-asserted,
130/// unauthenticated claim, so trusting it would let an unsigned message occupy
131/// a role (a forgery path). A message with no `signed` wrapper has no
132/// ratifying key and cannot occupy a sender role.
133fn signer_of(msg: &Message) -> Option<&str> {
134    let mut cur = msg;
135    loop {
136        match cur {
137            Message::Wrapped {
138                wrapper: WrapperType::Signed,
139                params,
140                content,
141            } => {
142                if let Some(SExpr::Atom(Atom::Symbol(s))) = params.first() {
143                    return Some(s.as_str());
144                }
145                cur = content;
146            }
147            Message::Wrapped { content, .. } => cur = content,
148            Message::Dialect { inner, .. } => cur = inner,
149            // No signed wrapper enclosed this payload: no ratifying key.
150            Message::Simple { .. } | Message::Meta { .. } => return None,
151        }
152    }
153}
154
155fn role_violation(reason: String) -> VerificationResult {
156    VerificationResult::Violation(CausalViolation::RoleConformance { reason })
157}
158
159/// The keys the cast expects as recipients for an annotation's `:to` set:
160/// the singleton key per singleton role, every sealed occupant per indexed
161/// role.
162fn expected_recipient_keys<'a>(ann: &RoleAnnotation, cast: &'a Cast) -> BTreeSet<&'a str> {
163    let mut keys: BTreeSet<&str> = BTreeSet::new();
164    for role in &ann.to {
165        if let Some(k) = cast.singleton.get(role) {
166            keys.insert(k.0.as_str());
167        }
168        if let Some(ks) = cast.indexed.get(role) {
169            keys.extend(ks.iter().map(|k| k.0.as_str()));
170        }
171    }
172    keys
173}
174
175/// Role-local verification (REQ-612..620, 623, 626, 628; CON-602): the
176/// lattice meet of role conformance, the unchanged R5 predecessor check
177/// against the dialect-level protocol, and the occupant-counted fan-in,
178/// gated by the root's dialect pin when one is present.
179pub fn verify_causal_for_role<S: MessageStore>(
180    msg: &Message,
181    endpoint: &Endpoint,
182    d: &Dialect,
183    cast: &Cast,
184    store: &S,
185    thread: &ThreadId,
186    root: &ContentHash,
187) -> VerificationResult {
188    let _ = endpoint; // the verdict is endpoint-independent in v1 (exact
189                      // conformance); the parameter fixes the caller's view
190
191    // REQ-628: dialect pin. When the thread's root cast pins the governing
192    // dialect's content hash and the verifier's installed dialect carries
193    // its hash (DialectRegistry::install populates it), the two must agree —
194    // otherwise this verifier would check the thread against a different
195    // protocol than the root named, so every message of the thread is a
196    // Violation. An unpinned cast (`dialect_pin: None`) is accepted as-is:
197    // the spec's transition plan is warn-then-reject, and the verdict
198    // lattice (Unknown/Valid/Violation) has no warning level to carry the
199    // "warn" half, so this release accepts silently.
200    // SIMPLIFY: when the transition window closes, reject `None` pins here
201    // (and surface a warning signal in the interim if one is added).
202    if let (Some(pinned), Some(installed)) = (cast.dialect_pin.as_deref(), d.hash.as_deref()) {
203        if pinned != installed {
204            return role_violation(format!(
205                "{}",
206                R6Violation::DialectPinMismatch {
207                    pinned: String::from(pinned),
208                    installed: String::from(installed),
209                }
210            ));
211        }
212    }
213
214    // REQ-613: a with-roles wrapper is legal only as the thread's root,
215    // carrying the thread's one cast.
216    if msg.wrapper_type() == Some(WrapperType::WithRoles) {
217        return verify_cast_wrapper(msg, d, cast, store, thread, root);
218    }
219
220    let Some(simple) = msg.innermost_simple() else {
221        // Meta messages carry no role obligations.
222        return VerificationResult::Valid;
223    };
224    let perf = match simple.performative() {
225        Some(p) => p.name(),
226        None => return VerificationResult::Valid,
227    };
228    let annotation = d.find_performative(perf).and_then(|p| p.role.as_ref());
229
230    // (i) Role conformance (REQ-612/615/626).
231    let conformance = match annotation {
232        Some(ann) => check_conformance(msg, simple, ann, cast),
233        // Unannotated performative: no role obligation (R6 guarantees
234        // protocol performatives are annotated in installed dialects).
235        None => VerificationResult::Valid,
236    };
237    if let VerificationResult::Violation(_) = conformance {
238        return conformance;
239    }
240
241    // (iii) R5 predecessor-type check against the dialect-level protocol
242    // (ADR-604), with root typing (REQ-623) applied to the references.
243    let caused_by = simple.caused_by().cloned();
244    let rewritten = caused_by
245        .as_ref()
246        .map(|cb| rewrite_root_references(cb, root));
247    let r5 = match &d.causal_protocol {
248        Some(protocol) if crate::repeat::has_repeat(protocol) => crate::repeat::verify(
249            perf,
250            caused_by.as_ref(),
251            store,
252            protocol,
253            thread,
254            Some(root),
255        ),
256        Some(protocol) => verify_causal(perf, rewritten.as_ref(), store, protocol, thread),
257        None => VerificationResult::Valid,
258    };
259
260    // (ii+) Occupant-counted fan-in (REQ-618) — the one extension over R5.
261    let fanin = repeat_occupant_fanin(perf, caused_by.as_ref(), d, cast, store, thread, root);
262
263    conformance.meet(r5).meet(fanin)
264}
265
266/// REQ-613: verify a `with-roles` wrapper. It is legal only as *the*
267/// thread root: the caller-supplied `root` hash must resolve to a
268/// `with-roles` wrapper equal to this one, its inner message must open the
269/// thread (`:caused-by begin`), and its bindings must denote exactly the
270/// thread's root cast. A second/mid-thread wrapper — one whose content
271/// differs from the message stored at `root` — is a `Violation` (binding is
272/// immutable for the life of the thread).
273fn verify_cast_wrapper<S: MessageStore>(
274    msg: &Message,
275    d: &Dialect,
276    cast: &Cast,
277    store: &S,
278    thread: &ThreadId,
279    root: &ContentHash,
280) -> VerificationResult {
281    let Message::Wrapped {
282        params, content, ..
283    } = msg
284    else {
285        unreachable!("guarded by wrapper_type");
286    };
287    // Exact shape (CON-601, REQ-628): the wrapper is `(with-roles
288    // (<bindings>) [:dialect f1220<hex64>] <signed-form>)` — the bindings
289    // list, then at most the optional dialect pin, no more. A malformed pin
290    // is a parse rejection, never repaired (LangSec principle 4).
291    let parsed = match parse_wrapper_cast(params, &d.roles) {
292        Ok(c) => c,
293        Err(v) => return role_violation(format!("{v}")),
294    };
295    if &parsed != cast {
296        return role_violation(String::from(
297            "with-roles wrapper does not match the thread's root cast (REQ-613)",
298        ));
299    }
300    // The payload MUST be the existing `signed` form (CON-601): the cast is
301    // ratified by the initiator's signature, so an unsigned root is not a
302    // valid nomination. Reject anything whose immediate content is not a
303    // signed wrapper before accepting the cast (REQ-611).
304    if !matches!(
305        content.as_ref(),
306        Message::Wrapped {
307            wrapper: WrapperType::Signed,
308            ..
309        }
310    ) {
311        return role_violation(String::from(
312            "with-roles payload must be a signed message (CON-601)",
313        ));
314    }
315    // Root uniqueness (REQ-613): if the store already holds the thread's
316    // root, this wrapper is legal only if it *is* that root message. A
317    // distinct wrapper (a forged or duplicate root) is rejected, which also
318    // stops it being referenced-as-root by a re-parenting attack.
319    if let Some(root_msg) = store.lookup_in_thread(root, thread) {
320        if root_msg != msg {
321            return role_violation(String::from(
322                "a second with-roles wrapper is not the thread root (REQ-613)",
323            ));
324        }
325    }
326    match content.innermost_simple().and_then(|m| m.caused_by()) {
327        Some(CausedBy::Begin) => VerificationResult::Valid,
328        _ => role_violation(String::from(
329            "with-roles wrapper must be the thread's causal root (REQ-613)",
330        )),
331    }
332}
333
334/// REQ-612/615/626: sender key equals the cast binding for the `:from`
335/// role; recipient keys equal the cast's keys for the `:to` set exactly.
336fn check_conformance(
337    outer: &Message,
338    simple: &Message,
339    ann: &RoleAnnotation,
340    cast: &Cast,
341) -> VerificationResult {
342    // Sender (REQ-612): ratification by signature — the sender key must be
343    // one the cast admits for the sender role. Receive-only roles never
344    // send, so this clause never fires for them (REQ-626).
345    let Some(sender) = signer_of(outer) else {
346        return role_violation(String::from("role-annotated message carries no sender key"));
347    };
348    if !cast.admits(&ann.from, &AgentKey(String::from(sender))) {
349        return role_violation(format!(
350            "sender '{sender}' is not the cast's occupant of role '{}' (REQ-612)",
351            ann.from
352        ));
353    }
354    // Recipients (REQ-615): exact conformance, no subtyping (v1).
355    let expected = expected_recipient_keys(ann, cast);
356    let actual = simple.recipient_set();
357    if expected != actual {
358        return role_violation(format!(
359            "recipients {actual:?} do not match the cast keys {expected:?} for :to roles {:?} (REQ-615)",
360            ann.to
361        ));
362    }
363    VerificationResult::Valid
364}
365
366/// REQ-623 (root typing): rewrite a `:caused-by` reference to the thread's
367/// *genuine* root (the caller-supplied `root` hash) into the `begin`
368/// predecessor type. Scoped to the exact root hash — not "any stored
369/// `with-roles` wrapper" — so a forged mid-thread wrapper cannot be
370/// referenced-as-root to smuggle a message in as a first step. A `Multiple`
371/// is only ever a fan-in over non-root predecessors in v1, so it is left
372/// untouched (mixing the root into a fan-in has no v1 use and would type
373/// inconsistently otherwise).
374fn rewrite_root_references(cb: &CausedBy, root: &ContentHash) -> CausedBy {
375    match cb {
376        CausedBy::Single(h) if h == &root.0 => CausedBy::Begin,
377        other => other.clone(),
378    }
379}
380
381// Copy positions and indexed-role coverage must agree on the SAME candidate.
382fn repeat_occupant_fanin<S: MessageStore>(
383    perf: &str,
384    caused_by: Option<&CausedBy>,
385    d: &Dialect,
386    cast: &Cast,
387    store: &S,
388    thread: &ThreadId,
389    root: &ContentHash,
390) -> VerificationResult {
391    let Some(cp) = d
392        .causal_protocol
393        .as_ref()
394        .filter(|p| crate::repeat::has_repeat(p))
395    else {
396        return occupant_fanin(perf, caused_by, d, cast, store, thread, None);
397    };
398    let hashes = match caused_by {
399        Some(CausedBy::Single(h)) => alloc::vec![h.clone()],
400        Some(CausedBy::Multiple(hs)) => hs.clone(),
401        _ => Vec::new(),
402    };
403    let resolution = crate::repeat::Resolution::new(store, cp, thread, Some(root), hashes);
404    let mut result = None;
405    for (name, step) in &cp.steps {
406        if crate::protocol::repeat_base_name(name) != perf
407            || !matches!(resolution.step(step, caused_by), VerificationResult::Valid)
408        {
409            continue;
410        }
411        let value = occupant_fanin(name, caused_by, d, cast, store, thread, Some(&resolution));
412        match value {
413            VerificationResult::Valid => return value,
414            VerificationResult::Unknown => result = Some(value),
415            _ if !matches!(result, Some(VerificationResult::Unknown)) => result = Some(value),
416            _ => {}
417        }
418    }
419    // No causally valid candidate: R5 already supplies Unknown or Violation.
420    result.unwrap_or(VerificationResult::Valid)
421}
422
423/// REQ-618: occupant-counted `(all …)` fan-in. While any referenced
424/// predecessor is absent the verdict is `Unknown` (R5 reports the same);
425/// once all references resolve, the present referenced instances of each
426/// indexed-sender predecessor type must include a distinct cast-admitted
427/// sender for *every* sealed occupant, else `Violation` — permanent from
428/// resolution (REQ-620).
429fn occupant_fanin<S: MessageStore>(
430    perf: &str,
431    caused_by: Option<&CausedBy>,
432    d: &Dialect,
433    cast: &Cast,
434    store: &S,
435    thread: &ThreadId,
436    resolution: Option<&crate::repeat::Resolution<'_, S>>,
437) -> VerificationResult {
438    let Some(cp) = &d.causal_protocol else {
439        return VerificationResult::Valid;
440    };
441    let Some(step) = cp.steps.get(perf) else {
442        return VerificationResult::Valid;
443    };
444
445    // Indexed-sender predecessor types inside (all …) fan-ins.
446    let mut counted: Vec<(&str, &BTreeSet<AgentKey>)> = Vec::new();
447    for nr in &step.predecessors {
448        let NodeRef::All(preds) = nr else { continue };
449        for pred in preds {
450            let Some(p_ann) = d
451                .find_performative(crate::protocol::repeat_base_name(pred))
452                .and_then(|p| p.role.as_ref())
453            else {
454                continue;
455            };
456            // The cast holds a sealed membership only for indexed roles, so a
457            // `Some` here already means `p_ann.from` is an indexed sender — no
458            // separate cardinality check against `d.roles` is needed.
459            if let Some(occupants) = cast.indexed.get(&p_ann.from) {
460                counted.push((pred.as_str(), occupants));
461            }
462        }
463    }
464    if counted.is_empty() {
465        return VerificationResult::Valid;
466    }
467
468    // An occupant fan-in is only meaningful over a `(h1 h2 …)` reference.
469    // With a single or absent `:caused-by`, this is not a well-formed
470    // fan-in message at all — defer to R5, which reports the accurate
471    // `MissingCausedBy`/`InvalidPredecessor`, rather than mislabelling it
472    // as an occupant-coverage failure.
473    let CausedBy::Multiple(hs) = (match caused_by {
474        Some(cb) => cb,
475        None => return VerificationResult::Valid,
476    }) else {
477        return VerificationResult::Valid;
478    };
479    let hashes: Vec<&str> = hs.iter().map(String::as_str).collect();
480    let mut resolved: Vec<(&str, &Message)> = Vec::new();
481    for h in &hashes {
482        match store.lookup_in_thread(&ContentHash(String::from(*h)), thread) {
483            Some(m) => resolved.push((h, m)),
484            // SPEC-015 REQ-703: completion requires content. Only full
485            // messages enter `resolved` — a member present solely as a
486            // redacted envelope (`store.envelope_in_thread`) is deliberately
487            // NOT consulted here, because fan-in membership is "present and
488            // Valid" and full validity includes payload grammaticality. The
489            // decider's verdict stays Unknown (not-yet-complete) until the
490            // full members arrive, which is monotone-safe; the envelope
491            // satisfies only the safety-level type checks of R5
492            // (`protocol::predecessor_type`, REQ-702).
493            None => return VerificationResult::Unknown,
494        }
495    }
496
497    for (pred_type, occupants) in counted {
498        let mut senders: BTreeSet<&str> = BTreeSet::new();
499        for (hash, m) in &resolved {
500            let Some(simple) = m.innermost_simple() else {
501                continue;
502            };
503            if match resolution {
504                Some(r) => !matches!(r.at(hash, pred_type), VerificationResult::Valid),
505                None => simple.performative().map(|p| p.name()) != Some(pred_type),
506            } {
507                continue;
508            }
509            if let Some(k) = signer_of(m) {
510                // Count only cast-admitted instances (REQ-618).
511                if occupants.contains(&AgentKey(String::from(k))) {
512                    senders.insert(k);
513                }
514            }
515        }
516        let missing: Vec<&str> = occupants
517            .iter()
518            .map(|k| k.0.as_str())
519            .filter(|k| !senders.contains(*k))
520            .collect();
521        if !missing.is_empty() {
522            return role_violation(format!(
523                "fan-in over '{pred_type}' lacks instances from sealed occupant(s) {missing:?} (REQ-618)"
524            ));
525        }
526    }
527    VerificationResult::Valid
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use crate::dialect::{Dialect, PerformativeDef, ResourceBounds};
534    use crate::protocol::StepDecl;
535    use crate::role::{parse_cast, parse_roles};
536    use crate::store::ThreadedMessageStore;
537    use alloc::string::ToString;
538    use alloc::vec;
539
540    fn perf(name: &str, from: &str, to: &[&str]) -> PerformativeDef {
541        PerformativeDef {
542            name: name.to_string(),
543            params: Vec::new(),
544            template: SExpr::Atom(Atom::Symbol("t".to_string())),
545            role: Some(RoleAnnotation {
546                from: from.to_string(),
547                to: to.iter().map(|s| s.to_string()).collect(),
548            }),
549        }
550    }
551
552    fn single(name: &str) -> NodeRef {
553        NodeRef::Single(name.to_string())
554    }
555
556    fn any(names: &[&str]) -> NodeRef {
557        NodeRef::Any(names.iter().map(|s| s.to_string()).collect())
558    }
559
560    fn all_of(names: &[&str]) -> NodeRef {
561        NodeRef::All(names.iter().map(|s| s.to_string()).collect())
562    }
563
564    fn step(name: &str, preds: Vec<NodeRef>, succs: Vec<NodeRef>) -> (String, StepDecl) {
565        (
566            name.to_string(),
567            StepDecl {
568                performative: name.to_string(),
569                predecessors: preds,
570                successors: succs,
571            },
572        )
573    }
574
575    fn dialect(
576        roles_src: &str,
577        perfs: Vec<PerformativeDef>,
578        steps: Vec<(String, StepDecl)>,
579    ) -> Dialect {
580        Dialect {
581            types: Default::default(),
582            roles: parse_roles(&roles_src.parse::<SExpr>().unwrap()).unwrap(),
583            state: None,
584            state_bounds: None,
585            causal_locality: Default::default(),
586            name: "test".to_string(),
587            extends: Vec::new(),
588            author: None,
589            performatives: perfs,
590            resources: ResourceBounds {
591                max_depth: 8,
592                max_expansion_size: 512,
593            },
594            examples: Vec::new(),
595            signature: None,
596            hash: None,
597            protocol: None,
598            causal_protocol: Some(CausalProtocol {
599                steps: steps.into_iter().collect(),
600            }),
601            shapes: Vec::new(),
602        }
603    }
604
605    /// The widened OAuth dialect of the paper (R6-clean).
606    fn oauth() -> Dialect {
607        dialect(
608            "(server client authoriser)",
609            vec![
610                perf("login", "server", &["client", "authoriser"]),
611                perf("abort", "server", &["client", "authoriser"]),
612                perf("passwd", "client", &["authoriser", "server"]),
613                perf("auth", "authoriser", &["server"]),
614                perf("quit", "client", &["authoriser"]),
615            ],
616            vec![
617                step("begin", vec![], vec![any(&["login", "abort"])]),
618                step("login", vec![single("begin")], vec![single("passwd")]),
619                step("abort", vec![single("begin")], vec![single("quit")]),
620                step("passwd", vec![single("login")], vec![single("auth")]),
621                step("auth", vec![single("passwd")], vec![]),
622                step("quit", vec![single("abort")], vec![]),
623            ],
624        )
625    }
626
627    fn oauth_cast(d: &Dialect) -> Cast {
628        parse_cast(
629            &"((server @srv) (client @cli) (authoriser @as))"
630                .parse::<SExpr>()
631                .unwrap(),
632            &d.roles,
633        )
634        .unwrap()
635    }
636
637    fn ep(role: &str) -> Endpoint {
638        Endpoint {
639            role: role.to_string(),
640            occupant: None,
641        }
642    }
643
644    fn msg(src: &str) -> Message {
645        Message::try_from(&src.parse::<SExpr>().unwrap()).unwrap()
646    }
647
648    fn tid() -> ThreadId {
649        ThreadId("conv".to_string())
650    }
651
652    fn put(store: &mut ThreadedMessageStore, h: &str, m: &Message) {
653        store.append(ContentHash(h.to_string()), tid(), m.clone());
654    }
655
656    fn oauth_h0() -> Message {
657        msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @srv \"sig\" (hello :thread \"conv\" :caused-by begin)))")
658    }
659
660    // ---- REQ-609/610 / TEST-609/610/630: projection ----
661
662    #[test]
663    fn only_exact_single_root_reference_is_typed_as_begin() {
664        let root = ContentHash("root".into());
665        assert_eq!(
666            rewrite_root_references(&CausedBy::Single("root".into()), &root),
667            CausedBy::Begin
668        );
669        for reference in [
670            CausedBy::Begin,
671            CausedBy::Single("other".into()),
672            CausedBy::Multiple(vec!["root".into(), "other".into()]),
673        ] {
674            assert_eq!(rewrite_root_references(&reference, &root), reference);
675        }
676    }
677
678    #[test]
679    fn oauth_projections_match_the_paper() {
680        let d = oauth();
681        let server = project(&d, &ep("server"), None);
682        assert_eq!(server.steps.get("login"), Some(&LocalStep::Send));
683        assert_eq!(server.steps.get("abort"), Some(&LocalStep::Send));
684        assert_eq!(server.steps.get("passwd"), Some(&LocalStep::Recv));
685        assert_eq!(server.steps.get("auth"), Some(&LocalStep::Recv));
686        assert_eq!(server.steps.get("quit"), None, "bystander erased");
687
688        let client = project(&d, &ep("client"), None);
689        assert_eq!(client.steps.get("passwd"), Some(&LocalStep::Send));
690        assert_eq!(client.steps.get("quit"), Some(&LocalStep::Send));
691        assert_eq!(client.steps.get("login"), Some(&LocalStep::Recv));
692        assert_eq!(client.steps.get("auth"), None, "bystander erased");
693
694        let authoriser = project(&d, &ep("authoriser"), None);
695        assert_eq!(authoriser.steps.get("auth"), Some(&LocalStep::Send));
696        assert_eq!(authoriser.steps.get("passwd"), Some(&LocalStep::Recv));
697        assert_eq!(authoriser.steps.get("quit"), Some(&LocalStep::Recv));
698    }
699
700    #[test]
701    fn projection_keeps_raw_predecessor_clauses() {
702        let d = oauth();
703        for role in ["server", "client", "authoriser"] {
704            let local = project(&d, &ep(role), None);
705            assert_eq!(local.protocol, d.causal_protocol, "raw edges (REQ-610)");
706        }
707    }
708
709    #[test]
710    fn projection_is_deterministic() {
711        let d = oauth();
712        assert_eq!(
713            project(&d, &ep("client"), None),
714            project(&d, &ep("client"), None)
715        );
716    }
717
718    // ---- SPEC-015 REQ-709 / TEST-709: ExpectEnvelope steps ----
719
720    /// The paper's OAuth fragment *as written* (R6(vi)-failing), with the
721    /// dialect-level closure recorded as `DialectRegistry::install` would
722    /// under `(:causal-locality derive)`.
723    fn derived_oauth() -> Dialect {
724        let mut d = dialect(
725            "(server client authoriser)",
726            vec![
727                perf("login", "server", &["client"]),
728                perf("abort", "server", &["client"]),
729                perf("passwd", "client", &["authoriser"]),
730                perf("auth", "authoriser", &["server"]),
731                perf("quit", "client", &["authoriser"]),
732            ],
733            vec![
734                step("begin", vec![], vec![any(&["login", "abort"])]),
735                step("login", vec![single("begin")], vec![single("passwd")]),
736                step("abort", vec![single("begin")], vec![single("quit")]),
737                step("passwd", vec![single("login")], vec![single("auth")]),
738                step("auth", vec![single("passwd")], vec![]),
739                step("quit", vec![single("abort")], vec![]),
740            ],
741        );
742        d.causal_locality =
743            crate::role::CausalLocality::Derive(crate::r6::derive_envelope_routes(&d));
744        d
745    }
746
747    #[test]
748    fn reject_mode_projection_has_no_envelope_steps() {
749        // The v1 reading, bit-for-bit: under the default `reject` no
750        // ExpectEnvelope step exists for any endpoint.
751        let d = oauth();
752        for role in ["server", "client", "authoriser"] {
753            assert!(project(&d, &ep(role), None).expect_envelopes.is_empty());
754        }
755    }
756
757    #[test]
758    fn derived_projection_emits_expect_envelope_per_route() {
759        let d = derived_oauth();
760        // Routes: login ⇒ authoriser, abort ⇒ authoriser, passwd ⇒ server.
761        let authoriser = project(&d, &ep("authoriser"), None);
762        let expected: BTreeSet<String> = ["login", "abort"].iter().map(|s| s.to_string()).collect();
763        assert_eq!(authoriser.expect_envelopes, expected);
764        let server = project(&d, &ep("server"), None);
765        let expected: BTreeSet<String> = ["passwd"].iter().map(|s| s.to_string()).collect();
766        assert_eq!(server.expect_envelopes, expected);
767        // client is on no derived route.
768        assert!(project(&d, &ep("client"), None).expect_envelopes.is_empty());
769    }
770
771    #[test]
772    fn expect_envelope_leaves_send_recv_steps_untouched() {
773        // The Send/Recv step map of the derived dialect equals the
774        // unwidened v1 projection — payload delivery is untouched.
775        let d = derived_oauth();
776        let mut v1 = d.clone();
777        v1.causal_locality = crate::role::CausalLocality::Reject;
778        for role in ["server", "client", "authoriser"] {
779            assert_eq!(
780                project(&d, &ep(role), None).steps,
781                project(&v1, &ep(role), None).steps,
782            );
783        }
784    }
785
786    #[test]
787    fn per_occupant_expect_envelope_steps_come_from_the_sealed_cast() {
788        // The announcing auction: declare-winner :to bidder passes
789        // dialect-level R6(vi), so the install table is empty and the
790        // ExpectEnvelope steps exist only for occupant endpoints under a
791        // sealed cast (thread open) — covering the widened prefix
792        // (commit), not just reveal.
793        let mut d = dialect(
794            "(auctioneer (* bidder))",
795            vec![
796                perf("commit", "bidder", &["auctioneer"]),
797                perf("reveal", "bidder", &["auctioneer"]),
798                perf("declare-winner", "auctioneer", &["bidder"]),
799            ],
800            vec![
801                step("begin", vec![], vec![single("commit")]),
802                step("commit", vec![single("begin")], vec![single("reveal")]),
803                step("reveal", vec![single("commit")], vec![]),
804                step("declare-winner", vec![all_of(&["reveal"])], vec![]),
805            ],
806        );
807        d.causal_locality =
808            crate::role::CausalLocality::Derive(crate::r6::derive_envelope_routes(&d));
809        let cast = auction_cast(&d);
810
811        // Occupant endpoint at thread open: awaits co-occupant envelopes
812        // of reveal AND commit — while still *sending* its own instances.
813        let b1 = Endpoint {
814            role: "bidder".to_string(),
815            occupant: Some(AgentKey("@b1".to_string())),
816        };
817        let local = project(&d, &b1, Some(&cast));
818        let expected: BTreeSet<String> =
819            ["commit", "reveal"].iter().map(|s| s.to_string()).collect();
820        assert_eq!(local.expect_envelopes, expected);
821        assert_eq!(local.steps.get("commit"), Some(&LocalStep::Send));
822        assert_eq!(local.steps.get("reveal"), Some(&LocalStep::Send));
823
824        // Without a cast (before thread open) the per-occupant routes
825        // cannot exist yet; the auctioneer is on no route either way.
826        assert!(project(&d, &b1, None).expect_envelopes.is_empty());
827        let auc = project(&d, &ep("auctioneer"), Some(&cast));
828        assert!(auc.expect_envelopes.is_empty());
829    }
830
831    // ---- REQ-623 / TEST-623: root typing ----
832
833    #[test]
834    fn first_step_naming_root_hash_verifies() {
835        let d = oauth();
836        let cast = oauth_cast(&d);
837        let mut store = ThreadedMessageStore::new();
838        put(&mut store, "h0", &oauth_h0());
839        let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
840        assert_eq!(
841            verify_causal_for_role(
842                &h1,
843                &ep("client"),
844                &d,
845                &cast,
846                &store,
847                &tid(),
848                &ContentHash("h0".to_string())
849            ),
850            VerificationResult::Valid
851        );
852    }
853
854    // ---- REQ-612/615 / TEST-612/615: conformance ----
855
856    #[test]
857    fn non_nominee_cannot_squat_a_role() {
858        let d = oauth();
859        let cast = oauth_cast(&d);
860        let mut store = ThreadedMessageStore::new();
861        put(&mut store, "h0", &oauth_h0());
862        let evil = msg("(signed @evil \"sig\" (lang test (login (@as @cli) \"n\" :caused-by h0)))");
863        assert!(matches!(
864            verify_causal_for_role(
865                &evil,
866                &ep("client"),
867                &d,
868                &cast,
869                &store,
870                &tid(),
871                &ContentHash("h0".to_string())
872            ),
873            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
874        ));
875    }
876
877    #[test]
878    fn narrowed_recipients_violate_conformance() {
879        let d = oauth();
880        let cast = oauth_cast(&d);
881        let mut store = ThreadedMessageStore::new();
882        put(&mut store, "h0", &oauth_h0());
883        // login must go to both client and authoriser under the widened :to
884        let narrow = msg("(signed @srv \"sig\" (lang test (login @cli \"n\" :caused-by h0)))");
885        assert!(matches!(
886            verify_causal_for_role(
887                &narrow,
888                &ep("client"),
889                &d,
890                &cast,
891                &store,
892                &tid(),
893                &ContentHash("h0".to_string())
894            ),
895            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
896        ));
897    }
898
899    // ---- REQ-619 / TEST-619 + out-of-order delivery ----
900
901    #[test]
902    fn out_of_order_is_unknown_then_valid() {
903        let d = oauth();
904        let cast = oauth_cast(&d);
905        let mut store = ThreadedMessageStore::new();
906        put(&mut store, "h0", &oauth_h0());
907        let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
908        let h2 =
909            msg("(signed @cli \"sig\" (lang test (passwd (@as @srv) \"cred\" :caused-by h1)))");
910        // h2 arrives before h1: Unknown (a message the role will see has
911        // not yet arrived), never Violation.
912        assert_eq!(
913            verify_causal_for_role(
914                &h2,
915                &ep("authoriser"),
916                &d,
917                &cast,
918                &store,
919                &tid(),
920                &ContentHash("h0".to_string())
921            ),
922            VerificationResult::Unknown
923        );
924        put(&mut store, "h1", &h1);
925        assert_eq!(
926            verify_causal_for_role(
927                &h2,
928                &ep("authoriser"),
929                &d,
930                &cast,
931                &store,
932                &tid(),
933                &ContentHash("h0".to_string())
934            ),
935            VerificationResult::Valid
936        );
937    }
938
939    #[test]
940    fn vacant_role_dependency_stays_unknown() {
941        let d = oauth();
942        let cast = oauth_cast(&d);
943        let store = ThreadedMessageStore::new();
944        let auth = msg("(signed @as \"sig\" (lang test (auth @srv \"tok\" :caused-by h-never)))");
945        assert_eq!(
946            verify_causal_for_role(
947                &auth,
948                &ep("server"),
949                &d,
950                &cast,
951                &store,
952                &tid(),
953                &ContentHash("h0".to_string())
954            ),
955            VerificationResult::Unknown
956        );
957    }
958
959    // ---- REQ-613 / TEST-613: root uniqueness ----
960
961    #[test]
962    fn foreign_cast_wrapper_is_a_violation() {
963        let d = oauth();
964        let cast = oauth_cast(&d);
965        let store = ThreadedMessageStore::new();
966        let second = msg("(with-roles ((server @evil) (client @cli) (authoriser @as)) (signed @evil \"sig\" (hello :caused-by begin)))");
967        assert!(matches!(
968            verify_causal_for_role(
969                &second,
970                &ep("client"),
971                &d,
972                &cast,
973                &store,
974                &tid(),
975                &ContentHash("h0".to_string())
976            ),
977            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
978        ));
979    }
980
981    #[test]
982    fn non_root_wrapper_is_a_violation() {
983        let d = oauth();
984        let cast = oauth_cast(&d);
985        let store = ThreadedMessageStore::new();
986        let late = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @srv \"sig\" (hello :caused-by h0)))");
987        assert!(matches!(
988            verify_causal_for_role(
989                &late,
990                &ep("client"),
991                &d,
992                &cast,
993                &store,
994                &tid(),
995                &ContentHash("h0".to_string())
996            ),
997            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
998        ));
999    }
1000
1001    // ---- Forgery regressions (adversarial review, HIGH findings) ----
1002
1003    #[test]
1004    fn unsigned_sender_field_cannot_occupy_a_role() {
1005        // An unsigned message self-asserting :sender must NOT ratify a role
1006        // (ratification is by signature, REQ-612).
1007        let d = oauth();
1008        let cast = oauth_cast(&d);
1009        let mut store = ThreadedMessageStore::new();
1010        put(&mut store, "h0", &oauth_h0());
1011        let forged = msg("(lang test (login (@as @cli) \"n\" :sender @srv :caused-by h0))");
1012        assert!(matches!(
1013            verify_causal_for_role(
1014                &forged,
1015                &ep("client"),
1016                &d,
1017                &cast,
1018                &store,
1019                &tid(),
1020                &ContentHash("h0".to_string())
1021            ),
1022            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1023        ));
1024    }
1025
1026    #[test]
1027    fn forged_second_root_wrapper_is_rejected() {
1028        // A second with-roles wrapper (distinct from the stored root) is a
1029        // Violation, and cannot be referenced-as-root (REQ-613).
1030        let d = oauth();
1031        let cast = oauth_cast(&d);
1032        let mut store = ThreadedMessageStore::new();
1033        put(&mut store, "h0", &oauth_h0());
1034        let second = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @cli \"sig\" (hello :caused-by begin)))");
1035        put(&mut store, "h9", &second);
1036        // The forged wrapper itself is a Violation (not the thread root).
1037        assert!(matches!(
1038            verify_causal_for_role(
1039                &second,
1040                &ep("client"),
1041                &d,
1042                &cast,
1043                &store,
1044                &tid(),
1045                &ContentHash("h0".to_string())
1046            ),
1047            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1048        ));
1049        // A message re-parented onto the forged wrapper does NOT verify as a
1050        // first step: h9 is not the root, so its type (hello) is an illegal
1051        // predecessor of login.
1052        let reparented =
1053            msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n\" :caused-by h9)))");
1054        assert!(matches!(
1055            verify_causal_for_role(
1056                &reparented,
1057                &ep("client"),
1058                &d,
1059                &cast,
1060                &store,
1061                &tid(),
1062                &ContentHash("h0".to_string())
1063            ),
1064            VerificationResult::Violation(_)
1065        ));
1066    }
1067
1068    #[test]
1069    fn receive_only_role_needs_no_signature_to_be_addressed() {
1070        // REQ-626: a message addressed to a nominated receive-only role is
1071        // conformant without any ratifying signature from that role — the
1072        // recipient never signs. Here `client` is a pure recipient of login.
1073        let d = oauth();
1074        let cast = oauth_cast(&d);
1075        let mut store = ThreadedMessageStore::new();
1076        put(&mut store, "h0", &oauth_h0());
1077        let login =
1078            msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
1079        // client is addressed but contributes no signature; still Valid.
1080        assert_eq!(
1081            verify_causal_for_role(
1082                &login,
1083                &ep("client"),
1084                &d,
1085                &cast,
1086                &store,
1087                &tid(),
1088                &ContentHash("h0".to_string())
1089            ),
1090            VerificationResult::Valid
1091        );
1092    }
1093
1094    #[test]
1095    fn matching_root_wrapper_is_valid() {
1096        let d = oauth();
1097        let cast = oauth_cast(&d);
1098        let store = ThreadedMessageStore::new();
1099        assert_eq!(
1100            verify_causal_for_role(
1101                &oauth_h0(),
1102                &ep("client"),
1103                &d,
1104                &cast,
1105                &store,
1106                &tid(),
1107                &ContentHash("h0".to_string())
1108            ),
1109            VerificationResult::Valid
1110        );
1111    }
1112
1113    #[test]
1114    fn unsigned_root_payload_is_rejected() {
1115        // CON-601: the with-roles payload must be the signed form. An
1116        // unsigned inner message, even with the right cast and caused-by
1117        // begin, is not a valid nomination.
1118        let d = oauth();
1119        let cast = oauth_cast(&d);
1120        let store = ThreadedMessageStore::new();
1121        let unsigned = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (hello :thread \"conv\" :caused-by begin))");
1122        assert!(matches!(
1123            verify_causal_for_role(
1124                &unsigned,
1125                &ep("client"),
1126                &d,
1127                &cast,
1128                &store,
1129                &tid(),
1130                &ContentHash("h0".to_string())
1131            ),
1132            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1133        ));
1134    }
1135
1136    #[test]
1137    fn root_wrapper_with_extra_params_is_rejected() {
1138        // CON-601 exact arity: exactly one bindings list.
1139        let d = oauth();
1140        let cast = oauth_cast(&d);
1141        let store = ThreadedMessageStore::new();
1142        let extra = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) junk (signed @srv \"sig\" (hello :caused-by begin)))");
1143        assert!(matches!(
1144            verify_causal_for_role(
1145                &extra,
1146                &ep("client"),
1147                &d,
1148                &cast,
1149                &store,
1150                &tid(),
1151                &ContentHash("h0".to_string())
1152            ),
1153            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1154        ));
1155    }
1156
1157    // ---- REQ-628 / TEST-642: dialect pin ----
1158
1159    /// The OAuth dialect with its canonical content hash populated, as
1160    /// `DialectRegistry::install` would leave it (`ensure_hash`).
1161    fn hashed_oauth() -> Dialect {
1162        let mut d = oauth();
1163        d.hash = Some(crate::canonical::dialect_hash(&d));
1164        d
1165    }
1166
1167    fn pinned_h0(pin: &str) -> Message {
1168        msg(&format!(
1169            "(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect {pin} (signed @srv \"sig\" (hello :thread \"conv\" :caused-by begin)))"
1170        ))
1171    }
1172
1173    /// The thread's root cast as the wrapper nominates it, pin included.
1174    fn pinned_cast(d: &Dialect, root: &Message) -> Cast {
1175        let Message::Wrapped { params, .. } = root else {
1176            panic!("root fixture is a wrapper");
1177        };
1178        parse_wrapper_cast(params, &d.roles).unwrap()
1179    }
1180
1181    #[test]
1182    fn pinned_root_matching_installed_hash_verifies() {
1183        let d = hashed_oauth();
1184        let pin = d.hash.clone().unwrap();
1185        let root = pinned_h0(&pin);
1186        let cast = pinned_cast(&d, &root);
1187        let mut store = ThreadedMessageStore::new();
1188        put(&mut store, "h0", &root);
1189        // The pinned wrapper itself verifies …
1190        assert_eq!(
1191            verify_causal_for_role(
1192                &root,
1193                &ep("client"),
1194                &d,
1195                &cast,
1196                &store,
1197                &tid(),
1198                &ContentHash("h0".to_string())
1199            ),
1200            VerificationResult::Valid
1201        );
1202        // … and so does a first step of the pinned thread.
1203        let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
1204        assert_eq!(
1205            verify_causal_for_role(
1206                &h1,
1207                &ep("client"),
1208                &d,
1209                &cast,
1210                &store,
1211                &tid(),
1212                &ContentHash("h0".to_string())
1213            ),
1214            VerificationResult::Valid
1215        );
1216    }
1217
1218    #[test]
1219    fn pin_mismatch_is_a_typed_violation_for_every_thread_message() {
1220        // The root pins a different (same-named, divergent) dialect than
1221        // the verifier installed: the typed REQ-628 violation fires for the
1222        // wrapper and for every subsequent message of the thread.
1223        let d = hashed_oauth();
1224        let stale = format!("f1220{}", "0".repeat(64));
1225        let root = pinned_h0(&stale);
1226        let cast = pinned_cast(&d, &root);
1227        let mut store = ThreadedMessageStore::new();
1228        put(&mut store, "h0", &root);
1229        let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
1230        for m in [&root, &h1] {
1231            match verify_causal_for_role(
1232                m,
1233                &ep("client"),
1234                &d,
1235                &cast,
1236                &store,
1237                &tid(),
1238                &ContentHash("h0".to_string()),
1239            ) {
1240                VerificationResult::Violation(CausalViolation::RoleConformance { reason }) => {
1241                    assert!(
1242                        reason.contains("REQ-628"),
1243                        "expected the typed pin violation, got: {reason}"
1244                    );
1245                }
1246                other => panic!("expected the REQ-628 violation, got {other:?}"),
1247            }
1248        }
1249    }
1250
1251    #[test]
1252    fn unpinned_root_still_verifies_during_transition() {
1253        // REQ-628 transition (warn-then-reject): an unpinned wrapper is
1254        // accepted as today, even when the installed dialect carries its
1255        // hash — see the REQ-628 comment in `verify_causal_for_role`.
1256        let d = hashed_oauth();
1257        let cast = oauth_cast(&d);
1258        let mut store = ThreadedMessageStore::new();
1259        put(&mut store, "h0", &oauth_h0());
1260        assert_eq!(
1261            verify_causal_for_role(
1262                &oauth_h0(),
1263                &ep("client"),
1264                &d,
1265                &cast,
1266                &store,
1267                &tid(),
1268                &ContentHash("h0".to_string())
1269            ),
1270            VerificationResult::Valid
1271        );
1272        let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
1273        assert_eq!(
1274            verify_causal_for_role(
1275                &h1,
1276                &ep("client"),
1277                &d,
1278                &cast,
1279                &store,
1280                &tid(),
1281                &ContentHash("h0".to_string())
1282            ),
1283            VerificationResult::Valid
1284        );
1285    }
1286
1287    #[test]
1288    fn malformed_pin_on_root_is_rejected() {
1289        // LangSec: a malformed `:dialect` value (bad prefix, wrong length)
1290        // is a parse rejection surfaced as a Violation, never repaired.
1291        let d = hashed_oauth();
1292        let cast = oauth_cast(&d);
1293        let store = ThreadedMessageStore::new();
1294        for bad in [
1295            "(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect f1220abc (signed @srv \"sig\" (hello :caused-by begin)))",
1296            "(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect md5:0000 (signed @srv \"sig\" (hello :caused-by begin)))",
1297        ] {
1298            assert!(matches!(
1299                verify_causal_for_role(
1300                    &msg(bad),
1301                    &ep("client"),
1302                    &d,
1303                    &cast,
1304                    &store,
1305                    &tid(),
1306                    &ContentHash("h0".to_string())
1307                ),
1308                VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1309            ));
1310        }
1311    }
1312
1313    // ---- REQ-618 / TEST-618: occupant-counted fan-in (auction) ----
1314
1315    fn auction() -> Dialect {
1316        dialect(
1317            "(auctioneer (* bidder))",
1318            vec![
1319                perf("commit", "bidder", &["auctioneer"]),
1320                perf("reveal", "bidder", &["auctioneer"]),
1321                perf("declare-winner", "auctioneer", &[]),
1322            ],
1323            vec![
1324                step("begin", vec![], vec![single("commit")]),
1325                step("commit", vec![single("begin")], vec![single("reveal")]),
1326                step("reveal", vec![single("commit")], vec![]),
1327                step("declare-winner", vec![all_of(&["reveal"])], vec![]),
1328            ],
1329        )
1330    }
1331
1332    fn auction_cast(d: &Dialect) -> Cast {
1333        parse_cast(
1334            &"((auctioneer @auc) (bidder @b1 @b2 @b3))"
1335                .parse::<SExpr>()
1336                .unwrap(),
1337            &d.roles,
1338        )
1339        .unwrap()
1340    }
1341
1342    fn auction_store() -> ThreadedMessageStore {
1343        let mut store = ThreadedMessageStore::new();
1344        put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :thread \"conv\" :caused-by begin)))"));
1345        for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
1346            let hc = alloc::format!("h{}", i + 1);
1347            let hr = alloc::format!("h{}", i + 4);
1348            put(
1349                &mut store,
1350                &hc,
1351                &msg(&alloc::format!(
1352                    "(signed {b} \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"
1353                )),
1354            );
1355            put(
1356                &mut store,
1357                &hr,
1358                &msg(&alloc::format!(
1359                    "(signed {b} \"sig\" (lang test (reveal @auc 42 :caused-by {hc})))"
1360                )),
1361            );
1362        }
1363        store
1364    }
1365
1366    #[test]
1367    fn fanin_unknown_until_all_reveals_then_valid() {
1368        let d = auction();
1369        let cast = auction_cast(&d);
1370        let mut store = ThreadedMessageStore::new();
1371        put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :caused-by begin)))"));
1372        put(
1373            &mut store,
1374            "h1",
1375            &msg("(signed @b1 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
1376        );
1377        put(
1378            &mut store,
1379            "h2",
1380            &msg("(signed @b2 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
1381        );
1382        put(
1383            &mut store,
1384            "h4",
1385            &msg("(signed @b1 \"sig\" (lang test (reveal @auc 42 :caused-by h1)))"),
1386        );
1387        put(
1388            &mut store,
1389            "h5",
1390            &msg("(signed @b2 \"sig\" (lang test (reveal @auc 17 :caused-by h2)))"),
1391        );
1392        let h7 =
1393            msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
1394        // h6 absent: Unknown
1395        assert_eq!(
1396            verify_causal_for_role(
1397                &h7,
1398                &ep("auctioneer"),
1399                &d,
1400                &cast,
1401                &store,
1402                &tid(),
1403                &ContentHash("h0".to_string())
1404            ),
1405            VerificationResult::Unknown
1406        );
1407        put(
1408            &mut store,
1409            "h3",
1410            &msg("(signed @b3 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
1411        );
1412        put(
1413            &mut store,
1414            "h6",
1415            &msg("(signed @b3 \"sig\" (lang test (reveal @auc 55 :caused-by h3)))"),
1416        );
1417        assert_eq!(
1418            verify_causal_for_role(
1419                &h7,
1420                &ep("auctioneer"),
1421                &d,
1422                &cast,
1423                &store,
1424                &tid(),
1425                &ContentHash("h0".to_string())
1426            ),
1427            VerificationResult::Valid
1428        );
1429    }
1430
1431    #[test]
1432    fn resolved_fanin_missing_an_occupant_is_a_violation() {
1433        // R5's type-level (all reveal) is satisfied by ANY reveal; the
1434        // occupant count is the role layer's extension (REQ-618).
1435        let d = auction();
1436        let cast = auction_cast(&d);
1437        let store = auction_store();
1438        let h7 =
1439            msg("(signed @auc \"sig\" (lang test (declare-winner \"b1\" :caused-by (h4 h5))))");
1440        assert!(matches!(
1441            verify_causal_for_role(
1442                &h7,
1443                &ep("auctioneer"),
1444                &d,
1445                &cast,
1446                &store,
1447                &tid(),
1448                &ContentHash("h0".to_string())
1449            ),
1450            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1451        ));
1452    }
1453
1454    #[test]
1455    fn non_member_instance_does_not_count_toward_coverage() {
1456        let d = auction();
1457        let cast = auction_cast(&d);
1458        let mut store = auction_store();
1459        // b4 is outside the sealed membership; its reveal replaces b3's.
1460        put(
1461            &mut store,
1462            "hx",
1463            &msg("(signed @b4 \"sig\" (lang test (reveal @auc 99 :caused-by h3)))"),
1464        );
1465        let h7 =
1466            msg("(signed @auc \"sig\" (lang test (declare-winner \"b1\" :caused-by (h4 h5 hx))))");
1467        assert!(matches!(
1468            verify_causal_for_role(
1469                &h7,
1470                &ep("auctioneer"),
1471                &d,
1472                &cast,
1473                &store,
1474                &tid(),
1475                &ContentHash("h0".to_string())
1476            ),
1477            VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1478        ));
1479    }
1480
1481    #[test]
1482    fn full_auction_trace_verifies_end_to_end() {
1483        let d = auction();
1484        let cast = auction_cast(&d);
1485        let store = auction_store();
1486        for (h, role) in [
1487            ("h1", "bidder"),
1488            ("h2", "bidder"),
1489            ("h3", "bidder"),
1490            ("h4", "bidder"),
1491            ("h5", "bidder"),
1492            ("h6", "bidder"),
1493        ] {
1494            let m = store
1495                .lookup_in_thread(&ContentHash(h.to_string()), &tid())
1496                .unwrap()
1497                .clone();
1498            assert_eq!(
1499                verify_causal_for_role(
1500                    &m,
1501                    &ep(role),
1502                    &d,
1503                    &cast,
1504                    &store,
1505                    &tid(),
1506                    &ContentHash("h0".to_string())
1507                ),
1508                VerificationResult::Valid,
1509                "{h} should be Valid"
1510            );
1511        }
1512        let h7 =
1513            msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
1514        assert_eq!(
1515            verify_causal_for_role(
1516                &h7,
1517                &ep("auctioneer"),
1518                &d,
1519                &cast,
1520                &store,
1521                &tid(),
1522                &ContentHash("h0".to_string())
1523            ),
1524            VerificationResult::Valid
1525        );
1526    }
1527
1528    // ---- SPEC-015 TEST-703: completion still requires content ----
1529
1530    use crate::attest::{sign_attestation_v2, AttestationHeader};
1531    use crate::envelope::RedactedEnvelope;
1532    use crate::keyid::KeyId;
1533    use crate::r4::Signer;
1534
1535    /// Data-dependent test signer (as in `attest.rs`); distinct secrets
1536    /// model the distinct bidder keys.
1537    struct TestSigner {
1538        secret: &'static str,
1539    }
1540
1541    impl Signer for TestSigner {
1542        fn sign(&self, data: &[u8]) -> Vec<u8> {
1543            use sha2::{Digest, Sha256};
1544            let mut h = Sha256::new();
1545            h.update(self.secret.as_bytes());
1546            h.update(data);
1547            h.finalize().to_vec()
1548        }
1549        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
1550            self.sign(data) == sig
1551        }
1552    }
1553
1554    /// A signed reveal envelope for bidder `b` (SPEC-015 REQ-700/701):
1555    /// authenticated header only — no bid value anywhere.
1556    fn reveal_envelope(bidder: &str, content_hash: &str, commit_hash: &str) -> RedactedEnvelope {
1557        let mut to = BTreeSet::new();
1558        to.insert(KeyId::parse("@auc").unwrap());
1559        let header = AttestationHeader {
1560            content_hash: content_hash.to_string(),
1561            performative: String::from("reveal"),
1562            from: KeyId::parse(bidder).unwrap(),
1563            to,
1564            thread: String::from("conv"),
1565            caused_by: Some(crate::message::CausedBy::Single(String::from(commit_hash))),
1566        };
1567        let signer = TestSigner {
1568            secret: match bidder {
1569                "@b1" => "b1",
1570                "@b2" => "b2",
1571                _ => "b3",
1572            },
1573        };
1574        let signature = sign_attestation_v2(&signer, &header).unwrap();
1575        RedactedEnvelope { header, signature }
1576    }
1577
1578    /// TEST-703: a fan-in decider whose member reveals are present only as
1579    /// envelopes reports the fan-in not-yet-complete (Unknown); supplying
1580    /// the full members completes it (Valid). Meanwhile the *safety-level*
1581    /// R5 check resolves from the very same envelopes (REQ-702) — the
1582    /// REQ-703 boundary is exactly the completion-level occupant fan-in.
1583    #[test]
1584    fn test_703_envelope_only_members_leave_the_fanin_incomplete() {
1585        let d = auction();
1586        let cast = auction_cast(&d);
1587        // Root and full commits; reveals arrive only as redacted envelopes.
1588        let mut store = ThreadedMessageStore::new();
1589        put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :thread \"conv\" :caused-by begin)))"));
1590        for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
1591            let hc = alloc::format!("h{}", i + 1);
1592            put(
1593                &mut store,
1594                &hc,
1595                &msg(&alloc::format!(
1596                    "(signed {b} \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"
1597                )),
1598            );
1599            let hr = alloc::format!("h{}", i + 4);
1600            let signer = TestSigner {
1601                secret: match *b {
1602                    "@b1" => "b1",
1603                    "@b2" => "b2",
1604                    _ => "b3",
1605                },
1606            };
1607            store
1608                .append_envelope(reveal_envelope(b, &hr, &hc), &signer)
1609                .unwrap();
1610        }
1611
1612        let h7 =
1613            msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
1614
1615        // Safety level (REQ-702): the R5 type check over the fan-in
1616        // resolves from the envelopes' authenticated types.
1617        let simple = h7.innermost_simple().unwrap();
1618        assert_eq!(
1619            crate::protocol::verify_causal(
1620                "declare-winner",
1621                simple.caused_by(),
1622                &store,
1623                d.causal_protocol.as_ref().unwrap(),
1624                &tid(),
1625            ),
1626            VerificationResult::Valid
1627        );
1628
1629        // Completion level (REQ-703): the occupant fan-in still demands
1630        // full messages — envelope-only members are not-yet-complete.
1631        let decide = |store: &ThreadedMessageStore| {
1632            verify_causal_for_role(
1633                &h7,
1634                &ep("auctioneer"),
1635                &d,
1636                &cast,
1637                store,
1638                &tid(),
1639                &ContentHash("h0".to_string()),
1640            )
1641        };
1642        assert_eq!(decide(&store), VerificationResult::Unknown);
1643
1644        // Supplying the full members completes the fan-in.
1645        for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
1646            put(
1647                &mut store,
1648                &alloc::format!("h{}", i + 4),
1649                &msg(&alloc::format!(
1650                    "(signed {b} \"sig\" (lang test (reveal @auc 42 :caused-by h{})))",
1651                    i + 1
1652                )),
1653            );
1654        }
1655        assert_eq!(decide(&store), VerificationResult::Valid);
1656    }
1657}