Skip to main content

cbcl_core/
role.rs

1//! Role layer types and parsing (SPEC-014).
2//!
3//! Types and SExpr-level recognisers for the role layer: role declarations
4//! (REQ-600, CON-600), per-performative `:from`/`:to` annotations (REQ-601,
5//! CON-600), and the thread cast nominated by a `with-roles` wrapper
6//! (REQ-611, CON-601). Fail-closed: malformed annotations are rejected, never
7//! repaired (LangSec principle 4).
8//!
9//! The indexed-role marker is the head-position form `(* name)` (ADR-600).
10//! Key identifiers ([`AgentKey`]) are whole symbols (e.g. `@alice`), compared
11//! for equality as strings; cryptographic validity of the signature binding a
12//! message to its key is an R4-layer precondition (CON-602).
13
14#![forbid(unsafe_code)]
15
16use crate::sexpr::{Atom, SExpr};
17use alloc::collections::{BTreeMap, BTreeSet};
18use alloc::format;
19use alloc::string::String;
20use alloc::vec::Vec;
21use core::fmt;
22
23/// How many occupants a role admits (SPEC-014 §Terminology).
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26pub enum RoleCardinality {
27    /// Exactly one occupant, pinned by the cast (REQ-612).
28    Singleton,
29    /// Many occupants, membership sealed at thread open (REQ-614);
30    /// declared `(* name)` (ADR-600).
31    Indexed,
32}
33
34/// A declared role (CON-600, REQ-600).
35#[derive(Debug, Clone, PartialEq, Eq)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37pub struct RoleDecl {
38    pub name: String,
39    pub cardinality: RoleCardinality,
40}
41
42/// Per-performative `:from`/`:to` annotation (CON-600, REQ-601).
43///
44/// `to` is a set from the start: bare symbol = singleton, list = multicast,
45/// `()` = empty (a terminal act addressed to no other role).
46#[derive(Debug, Clone, PartialEq, Eq)]
47#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48pub struct RoleAnnotation {
49    pub from: String,
50    pub to: BTreeSet<String>,
51}
52
53/// Key identifier as it appears in casts and signed messages (e.g. `@alice`).
54///
55/// Equality is whole-symbol string equality; cryptographic validity of the
56/// signature that binds a message to this identifier is an R4-layer
57/// precondition, outside this module (CON-602).
58#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
60pub struct AgentKey(pub String);
61
62/// The assignment of agents to roles for one thread (CON-601, REQ-611).
63///
64/// Nominated by the initiator at the causal root; tamper-evident because the
65/// root's content hash anchors every subsequent `:caused-by` link. Indexed
66/// memberships are *sealed*: occupant-dependent checks read them exclusively
67/// from here (REQ-614).
68#[derive(Debug, Clone, PartialEq, Eq)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
70pub struct Cast {
71    pub singleton: BTreeMap<String, AgentKey>,
72    pub indexed: BTreeMap<String, BTreeSet<AgentKey>>,
73    /// REQ-628: the `f1220<hex64>` content hash of the dialect that
74    /// governs the thread, from the wrapper's optional `:dialect` field.
75    /// `None` for an unpinned root (accepted during the spec's
76    /// warn-then-reject transition window).
77    #[cfg_attr(feature = "serde", serde(default))]
78    pub dialect_pin: Option<String>,
79}
80
81impl Cast {
82    /// Whether `key` may occupy `role` under this cast.
83    pub fn admits(&self, role: &str, key: &AgentKey) -> bool {
84        match self.singleton.get(role) {
85            Some(k) => k == key,
86            None => self.indexed.get(role).is_some_and(|ks| ks.contains(key)),
87        }
88    }
89}
90
91/// A `(role, occupant)` pair; `occupant` is `None` for singleton roles
92/// (CON-602).
93#[derive(Debug, Clone, PartialEq, Eq)]
94#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
95pub struct Endpoint {
96    pub role: String,
97    pub occupant: Option<AgentKey>,
98}
99
100/// How the installer treats R6(vi) causal-locality failures (SPEC-015
101/// REQ-709, ADR-704): the dialect's `(:causal-locality derive|reject)`
102/// declaration. The default is [`CausalLocality::Reject`] — the v1
103/// behaviour, bit-for-bit.
104#[derive(Debug, Clone, PartialEq, Eq, Default)]
105#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
106pub enum CausalLocality {
107    /// R6(vi) failures reject the dialect at install (v1 semantics).
108    #[default]
109    Reject,
110    /// R6(vi) stops being a rejection condition and becomes a compilation
111    /// step: the installer derives the envelope-widening closure and
112    /// records it here. The table is *derived*, never authored — the
113    /// parser always produces an empty table, and
114    /// `DialectRegistry::install` replaces it with the closure.
115    Derive(EnvelopeRoutes),
116}
117
118/// Dialect-level envelope-routing table (SPEC-015 REQ-709): protocol
119/// performative (step name) → the roles that receive its redacted envelope.
120///
121/// An envelope recipient counts as an endpoint role of the performative
122/// *for R6(vi) observability only*: payload `:to` sets are untouched, and
123/// projection emits an ExpectEnvelope step (never Send/Recv) per route.
124/// Derived at install as a pure, deterministic fixpoint of the dialect
125/// alone — every agent derives identical routes.
126#[derive(Debug, Clone, PartialEq, Eq, Default)]
127#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
128pub struct EnvelopeRoutes(pub BTreeMap<String, BTreeSet<String>>);
129
130impl EnvelopeRoutes {
131    /// Whether `role` is an envelope recipient of `performative`.
132    pub fn routes_to(&self, performative: &str, role: &str) -> bool {
133        self.0.get(performative).is_some_and(|s| s.contains(role))
134    }
135}
136
137/// Per-occupant envelope-routing table (SPEC-015 REQ-709), the thread-open
138/// half of the two-level derivation: performative → the sealed occupant
139/// keys that receive redacted envelopes of its instances.
140///
141/// It cannot exist earlier than thread open — these routes are O(n²) in a
142/// cast fixed only then — and it is a pure function of the dialect and the
143/// sealed cast, so every agent derives identical routes. Indexed-role
144/// routes appear only here, never in the install-time table.
145#[derive(Debug, Clone, PartialEq, Eq, Default)]
146#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
147pub struct OccupantEnvelopeRoutes(pub BTreeMap<String, BTreeSet<AgentKey>>);
148
149/// R6 violation (CON-603): one variant per rejectable condition, each
150/// carrying the names needed to locate the defect.
151#[derive(Debug, Clone, PartialEq, Eq)]
152#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
153pub enum R6Violation {
154    /// REQ-601: a protocol performative lacks `:from` or `:to`.
155    MissingFromTo { performative: String },
156    /// REQ-602: `:from`/`:to` names a role absent from `:roles`.
157    UndeclaredRole { performative: String, role: String },
158    /// REQ-602: `:from`/`:to` present while no `:roles` is declared.
159    StrayAnnotation { performative: String },
160    /// REQ-603: a choice whose members do not share one sender role.
161    ChooserIncoherent { members: Vec<String> },
162    /// REQ-604: an endpoint role of `performative` is not an endpoint role
163    /// of `predecessor`.
164    NotCausallyLocal {
165        performative: String,
166        predecessor: String,
167        role: String,
168    },
169    /// REQ-605: a declared role unreachable from `begin`.
170    UnreachableRole { role: String },
171    /// CON-600: malformed `:roles` value.
172    MalformedRoles { detail: String },
173    /// CON-600: malformed `:from`/`:to` value.
174    MalformedFromTo {
175        performative: String,
176        detail: String,
177    },
178    /// CON-601: malformed `with-roles` bindings.
179    MalformedCast { detail: String },
180    /// CON-601: a cast binding names a role not declared in `:roles`.
181    UnknownRole { role: String },
182    /// CON-601: a singleton role bound to a number of keys other than one.
183    ArityMismatch { role: String, keys: usize },
184    /// REQ-608: per-occupant causal locality fails at `occupant`.
185    PerOccupantLocalityFailure {
186        performative: String,
187        occupant: String,
188    },
189    /// REQ-628: the root's `:dialect` pin differs from the installed
190    /// dialect's content hash.
191    DialectPinMismatch { pinned: String, installed: String },
192}
193
194impl fmt::Display for R6Violation {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        match self {
197            R6Violation::MissingFromTo { performative } => write!(
198                f,
199                "R6 violation: performative '{performative}' lacks :from or :to (REQ-601)"
200            ),
201            R6Violation::UndeclaredRole { performative, role } => write!(
202                f,
203                "R6 violation: performative '{performative}' names undeclared role '{role}' (REQ-602)"
204            ),
205            R6Violation::StrayAnnotation { performative } => write!(
206                f,
207                "R6 violation: performative '{performative}' carries :from/:to but the dialect declares no :roles (REQ-602)"
208            ),
209            R6Violation::ChooserIncoherent { members } => write!(
210                f,
211                "R6 violation: choice {members:?} has no common sender role (REQ-603)"
212            ),
213            R6Violation::NotCausallyLocal {
214                performative,
215                predecessor,
216                role,
217            } => write!(
218                f,
219                "R6 violation: role '{role}' is an endpoint of '{performative}' but not of its predecessor '{predecessor}' (REQ-604)"
220            ),
221            R6Violation::UnreachableRole { role } => write!(
222                f,
223                "R6 violation: role '{role}' is not an endpoint of any performative reachable from begin (REQ-605)"
224            ),
225            R6Violation::MalformedRoles { detail } => {
226                write!(f, "R6 violation: malformed :roles — {detail} (CON-600)")
227            }
228            R6Violation::MalformedFromTo {
229                performative,
230                detail,
231            } => write!(
232                f,
233                "R6 violation: malformed :from/:to on '{performative}' — {detail} (CON-600)"
234            ),
235            R6Violation::MalformedCast { detail } => {
236                write!(f, "R6 violation: malformed cast — {detail} (CON-601)")
237            }
238            R6Violation::UnknownRole { role } => write!(
239                f,
240                "R6 violation: cast binds unknown role '{role}' (CON-601)"
241            ),
242            R6Violation::ArityMismatch { role, keys } => write!(
243                f,
244                "R6 violation: singleton role '{role}' bound to {keys} keys (CON-601)"
245            ),
246            R6Violation::PerOccupantLocalityFailure {
247                performative,
248                occupant,
249            } => write!(
250                f,
251                "R6 violation: '{performative}' fails per-occupant causal locality at occupant '{occupant}' (REQ-608)"
252            ),
253            R6Violation::DialectPinMismatch { pinned, installed } => write!(
254                f,
255                "R6 violation: root pins dialect '{pinned}' but the installed dialect hashes to '{installed}' (REQ-628)"
256            ),
257        }
258    }
259}
260
261/// Parse the value of a `:roles` attribute (CON-600, REQ-600).
262///
263/// `(auctioneer (* bidder))` → `[auctioneer: Singleton, bidder: Indexed]`.
264/// Rejects (fail closed): a non-list value, an empty list, non-symbol
265/// entries, a marker form that is not exactly `(* name)`, and duplicate role
266/// names.
267pub fn parse_roles(roles_value: &SExpr) -> Result<Vec<RoleDecl>, R6Violation> {
268    let items = match roles_value {
269        SExpr::List(items) if !items.is_empty() => items,
270        SExpr::List(_) => {
271            return Err(R6Violation::MalformedRoles {
272                detail: String::from("empty :roles ()"),
273            })
274        }
275        _ => {
276            return Err(R6Violation::MalformedRoles {
277                detail: String::from(":roles value is not a list"),
278            })
279        }
280    };
281    let mut decls: Vec<RoleDecl> = Vec::with_capacity(items.len());
282    for item in items {
283        let decl = match item {
284            SExpr::Atom(Atom::Symbol(name)) => RoleDecl {
285                name: name.clone(),
286                cardinality: RoleCardinality::Singleton,
287            },
288            SExpr::List(marker) => match marker.as_slice() {
289                [SExpr::Atom(Atom::Symbol(star)), SExpr::Atom(Atom::Symbol(name))]
290                    if star == "*" =>
291                {
292                    RoleDecl {
293                        name: name.clone(),
294                        cardinality: RoleCardinality::Indexed,
295                    }
296                }
297                _ => {
298                    return Err(R6Violation::MalformedRoles {
299                        detail: format!(
300                            "role declaration must be a symbol or (* name), got {item}"
301                        ),
302                    })
303                }
304            },
305            _ => {
306                return Err(R6Violation::MalformedRoles {
307                    detail: format!("role declaration must be a symbol or (* name), got {item}"),
308                })
309            }
310        };
311        if decls.iter().any(|d| d.name == decl.name) {
312            return Err(R6Violation::MalformedRoles {
313                detail: format!("duplicate role name '{}'", decl.name),
314            });
315        }
316        decls.push(decl);
317    }
318    Ok(decls)
319}
320
321/// Parse the value of a `:from` annotation: exactly one role symbol
322/// (CON-600).
323pub fn parse_from(performative: &str, from_value: &SExpr) -> Result<String, R6Violation> {
324    match from_value {
325        SExpr::Atom(Atom::Symbol(role)) => Ok(role.clone()),
326        other => Err(R6Violation::MalformedFromTo {
327            performative: String::from(performative),
328            detail: format!(":from must be exactly one role symbol, got {other}"),
329        }),
330    }
331}
332
333/// Parse the value of a `:to` annotation into a recipient set (CON-600):
334/// bare symbol = singleton set, list = multicast, `()` = empty. Rejects
335/// non-symbol members and duplicate members.
336pub fn parse_recipient_set(
337    performative: &str,
338    to_value: &SExpr,
339) -> Result<BTreeSet<String>, R6Violation> {
340    match to_value {
341        SExpr::Atom(Atom::Symbol(role)) => {
342            let mut set = BTreeSet::new();
343            set.insert(role.clone());
344            Ok(set)
345        }
346        SExpr::List(items) => {
347            let mut set = BTreeSet::new();
348            for item in items {
349                let SExpr::Atom(Atom::Symbol(role)) = item else {
350                    return Err(R6Violation::MalformedFromTo {
351                        performative: String::from(performative),
352                        detail: format!(":to members must be role symbols, got {item}"),
353                    });
354                };
355                if !set.insert(role.clone()) {
356                    return Err(R6Violation::MalformedFromTo {
357                        performative: String::from(performative),
358                        detail: format!("duplicate :to member '{role}'"),
359                    });
360                }
361            }
362            Ok(set)
363        }
364        other => Err(R6Violation::MalformedFromTo {
365            performative: String::from(performative),
366            detail: format!(":to must be a role symbol or a list, got {other}"),
367        }),
368    }
369}
370
371/// Parse a `with-roles` bindings list into a [`Cast`] (CON-601, REQ-611).
372///
373/// Every declared role must be bound exactly once (a cast *assigns* each
374/// role, REQ-611); a singleton role takes exactly one key
375/// ([`R6Violation::ArityMismatch`] otherwise); an indexed role takes one or
376/// more keys (its sealed membership, REQ-614); an undeclared role is
377/// [`R6Violation::UnknownRole`].
378pub fn parse_cast(bindings: &SExpr, roles: &[RoleDecl]) -> Result<Cast, R6Violation> {
379    let SExpr::List(items) = bindings else {
380        return Err(R6Violation::MalformedCast {
381            detail: String::from("bindings must be a list of (role key+) forms"),
382        });
383    };
384    let mut cast = Cast {
385        singleton: BTreeMap::new(),
386        indexed: BTreeMap::new(),
387        dialect_pin: None,
388    };
389    for item in items {
390        let SExpr::List(binding) = item else {
391            return Err(R6Violation::MalformedCast {
392                detail: format!("binding must be a (role key+) list, got {item}"),
393            });
394        };
395        let [SExpr::Atom(Atom::Symbol(role_name)), keys @ ..] = binding.as_slice() else {
396            return Err(R6Violation::MalformedCast {
397                detail: format!("binding must start with a role symbol, got {item}"),
398            });
399        };
400        let Some(decl) = roles.iter().find(|d| &d.name == role_name) else {
401            return Err(R6Violation::UnknownRole {
402                role: role_name.clone(),
403            });
404        };
405        if cast.singleton.contains_key(role_name) || cast.indexed.contains_key(role_name) {
406            return Err(R6Violation::MalformedCast {
407                detail: format!("duplicate binding for role '{role_name}'"),
408            });
409        }
410        let mut key_set: BTreeSet<AgentKey> = BTreeSet::new();
411        for key in keys {
412            let SExpr::Atom(Atom::Symbol(k)) = key else {
413                return Err(R6Violation::MalformedCast {
414                    detail: format!("key must be a symbol, got {key}"),
415                });
416            };
417            if !key_set.insert(AgentKey(k.clone())) {
418                return Err(R6Violation::MalformedCast {
419                    detail: format!("duplicate key '{k}' for role '{role_name}'"),
420                });
421            }
422        }
423        match decl.cardinality {
424            RoleCardinality::Singleton => {
425                if key_set.len() != 1 {
426                    return Err(R6Violation::ArityMismatch {
427                        role: role_name.clone(),
428                        keys: key_set.len(),
429                    });
430                }
431                let key = key_set.into_iter().next().expect("len == 1");
432                cast.singleton.insert(role_name.clone(), key);
433            }
434            RoleCardinality::Indexed => {
435                if key_set.is_empty() {
436                    return Err(R6Violation::MalformedCast {
437                        detail: format!("indexed role '{role_name}' bound to no keys"),
438                    });
439                }
440                cast.indexed.insert(role_name.clone(), key_set);
441            }
442        }
443    }
444    for decl in roles {
445        let bound =
446            cast.singleton.contains_key(&decl.name) || cast.indexed.contains_key(&decl.name);
447        if !bound {
448            return Err(R6Violation::MalformedCast {
449                detail: format!("declared role '{}' is not bound by the cast", decl.name),
450            });
451        }
452    }
453    Ok(cast)
454}
455
456/// Length of the lowercase-hex digest in a `f1220<hex64>` pin (REQ-628).
457const PIN_HEX_LEN: usize = 64;
458
459/// Parse the value of a `with-roles` `:dialect` field (REQ-628): exactly
460/// the string `"f1220<lowercase-hex64>"` on the strict wire path. Typed
461/// symbol atoms remain accepted for existing in-process callers. The digest
462/// is the form [`Dialect::hash`] takes at install. A bad prefix, wrong digest
463/// length or non-hex character is rejected, never repaired (LangSec principle 4).
464///
465/// [`Dialect::hash`]: crate::dialect::Dialect::hash
466pub fn parse_dialect_pin(value: &SExpr) -> Result<String, R6Violation> {
467    let pin = match value {
468        SExpr::Atom(Atom::Str(pin) | Atom::Symbol(pin)) => pin,
469        _ => {
470            return Err(R6Violation::MalformedCast {
471                detail: format!(
472                    ":dialect value must be a f1220<hex64> string or typed symbol, got {value}"
473                ),
474            })
475        }
476    };
477    let Some(hex) = pin.strip_prefix("f1220") else {
478        return Err(R6Violation::MalformedCast {
479            detail: format!(":dialect value must start with 'f1220', got '{pin}'"),
480        });
481    };
482    if hex.len() != PIN_HEX_LEN || !hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
483        return Err(R6Violation::MalformedCast {
484            detail: format!(
485                ":dialect digest must be exactly {PIN_HEX_LEN} lowercase hex characters, got '{hex}'"
486            ),
487        });
488    }
489    Ok(pin.clone())
490}
491
492/// Parse a `with-roles` wrapper's parameter list into a [`Cast`] (CON-601,
493/// REQ-628): the bindings list, optionally followed by
494/// `:dialect "f1220<hex64>"` in that fixed position. Any other shape —
495/// extra fields, a misplaced pin, an unknown keyword — is rejected, never
496/// repaired (LangSec principle 4).
497pub fn parse_wrapper_cast(params: &[SExpr], roles: &[RoleDecl]) -> Result<Cast, R6Violation> {
498    let (bindings, pin) = match params {
499        [bindings] => (bindings, None),
500        [bindings, SExpr::Atom(Atom::Keyword(k)), value] if k == "dialect" => {
501            (bindings, Some(parse_dialect_pin(value)?))
502        }
503        _ => {
504            return Err(R6Violation::MalformedCast {
505                detail: String::from(
506                    "with-roles wrapper must carry exactly one bindings list, \
507                     optionally followed by :dialect f1220<hex64> (CON-601, REQ-628)",
508                ),
509            })
510        }
511    };
512    let mut cast = parse_cast(bindings, roles)?;
513    cast.dialect_pin = pin;
514    Ok(cast)
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520    use alloc::string::ToString;
521    use alloc::vec;
522
523    fn sx(s: &str) -> SExpr {
524        s.parse().expect("test fixture parses")
525    }
526
527    // ---- R6Violation Display (CON-603: violations are Display-formatted
528    // like ProtocolViolation, carrying the names needed to locate the
529    // defect) ----
530
531    #[test]
532    fn violation_display_carries_locating_names() {
533        use alloc::string::ToString as _;
534        let v = R6Violation::NotCausallyLocal {
535            performative: "dispatch".to_string(),
536            predecessor: "accept".to_string(),
537            role: "warehouse".to_string(),
538        };
539        let s = alloc::format!("{v}");
540        assert!(s.contains("dispatch") && s.contains("accept") && s.contains("warehouse"));
541        assert!(s.contains("REQ-604"));
542
543        let a = R6Violation::ArityMismatch {
544            role: "auctioneer".to_string(),
545            keys: 2,
546        };
547        let s = alloc::format!("{a}");
548        assert!(s.contains("auctioneer") && s.contains('2') && s.contains("CON-601"));
549    }
550
551    fn auction_roles() -> Vec<RoleDecl> {
552        vec![
553            RoleDecl {
554                name: "auctioneer".to_string(),
555                cardinality: RoleCardinality::Singleton,
556            },
557            RoleDecl {
558                name: "bidder".to_string(),
559                cardinality: RoleCardinality::Indexed,
560            },
561        ]
562    }
563
564    // ---- parse_roles (REQ-600, TEST-600) ----
565
566    #[test]
567    fn roles_positive_singleton_and_indexed() {
568        let decls = parse_roles(&sx("(auctioneer (* bidder))")).unwrap();
569        assert_eq!(decls, auction_roles());
570    }
571
572    #[test]
573    fn roles_negative_empty_list() {
574        assert!(matches!(
575            parse_roles(&sx("()")),
576            Err(R6Violation::MalformedRoles { .. })
577        ));
578    }
579
580    #[test]
581    fn roles_negative_not_a_list() {
582        assert!(matches!(
583            parse_roles(&sx("auctioneer")),
584            Err(R6Violation::MalformedRoles { .. })
585        ));
586    }
587
588    #[test]
589    fn roles_negative_postfix_marker() {
590        // (bidder *) is the rejected postfix form — dispatch is on the head.
591        assert!(matches!(
592            parse_roles(&sx("((bidder *))")),
593            Err(R6Violation::MalformedRoles { .. })
594        ));
595    }
596
597    #[test]
598    fn roles_negative_marker_arity() {
599        assert!(matches!(
600            parse_roles(&sx("((*))")),
601            Err(R6Violation::MalformedRoles { .. })
602        ));
603        assert!(matches!(
604            parse_roles(&sx("((* a b))")),
605            Err(R6Violation::MalformedRoles { .. })
606        ));
607    }
608
609    #[test]
610    fn roles_negative_non_symbol_entry() {
611        assert!(matches!(
612            parse_roles(&sx("(auctioneer 42)")),
613            Err(R6Violation::MalformedRoles { .. })
614        ));
615    }
616
617    #[test]
618    fn roles_negative_duplicate_names() {
619        assert!(matches!(
620            parse_roles(&sx("(a (* a))")),
621            Err(R6Violation::MalformedRoles { .. })
622        ));
623    }
624
625    // ---- parse_from / parse_recipient_set (REQ-601 values, TEST-601) ----
626
627    #[test]
628    fn from_positive_symbol() {
629        assert_eq!(parse_from("login", &sx("server")).unwrap(), "server");
630    }
631
632    #[test]
633    fn from_negative_list() {
634        assert!(matches!(
635            parse_from("login", &sx("(server client)")),
636            Err(R6Violation::MalformedFromTo { .. })
637        ));
638    }
639
640    #[test]
641    fn to_positive_bare_symbol_is_singleton_set() {
642        let set = parse_recipient_set("login", &sx("client")).unwrap();
643        assert_eq!(set.len(), 1);
644        assert!(set.contains("client"));
645    }
646
647    #[test]
648    fn to_positive_multicast() {
649        let set = parse_recipient_set("login", &sx("(client authoriser)")).unwrap();
650        assert_eq!(set.len(), 2);
651        assert!(set.contains("client") && set.contains("authoriser"));
652    }
653
654    #[test]
655    fn to_positive_empty_terminal() {
656        let set = parse_recipient_set("declare-winner", &sx("()")).unwrap();
657        assert!(set.is_empty());
658    }
659
660    #[test]
661    fn to_negative_non_symbol_member() {
662        assert!(matches!(
663            parse_recipient_set("login", &sx("(client 7)")),
664            Err(R6Violation::MalformedFromTo { .. })
665        ));
666    }
667
668    #[test]
669    fn to_negative_duplicate_member() {
670        assert!(matches!(
671            parse_recipient_set("login", &sx("(client client)")),
672            Err(R6Violation::MalformedFromTo { .. })
673        ));
674    }
675
676    // ---- parse_cast (REQ-611/614, TEST-611/614) ----
677
678    #[test]
679    fn cast_positive_auction() {
680        let cast = parse_cast(
681            &sx("((auctioneer @auc) (bidder @b1 @b2 @b3))"),
682            &auction_roles(),
683        )
684        .unwrap();
685        assert_eq!(
686            cast.singleton.get("auctioneer"),
687            Some(&AgentKey("@auc".to_string()))
688        );
689        let members = cast.indexed.get("bidder").unwrap();
690        assert_eq!(members.len(), 3);
691        assert!(cast.admits("bidder", &AgentKey("@b2".to_string())));
692        assert!(!cast.admits("bidder", &AgentKey("@b4".to_string())));
693        assert!(cast.admits("auctioneer", &AgentKey("@auc".to_string())));
694    }
695
696    #[test]
697    fn cast_negative_singleton_two_keys() {
698        assert!(matches!(
699            parse_cast(&sx("((auctioneer @a @b) (bidder @b1))"), &auction_roles()),
700            Err(R6Violation::ArityMismatch { keys: 2, .. })
701        ));
702    }
703
704    #[test]
705    fn cast_negative_unknown_role() {
706        assert!(matches!(
707            parse_cast(
708                &sx("((auctioneer @auc) (bidder @b1) (ghost @g))"),
709                &auction_roles()
710            ),
711            Err(R6Violation::UnknownRole { .. })
712        ));
713    }
714
715    #[test]
716    fn cast_negative_missing_binding() {
717        assert!(matches!(
718            parse_cast(&sx("((auctioneer @auc))"), &auction_roles()),
719            Err(R6Violation::MalformedCast { .. })
720        ));
721    }
722
723    #[test]
724    fn cast_negative_duplicate_binding() {
725        assert!(matches!(
726            parse_cast(
727                &sx("((auctioneer @auc) (auctioneer @b) (bidder @b1))"),
728                &auction_roles()
729            ),
730            Err(R6Violation::MalformedCast { .. })
731        ));
732    }
733
734    #[test]
735    fn cast_negative_indexed_no_keys() {
736        assert!(matches!(
737            parse_cast(&sx("((auctioneer @auc) (bidder))"), &auction_roles()),
738            Err(R6Violation::MalformedCast { .. })
739        ));
740    }
741
742    #[test]
743    fn cast_negative_non_list_binding() {
744        assert!(matches!(
745            parse_cast(&sx("(auctioneer @auc)"), &auction_roles()),
746            Err(R6Violation::MalformedCast { .. })
747        ));
748    }
749
750    // ---- parse_wrapper_cast / parse_dialect_pin (REQ-628, TEST-642) ----
751
752    fn hex64(c: char) -> String {
753        core::iter::repeat(c).take(64).collect()
754    }
755
756    #[test]
757    fn wrapper_cast_without_pin_has_none() {
758        let cast = parse_wrapper_cast(&[sx("((auctioneer @auc) (bidder @b1))")], &auction_roles())
759            .unwrap();
760        assert_eq!(cast.dialect_pin, None);
761    }
762
763    #[test]
764    fn wrapper_cast_with_wellformed_pin_carries_it() {
765        let pin = alloc::format!("f1220{}", hex64('a'));
766        let cast = parse_wrapper_cast(
767            &[
768                sx("((auctioneer @auc) (bidder @b1))"),
769                sx(":dialect"),
770                sx(&pin),
771            ],
772            &auction_roles(),
773        )
774        .unwrap();
775        assert_eq!(cast.dialect_pin.as_deref(), Some(pin.as_str()));
776    }
777
778    #[test]
779    fn pin_negative_bad_prefix() {
780        assert!(matches!(
781            parse_dialect_pin(&sx(&alloc::format!("md5:{}", hex64('a')))),
782            Err(R6Violation::MalformedCast { .. })
783        ));
784    }
785
786    #[test]
787    fn pin_negative_wrong_length() {
788        assert!(matches!(
789            parse_dialect_pin(&sx("f1220abc")),
790            Err(R6Violation::MalformedCast { .. })
791        ));
792        assert!(matches!(
793            parse_dialect_pin(&sx(&alloc::format!("f1220{}a", hex64('a')))),
794            Err(R6Violation::MalformedCast { .. })
795        ));
796    }
797
798    #[test]
799    fn pin_negative_non_hex_digits() {
800        // 'g' is outside the hex alphabet; 'A' is uppercase — both rejected,
801        // never case-folded or repaired (LangSec principle 4).
802        assert!(matches!(
803            parse_dialect_pin(&sx(&alloc::format!("f1220{}", hex64('g')))),
804            Err(R6Violation::MalformedCast { .. })
805        ));
806        assert!(matches!(
807            parse_dialect_pin(&sx(&alloc::format!("f1220{}", hex64('A')))),
808            Err(R6Violation::MalformedCast { .. })
809        ));
810    }
811
812    #[test]
813    fn pin_negative_non_text_value() {
814        assert!(matches!(
815            parse_dialect_pin(&sx("(sha256 x)")),
816            Err(R6Violation::MalformedCast { .. })
817        ));
818    }
819
820    #[test]
821    fn wrapper_cast_negative_extra_fields() {
822        let pin = alloc::format!("f1220{}", hex64('a'));
823        // Trailing garbage after the pin.
824        assert!(matches!(
825            parse_wrapper_cast(
826                &[
827                    sx("((auctioneer @auc) (bidder @b1))"),
828                    sx(":dialect"),
829                    sx(&pin),
830                    sx("junk"),
831                ],
832                &auction_roles(),
833            ),
834            Err(R6Violation::MalformedCast { .. })
835        ));
836        // Unknown keyword field in the pin position.
837        assert!(matches!(
838            parse_wrapper_cast(
839                &[
840                    sx("((auctioneer @auc) (bidder @b1))"),
841                    sx(":lang"),
842                    sx(&pin),
843                ],
844                &auction_roles(),
845            ),
846            Err(R6Violation::MalformedCast { .. })
847        ));
848    }
849}