Skip to main content

cbcl_core/
message.rs

1//! Message types and core performatives.
2//!
3//! Mirrors `Message.lean` from the Lean 4 proof library.
4
5#![forbid(unsafe_code)]
6
7use crate::protocol::BEGIN_KEYWORD;
8use crate::sexpr::{Atom, SExpr};
9use alloc::boxed::Box;
10use alloc::string::String;
11use alloc::vec;
12use alloc::vec::Vec;
13use core::fmt;
14
15/// Causal predecessor reference for a message (REQ-202).
16///
17/// Encodes the `:caused-by` keyword parameter:
18/// - `Begin` — this message starts a new causal chain (`:caused-by "begin"`)
19/// - `Single(hash)` — single predecessor (`:caused-by <hash>`)
20/// - `Multiple(hashes)` — multiple predecessors (`:caused-by (<h1> <h2> ...)`)
21///
22/// For the `Multiple` variant, hashes are stored in canonical (sorted) order
23/// to ensure deterministic hashing.
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26pub enum CausedBy {
27    /// This message begins a new causal chain.
28    Begin,
29    /// Single causal predecessor, identified by content hash.
30    Single(String),
31    /// Multiple causal predecessors, sorted lexicographically for canonical ordering.
32    Multiple(Vec<String>),
33}
34
35/// The 8 core performatives (REQ-010).
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
38pub enum CorePerformative {
39    Tell,
40    Ask,
41    Reply,
42    Error,
43    Ok,
44    Cancel,
45    Hello,
46    Bye,
47}
48
49impl CorePerformative {
50    /// Returns the string name of this core performative.
51    pub fn as_str(&self) -> &'static str {
52        match self {
53            CorePerformative::Tell => "tell",
54            CorePerformative::Ask => "ask",
55            CorePerformative::Reply => "reply",
56            CorePerformative::Error => "error",
57            CorePerformative::Ok => "ok",
58            CorePerformative::Cancel => "cancel",
59            CorePerformative::Hello => "hello",
60            CorePerformative::Bye => "bye",
61        }
62    }
63
64    /// Parse a string into a core performative, if valid.
65    pub fn parse(s: &str) -> Option<Self> {
66        match s {
67            "tell" => Some(CorePerformative::Tell),
68            "ask" => Some(CorePerformative::Ask),
69            "reply" => Some(CorePerformative::Reply),
70            "error" => Some(CorePerformative::Error),
71            "ok" => Some(CorePerformative::Ok),
72            "cancel" => Some(CorePerformative::Cancel),
73            "hello" => Some(CorePerformative::Hello),
74            "bye" => Some(CorePerformative::Bye),
75            _ => None,
76        }
77    }
78}
79
80/// Core performative names (REQ-014).
81pub const CORE_PERFORMATIVE_NAMES: &[&str] = &[
82    "tell", "ask", "reply", "error", "ok", "cancel", "hello", "bye",
83];
84
85/// Check if a string is a core performative name (REQ-014).
86pub fn is_core_performative_name(s: &str) -> bool {
87    CORE_PERFORMATIVE_NAMES.contains(&s)
88}
89
90/// Either a core or custom performative (REQ-011).
91#[derive(Debug, Clone, PartialEq, Eq, Hash)]
92#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
93pub enum Performative {
94    Core(CorePerformative),
95    Custom(String),
96}
97
98impl Performative {
99    /// Returns the string name of this performative.
100    pub fn name(&self) -> &str {
101        match self {
102            Performative::Core(c) => c.as_str(),
103            Performative::Custom(s) => s.as_str(),
104        }
105    }
106
107    /// Returns true if this is a core performative.
108    pub fn is_core(&self) -> bool {
109        matches!(self, Performative::Core(_))
110    }
111}
112
113/// Recipient position of a Simple message (SPEC-014 REQ-622).
114///
115/// A bare `@key` symbol is a single recipient (the pre-SPEC-014 form,
116/// byte-identical on re-serialisation); a non-empty list of `@key` symbols
117/// is a multicast, serialised in canonical (sorted) order. A performative
118/// whose `:to` annotation is the empty set simply carries no recipient
119/// position.
120#[derive(Debug, Clone, PartialEq, Eq, Hash)]
121#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
122pub enum Recipients {
123    /// Single recipient: `(perf @r …)`.
124    One(String),
125    /// Multicast: `(perf (@r1 @r2) …)`; canonical order via `BTreeSet`.
126    Set(alloc::collections::BTreeSet<String>),
127}
128
129impl Recipients {
130    /// The single recipient, if this is the `One` form.
131    pub fn as_single(&self) -> Option<&str> {
132        match self {
133            Recipients::One(r) => Some(r.as_str()),
134            Recipients::Set(_) => None,
135        }
136    }
137
138    /// All recipients as a normalized sorted set.
139    pub fn as_set(&self) -> alloc::collections::BTreeSet<&str> {
140        match self {
141            Recipients::One(r) => {
142                let mut s = alloc::collections::BTreeSet::new();
143                s.insert(r.as_str());
144                s
145            }
146            Recipients::Set(rs) => rs.iter().map(|r| r.as_str()).collect(),
147        }
148    }
149}
150
151impl From<String> for Recipients {
152    fn from(r: String) -> Self {
153        Recipients::One(r)
154    }
155}
156
157impl From<&str> for Recipients {
158    fn from(r: &str) -> Self {
159        Recipients::One(String::from(r))
160    }
161}
162
163/// Message type classification (REQ-012).
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
166pub enum MessageType {
167    Simple,
168    Meta,
169    Dialect,
170    Wrapped,
171}
172
173/// Wrapper type for wrapped messages (REQ-012).
174///
175/// Four wrapper forms: `envelope`, `signed`, `with-limits`, and the
176/// cast-bearing `with-roles` thread root (SPEC-014 REQ-625).
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
178#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
179pub enum WrapperType {
180    Envelope,
181    Signed,
182    WithLimits,
183    /// `(with-roles (<bindings>) <signed-message>)` — the cast nomination
184    /// wrapper at a thread's causal root (SPEC-014 REQ-611/625, CON-601).
185    /// The bindings list travels in `params`; the inner signed message is
186    /// carried unchanged.
187    WithRoles,
188}
189
190impl WrapperType {
191    /// Returns the canonical string name of this wrapper type.
192    pub fn as_str(&self) -> &'static str {
193        match self {
194            WrapperType::Envelope => "envelope",
195            WrapperType::Signed => "signed",
196            WrapperType::WithLimits => "with-limits",
197            WrapperType::WithRoles => "with-roles",
198        }
199    }
200
201    /// Parse a string into a wrapper type, if valid.
202    pub fn parse(s: &str) -> Option<Self> {
203        match s {
204            "envelope" => Some(WrapperType::Envelope),
205            "signed" => Some(WrapperType::Signed),
206            "with-limits" => Some(WrapperType::WithLimits),
207            "with-roles" => Some(WrapperType::WithRoles),
208            _ => None,
209        }
210    }
211}
212
213/// A CBCL message (REQ-013).
214///
215/// Four variants matching the CBCL grammar:
216/// - `Simple`: `(performative [recipient] content [:key val ...])`
217/// - `Meta`: `(meta <operation>)`
218/// - `Dialect`: `(lang <dialect-name> <inner-message>)`
219/// - `Wrapped`: `(envelope|signed|with-limits <params...> <inner-message>)`
220///
221/// Mirrors `CBCL.Message` in `Message.lean:41–47` and
222/// `CBCL.MessageType` in `Message.lean:33–37`.
223#[derive(Debug, Clone, PartialEq, Eq)]
224#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
225pub enum Message {
226    /// Simple message: `(performative [recipient] content [:key val ...])`
227    Simple {
228        performative: Performative,
229        recipient: Option<Recipients>,
230        content: SExpr,
231        params: Vec<SExpr>,
232        thread: Option<String>,
233        sender: Option<String>,
234        caused_by: Option<CausedBy>,
235    },
236    /// Meta message: `(meta <dialect_def>)`
237    Meta { dialect_def: SExpr },
238    /// Dialect-scoped message: `(lang <dialect_name> <inner>)`
239    Dialect {
240        dialect_name: String,
241        inner: Box<Message>,
242    },
243    /// Wrapped message: `(envelope|signed|with-limits <params...> <content>)`
244    Wrapped {
245        wrapper: WrapperType,
246        params: Vec<SExpr>,
247        content: Box<Message>,
248    },
249}
250
251// ---------------------------------------------------------------------------
252// Typed extraction methods
253// ---------------------------------------------------------------------------
254
255impl Message {
256    /// Recognise a message as [`TryFrom<&SExpr>`] does, except that a custom
257    /// performative outside a `(lang …)` wrapper is accepted as a bare
258    /// `Performative::Custom` instead of being refused under the scoping rule.
259    ///
260    /// For hosts that dispatch such a frame by its head name themselves and
261    /// accept only the names they know — the chat hub's control plane
262    /// (`adddialect`, `fetchdialect`, `addagent`, …), which its lax parser
263    /// gates with a performative allow-list. Content messages go through
264    /// `TryFrom`, where the scoping rule stands: nothing in a bare custom head
265    /// says which dialect defines it.
266    pub fn parse_lax(sexpr: &SExpr) -> Result<Self, MessageParseError> {
267        parse_message_scoped(sexpr, LangScope::Lax)
268    }
269
270    /// Returns the message type classification.
271    pub fn message_type(&self) -> MessageType {
272        match self {
273            Message::Simple { .. } => MessageType::Simple,
274            Message::Meta { .. } => MessageType::Meta,
275            Message::Dialect { .. } => MessageType::Dialect,
276            Message::Wrapped { .. } => MessageType::Wrapped,
277        }
278    }
279
280    /// Returns the performative if this is a Simple message.
281    pub fn performative(&self) -> Option<&Performative> {
282        match self {
283            Message::Simple { performative, .. } => Some(performative),
284            _ => None,
285        }
286    }
287
288    /// Returns the recipient if this is a Simple message with exactly one.
289    pub fn recipient(&self) -> Option<&str> {
290        match self {
291            Message::Simple {
292                recipient: Some(r), ..
293            } => r.as_single(),
294            _ => None,
295        }
296    }
297
298    /// Canonical signed-envelope audience, retaining the `@` sigil.
299    /// Descends wrappers to the act. An outermost envelope routes a non-empty
300    /// recipient position through its single symbol `:to` (cbcl-bus SPEC-100
301    /// CON-009). Recipient-less, ambiguous and un-enveloped multicast frames
302    /// fail closed. Meta operations have no message recipient.
303    pub fn canonical_recipient(&self) -> Result<&str, &'static str> {
304        let simple = self.innermost_simple().ok_or("message has no recipient")?;
305        if simple.recipient_set().is_empty() {
306            return Err("message has no recipient");
307        }
308        if let Message::Wrapped {
309            wrapper: WrapperType::Envelope,
310            params,
311            ..
312        } = self
313        {
314            let mut audience = None;
315            let mut iter = params.iter();
316            while let Some(param) = iter.next() {
317                if let SExpr::Atom(Atom::Keyword(key)) = param {
318                    let value = iter.next();
319                    if key == "to" {
320                        if audience.is_some() {
321                            return Err("ambiguous envelope recipient");
322                        }
323                        audience = Some(match value {
324                            Some(SExpr::Atom(Atom::Symbol(s))) if s.starts_with('@') => s.as_str(),
325                            _ => return Err("envelope :to must be a recipient symbol"),
326                        });
327                    }
328                }
329            }
330            return audience.ok_or("envelope requires :to");
331        }
332        simple
333            .recipient()
334            .ok_or("message must have exactly one recipient")
335    }
336
337    /// Returns all recipients of a Simple message as a normalized set
338    /// (empty when the recipient position is absent) — SPEC-014 REQ-622.
339    pub fn recipient_set(&self) -> alloc::collections::BTreeSet<&str> {
340        match self {
341            Message::Simple {
342                recipient: Some(r), ..
343            } => r.as_set(),
344            _ => alloc::collections::BTreeSet::new(),
345        }
346    }
347
348    /// Returns the content if this is a Simple message.
349    pub fn content(&self) -> Option<&SExpr> {
350        match self {
351            Message::Simple { content, .. } => Some(content),
352            _ => None,
353        }
354    }
355
356    /// Returns the thread if this is a Simple message with one.
357    pub fn thread(&self) -> Option<&str> {
358        match self {
359            Message::Simple {
360                thread: Some(t), ..
361            } => Some(t.as_str()),
362            _ => None,
363        }
364    }
365
366    /// Returns the sender if this is a Simple message with one.
367    pub fn sender(&self) -> Option<&str> {
368        match self {
369            Message::Simple {
370                sender: Some(s), ..
371            } => Some(s.as_str()),
372            _ => None,
373        }
374    }
375
376    /// Returns the caused-by reference if this is a Simple message with one.
377    pub fn caused_by(&self) -> Option<&CausedBy> {
378        match self {
379            Message::Simple {
380                caused_by: Some(cb),
381                ..
382            } => Some(cb),
383            _ => None,
384        }
385    }
386
387    /// Returns the dialect definition if this is a Meta message.
388    pub fn dialect_def(&self) -> Option<&SExpr> {
389        match self {
390            Message::Meta { dialect_def } => Some(dialect_def),
391            _ => None,
392        }
393    }
394
395    /// Returns the dialect name if this is a Dialect message.
396    pub fn dialect_name(&self) -> Option<&str> {
397        match self {
398            Message::Dialect { dialect_name, .. } => Some(dialect_name.as_str()),
399            _ => None,
400        }
401    }
402
403    /// Returns the inner message for Dialect or Wrapped messages.
404    pub fn inner_message(&self) -> Option<&Message> {
405        match self {
406            Message::Dialect { inner, .. } => Some(inner),
407            Message::Wrapped { content, .. } => Some(content),
408            _ => None,
409        }
410    }
411
412    /// Walk through `Wrapped` and `Dialect` envelopes to the innermost
413    /// `Message::Simple`. Returns `None` if no Simple is found (e.g. a `Meta`
414    /// message). Used by the parser pipeline and the agent to ensure
415    /// wrappers cannot be used to bypass causal/shape verification.
416    pub fn innermost_simple(&self) -> Option<&Message> {
417        let mut cur = self;
418        loop {
419            match cur {
420                Message::Simple { .. } => return Some(cur),
421                Message::Wrapped { content, .. } => cur = content,
422                Message::Dialect { inner, .. } => cur = inner,
423                Message::Meta { .. } => return None,
424            }
425        }
426    }
427
428    /// Returns the wrapper type if this is a Wrapped message.
429    pub fn wrapper_type(&self) -> Option<WrapperType> {
430        match self {
431            Message::Wrapped { wrapper, .. } => Some(*wrapper),
432            _ => None,
433        }
434    }
435}
436
437// ---------------------------------------------------------------------------
438// From<Message> for SExpr
439// ---------------------------------------------------------------------------
440
441impl From<Message> for SExpr {
442    fn from(msg: Message) -> SExpr {
443        match msg {
444            Message::Simple {
445                performative,
446                recipient,
447                content,
448                params,
449                thread,
450                sender,
451                caused_by,
452            } => {
453                let mut items = vec![SExpr::Atom(Atom::Symbol(String::from(performative.name())))];
454                match recipient {
455                    Some(Recipients::One(r)) => {
456                        items.push(SExpr::Atom(Atom::Symbol(r)));
457                    }
458                    Some(Recipients::Set(rs)) => {
459                        items.push(SExpr::List(
460                            rs.into_iter()
461                                .map(|r| SExpr::Atom(Atom::Symbol(r)))
462                                .collect(),
463                        ));
464                    }
465                    None => {}
466                }
467                items.push(content);
468                items.extend(crate::canonical::canonical_params(&params));
469                if let Some(t) = thread {
470                    items.push(SExpr::Atom(Atom::Keyword(String::from("thread"))));
471                    items.push(SExpr::Atom(Atom::Str(t)));
472                }
473                if let Some(s) = sender {
474                    items.push(SExpr::Atom(Atom::Keyword(String::from("sender"))));
475                    items.push(SExpr::Atom(Atom::Str(s)));
476                }
477                if let Some(cb) = caused_by {
478                    items.push(SExpr::Atom(Atom::Keyword(String::from("caused-by"))));
479                    match cb {
480                        CausedBy::Begin => {
481                            items.push(SExpr::Atom(Atom::Symbol(String::from(BEGIN_KEYWORD))));
482                        }
483                        CausedBy::Single(h) => {
484                            items.push(SExpr::Atom(Atom::Symbol(h)));
485                        }
486                        CausedBy::Multiple(hs) => {
487                            let hash_exprs = hs
488                                .iter()
489                                .map(|h| SExpr::Atom(Atom::Symbol(h.clone())))
490                                .collect();
491                            items.push(SExpr::List(hash_exprs));
492                        }
493                    }
494                }
495                SExpr::List(items)
496            }
497            Message::Meta { dialect_def } => SExpr::List(vec![
498                SExpr::Atom(Atom::Symbol(String::from("meta"))),
499                dialect_def,
500            ]),
501            Message::Dialect {
502                dialect_name,
503                inner,
504            } => SExpr::List(vec![
505                SExpr::Atom(Atom::Symbol(String::from("lang"))),
506                SExpr::Atom(Atom::Symbol(dialect_name)),
507                SExpr::from(*inner),
508            ]),
509            Message::Wrapped {
510                wrapper,
511                params,
512                content,
513            } => {
514                let mut items = vec![SExpr::Atom(Atom::Symbol(String::from(wrapper.as_str())))];
515                items.extend(crate::canonical::canonical_params(&params));
516                items.push(SExpr::from(*content));
517                SExpr::List(items)
518            }
519        }
520    }
521}
522
523impl From<&Message> for SExpr {
524    fn from(msg: &Message) -> SExpr {
525        SExpr::from(msg.clone())
526    }
527}
528
529// ---------------------------------------------------------------------------
530// TryFrom<&SExpr> for Message
531// ---------------------------------------------------------------------------
532
533/// Error returned when converting an SExpr to a Message fails.
534#[derive(Debug, Clone, PartialEq, Eq)]
535pub struct MessageParseError(pub String);
536
537impl fmt::Display for MessageParseError {
538    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539        f.write_str(&self.0)
540    }
541}
542
543impl TryFrom<&SExpr> for Message {
544    type Error = MessageParseError;
545
546    fn try_from(sexpr: &SExpr) -> Result<Self, Self::Error> {
547        parse_message_scoped(sexpr, LangScope::Unscoped)
548    }
549}
550
551/// Whether the message being recognised sits inside a `(lang …)` wrapper
552/// (REQ-033).
553///
554/// This is the only context a *custom* performative may appear in. The `lang`
555/// tag plus the dialect name is the deterministic dispatch token that selects
556/// which dialect's subgrammar applies; without it the head symbol alone would
557/// have to select it, and which dialect that names is a property of the
558/// receiver's installed set rather than of the message. Two agents holding
559/// different dialects would then read the same bytes differently, which is the
560/// parser-equivalence failure the whole design exists to exclude.
561///
562/// Because dispatch goes through `lang`, two dialects defining the same
563/// performative name is not a conflict at all — the wrapper says which one is
564/// meant. That coexistence is the feature the scoping rule buys.
565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
566enum LangScope {
567    /// No enclosing `(lang …)`: only core performatives may head a message.
568    Unscoped,
569    /// Inside a `(lang <dialect> …)`, possibly through wrappers.
570    Scoped,
571    /// No enclosing `(lang …)`, but the caller dispatches a bare custom head
572    /// by name itself and asked for it ([`Message::parse_lax`]): a control
573    /// frame of a host whose control plane predates the scoping rule. Never a
574    /// content message.
575    Lax,
576}
577
578/// Recognise a message, tracking whether a `(lang …)` wrapper encloses it.
579///
580/// Wrappers propagate the scope they were found in, so
581/// `(lang d (signed "…" (offer …)))` recognises `offer` as scoped, while
582/// `(signed "…" (offer …))` does not.
583fn parse_message_scoped(sexpr: &SExpr, scope: LangScope) -> Result<Message, MessageParseError> {
584    let items = match sexpr {
585        SExpr::List(items) if !items.is_empty() => items,
586        SExpr::List(_) => return Err(MessageParseError(String::from("empty message"))),
587        _ => return Err(MessageParseError(String::from("message must be a list"))),
588    };
589
590    let head = match &items[0] {
591        SExpr::Atom(Atom::Symbol(s)) => s.as_str(),
592        _ => {
593            return Err(MessageParseError(String::from(
594                "message head must be a symbol",
595            )))
596        }
597    };
598
599    match head {
600        "meta" => parse_meta(&items[1..]),
601        "lang" => parse_dialect_msg(&items[1..]),
602        w if WrapperType::parse(w).is_some() => {
603            parse_wrapped(WrapperType::parse(w).unwrap(), &items[1..], scope)
604        }
605        _ => parse_simple(head, &items[1..], scope),
606    }
607}
608
609fn parse_meta(tail: &[SExpr]) -> Result<Message, MessageParseError> {
610    if tail.is_empty() {
611        return Err(MessageParseError(String::from(
612            "meta message requires an operation",
613        )));
614    }
615    Ok(Message::Meta {
616        dialect_def: tail[0].clone(),
617    })
618}
619
620fn parse_dialect_msg(tail: &[SExpr]) -> Result<Message, MessageParseError> {
621    if tail.len() < 2 {
622        return Err(MessageParseError(String::from(
623            "dialect message requires dialect name and inner message",
624        )));
625    }
626    let dialect_name = match &tail[0] {
627        SExpr::Atom(Atom::Symbol(s)) => s.clone(),
628        _ => {
629            return Err(MessageParseError(String::from(
630                "dialect name must be a symbol",
631            )))
632        }
633    };
634    // Entering a `lang` wrapper is what puts the inner message in scope: the
635    // dialect name is now fixed by the message itself (REQ-033).
636    let inner = parse_message_scoped(&tail[1], LangScope::Scoped)?;
637    Ok(Message::Dialect {
638        dialect_name,
639        inner: Box::new(inner),
640    })
641}
642
643fn parse_wrapped(
644    wrapper: WrapperType,
645    tail: &[SExpr],
646    scope: LangScope,
647) -> Result<Message, MessageParseError> {
648    // The last list element is the inner message; everything before it is params.
649    let inner_idx = tail.iter().rposition(|item| matches!(item, SExpr::List(_)));
650    match inner_idx {
651        Some(idx) => {
652            if idx + 1 != tail.len() {
653                return Err(MessageParseError(String::from(
654                    "wrapper inner message must be last",
655                )));
656            }
657            // A wrapper neither establishes nor discards a lang scope; it
658            // carries through whatever it was found in.
659            let inner = parse_message_scoped(&tail[idx], scope)?;
660            let params = &tail[..idx];
661            validate_param_keywords(params)?;
662            let params = crate::canonical::canonical_params(params);
663            Ok(Message::Wrapped {
664                wrapper,
665                params,
666                content: Box::new(inner),
667            })
668        }
669        None => Err(MessageParseError(String::from(
670            "wrapped message requires an inner message",
671        ))),
672    }
673}
674
675/// Whether an S-expression is a single address token (`@key`).
676fn is_address(s: &SExpr) -> bool {
677    matches!(s, SExpr::Atom(Atom::Symbol(sym)) if sym.starts_with('@'))
678}
679
680/// Recognise parameter structure before normalising it (SPEC-042 REQ-4201).
681fn validate_param_keywords(params: &[SExpr]) -> Result<(), MessageParseError> {
682    let mut seen = alloc::collections::BTreeSet::new();
683    let mut i = 0;
684    while i < params.len() {
685        if let SExpr::Atom(Atom::Keyword(key)) = &params[i] {
686            if i + 1 == params.len() {
687                return Err(MessageParseError(alloc::format!(
688                    "keyword :{key} missing value"
689                )));
690            }
691            if !seen.insert(key) {
692                return Err(MessageParseError(alloc::format!(
693                    "duplicate keyword :{key}"
694                )));
695            }
696            i += 2;
697        } else {
698            i += 1;
699        }
700    }
701    Ok(())
702}
703
704/// Whether an S-expression is an *address group*: a single address `@x` or a
705/// non-empty list of addresses `(@a @b)`. These are exactly the forms the
706/// recipient position accepts, so they are forbidden as positional content
707/// (which is what keeps `@` sigil-disciplined and serialise ∘ parse injective).
708/// A mixed list like `(introduce @bob)` is not an address group — it is
709/// ordinary content with a nested address.
710fn is_address_group(s: &SExpr) -> bool {
711    match s {
712        SExpr::Atom(Atom::Symbol(sym)) => sym.starts_with('@'),
713        SExpr::List(items) => !items.is_empty() && items.iter().all(is_address),
714        _ => false,
715    }
716}
717
718fn parse_simple(
719    head: &str,
720    tail: &[SExpr],
721    scope: LangScope,
722) -> Result<Message, MessageParseError> {
723    validate_param_keywords(tail)?;
724    let performative = match CorePerformative::parse(head) {
725        Some(cp) => Performative::Core(cp),
726        // A custom performative outside a `(lang …)` wrapper has no
727        // deterministic dispatch: nothing in the message says which dialect
728        // defines it. Reject rather than resolve against the installed set
729        // (REQ-033) — see `LangScope`.
730        None if scope == LangScope::Unscoped => {
731            return Err(MessageParseError(alloc::format!(
732                "'{head}' is not a core performative; a dialect performative must be \
733                 invoked inside (lang <dialect> ...) so the message names the dialect \
734                 that defines it"
735            )))
736        }
737        None => Performative::Custom(String::from(head)),
738    };
739
740    let mut recipient = None;
741    let mut content = None;
742    let mut thread = None;
743    let mut sender_val = None;
744    let mut caused_by = None;
745    let mut params = Vec::new();
746    let mut i = 0;
747
748    // Check for a recipient as the first arg: an @-prefixed symbol
749    // (single) or a non-empty list of @-prefixed symbols (multicast,
750    // SPEC-014 REQ-622). An empty list stays content (pre-SPEC-014 form).
751    if i < tail.len() {
752        match &tail[i] {
753            SExpr::Atom(Atom::Symbol(s)) if s.starts_with('@') => {
754                recipient = Some(Recipients::One(s.clone()));
755                i += 1;
756            }
757            SExpr::List(items) if !items.is_empty() && items.iter().all(is_address) => {
758                let set: alloc::collections::BTreeSet<String> = items
759                    .iter()
760                    .map(|it| match it {
761                        SExpr::Atom(Atom::Symbol(s)) => s.clone(),
762                        _ => unreachable!("guarded by the match arm"),
763                    })
764                    .collect();
765                recipient = Some(Recipients::Set(set));
766                i += 1;
767            }
768            _ => {}
769        }
770    }
771
772    // Parse remaining args: first non-keyword is content, rest are params.
773    while i < tail.len() {
774        match &tail[i] {
775            SExpr::Atom(Atom::Keyword(k)) => {
776                if i + 1 >= tail.len() {
777                    return Err(MessageParseError(alloc::format!(
778                        "keyword :{k} missing value"
779                    )));
780                }
781                let val = &tail[i + 1];
782                if k == "thread" {
783                    thread = Some(extract_string_or_symbol(val));
784                } else if k == "sender" {
785                    sender_val = Some(extract_string_or_symbol(val));
786                } else if k == "caused-by" {
787                    caused_by = Some(parse_caused_by(val)?);
788                } else {
789                    params.push(tail[i].clone());
790                    params.push(val.clone());
791                }
792                i += 2;
793            }
794            // An address group — a bare `@x` or an all-`@` list `(@a @b)` —
795            // is not data. These are exactly the forms the recipient parser
796            // accepts above, so admitting them as content would overload the
797            // surface syntax and break serialise ∘ parse (a content address
798            // group re-parses as the recipient). Reject them in the positional
799            // slot; addresses belong in the recipient slot or a keyword value.
800            // A *mixed* list (e.g. `(introduce @bob)`) is ordinary content —
801            // nested addresses are fine — as are `@`-runs inside a string.
802            positional if is_address_group(positional) => {
803                return Err(MessageParseError(alloc::format!(
804                    "address(es) '{positional}' in content position; addresses \
805                     go in the recipient slot or a keyword value"
806                )));
807            }
808            _ => {
809                if content.is_none() {
810                    content = Some(tail[i].clone());
811                } else {
812                    params.push(tail[i].clone());
813                }
814                i += 1;
815            }
816        }
817    }
818
819    Ok(Message::Simple {
820        performative,
821        recipient,
822        content: content.unwrap_or(SExpr::List(Vec::new())),
823        params: crate::canonical::canonical_params(&params),
824        thread,
825        sender: sender_val,
826        caused_by,
827    })
828}
829
830/// Parse the value of a `:caused-by` keyword parameter.
831///
832/// Accepts three forms:
833/// - `"begin"` or `begin` symbol → `CausedBy::Begin`
834/// - Single atom (hash) → `CausedBy::Single(hash)`
835/// - List of atoms (hashes) → `CausedBy::Multiple(sorted_hashes)`
836fn parse_caused_by(val: &SExpr) -> Result<CausedBy, MessageParseError> {
837    match val {
838        SExpr::Atom(Atom::Symbol(s)) if s == BEGIN_KEYWORD => Ok(CausedBy::Begin),
839        SExpr::Atom(Atom::Str(s)) if s == BEGIN_KEYWORD => Ok(CausedBy::Begin),
840        SExpr::Atom(Atom::Symbol(s)) => Ok(CausedBy::Single(s.clone())),
841        SExpr::Atom(Atom::Str(s)) => Ok(CausedBy::Single(s.clone())),
842        SExpr::List(items) => {
843            if items.is_empty() {
844                return Err(MessageParseError(String::from(
845                    ":caused-by list must not be empty",
846                )));
847            }
848            let mut hashes = Vec::with_capacity(items.len());
849            for item in items {
850                match item {
851                    SExpr::Atom(Atom::Symbol(s)) | SExpr::Atom(Atom::Str(s)) => {
852                        hashes.push(s.clone());
853                    }
854                    _ => {
855                        return Err(MessageParseError(String::from(
856                            ":caused-by list elements must be symbols or strings",
857                        )));
858                    }
859                }
860            }
861            // Canonical ordering: sort lexicographically (REQ-202)
862            hashes.sort();
863            Ok(CausedBy::Multiple(hashes))
864        }
865        _ => Err(MessageParseError(String::from(
866            ":caused-by value must be a symbol, string, or list of hashes",
867        ))),
868    }
869}
870
871fn extract_string_or_symbol(sexpr: &SExpr) -> String {
872    match sexpr {
873        SExpr::Atom(Atom::Str(s)) | SExpr::Atom(Atom::Symbol(s)) => s.clone(),
874        other => alloc::format!("{other}"),
875    }
876}
877
878// ---------------------------------------------------------------------------
879// Tests
880// ---------------------------------------------------------------------------
881
882#[cfg(test)]
883mod tests {
884    use super::*;
885    use alloc::string::ToString;
886
887    #[test]
888    fn core_performative_names_count() {
889        assert_eq!(CORE_PERFORMATIVE_NAMES.len(), 8);
890    }
891
892    #[test]
893    fn is_core_performative() {
894        assert!(is_core_performative_name("tell"));
895        assert!(is_core_performative_name("bye"));
896        assert!(!is_core_performative_name("custom-perf"));
897    }
898
899    #[test]
900    fn core_performative_roundtrip() {
901        for name in CORE_PERFORMATIVE_NAMES {
902            let cp = CorePerformative::parse(name).unwrap();
903            assert_eq!(cp.as_str(), *name);
904        }
905    }
906
907    #[test]
908    fn performative_name() {
909        assert_eq!(Performative::Core(CorePerformative::Tell).name(), "tell");
910        assert_eq!(
911            Performative::Custom(String::from("propose-step")).name(),
912            "propose-step"
913        );
914    }
915
916    #[test]
917    fn wrapper_type_roundtrip() {
918        for (s, w) in [
919            ("envelope", WrapperType::Envelope),
920            ("signed", WrapperType::Signed),
921            ("with-limits", WrapperType::WithLimits),
922        ] {
923            assert_eq!(WrapperType::parse(s), Some(w));
924            assert_eq!(w.as_str(), s);
925        }
926        assert_eq!(WrapperType::parse("unknown"), None);
927    }
928
929    #[test]
930    fn message_type_classification() {
931        let simple = Message::Simple {
932            performative: Performative::Core(CorePerformative::Tell),
933            recipient: None,
934            content: SExpr::Atom(Atom::Str("hi".into())),
935            params: vec![],
936            thread: None,
937            sender: None,
938            caused_by: None,
939        };
940        assert_eq!(simple.message_type(), MessageType::Simple);
941
942        let meta = Message::Meta {
943            dialect_def: SExpr::List(vec![]),
944        };
945        assert_eq!(meta.message_type(), MessageType::Meta);
946
947        let dialect = Message::Dialect {
948            dialect_name: "test".into(),
949            inner: Box::new(simple.clone()),
950        };
951        assert_eq!(dialect.message_type(), MessageType::Dialect);
952
953        let wrapped = Message::Wrapped {
954            wrapper: WrapperType::Envelope,
955            params: vec![],
956            content: Box::new(simple),
957        };
958        assert_eq!(wrapped.message_type(), MessageType::Wrapped);
959    }
960
961    // -- Typed extraction --
962
963    #[test]
964    fn simple_extraction_methods() {
965        let msg = Message::Simple {
966            performative: Performative::Core(CorePerformative::Tell),
967            recipient: Some("@bob".into()),
968            content: SExpr::Atom(Atom::Str("hello".into())),
969            params: vec![],
970            thread: Some("conv-1".into()),
971            sender: Some("@alice".into()),
972            caused_by: None,
973        };
974        assert_eq!(msg.performative().unwrap().name(), "tell");
975        assert_eq!(msg.recipient(), Some("@bob"));
976        assert_eq!(msg.content(), Some(&SExpr::Atom(Atom::Str("hello".into()))));
977        assert_eq!(msg.thread(), Some("conv-1"));
978        assert_eq!(msg.sender(), Some("@alice"));
979        assert!(msg.dialect_def().is_none());
980        assert!(msg.inner_message().is_none());
981        assert!(msg.wrapper_type().is_none());
982    }
983
984    #[test]
985    fn meta_extraction_methods() {
986        let def = SExpr::List(vec![
987            SExpr::Atom(Atom::Symbol("define".into())),
988            SExpr::Atom(Atom::Symbol("test-dialect".into())),
989        ]);
990        let msg = Message::Meta {
991            dialect_def: def.clone(),
992        };
993        assert_eq!(msg.dialect_def(), Some(&def));
994        assert!(msg.performative().is_none());
995    }
996
997    #[test]
998    fn dialect_extraction_methods() {
999        let inner = Message::Simple {
1000            performative: Performative::Core(CorePerformative::Tell),
1001            recipient: None,
1002            content: SExpr::Atom(Atom::Str("hi".into())),
1003            params: vec![],
1004            thread: None,
1005            sender: None,
1006            caused_by: None,
1007        };
1008        let msg = Message::Dialect {
1009            dialect_name: "logistics".into(),
1010            inner: Box::new(inner.clone()),
1011        };
1012        assert_eq!(msg.dialect_name(), Some("logistics"));
1013        assert_eq!(msg.inner_message(), Some(&inner));
1014    }
1015
1016    #[test]
1017    fn wrapped_extraction_methods() {
1018        let inner = Message::Simple {
1019            performative: Performative::Core(CorePerformative::Tell),
1020            recipient: None,
1021            content: SExpr::Atom(Atom::Str("hi".into())),
1022            params: vec![],
1023            thread: None,
1024            sender: None,
1025            caused_by: None,
1026        };
1027        let msg = Message::Wrapped {
1028            wrapper: WrapperType::Signed,
1029            params: vec![SExpr::Atom(Atom::Str("sig".into()))],
1030            content: Box::new(inner.clone()),
1031        };
1032        assert_eq!(msg.wrapper_type(), Some(WrapperType::Signed));
1033        assert_eq!(msg.inner_message(), Some(&inner));
1034    }
1035
1036    // -- TryFrom<&SExpr> for Message --
1037
1038    fn sym(s: &str) -> SExpr {
1039        SExpr::Atom(Atom::Symbol(String::from(s)))
1040    }
1041
1042    fn str_expr(s: &str) -> SExpr {
1043        SExpr::Atom(Atom::Str(String::from(s)))
1044    }
1045
1046    fn kw(s: &str) -> SExpr {
1047        SExpr::Atom(Atom::Keyword(String::from(s)))
1048    }
1049
1050    fn list(items: Vec<SExpr>) -> SExpr {
1051        SExpr::List(items)
1052    }
1053
1054    #[test]
1055    fn try_from_simple_tell() {
1056        let sexpr = list(vec![sym("tell"), sym("@bob"), str_expr("hello")]);
1057        let msg = Message::try_from(&sexpr).unwrap();
1058        assert_eq!(msg.message_type(), MessageType::Simple);
1059        assert_eq!(msg.performative().unwrap().name(), "tell");
1060        assert_eq!(msg.recipient(), Some("@bob"));
1061        assert_eq!(msg.content(), Some(&str_expr("hello")));
1062    }
1063
1064    #[test]
1065    fn try_from_simple_no_recipient() {
1066        let sexpr = list(vec![sym("reply"), str_expr("done")]);
1067        let msg = Message::try_from(&sexpr).unwrap();
1068        assert!(msg.recipient().is_none());
1069        assert_eq!(msg.content(), Some(&str_expr("done")));
1070    }
1071
1072    #[test]
1073    fn try_from_simple_with_thread() {
1074        let sexpr = list(vec![
1075            sym("tell"),
1076            str_expr("hello"),
1077            kw("thread"),
1078            sym("conv-17"),
1079        ]);
1080        let msg = Message::try_from(&sexpr).unwrap();
1081        assert_eq!(msg.thread(), Some("conv-17"));
1082    }
1083
1084    #[test]
1085    fn try_from_simple_with_keyword_params() {
1086        let sexpr = list(vec![
1087            sym("ask"),
1088            sym("@alice"),
1089            str_expr("What?"),
1090            kw("timeout"),
1091            SExpr::Atom(Atom::Num(30)),
1092        ]);
1093        let msg = Message::try_from(&sexpr).unwrap();
1094        if let Message::Simple { params, .. } = &msg {
1095            assert_eq!(params.len(), 2); // :timeout and 30
1096        } else {
1097            panic!("expected Simple");
1098        }
1099    }
1100
1101    #[test]
1102    fn try_from_meta() {
1103        let op = list(vec![sym("define"), sym("test-dialect")]);
1104        let sexpr = list(vec![sym("meta"), op.clone()]);
1105        let msg = Message::try_from(&sexpr).unwrap();
1106        assert_eq!(msg.message_type(), MessageType::Meta);
1107        assert_eq!(msg.dialect_def(), Some(&op));
1108    }
1109
1110    #[test]
1111    fn try_from_dialect() {
1112        let inner = list(vec![sym("tell"), sym("@system"), str_expr("PKG-123")]);
1113        let sexpr = list(vec![sym("lang"), sym("logistics"), inner]);
1114        let msg = Message::try_from(&sexpr).unwrap();
1115        assert_eq!(msg.message_type(), MessageType::Dialect);
1116        assert_eq!(msg.dialect_name(), Some("logistics"));
1117        let inner_msg = msg.inner_message().unwrap();
1118        assert_eq!(inner_msg.message_type(), MessageType::Simple);
1119        assert_eq!(inner_msg.performative().unwrap().name(), "tell");
1120    }
1121
1122    #[test]
1123    fn try_from_wrapped_envelope() {
1124        let inner = list(vec![sym("tell"), sym("@bob"), str_expr("Hello")]);
1125        let sexpr = list(vec![
1126            sym("envelope"),
1127            kw("from"),
1128            sym("@alice"),
1129            kw("to"),
1130            sym("@bob"),
1131            inner,
1132        ]);
1133        let msg = Message::try_from(&sexpr).unwrap();
1134        assert_eq!(msg.message_type(), MessageType::Wrapped);
1135        assert_eq!(msg.wrapper_type(), Some(WrapperType::Envelope));
1136        if let Message::Wrapped { params, .. } = &msg {
1137            assert_eq!(params.len(), 4); // :from @alice :to @bob
1138        }
1139    }
1140
1141    #[test]
1142    fn try_from_wrapped_signed() {
1143        let inner = list(vec![sym("tell"), sym("@bob"), str_expr("Verified")]);
1144        let sexpr = list(vec![sym("signed"), str_expr("base64sig"), inner]);
1145        let msg = Message::try_from(&sexpr).unwrap();
1146        assert_eq!(msg.wrapper_type(), Some(WrapperType::Signed));
1147        if let Message::Wrapped { params, .. } = &msg {
1148            assert_eq!(params, &[str_expr("base64sig")]);
1149        }
1150    }
1151
1152    #[test]
1153    fn try_from_wrapped_with_limits() {
1154        let inner = list(vec![sym("tell"), sym("@bob"), str_expr("Constrained")]);
1155        let sexpr = list(vec![
1156            sym("with-limits"),
1157            kw("depth"),
1158            SExpr::Atom(Atom::Num(10)),
1159            kw("cpu"),
1160            SExpr::Atom(Atom::Num(100)),
1161            inner,
1162        ]);
1163        let msg = Message::try_from(&sexpr).unwrap();
1164        assert_eq!(msg.wrapper_type(), Some(WrapperType::WithLimits));
1165    }
1166
1167    #[test]
1168    fn try_from_errors() {
1169        // Empty list
1170        assert!(Message::try_from(&list(vec![])).is_err());
1171        // Non-list
1172        assert!(Message::try_from(&sym("hello")).is_err());
1173        // Non-symbol head
1174        assert!(Message::try_from(&list(vec![str_expr("tell")])).is_err());
1175        // Meta without operation
1176        assert!(Message::try_from(&list(vec![sym("meta")])).is_err());
1177        // Dialect without inner
1178        assert!(Message::try_from(&list(vec![sym("lang"), sym("d")])).is_err());
1179    }
1180
1181    #[test]
1182    fn message_parse_error_display() {
1183        let err = MessageParseError(String::from("test error"));
1184        assert_eq!(err.to_string(), "test error");
1185    }
1186
1187    // -- From<Message> for SExpr --
1188
1189    #[test]
1190    fn simple_to_sexpr() {
1191        let msg = Message::Simple {
1192            performative: Performative::Core(CorePerformative::Tell),
1193            recipient: Some("@bob".into()),
1194            content: str_expr("hello"),
1195            params: vec![],
1196            thread: None,
1197            sender: None,
1198            caused_by: None,
1199        };
1200        let sexpr = SExpr::from(msg);
1201        assert_eq!(sexpr.to_string(), "(tell @bob \"hello\")");
1202    }
1203
1204    #[test]
1205    fn simple_with_thread_to_sexpr() {
1206        let msg = Message::Simple {
1207            performative: Performative::Core(CorePerformative::Reply),
1208            recipient: None,
1209            content: str_expr("done"),
1210            params: vec![],
1211            thread: Some("conv-17".into()),
1212            sender: None,
1213            caused_by: None,
1214        };
1215        let sexpr = SExpr::from(msg);
1216        assert_eq!(sexpr.to_string(), "(reply \"done\" :thread \"conv-17\")");
1217    }
1218
1219    #[test]
1220    fn meta_to_sexpr() {
1221        let msg = Message::Meta {
1222            dialect_def: list(vec![sym("define"), sym("test-dialect")]),
1223        };
1224        let sexpr = SExpr::from(msg);
1225        assert_eq!(sexpr.to_string(), "(meta (define test-dialect))");
1226    }
1227
1228    #[test]
1229    fn dialect_to_sexpr() {
1230        let msg = Message::Dialect {
1231            dialect_name: "logistics".into(),
1232            inner: Box::new(Message::Simple {
1233                performative: Performative::Core(CorePerformative::Tell),
1234                recipient: Some("@system".into()),
1235                content: str_expr("PKG-123"),
1236                params: vec![],
1237                thread: None,
1238                sender: None,
1239                caused_by: None,
1240            }),
1241        };
1242        let sexpr = SExpr::from(msg);
1243        assert_eq!(
1244            sexpr.to_string(),
1245            "(lang logistics (tell @system \"PKG-123\"))"
1246        );
1247    }
1248
1249    #[test]
1250    fn wrapped_to_sexpr() {
1251        let msg = Message::Wrapped {
1252            wrapper: WrapperType::Signed,
1253            params: vec![str_expr("base64sig")],
1254            content: Box::new(Message::Simple {
1255                performative: Performative::Core(CorePerformative::Tell),
1256                recipient: Some("@bob".into()),
1257                content: str_expr("Verified"),
1258                params: vec![],
1259                thread: None,
1260                sender: None,
1261                caused_by: None,
1262            }),
1263        };
1264        let sexpr = SExpr::from(msg);
1265        assert_eq!(
1266            sexpr.to_string(),
1267            "(signed \"base64sig\" (tell @bob \"Verified\"))"
1268        );
1269    }
1270
1271    // -- Round-trip tests --
1272
1273    #[test]
1274    fn roundtrip_simple() {
1275        let original = list(vec![sym("tell"), sym("@bob"), str_expr("hello")]);
1276        let msg = Message::try_from(&original).unwrap();
1277        let back = SExpr::from(msg);
1278        assert_eq!(back, original);
1279    }
1280
1281    #[test]
1282    fn roundtrip_meta() {
1283        let original = list(vec![
1284            sym("meta"),
1285            list(vec![sym("query"), list(vec![sym("speak?"), sym("cbcl")])]),
1286        ]);
1287        let msg = Message::try_from(&original).unwrap();
1288        let back = SExpr::from(msg);
1289        assert_eq!(back, original);
1290    }
1291
1292    #[test]
1293    fn roundtrip_dialect() {
1294        let original = list(vec![
1295            sym("lang"),
1296            sym("logistics"),
1297            list(vec![sym("tell"), sym("@system"), str_expr("PKG-123")]),
1298        ]);
1299        let msg = Message::try_from(&original).unwrap();
1300        let back = SExpr::from(msg);
1301        assert_eq!(back, original);
1302    }
1303
1304    #[test]
1305    fn roundtrip_wrapped() {
1306        let original = list(vec![
1307            sym("signed"),
1308            str_expr("base64sig"),
1309            list(vec![sym("tell"), sym("@bob"), str_expr("Verified")]),
1310        ]);
1311        let msg = Message::try_from(&original).unwrap();
1312        let back = SExpr::from(msg);
1313        assert_eq!(back, original);
1314    }
1315
1316    #[test]
1317    fn custom_performative() {
1318        let sexpr = list(vec![sym("propose-step"), sym("s1"), sym("pickup")]);
1319        assert!(Message::try_from(&sexpr).is_err());
1320        let sexpr = list(vec![sym("lang"), sym("cbcl-planning"), sexpr]);
1321        let msg = Message::try_from(&sexpr).unwrap();
1322        assert_eq!(
1323            msg.innermost_simple().unwrap().performative(),
1324            Some(&Performative::Custom(String::from("propose-step")))
1325        );
1326    }
1327
1328    // -- CausedBy (REQ-202, TEST-202) --
1329
1330    #[test]
1331    fn caused_by_begin_symbol() {
1332        let sexpr = list(vec![
1333            sym("tell"),
1334            str_expr("hello"),
1335            kw("caused-by"),
1336            sym("begin"),
1337        ]);
1338        let msg = Message::try_from(&sexpr).unwrap();
1339        assert_eq!(msg.caused_by(), Some(&CausedBy::Begin));
1340    }
1341
1342    #[test]
1343    fn caused_by_begin_string() {
1344        let sexpr = list(vec![
1345            sym("tell"),
1346            str_expr("hello"),
1347            kw("caused-by"),
1348            str_expr("begin"),
1349        ]);
1350        let msg = Message::try_from(&sexpr).unwrap();
1351        assert_eq!(msg.caused_by(), Some(&CausedBy::Begin));
1352    }
1353
1354    #[test]
1355    fn caused_by_single_hash() {
1356        let sexpr = list(vec![
1357            sym("reply"),
1358            str_expr("done"),
1359            kw("caused-by"),
1360            sym("f1220abc123"),
1361        ]);
1362        let msg = Message::try_from(&sexpr).unwrap();
1363        assert_eq!(
1364            msg.caused_by(),
1365            Some(&CausedBy::Single(String::from("f1220abc123")))
1366        );
1367    }
1368
1369    #[test]
1370    fn caused_by_single_hash_string() {
1371        let sexpr = list(vec![
1372            sym("reply"),
1373            str_expr("done"),
1374            kw("caused-by"),
1375            str_expr("f1220abc123"),
1376        ]);
1377        let msg = Message::try_from(&sexpr).unwrap();
1378        assert_eq!(
1379            msg.caused_by(),
1380            Some(&CausedBy::Single(String::from("f1220abc123")))
1381        );
1382    }
1383
1384    #[test]
1385    fn caused_by_multiple_hashes() {
1386        let sexpr = list(vec![
1387            sym("ok"),
1388            str_expr("ack"),
1389            kw("caused-by"),
1390            list(vec![sym("f1220bbb"), sym("f1220aaa")]),
1391        ]);
1392        let msg = Message::try_from(&sexpr).unwrap();
1393        // Multiple hashes are sorted lexicographically
1394        assert_eq!(
1395            msg.caused_by(),
1396            Some(&CausedBy::Multiple(vec![
1397                String::from("f1220aaa"),
1398                String::from("f1220bbb"),
1399            ]))
1400        );
1401    }
1402
1403    #[test]
1404    fn caused_by_multiple_canonical_sort() {
1405        // Verify that different input orderings produce the same canonical form
1406        let sexpr1 = list(vec![
1407            sym("ok"),
1408            str_expr("ack"),
1409            kw("caused-by"),
1410            list(vec![sym("c"), sym("a"), sym("b")]),
1411        ]);
1412        let sexpr2 = list(vec![
1413            sym("ok"),
1414            str_expr("ack"),
1415            kw("caused-by"),
1416            list(vec![sym("b"), sym("c"), sym("a")]),
1417        ]);
1418        let msg1 = Message::try_from(&sexpr1).unwrap();
1419        let msg2 = Message::try_from(&sexpr2).unwrap();
1420        assert_eq!(msg1.caused_by(), msg2.caused_by());
1421        assert_eq!(
1422            msg1.caused_by(),
1423            Some(&CausedBy::Multiple(vec![
1424                String::from("a"),
1425                String::from("b"),
1426                String::from("c"),
1427            ]))
1428        );
1429    }
1430
1431    #[test]
1432    fn caused_by_none_when_absent() {
1433        let sexpr = list(vec![sym("tell"), str_expr("hello")]);
1434        let msg = Message::try_from(&sexpr).unwrap();
1435        assert!(msg.caused_by().is_none());
1436    }
1437
1438    #[test]
1439    fn caused_by_empty_list_error() {
1440        let sexpr = list(vec![
1441            sym("tell"),
1442            str_expr("hello"),
1443            kw("caused-by"),
1444            list(vec![]),
1445        ]);
1446        assert!(Message::try_from(&sexpr).is_err());
1447    }
1448
1449    #[test]
1450    fn caused_by_invalid_type_error() {
1451        let sexpr = list(vec![
1452            sym("tell"),
1453            str_expr("hello"),
1454            kw("caused-by"),
1455            SExpr::Atom(Atom::Num(42)),
1456        ]);
1457        assert!(Message::try_from(&sexpr).is_err());
1458    }
1459
1460    #[test]
1461    fn caused_by_roundtrip_begin() {
1462        let original = list(vec![
1463            sym("tell"),
1464            str_expr("hello"),
1465            kw("caused-by"),
1466            sym("begin"),
1467        ]);
1468        let msg = Message::try_from(&original).unwrap();
1469        let back = SExpr::from(msg);
1470        assert_eq!(back, original);
1471    }
1472
1473    #[test]
1474    fn caused_by_roundtrip_single() {
1475        let original = list(vec![
1476            sym("reply"),
1477            str_expr("done"),
1478            kw("caused-by"),
1479            sym("f1220abc"),
1480        ]);
1481        let msg = Message::try_from(&original).unwrap();
1482        let back = SExpr::from(msg);
1483        assert_eq!(back, original);
1484    }
1485
1486    #[test]
1487    fn caused_by_roundtrip_multiple_sorted() {
1488        // Input already sorted → roundtrip exact match
1489        let original = list(vec![
1490            sym("ok"),
1491            str_expr("ack"),
1492            kw("caused-by"),
1493            list(vec![sym("aaa"), sym("bbb"), sym("ccc")]),
1494        ]);
1495        let msg = Message::try_from(&original).unwrap();
1496        let back = SExpr::from(msg);
1497        assert_eq!(back, original);
1498    }
1499
1500    #[test]
1501    fn caused_by_roundtrip_multiple_canonicalized() {
1502        // Input unsorted → extract canonicalizes → roundtrip produces sorted form
1503        let input = list(vec![
1504            sym("ok"),
1505            str_expr("ack"),
1506            kw("caused-by"),
1507            list(vec![sym("ccc"), sym("aaa"), sym("bbb")]),
1508        ]);
1509        let msg = Message::try_from(&input).unwrap();
1510        let back = SExpr::from(msg);
1511        let expected = list(vec![
1512            sym("ok"),
1513            str_expr("ack"),
1514            kw("caused-by"),
1515            list(vec![sym("aaa"), sym("bbb"), sym("ccc")]),
1516        ]);
1517        assert_eq!(back, expected);
1518    }
1519
1520    #[test]
1521    fn caused_by_with_thread_and_sender() {
1522        let sexpr = list(vec![
1523            sym("tell"),
1524            sym("@bob"),
1525            str_expr("hello"),
1526            kw("thread"),
1527            sym("conv-1"),
1528            kw("sender"),
1529            sym("@alice"),
1530            kw("caused-by"),
1531            sym("f1220xyz"),
1532        ]);
1533        let msg = Message::try_from(&sexpr).unwrap();
1534        assert_eq!(msg.thread(), Some("conv-1"));
1535        assert_eq!(msg.sender(), Some("@alice"));
1536        assert_eq!(
1537            msg.caused_by(),
1538            Some(&CausedBy::Single(String::from("f1220xyz")))
1539        );
1540    }
1541
1542    #[test]
1543    fn caused_by_extract_hash_deterministic() {
1544        // REQ-202: extract → canonical → hash is deterministic
1545        use crate::canonical::canonical_encode;
1546
1547        let sexpr1 = list(vec![
1548            sym("ok"),
1549            str_expr("ack"),
1550            kw("caused-by"),
1551            list(vec![sym("z"), sym("a"), sym("m")]),
1552        ]);
1553        let sexpr2 = list(vec![
1554            sym("ok"),
1555            str_expr("ack"),
1556            kw("caused-by"),
1557            list(vec![sym("m"), sym("z"), sym("a")]),
1558        ]);
1559        let msg1 = Message::try_from(&sexpr1).unwrap();
1560        let msg2 = Message::try_from(&sexpr2).unwrap();
1561        let bytes1 = canonical_encode(&SExpr::from(msg1));
1562        let bytes2 = canonical_encode(&SExpr::from(msg2));
1563        assert_eq!(
1564            bytes1, bytes2,
1565            "canonical encoding must be deterministic after sorting"
1566        );
1567    }
1568
1569    // ---- SPEC-014 REQ-622: recipient sets ----
1570
1571    #[test]
1572    fn multicast_recipient_parses_and_roundtrips() {
1573        let sexpr: SExpr = "(lang oauth (login (@cli @as) \"n-42\" :caused-by h0))"
1574            .parse()
1575            .unwrap();
1576        let msg = Message::try_from(&sexpr).unwrap();
1577        let set = msg.innermost_simple().unwrap().recipient_set();
1578        assert_eq!(set.len(), 2);
1579        assert!(set.contains("@cli") && set.contains("@as"));
1580        // round-trip: serialise and re-parse preserves the set
1581        let back = SExpr::from(&msg);
1582        let msg2 = Message::try_from(&back).unwrap();
1583        assert_eq!(msg, msg2);
1584    }
1585
1586    #[test]
1587    fn multicast_serialisation_is_canonical_sorted() {
1588        let a: SExpr = "(lang oauth (login (@b @a) \"x\"))".parse().unwrap();
1589        let b: SExpr = "(lang oauth (login (@a @b) \"x\"))".parse().unwrap();
1590        let ma = Message::try_from(&a).unwrap();
1591        let mb = Message::try_from(&b).unwrap();
1592        assert_eq!(SExpr::from(&ma), SExpr::from(&mb));
1593    }
1594
1595    #[test]
1596    fn single_recipient_form_is_unchanged() {
1597        let sexpr: SExpr = "(tell @bob \"hi\")".parse().unwrap();
1598        let msg = Message::try_from(&sexpr).unwrap();
1599        assert_eq!(msg.recipient(), Some("@bob"));
1600        assert_eq!(SExpr::from(&msg), sexpr);
1601    }
1602
1603    #[test]
1604    fn empty_list_stays_content_not_recipient() {
1605        let sexpr: SExpr = "(tell () :thread \"t\")".parse().unwrap();
1606        let msg = Message::try_from(&sexpr).unwrap();
1607        assert!(msg.recipient_set().is_empty());
1608        assert_eq!(msg.content(), Some(&SExpr::List(Vec::new())));
1609    }
1610
1611    #[test]
1612    fn non_recipient_list_stays_content() {
1613        let sexpr: SExpr = "(tell (a b) \"x\")".parse().unwrap();
1614        let msg = Message::try_from(&sexpr).unwrap();
1615        assert!(msg.recipient_set().is_empty());
1616    }
1617
1618    // ---- Addresses are sigil-disciplined: a bare `@`-symbol is an address,
1619    // never positional content. Found by the role_layer round-trip fuzzer. ----
1620
1621    fn parses(src: &str) -> bool {
1622        let sexpr: SExpr = src.parse().unwrap();
1623        Message::try_from(&sexpr).is_ok()
1624    }
1625
1626    fn round_trips(src: &str) {
1627        let sexpr: SExpr = src.parse().unwrap();
1628        let msg = Message::try_from(&sexpr).unwrap();
1629        let back = SExpr::from(&msg);
1630        let msg2 = Message::try_from(&back).unwrap();
1631        assert_eq!(msg, msg2, "round-trip must be identity for {src}");
1632    }
1633
1634    #[test]
1635    fn address_group_in_content_position_is_rejected() {
1636        // Bare address after keyword params, no recipient (fuzzer find #1).
1637        assert!(!parses("(tell :session \"foo\" @key)"));
1638        // A second bare address after the recipient.
1639        assert!(!parses("(reply @alice @bob)"));
1640        // A bare address in a positional param slot (after content).
1641        assert!(!parses("(tell @client \"msg\" @extra)"));
1642        // An all-`@` *list* in the content position collides with the
1643        // recipient set form `(@a @b)` (fuzzer find #2).
1644        assert!(!parses("(tell :kw \"v\" (@a @b))"));
1645        assert!(!parses("(reply @dest (@a @b))"));
1646        // ...but the same list *leading* is a legitimate recipient set.
1647        assert!(parses("(tell (@@@))"));
1648        assert!(parses("(tell (@a @b) \"content\")"));
1649    }
1650
1651    #[test]
1652    fn addresses_in_content_are_fine_when_tagged_or_wrapped() {
1653        // Keyword value.
1654        assert!(parses("(tell @client :ref @bob :action \"review\")"));
1655        round_trips("(tell @client :ref @bob :action \"review\")");
1656        // Nested inside a structured (list) content.
1657        assert!(parses("(tell @client (introduce @bob))"));
1658        round_trips("(tell @client (introduce @bob))");
1659        // Inside a string literal — just text, not an address token.
1660        assert!(parses("(tell @client \"ping @bob\")"));
1661        round_trips("(tell @client \"ping @bob\")");
1662        // Multicast recipient set + string content (the paper's OAuth trace).
1663        assert!(parses(
1664            "(lang oauth (login (@cli @as) \"n-42\" \"profile\"))"
1665        ));
1666        round_trips("(lang oauth (login (@cli @as) \"n-42\" \"profile\"))");
1667    }
1668
1669    #[test]
1670    fn two_recipients_must_use_the_set_form() {
1671        // The nudge: `(@a @b)` is unambiguous; `@a @b` is not (and is rejected).
1672        assert!(parses("(reply (@alice @bob) \"ok\")"));
1673        assert!(!parses("(reply @alice @bob \"ok\")"));
1674    }
1675
1676    // ---- SPEC-014 REQ-625: with-roles typed wrapper ----
1677
1678    #[test]
1679    fn with_roles_parses_as_typed_wrapper() {
1680        let sexpr: SExpr =
1681            "(with-roles ((auctioneer @auc) (bidder @b1 @b2)) (signed @auc \"sig\" (hello :thread \"conv-7\" :caused-by begin)))"
1682                .parse()
1683                .unwrap();
1684        let msg = Message::try_from(&sexpr).unwrap();
1685        let Message::Wrapped {
1686            wrapper,
1687            params,
1688            content,
1689        } = &msg
1690        else {
1691            panic!("with-roles must parse as Wrapped, got {msg:?}");
1692        };
1693        assert_eq!(*wrapper, WrapperType::WithRoles);
1694        assert_eq!(params.len(), 1, "bindings list travels in params");
1695        // inner signed message carried unchanged
1696        let Message::Wrapped {
1697            wrapper: inner_w, ..
1698        } = content.as_ref()
1699        else {
1700            panic!("inner must be the signed wrapper");
1701        };
1702        assert_eq!(*inner_w, WrapperType::Signed);
1703        // round-trip
1704        let back = SExpr::from(&msg);
1705        assert_eq!(Message::try_from(&back).unwrap(), msg);
1706    }
1707
1708    #[test]
1709    fn with_roles_bindings_parse_into_cast() {
1710        use crate::role::{parse_cast, parse_roles};
1711        let sexpr: SExpr =
1712            "(with-roles ((auctioneer @auc) (bidder @b1 @b2)) (signed @auc \"sig\" (hello :caused-by begin)))"
1713                .parse()
1714                .unwrap();
1715        let msg = Message::try_from(&sexpr).unwrap();
1716        let Message::Wrapped { params, .. } = &msg else {
1717            unreachable!()
1718        };
1719        let roles = parse_roles(&"(auctioneer (* bidder))".parse().unwrap()).unwrap();
1720        let cast = parse_cast(&params[0], &roles).unwrap();
1721        assert_eq!(cast.indexed.get("bidder").unwrap().len(), 2);
1722    }
1723
1724    #[test]
1725    fn with_roles_dialect_pin_parses_into_cast() {
1726        // SPEC-014 REQ-628: the optional `:dialect f1220<hex64>` field
1727        // travels in the wrapper params and lands on `Cast::dialect_pin`.
1728        use crate::role::{parse_roles, parse_wrapper_cast};
1729        let pin = alloc::format!("f1220{}", "a".repeat(64));
1730        let sexpr: SExpr = alloc::format!(
1731            "(with-roles ((auctioneer @auc) (bidder @b1 @b2)) :dialect {pin} (signed @auc \"sig\" (hello :caused-by begin)))"
1732        )
1733        .parse()
1734        .unwrap();
1735        let msg = Message::try_from(&sexpr).unwrap();
1736        let Message::Wrapped { params, .. } = &msg else {
1737            unreachable!()
1738        };
1739        assert_eq!(params.len(), 3, "bindings + :dialect keyword + pin");
1740        let roles = parse_roles(&"(auctioneer (* bidder))".parse().unwrap()).unwrap();
1741        let cast = parse_wrapper_cast(params, &roles).unwrap();
1742        assert_eq!(cast.dialect_pin.as_deref(), Some(pin.as_str()));
1743        // round-trip preserves the pin
1744        let back = SExpr::from(&msg);
1745        assert_eq!(Message::try_from(&back).unwrap(), msg);
1746    }
1747}