Skip to main content

acl_core/
runtime.rs

1//! Protocol runtime (spec §33.4) and multiparty projection (§33.5).
2//!
3//! Phase 2: `Runtime` executes a compiled `.aclp` program as a live agent:
4//! deliver events in, actions come out, everything lands in an auditable
5//! transcript. Transport-agnostic and deterministic — a pure function of
6//! (program, delivered events).
7//!
8//! Phase 3: `project` compiles the GLOBAL protocol into a per-role
9//! ENDPOINT: each role sees only the handlers it must execute and the
10//! sends it must emit. Two projected endpoints, run side by side through
11//! two runtimes wired by a bus, reproduce the global conversation.
12
13use crate::dialogue::dialogue_legal;
14use crate::idl::IdlError;
15use crate::protocol::{EndWhen, Expr, Handler, OnTrigger, ProtocolAction, ProtocolProgram};
16use crate::cl::CommitmentStatus;
17use crate::Performative;
18use std::collections::BTreeMap;
19
20// ---------------------------------------------------------------- endpoints
21
22/// A per-role view of a global protocol (§33.5).
23#[derive(Debug, Clone, PartialEq)]
24pub struct RoleEndpoint {
25    pub role: String,
26    pub handlers: Vec<Handler>,
27}
28
29/// Which roles a handler's TRIGGER concerns: `on X from A` fires in the
30/// role(s) that are NOT A. With two roles this is exactly one role.
31pub fn handler_executor<'a>(prog: &'a ProtocolProgram, h: &Handler) -> Vec<&'a str> {
32    match &h.trigger {
33        // §43: `as <role>` restricts the executor to that ONE role
34        OnTrigger::Event { as_role: Some(r), .. } => prog
35            .roles
36            .iter()
37            .map(|s| s.as_str())
38            .filter(|x| *x == r.as_str())
39            .collect(),
40        OnTrigger::Event { from: Some(sender), .. } => prog
41            .roles
42            .iter()
43            .map(|s| s.as_str())
44            .filter(|r| *r != sender.as_str())
45            .collect(),
46        OnTrigger::Event { from: None, .. } => {
47            // unattributed trigger: every role EXCEPT none — in a 2-role
48            // protocol this is the counterpart; keep both for n>2 safety
49            prog.roles.iter().map(|s| s.as_str()).collect()
50        }
51        OnTrigger::Timer { as_role, .. } => match as_role {
52            // attributed timer: fires in that role only
53            Some(r) => prog
54                .roles
55                .iter()
56                .map(|s| s.as_str())
57                .filter(|x| *x == r.as_str())
58                .collect(),
59            None => prog.roles.iter().map(|s| s.as_str()).collect(),
60        },
61        OnTrigger::Breach | OnTrigger::Expired => {
62            // the DEBTOR reports: executor = the role that is NOT the
63            // handler's send target (send failure TO buyer ⇒ seller speaks)
64            let target = h.actions.iter().find_map(|a| match a {
65                ProtocolAction::Send { to: Some(t), .. } => Some(t.as_str()),
66                _ => None,
67            });
68            match target {
69                Some(t) if prog.roles.iter().any(|r| r == t) => prog
70                    .roles
71                    .iter()
72                    .map(|s| s.as_str())
73                    .filter(|r| *r != t)
74                    .collect(),
75                _ => prog.roles.iter().map(|s| s.as_str()).collect(),
76            }
77        }
78    }
79}
80
81/// Project a global protocol onto `role`'s endpoint (§33.5).
82///
83/// Rules (phase 3, two-role semantics):
84/// - a handler executes in the role that RECEIVES its trigger
85///   (`from R` ⇒ every role ≠ R; omitted ⇒ counterpart default)
86/// - `send X to R2` emits only in the executor's endpoint; `to` defaults
87///   to the counterpart of the executor
88/// - state actions (`begin`, `fulfil`, `retract`) execute in the executor
89pub fn project(prog: &ProtocolProgram, role: &str) -> Result<RoleEndpoint, Vec<IdlError>> {
90    let mut errors = Vec::new();
91    if !prog.roles.iter().any(|r| r == role) {
92        return Err(vec![IdlError {
93            line: 0,
94            message: format!("cannot project: role '{role}' is not declared"),
95        }]);
96    }
97    // §43: n-role projection — every handler already carries explicit
98    // attribution (check() requires `from` and `to` for 3+ role
99    // protocols); the projection itself is role-set agnostic
100    let two_role = prog.roles.len() == 2;
101    let other = prog
102        .roles
103        .iter()
104        .map(|s| s.as_str())
105        .find(|r| *r != role)
106        .unwrap_or("");
107
108    let mut handlers = Vec::new();
109    for h in &prog.handlers {
110        let executors = handler_executor(prog, h);
111        if !executors.contains(&role) {
112            continue; // this handler runs in the other endpoint
113        }
114        let mut actions = Vec::new();
115        for a in &h.actions {
116            match a {
117                ProtocolAction::Send { performative, to, fields, retry } => {
118                    // the sender is the executor; resolve the receiver
119                    let target = match to {
120                        Some(r) => {
121                            if !prog.roles.iter().any(|x| x == r) {
122                                errors.push(IdlError {
123                                    line: 0,
124                                    message: format!("send targets undeclared role '{r}'"),
125                                });
126                            }
127                            if r == role {
128                                errors.push(IdlError {
129                                    line: 0,
130                                    message: format!("send targets the sender role '{r}'"),
131                                });
132                            }
133                            Some(r.clone())
134                        }
135                        // §43: the counterpart default only exists in a
136                        // 2-role protocol; check() forces explicit `to`
137                        // otherwise
138                        None if two_role => Some(other.to_string()),
139                        None => {
140                            errors.push(IdlError {
141                                line: 0,
142                                message: format!(
143                                    "send without 'to' in a {}-role protocol (n-role requires explicit targets)",
144                                    prog.roles.len()
145                                ),
146                            });
147                            None
148                        }
149                    };
150                    if let Some(t) = target {
151                        if !t.is_empty() {
152                            // §33.5: the receiving role sees this send as an
153                            // incoming event — nothing to do in ITS handlers;
154                            // the executor emits it
155                            actions.push(ProtocolAction::Send {
156                                performative: *performative,
157                                to: Some(t),
158                                fields: fields.clone(),
159                                retry: retry.clone(),
160                            });
161                        }
162                    }
163                }
164                other_action => actions.push(other_action.clone()),
165            }
166        }
167        if !actions.is_empty() || matches!(h.trigger, OnTrigger::Event { .. }) {
168            handlers.push(Handler { trigger: h.trigger.clone(), guard: h.guard.clone(), actions, line: 0 });
169        }
170    }
171
172    if errors.is_empty() {
173        Ok(RoleEndpoint { role: role.to_string(), handlers })
174    } else {
175        Err(errors)
176    }
177}
178
179// ---------------------------------------------------------------- runtime
180
181/// Session variable value (phase 2: the types the runtime understands).
182#[derive(Debug, Clone, PartialEq)]
183pub enum StateValue {
184    Record(std::collections::BTreeMap<String, StateValue>),
185    Bool(bool),
186    Int(i64),
187    /// §38.3: floating-point values (inferred from pattern captures,
188    /// arithmetic results) — serialized as MsgPack f64 / JSON number
189    Float(f64),
190    Str(String),
191    /// §35: collections in session state
192    List(Vec<StateValue>),
193    Map(BTreeMap<String, StateValue>),
194    Unset,
195}
196
197/// Something that happens TO the agent.
198#[derive(Debug, Clone, PartialEq)]
199pub enum Event {
200    /// an incoming speech act from another role (`fields` = structured
201    /// payload for content matching, §34) — §46: values are TYPED on the
202    /// wire (FieldValue); string literals convert implicitly, so existing
203    /// construction sites keep compiling, and native int/float/bool skip
204    /// the `infer_value` heuristic entirely
205    In {
206        from: String,
207        performative: Performative,
208        pattern: Option<String>,
209        fields: Option<BTreeMap<String, FieldValue>>,
210    },
211    /// an owed commitment was broken (by the OTHER side or by time)
212    Breach,
213    /// §38.7: an internal action failure (set/push/put eval error, send
214    /// retry exhaustion) — routed to the session's `on error` handler
215    InternalError(String),
216    /// §49: a host time advance — journaled so replay reproduces timers,
217    /// awaits and retry deadlines EXACTLY
218    Tick(i64),
219    /// §49: a session close — journaled so replay closes the same sessions
220    SessionClosed,
221    /// §54: a session OPEN — journaled IN ORDER (with the role) so replay
222    /// respects capacity and session-ID reincarnations
223    SessionOpened { role: String },
224    /// the deadline passed
225    Expired,
226}
227
228/// Something the agent emits.
229#[derive(Debug, Clone, PartialEq)]
230pub struct OutEvent {
231    pub to: Option<String>,
232    pub performative: Performative,
233    /// structured payload (§34) — subset-matched by receiving handlers
234    pub fields: Option<BTreeMap<String, FieldValue>>,
235}
236
237/// §46: a typed field value on the wire — string literals convert
238/// implicitly (From<&str>/From<String>) so protocol programs keep working;
239/// native ints/floats/bools arrive typed and skip type inference
240#[derive(Debug, Clone, PartialEq)]
241pub enum FieldValue {
242    Str(String),
243    Int(i64),
244    Float(f64),
245    Bool(bool),
246}
247
248impl From<&str> for FieldValue {
249    fn from(s: &str) -> Self {
250        FieldValue::Str(s.to_string())
251    }
252}
253
254impl From<String> for FieldValue {
255    fn from(s: String) -> Self {
256        FieldValue::Str(s)
257    }
258}
259
260impl From<i64> for FieldValue {
261    fn from(i: i64) -> Self {
262        FieldValue::Int(i)
263    }
264}
265
266impl From<f64> for FieldValue {
267    fn from(f: f64) -> Self {
268        FieldValue::Float(f)
269    }
270}
271
272impl From<bool> for FieldValue {
273    fn from(b: bool) -> Self {
274        FieldValue::Bool(b)
275    }
276}
277
278impl From<FieldValue> for StateValue {
279    fn from(f: FieldValue) -> Self {
280        match f {
281            FieldValue::Str(s) => StateValue::Str(s),
282            FieldValue::Int(i) => StateValue::Int(i),
283            FieldValue::Float(f) => StateValue::Float(f),
284            FieldValue::Bool(b) => StateValue::Bool(b),
285        }
286    }
287}
288
289impl FieldValue {
290    /// the plain-text rendering used by string patterns and logs
291    pub fn text(&self) -> String {
292        match self {
293            FieldValue::Str(s) => s.clone(),
294            FieldValue::Int(i) => i.to_string(),
295            FieldValue::Float(f) => f.to_string(),
296            FieldValue::Bool(b) => b.to_string(),
297        }
298    }
299
300    /// §46: typed conversion — Str goes through infer_value (a string
301    /// payload may still BE a number written as text); native types pass
302    /// through untouched
303    pub fn to_state_value(&self) -> StateValue {
304        match self {
305            FieldValue::Str(s) => infer_value(s),
306            other => other.clone().into(),
307        }
308    }
309}
310
311impl From<crate::cl::ClValue> for FieldValue {
312    fn from(v: crate::cl::ClValue) -> Self {
313        use crate::cl::ClValue;
314        match v {
315            ClValue::Str(s) => FieldValue::Str(s),
316            ClValue::Int(i) => FieldValue::Int(i),
317            ClValue::Float(f) => FieldValue::Float(f),
318            ClValue::Bool(b) => FieldValue::Bool(b),
319            other => FieldValue::Str(format!("{other:?}")),
320        }
321    }
322}
323
324/// §44: a declarative `await` collector — armed by an action, fed by
325/// deliver(), completed or timed out by tick()
326#[derive(Debug, Clone)]
327struct AwaitSpec {
328    count_left: i64,
329    performative: Performative,
330    into: String,
331    deadline_ms: i64,
332    flag: String,
333}
334
335/// §35.5: a send awaiting retry — driven by tick(), not by a clock.
336#[derive(Debug, Clone, PartialEq)]
337pub struct PendingSend {
338    pub to: Option<String>,
339    pub performative: Performative,
340    pub fields: Option<BTreeMap<String, String>>,
341    pub attempts_left: u32,
342    pub next_due: i64,
343    pub backoff_ms: i64,
344    pub exponential: bool,
345}
346
347/// One line of the auditable transcript (§33.3).
348#[derive(Debug, Clone, PartialEq)]
349pub struct LogEntry {
350    pub seq: u64,
351    pub dir: Dir,
352    pub text: String,
353}
354
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356pub enum Dir {
357    In,
358    Out,
359    State,
360}
361
362/// The live agent for ONE role: program + session state + commitment
363/// lifecycle + transcript.
364pub struct Runtime {
365    pub role: String,
366    /// public session id (set by SessionHost)
367    pub session: Option<String>,
368    /// this role's projected view — the runtime NEVER sees handlers
369    /// that belong to another role (§33.5)
370    endpoint: RoleEndpoint,
371    end_when: Option<EndWhen>,
372    program_states: BTreeMap<String, String>,
373    states: BTreeMap<String, StateValue>,
374    /// §38.1: user-defined functions available to this role
375    functions: BTreeMap<String, crate::protocol::Function>,
376    commitment: CommitmentStatus,
377    log: Vec<LogEntry>,
378    seq: u64,
379    /// next due ms per handler index (timers)
380    timer_due: Vec<i64>,
381    /// §34 transcript verification: this role's last seen performative
382    pub(crate) last_seen: Option<Performative>,
383    /// §35.5: sends awaiting retry
384    pending: Vec<PendingSend>,
385    /// §38.7: recursion guard for internal-error routing
386    handling_error: bool,
387    /// §44: active await collectors
388    awaits: Vec<AwaitSpec>,
389    /// §50: current conversation phase (first declared phase, or "")
390    phase: String,
391    /// §51: named commitments — id -> lifecycle status
392    commitments: BTreeMap<String, CommitmentStatus>,
393    /// §50: declared phases (for enter validation)
394    phases: Vec<String>,
395    /// §45: active try/catch — the catch actions of the innermost `try`
396    catch_stack: Vec<Vec<ProtocolAction>>,
397    /// §45: set when a caught failure cuts the remaining body short
398    catch_jump: bool,
399    /// §45: true while catch actions run — failures inside a catch are
400    /// NOT caught by the same try (routes to the session's on error)
401    in_catch: bool,
402    /// §35.4: host-injected clock (set by tick)
403    now_ms: i64,
404    /// §35.3: message templates for fmt()
405    templates: Vec<(String, String)>,
406    /// §41: declared record types (for list<T>/map<K,V> element checks)
407    program_types: std::collections::BTreeMap<String, Vec<(String, String)>>,
408    /// abort latch: compensation runs once
409    aborted: bool,
410    /// §16 enforcement: reject off-policy replies (opt-in)
411    enforce_dialogue: bool,
412    /// last performative we SENT (awaiting a legal reply)
413    last_out: Option<Performative>,
414    /// §35.4: abort conditions from the program
415    abort_when: Vec<crate::protocol::Guard>,
416}
417
418static EMPTY_SCOPE: std::sync::LazyLock<BTreeMap<String, StateValue>> =
419    std::sync::LazyLock::new(|| BTreeMap::new());
420
421impl Runtime {
422    pub fn new(prog: &ProtocolProgram, role: &str) -> Result<Self, IdlError> {
423        if !prog.roles.iter().any(|r| r == role) {
424            return Err(IdlError {
425                line: 0,
426                message: format!("runtime role '{role}' is not declared in the protocol"),
427            });
428        }
429        let endpoint = project(prog, role).map_err(|e| {
430            e.into_iter().next().unwrap_or(IdlError {
431                line: 0,
432                message: "projection failed".into(),
433            })
434        })?;
435        Ok(Runtime {
436            role: role.to_string(),
437            endpoint,
438            end_when: prog.end_when.clone(),
439            program_states: prog
440                .states
441                .iter()
442                .map(|s| (s.name.clone(), s.ty.clone().unwrap_or_default()))
443                .collect(),
444            states: prog
445                .states
446                .iter()
447                .map(|s| (s.name.clone(), StateValue::Unset))
448                .collect(),
449            functions: prog
450                .functions
451                .iter()
452                .map(|f| (f.name.clone(), f.clone()))
453                .collect(),
454            commitment: CommitmentStatus::Proposed,
455            log: Vec::new(),
456            seq: 0,
457            timer_due: prog
458                .handlers
459                .iter()
460                .map(|_| 0i64)
461                .collect(),
462            last_seen: None,
463            pending: Vec::new(),
464            handling_error: false,
465            awaits: Vec::new(),
466            phase: prog.phases.first().cloned().unwrap_or_default(),
467            commitments: BTreeMap::new(),
468            phases: prog.phases.clone(),
469            catch_stack: Vec::new(),
470            catch_jump: false,
471            in_catch: false,
472            now_ms: 0,
473            aborted: false,
474            enforce_dialogue: false,
475            last_out: None,
476            templates: prog.templates.clone(),
477            program_types: prog.types.clone(),
478            abort_when: prog.abort_when.clone(),
479            session: None,
480        })
481    }
482
483    pub fn state(&self, name: &str) -> Option<&StateValue> {
484        self.states.get(name)
485    }
486
487    pub fn set_state(&mut self, name: &str, v: StateValue) -> Result<(), String> {
488        // §34: typed session states — assignments are checked against the
489        // declared type; mismatches are logged, never fatal
490        if let Some(decl) = self.states.keys().find(|k| *k == name) {
491            let declared = self
492                .program_states
493                .get(decl)
494                .cloned()
495                .unwrap_or_default();
496            let d: &str = &declared;
497            let mismatch = match (d, &v) {
498                ("bool", StateValue::Bool(_)) | ("int", StateValue::Int(_)) | ("str", StateValue::Str(_)) => false,
499                ("float", StateValue::Float(_)) | ("float", StateValue::Int(_)) => false,
500                ("list", StateValue::List(_)) | ("map", StateValue::Map(_)) => false,
501                ("bool", _) | ("int", _) | ("str", _) | ("float", _) | ("list", _) | ("map", _) => {
502                    v != StateValue::Unset
503                }
504                // §41: generic containers `list<T>` / `map<K,V>` — the
505                // container kind AND every element must match
506                (t, StateValue::List(items)) if t.starts_with("list<") => {
507                    let elem = &t[5..t.len() - 1];
508                    !items.iter().all(|it| self.value_matches_type(elem, it))
509                }
510                (t, StateValue::Map(entries)) if t.starts_with("map<") => {
511                    let inner = &t[4..t.len() - 1];
512                    let (kt, vt) = inner.split_once(',').unwrap_or(("str", inner));
513                    let (kt, vt) = (kt.trim(), vt.trim());
514                    !entries.iter().all(|(k, val)| {
515                        self.value_matches_type(kt, &StateValue::Str(k.clone()))
516                            && self.value_matches_type(vt, val)
517                    })
518                }
519                // §41: record-typed states — a Record with matching __type
520                (t, StateValue::Record(m)) => {
521                    !m.get("__type").map_or(false, |tv| {
522                        matches!(tv, StateValue::Str(s) if s == t)
523                    })
524                }
525                (t, StateValue::Map(m)) if !t.starts_with("map<") => {
526                    // a record literal assigned to a record-typed state is a
527                    // Map only from JSON roundtrips — accept maps with __type
528                    !m.get("__type").map_or(false, |tv| {
529                        matches!(tv, StateValue::Str(s) if s == t)
530                    })
531                }
532                (t, StateValue::List(_)) if t.starts_with("list<") => false,
533                (t, _) if self.is_declared_record(t) => {
534                    // record-typed state assigned a non-record value
535                    v != StateValue::Unset
536                }
537                _ => false, // vocabulary types: untyped
538            };
539            if mismatch {
540                return Err(format!(
541                    "type mismatch: state '{name}' is '{declared}' but assigned {}",
542                    value_text(&v)
543                ));
544            }
545        }
546        self.states.insert(name.to_string(), v);
547        Ok(())
548    }
549
550    fn is_declared_record(&self, ty: &str) -> bool {
551        self.program_types.contains_key(ty)
552    }
553
554    /// §41: does a value conform to a declared element/state type?
555    fn value_matches_type(&self, ty: &str, v: &StateValue) -> bool {
556        match (ty, v) {
557            (_, StateValue::Unset) => true,
558            ("bool", StateValue::Bool(_)) | ("int", StateValue::Int(_))
559            | ("str", StateValue::Str(_)) | ("float", StateValue::Float(_)) => true,
560            ("float", StateValue::Int(_)) => true,
561            ("list", StateValue::List(_)) | ("map", StateValue::Map(_)) => true,
562            (t, StateValue::Record(m)) => {
563                m.get("__type").map_or(false, |tv| {
564                    matches!(tv, StateValue::Str(s) if s == t)
565                })
566            }
567            (t, StateValue::Map(m)) if self.is_declared_record(t) => {
568                m.get("__type").map_or(false, |tv| {
569                    matches!(tv, StateValue::Str(s) if s == t)
570                })
571            }
572            (t, StateValue::List(items)) if t.starts_with("list<") => {
573                let elem = &t[5..t.len() - 1];
574                items.iter().all(|it| self.value_matches_type(elem, it))
575            }
576            (t, StateValue::Map(entries)) if t.starts_with("map<") => {
577                let inner = &t[4..t.len() - 1];
578                let (kt, vt) = inner.split_once(',').unwrap_or(("str", inner));
579                let (kt, vt) = (kt.trim(), vt.trim());
580                entries.iter().all(|(k, val)| {
581                    self.value_matches_type(kt, &StateValue::Str(k.clone()))
582                        && self.value_matches_type(vt, val)
583                })
584            }
585            _ => false,
586        }
587    }
588
589    /// §53: the current conversation phase (instance-scoped)
590    pub fn now_phase(&self) -> &str {
591        &self.phase
592    }
593
594    /// §49: the runtime clock (absolute, host-injected) — replay equality
595    pub fn now_ms(&self) -> i64 {
596        self.now_ms
597    }
598
599    /// §35.9: full state snapshot (for replay verification)
600    pub fn states_snapshot(&self) -> BTreeMap<String, StateValue> {
601        self.states.clone()
602    }
603
604    /// §35.1: evaluate a pure expression against state + event fields
605    fn eval(&self, e: &Expr, ev: &Event, scope: &BTreeMap<String, StateValue>) -> Result<StateValue, String> {
606        let arg = match ev {
607            Event::In { fields, .. } => fields.clone().unwrap_or_default(),
608            _ => BTreeMap::new(),
609        };
610        let eval = |e: &Expr, s: &Runtime, sc: &BTreeMap<String, StateValue>| -> Result<StateValue, String> { s.eval(e, ev, sc) };
611        Ok(match e {
612            Expr::LitInt(i) => StateValue::Int(*i),
613            Expr::LitStr(s) => StateValue::Str(s.clone()),
614            Expr::LitBool(b) => StateValue::Bool(*b),
615            Expr::State(n) => scope.get(n).cloned().unwrap_or_else(|| self.states.get(n).cloned().unwrap_or(StateValue::Unset)),
616            Expr::Capture(n) => scope.get(n).cloned().unwrap_or(StateValue::Unset),
617            Expr::Arg(a) => match arg.get(a) {
618                Some(v) => v.to_state_value(),
619                None => StateValue::Unset,
620            },
621            Expr::Not(x) => match eval(x, self, scope)? {
622                StateValue::Bool(b) => StateValue::Bool(!b),
623                other => StateValue::Bool(!self.truthy(&other)),
624            },
625            Expr::Bin { op, l, r } => {
626                let lv = eval(l, self, scope)?;
627                let rv = eval(r, self, scope)?;
628                use crate::protocol::BinOp::*;
629                match op {
630                    And => StateValue::Bool(self.truthy(&lv) && self.truthy(&rv)),
631                    Or => StateValue::Bool(self.truthy(&lv) || self.truthy(&rv)),
632                    Lt | Le | Gt | Ge | Eq | Ne => {
633                        let c = compare(&lv, &rv, *op)?;
634                        StateValue::Bool(c)
635                    }
636                    Add | Sub | Mul | Div => arithmetic(&lv, &rv, *op)?,
637                }
638            }
639            Expr::Field { base, name } => {
640                let b = eval(base, self, scope)?;
641                match b {
642                    StateValue::Record(m) => m.get(name).cloned().unwrap_or(StateValue::Unset),
643                    StateValue::Map(m) => m.get(name).cloned().unwrap_or(StateValue::Unset),
644                    _ => StateValue::Unset,
645                }
646            }
647            Expr::RecLit { ty, fields } => {
648                let mut m = std::collections::BTreeMap::new();
649                m.insert("__type".to_string(), StateValue::Str(ty.clone()));
650                for (n, e) in fields {
651                    m.insert(n.clone(), eval(e, self, scope)?);
652                }
653                StateValue::Record(m)
654            }
655            Expr::Call { name, args } => {
656                let vals: Vec<StateValue> = args
657                    .iter()
658                    .map(|a| eval(a, self, scope))
659                    .collect::<Result<_, _>>()?;
660                if name == "fmt" {
661                    // fmt(template_or_inline, args...) — §35.3 user templates
662                    // + §38.9 rich interpolation: `${expr}` (states, captures,
663                    // arithmetic, fields) evaluated in the caller's scope;
664                    // `$${` is the literal escape. A registered template name
665                    // wins over an inline literal.
666                    let tname = match vals.first() {
667                        Some(StateValue::Str(s)) => s.clone(),
668                        _ => return Err("fmt needs a template name".into()),
669                    };
670                    let template = match self.templates.iter().find(|(n, _)| *n == tname) {
671                        Some((_, t)) => t.clone(),
672                        None if tname.contains("${") => tname,
673                        None => return Err(format!("no message template '{tname}'")),
674                    };
675                    let esc = "\u{1}";
676                    let mut out = String::new();
677                    let cs: Vec<char> = template.replace("$${", esc).chars().collect();
678                    let mut i = 0;
679                    while i < cs.len() {
680                        if cs[i] == '$' && i + 1 < cs.len() && cs[i + 1] == '{' {
681                            let mut depth = 1i64;
682                            let mut j = i + 2;
683                            while j < cs.len() && depth > 0 {
684                                match cs[j] {
685                                    '{' => depth += 1,
686                                    '}' => depth -= 1,
687                                    _ => {}
688                                }
689                                j += 1;
690                            }
691                            if depth != 0 {
692                                return Err("unterminated ${ in template".into());
693                            }
694                            let src: String = cs[i + 2..j - 1].iter().collect();
695                            let e = crate::protocol::Expr::parse_expr(src.trim())?;
696                            let v = self.eval(&e, ev, scope)?;
697                            out.push_str(&value_text(&v));
698                            i = j;
699                        } else {
700                            out.push(cs[i]);
701                            i += 1;
702                        }
703                    }
704                    let mut out = out.replace(esc, "${");
705                    // positional {i} placeholders still supported
706                    for (idx, v) in vals[1..].iter().enumerate() {
707                        out = out.replace(&format!("{{{idx}}}"), &value_text(v));
708                    }
709                    return Ok(StateValue::Str(out));
710                }
711                builtin(name, &vals)?
712            }
713        })
714    }
715
716    fn truthy(&self, v: &StateValue) -> bool {
717        match v {
718            StateValue::Bool(b) => *b,
719            StateValue::Int(i) => *i != 0,
720            StateValue::Float(f) => *f != 0.0,
721            StateValue::Str(s) => !s.is_empty(),
722            StateValue::List(l) => !l.is_empty(),
723            StateValue::Map(m) => !m.is_empty(),
724            StateValue::Record(m) => !m.is_empty(),
725            StateValue::Unset => false,
726        }
727    }
728
729    /// boolean view of session state for guard evaluation (§34)
730    fn bool_view(&self) -> BTreeMap<String, bool> {
731        self.states
732            .iter()
733            .map(|(k, v)| {
734                let b = match v {
735                    StateValue::Bool(b) => *b,
736                    StateValue::Int(i) => *i != 0,
737                    StateValue::Float(f) => *f != 0.0,
738                    StateValue::Str(s) => !s.is_empty(),
739                    StateValue::List(l) => !l.is_empty(),
740                    StateValue::Map(m) => !m.is_empty(),
741                    StateValue::Record(m) => !m.is_empty(),
742                    StateValue::Unset => false,
743                };
744                (k.clone(), b)
745            })
746            .collect()
747    }
748
749    /// §16: enable strict dialogue-matrix enforcement for this runtime
750    pub fn enforce_dialogue(&mut self, on: bool) {
751        self.enforce_dialogue = on;
752    }
753
754    pub fn commitment(&self) -> CommitmentStatus {
755        self.commitment
756    }
757
758    /// §51: lifecycle status of a NAMED commitment (Unset = unknown id)
759    pub fn commitment_status(&self, id: &str) -> Option<CommitmentStatus> {
760        self.commitments.get(id).copied()
761    }
762
763    pub fn transcript(&self) -> &[LogEntry] {
764        &self.log
765    }
766
767    fn log(&mut self, dir: Dir, text: String) {
768        self.seq += 1;
769        self.log.push(LogEntry { seq: self.seq, dir, text });
770    }
771
772    /// §38.7: route an internal failure to the session's `on error`
773    /// handler. The failure is always logged; the handler runs at most one
774    /// level deep (failures inside it are logged only — no error loops).
775    pub fn deliver_internal_error(&mut self, reason: String) -> Vec<OutEvent> {
776        self.log(Dir::State, format!("internal error: {reason}"));
777        if self.handling_error {
778            return Vec::new();
779        }
780        let ev = Event::InternalError(reason);
781        if let Some((hidx, caps)) = self.matching_handler(&ev) {
782            self.handling_error = true;
783            let out = self.run_handler(hidx, &ev, caps);
784            self.handling_error = false;
785            out
786        } else {
787            Vec::new()
788        }
789    }
790
791    /// Deliver an event: find the FIRST handler whose trigger matches and
792    /// execute its actions in order. Returns what the agent emits.
793    pub fn deliver(&mut self, ev: Event) -> Vec<OutEvent> {
794        // every incoming speech act enters the transcript, handled or not
795        self.log(Dir::In, event_text(&ev));
796        if let Event::In { performative, .. } = &ev {
797            self.last_seen = Some(*performative);
798        }
799        // §16: when enforcement is on, an incoming In-event must be a
800        // legal reply to our last outgoing move (off-policy = logged and
801        // silently dropped — the handler does NOT fire)
802        if self.enforce_dialogue {
803            if let Event::In { performative, .. } = &ev {
804                if let Some(prev) = self.last_out {
805                    if !dialogue_legal(prev, *performative) {
806                        self.log(
807                            Dir::State,
808                            format!(
809                                "off-policy reply dropped: {:?} after our {:?} (§16)",
810                                performative, prev
811                            ),
812                        );
813                        return Vec::new();
814                    }
815                }
816            }
817        }
818        // §44: an active await collector CONSUMES matching events (the
819        // collected payloads do not need handlers)
820        if let Event::In { performative, fields, .. } = &ev {
821            if let Some(i) = self.awaits.iter().position(|a| a.performative == *performative) {
822                let spec = self.awaits[i].clone();
823                let payload = StateValue::Map(
824                    fields
825                        .clone()
826                        .unwrap_or_default()
827                        .into_iter()
828                        .map(|(k, v)| (k, v.to_state_value()))
829                        .collect(),
830                );
831                // append to the list state
832                match self.states.get_mut(&spec.into) {
833                    Some(StateValue::List(l)) => l.push(payload),
834                    Some(slot) if matches!(slot, StateValue::Unset) => {
835                        *slot = StateValue::List(vec![payload]);
836                    }
837                    _ => {}
838                    None => {
839                        self.states.insert(spec.into.clone(), StateValue::List(vec![payload]));
840                    }
841                }
842                self.log(
843                    Dir::In,
844                    format!("await collected {} ({}/{} into {})", perf_name(spec.performative), spec.count_left, spec.count_left, spec.into),
845                );
846                if spec.count_left <= 1 {
847                    self.awaits.remove(i);
848                    let _ = self.set_state(&spec.flag, StateValue::Bool(true));
849                    self.log(Dir::State, format!("await satisfied: {} = true", spec.flag));
850                } else {
851                    self.awaits[i].count_left = spec.count_left - 1;
852                }
853                return Vec::new();
854            }
855        }
856        let (hidx, captures) = match self.matching_handler(&ev) {
857            Some((hidx, caps)) => (hidx, caps),
858            None => return Vec::new(),
859        };
860        let mut out = self.run_handler(hidx, &ev, captures);
861        // §35.4: abort conditions — checked after every delivery; when a
862        // guard holds, compensation handlers run once (latched)
863        if !self.aborted {
864            let guards = self.abort_when.clone();
865            for g in guards {
866                if g.eval(&self.bool_view()) {
867                    self.log(Dir::State, "abort condition met".into());
868                    out.extend(self.run_actions(&[ProtocolAction::Abort], &ev, &BTreeMap::new()));
869                    self.aborted = true;
870                    break;
871                }
872            }
873        }
874        out
875    }
876
877    fn matching_handler(&self, ev: &Event) -> Option<(usize, BTreeMap<String, StateValue>)> {
878        self.endpoint.handlers.iter().enumerate().find_map(|(i, h)| match (&h.trigger, ev) {
879            (OnTrigger::Event { performative, pattern, from, phase, .. }, Event::In { from: f, performative: p, pattern: pat, fields }) => {
880                let mut captures: BTreeMap<String, StateValue> = BTreeMap::new();
881                let content_ok = match (pattern.as_ref(), pat.as_ref(), fields) {
882                    // no pattern declared: matches anything
883                    (None, ..) => true,
884                    // literal pattern `("quote")`: equality with the event's pattern
885                    (Some(want), Some(got), _) if want.starts_with('(') => want == got,
886                    // §34 content pattern `{"k": "v"}`: subset match against
887                    // the event's structured fields; "*"-suffixed values are
888                    // prefix wildcards
889                    (Some(want), _, Some(fs)) if want.starts_with('{') => {
890                        match serde_json::from_str::<BTreeMap<String, String>>(want) {
891                            Ok(want_map) => want_map.iter().all(|(k, want_v)| {
892                                match fs.get(k) {
893                                    None => false,
894                                    Some(got_v) if want_v.ends_with('*') => {
895                                        got_v.text().starts_with(want_v.trim_end_matches('*'))
896                                    }
897                                    // §35.5: capture variables `{"k": "$var"}`
898                                    // — the event's value is bound to `var`,
899                                    // with §38.3 type inference (int, float,
900                                    // bool, else string)
901                                    Some(got_v) if want_v.starts_with('$') => {
902                                        captures.insert(want_v[1..].to_string(), got_v.to_state_value());
903                                        true
904                                    }
905                                    Some(got_v) => got_v.text() == want_v.to_string(),
906                                }
907                            }),
908                            Err(_) => false,
909                        }
910                    }
911                    // content pattern but event has no fields: no match
912                    (Some(_), _, None) => false,
913                    _ => false,
914                };
915                let guard_ok = h.guard.as_ref().map_or(true, |g| {
916                    match g {
917                        crate::protocol::Guard::ExprGuard(expr) => {
918                            // §38.3: expression guard — evaluate with captures
919                            // in scope; non-bool results use truthiness
920                            match self.eval(expr, ev, &captures) {
921                                Ok(v) => match v {
922                                    StateValue::Bool(b) => b,
923                                    _ => self.truthy(&v),
924                                },
925                                Err(_) => false, // eval error = guard fails
926                            }
927                        }
928                        _ => g.eval(&self.bool_view()),
929                    }
930                });
931                let phase_ok = match phase {
932                    Some(want) => self.phase == *want,
933                    None => true,
934                };
935                if content_ok
936                    && guard_ok
937                    && phase_ok
938                    && from.as_ref().map_or(true, |want| want == f)
939                    && (performative == p)
940                {
941                    return Some((i, captures));
942                }
943                None
944            }
945            (OnTrigger::Breach, Event::Breach) => Some((i, BTreeMap::new())),
946            (OnTrigger::Expired, Event::Expired) => Some((i, BTreeMap::new())),
947            // §38.7: internal failures match ONLY an unattributed `on error`
948            // handler (an `on error from X` is for external error messages)
949            (OnTrigger::Event { performative: Performative::Error, from: None, .. }, Event::InternalError(reason)) => {
950                let mut caps = BTreeMap::new();
951                caps.insert("reason".to_string(), StateValue::Str(reason.clone()));
952                Some((i, caps))
953            }
954            _ => None,
955        })
956    }
957
958    fn run_handler(&mut self, hidx: usize, ev: &Event, captures: BTreeMap<String, StateValue>) -> Vec<OutEvent> {
959        let actions = self.endpoint.handlers[hidx].actions.clone();
960        let mut out = Vec::new();
961        for a in &actions {
962            match a {
963                ProtocolAction::Send { performative, to, fields, retry } => {
964                    // §53: payload values may interpolate `${expr}` —
965                    // correlation between the conversation and the wire
966                    let fields = fields.clone().map(|m| {
967                        m.into_iter()
968                            .map(|(k, v)| {
969                                let v2 = if v.contains("${") {
970                                    self.interp(&v, ev, &captures).unwrap_or_else(|e| {
971                                        self.log(Dir::State, format!("send {k}: interpolation failed: {e}"));
972                                        v
973                                    })
974                                } else {
975                                    v
976                                };
977                                (k, v2)
978                            })
979                            .collect::<BTreeMap<_, _>>()
980                    });
981                    self.last_out = Some(*performative);
982                    self.log(
983                        Dir::Out,
984                        format!(
985                            "send {} to {}{}{}",
986                            perf_name(*performative),
987                            to.clone().unwrap_or_default(),
988                            fields.clone().map(|f| format!(" {}", serde_json::to_string(&f).unwrap_or_default())).unwrap_or_default(),
989                            retry.as_ref().map(|r| format!(" retry={} backoff={}ms{}", r.attempts, r.backoff_ms, if r.exponential { " exp" } else { "" })).unwrap_or_default()
990                        ),
991                    );
992                    if let Some(rp) = retry {
993                        self.pending.push(PendingSend {
994                            to: to.clone(),
995                            performative: *performative,
996                            fields: fields.clone(),
997                            attempts_left: rp.attempts,
998                            next_due: self.now_ms + rp.backoff_ms,
999                            backoff_ms: rp.backoff_ms,
1000                            exponential: rp.exponential,
1001                        });
1002                    }
1003                    out.push(OutEvent {
1004                            to: to.clone(),
1005                            performative: *performative,
1006                            fields: fields.as_ref().map(|m| {
1007                                m.iter().map(|(k, v)| (k.clone(), FieldValue::Str(v.clone()))).collect()
1008                            }),
1009                        });
1010                }
1011                ProtocolAction::Broadcast { performative, fields, to } => {
1012                    // §38.8: fan-out — one OutEvent per role named in the
1013                    // list state; non-list target is an internal error
1014                    self.last_out = Some(*performative);
1015                    let snapshot = self.states.get(to).cloned();
1016                    match snapshot.as_ref() {
1017                        Some(StateValue::List(items)) => {
1018                            self.log(
1019                                Dir::Out,
1020                                format!(
1021                                    "broadcast {} to {} ({} targets){}",
1022                                    perf_name(*performative),
1023                                    to,
1024                                    items.len(),
1025                                    fields.clone().map(|f| format!(" {}", serde_json::to_string(&f).unwrap_or_default())).unwrap_or_default()
1026                                ),
1027                            );
1028                            for item in items {
1029                                let target = match item {
1030                                    StateValue::Str(s) => s.clone(),
1031                                    other => continue, // non-string entries skipped
1032                                };
1033                                out.push(OutEvent {
1034                                    to: Some(target),
1035                                    performative: *performative,
1036                                    fields: fields.as_ref().map(|m| {
1037                                        m.iter().map(|(k, v)| (k.clone(), FieldValue::Str(v.clone()))).collect()
1038                                    }),
1039                                });
1040                            }
1041                        }
1042                        other => {
1043                            let reason = format!("broadcast to '{to}': not a list ({:?})", other.map(value_text).unwrap_or_default());
1044                            self.action_failed(reason, &mut out, &captures);
1045                        }
1046                    }
1047                }
1048                ProtocolAction::BeginId { id } => {
1049                    // §51: activate a NAMED commitment
1050                    match self.commitments.get(id) {
1051                        Some(CommitmentStatus::Proposed) | Some(CommitmentStatus::Active) => {
1052                            self.log(Dir::State, format!("begin {id} ignored: is {:?}", self.commitments.get(id).unwrap()));
1053                        }
1054                        _ => {
1055                            self.commitments.insert(id.clone(), CommitmentStatus::Active);
1056                            self.log(Dir::State, format!("commitment {id} -> active"));
1057                        }
1058                    }
1059                }
1060                ProtocolAction::FulfilId { id } => {
1061                    match self.commitments.get(id) {
1062                        Some(CommitmentStatus::Active) => {
1063                            self.commitments.insert(id.clone(), CommitmentStatus::Fulfilled);
1064                            self.log(Dir::State, format!("commitment {id} -> fulfilled"));
1065                        }
1066                        other => self.log(
1067                            Dir::State,
1068                            format!("fulfil {id} ignored: is {other:?}, not Active"),
1069                        ),
1070                    }
1071                }
1072                ProtocolAction::Enter { phase } => {
1073                    // §50: conversation phase transition
1074                    if self.phases.iter().any(|p| p == phase) {
1075                        self.phase = phase.clone();
1076                        self.log(Dir::State, format!("phase -> {phase}"));
1077                    } else {
1078                        out.extend(self.deliver_internal_error(format!(
1079                            "enter '{phase}': not a declared phase"
1080                        )));
1081                    }
1082                }
1083                ProtocolAction::Try { body, catch } => {
1084                    // §45: handler-local error flow
1085                    self.catch_stack.push(catch.clone());
1086                    let inner = self.run_actions(body, ev, &captures);
1087                    self.catch_stack.pop();
1088                    // §55: the cut stops at the try boundary
1089                    self.catch_jump = false;
1090                    out.extend(inner);
1091                }
1092                ProtocolAction::Await { count, performative, into, within_ms, flag } => {
1093                    // §44: arm the collector; flag starts false
1094                    self.awaits.push(AwaitSpec {
1095                        count_left: *count,
1096                        performative: *performative,
1097                        into: into.clone(),
1098                        deadline_ms: self.now_ms + within_ms,
1099                        flag: flag.clone(),
1100                    });
1101                    let _ = self.set_state(flag, StateValue::Bool(false));
1102                    self.log(
1103                        Dir::State,
1104                        format!(
1105                            "await {} {}: waiting for {} {} into {} within {}ms",
1106                            count, flag, count, perf_name(*performative), into, within_ms
1107                        ),
1108                    );
1109                }
1110                ProtocolAction::Set { name, field, expr } => match self.eval(expr, ev, &captures) {
1111                    Ok(v) => {
1112                        if let Err(e) = self.set_state(name, v.clone()) {
1113                            self.action_failed(format!("set {name}: {e}"), &mut out, &captures);
1114                        } else {
1115                            self.log(Dir::State, format!("set {} = {}", name, value_text(&v)));
1116                        }
1117                    }
1118                    Err(e) => self.action_failed(format!("set {name}: {e}"), &mut out, &captures),
1119                },
1120                ProtocolAction::Push { state, expr } => match self.eval(expr, ev, &captures) {
1121                    Ok(v) => {
1122                        let is_list = matches!(self.states.get(state), Some(StateValue::List(_)) | Some(StateValue::Unset) | None);
1123                        // §41: element must match a `list<T>` declaration
1124                        if is_list {
1125                            if let Some(ty) = self.program_states.get(state) {
1126                                if let Some(elem) = ty.strip_prefix("list<").map(|t| t.strip_suffix('>').unwrap_or(t)) {
1127                                    if ty.starts_with("list<") && !self.value_matches_type(elem, &v) {
1128                                        self.action_failed(
1129                                            format!(
1130                                            "push {state}: element {} does not match '{ty}'",
1131                                            value_text(&v)),
1132                                            &mut out,
1133                                            &captures,
1134                                        );
1135                                        continue;
1136                                    }
1137                                }
1138                            }
1139                        }
1140                        if !is_list {
1141                            let other = self.states.get(state).cloned().unwrap_or(StateValue::Unset);
1142                            let reason = format!("push {state}: not a list ({})", value_text(&other));
1143                            self.action_failed(reason, &mut out, &captures);
1144                            continue;
1145                        }
1146                        match self.states.get_mut(state) {
1147                            Some(StateValue::List(l)) => l.push(v),
1148                            _ => {
1149                                self.states.insert(state.clone(), StateValue::List(vec![v]));
1150                            }
1151                        }
1152                        self.log(Dir::State, format!("push {}", state));
1153                    }
1154                    Err(e) => self.action_failed(format!("push {state}: {e}"), &mut out, &captures),
1155                },
1156                ProtocolAction::Put { state, key, expr } => match self.eval(expr, ev, &captures) {
1157                    Ok(v) => {
1158                        let is_map = matches!(self.states.get(state), Some(StateValue::Map(_)) | Some(StateValue::Unset) | None);
1159                        // §41: key/value must match a `map<K,V>` declaration
1160                        if is_map {
1161                            if let Some(ty) = self.program_states.get(state) {
1162                                if let Some(inner) = ty.strip_prefix("map<").map(|t| t.strip_suffix('>').unwrap_or(t)) {
1163                                    if ty.starts_with("map<") {
1164                                        let (kt, vt) = inner.split_once(',').map(|(a, b)| (a.trim(), b.trim())).unwrap_or(("str", inner));
1165                                        let kv = StateValue::Str(key.clone());
1166                                        if !self.value_matches_type(kt, &kv) || !self.value_matches_type(vt, &v) {
1167                                            self.action_failed(
1168format!(
1169                                                "put {state}[{key}]: key/value does not match '{ty}'"),
1170&mut out,
1171&captures,
1172);
1173                                            continue;
1174                                            continue;
1175                                        }
1176                                    }
1177                                }
1178                            }
1179                        }
1180                        if !is_map {
1181                            let other = self.states.get(state).cloned().unwrap_or(StateValue::Unset);
1182                            let reason = format!("put {state}: not a map ({})", value_text(&other));
1183                            self.action_failed(reason, &mut out, &captures);
1184                            continue;
1185                        }
1186                        match self.states.get_mut(state) {
1187                            Some(StateValue::Map(m)) => {
1188                                m.insert(key.clone(), v);
1189                            }
1190                            _ => {
1191                                self.states.insert(state.clone(), StateValue::Map(BTreeMap::from([(key.clone(), v)])));
1192                            }
1193                        }
1194                        self.log(Dir::State, format!("put {}[{}]", state, key));
1195                    }
1196                    Err(e) => self.action_failed(format!("put {state}: {e}"), &mut out, &captures),
1197                },
1198                ProtocolAction::For { var, over, actions } => {
1199                    // iterate a SNAPSHOT (the body may mutate the list);
1200                    // the loop var is a scoped state, restored after
1201                    let snapshot = match self.states.get(over) {
1202                        Some(StateValue::List(l)) => l.clone(),
1203                        Some(other) => {
1204                            self.log(Dir::State, format!("for {}: not a list ({:?})", over, other));
1205                            continue;
1206                        }
1207                        None => continue,
1208                    };
1209                    let saved = self.states.get(var).cloned();
1210                    self.log(Dir::State, format!("for {} in {} ({} items)", var, over, snapshot.len()));
1211                    for item in snapshot {
1212                        self.states.insert(var.clone(), item.clone());
1213                        out.extend(self.run_actions(actions, ev, &captures));
1214                    }
1215                    match saved {
1216                        Some(v) => {
1217                            self.states.insert(var.clone(), v);
1218                        }
1219                        None => {
1220                            self.states.remove(var);
1221                        }
1222                    }
1223                }
1224                ProtocolAction::Return { expr } => {
1225                // Evaluated but not printed in the transcript
1226                let _ = self.eval(expr, ev, &captures);
1227            }
1228            ProtocolAction::Abort => {
1229                    // §35.4: fire compensation handlers, mark breached
1230                    self.log(Dir::State, "ABORT: compensation begins".into());
1231                    self.commitment = CommitmentStatus::Breached;
1232                    let abort_handlers: Vec<usize> = self
1233                        .endpoint
1234                        .handlers
1235                        .iter()
1236                        .enumerate()
1237                        .filter(|(_, h)| matches!(h.trigger, OnTrigger::Breach))
1238                        .map(|(i, _)| i)
1239                        .collect();
1240                    for i in abort_handlers {
1241                        out.extend(self.run_handler(i, &Event::Breach, BTreeMap::new()));
1242                    }
1243                }
1244                ProtocolAction::Begin => match self.commitment {
1245                    CommitmentStatus::Proposed => {
1246                        self.commitment = CommitmentStatus::Active;
1247                        self.log(Dir::State, "commitment proposed -> active".into());
1248                    }
1249                    other => self.log(
1250                        Dir::State,
1251                        format!("begin ignored: commitment is {other:?}, not Proposed"),
1252                    ),
1253                },
1254                ProtocolAction::Fulfil => match self.commitment {
1255                    CommitmentStatus::Active => {
1256                        self.commitment = CommitmentStatus::Fulfilled;
1257                        self.log(Dir::State, "commitment active -> fulfilled".into());
1258                    }
1259                    other => self.log(
1260                        Dir::State,
1261                        format!("fulfil ignored: commitment is {other:?}, not Active"),
1262                    ),
1263                },
1264                ProtocolAction::Retract { target } => {
1265                    // §32.1 as a statement: the fact becomes retracted in
1266                    // this role's view; the transcript keeps the history
1267                    let _ = self.set_state(target, StateValue::Bool(false));
1268                    self.log(Dir::State, format!("retract({target})"));
1269                }
1270            }
1271        }
1272        out
1273    }
1274
1275    /// run a list of actions (used by `for` bodies)
1276    /// §53: interpolate `${expr}` in a template string with the session
1277    /// scope — shared by fmt() and send/broadcast payloads
1278    fn interp(&self, template: &str, ev: &Event, scope: &BTreeMap<String, StateValue>) -> Result<String, String> {
1279        let esc = "\u{1}";
1280        let mut out = String::new();
1281        let cs: Vec<char> = template.replace("$${", esc).chars().collect();
1282        let mut i = 0;
1283        while i < cs.len() {
1284            if cs[i] == '$' && i + 1 < cs.len() && cs[i + 1] == '{' {
1285                let mut depth = 1i64;
1286                let mut j = i + 2;
1287                while j < cs.len() && depth > 0 {
1288                    match cs[j] {
1289                        '{' => depth += 1,
1290                        '}' => depth -= 1,
1291                        _ => {}
1292                    }
1293                    j += 1;
1294                }
1295                if depth != 0 {
1296                    return Err("unterminated ${ in template".into());
1297                }
1298                let src: String = cs[i + 2..j - 1].iter().collect();
1299                let e = crate::protocol::Expr::parse_expr(src.trim())?;
1300                let v = self.eval(&e, ev, scope)?;
1301                out.push_str(&value_text(&v));
1302                i = j;
1303            } else {
1304                out.push(cs[i]);
1305                i += 1;
1306            }
1307        }
1308        Ok(out.replace(esc, "${"))
1309    }
1310
1311    /// §45: route an action failure — inside a `try` the catch actions
1312    /// run and the remaining body is cut; otherwise the session's
1313    /// `on error` handler fires (§38.7)
1314    fn action_failed(
1315        &mut self,
1316        reason: String,
1317        out: &mut Vec<OutEvent>,
1318        captures: &BTreeMap<String, StateValue>,
1319    ) {
1320        if !self.in_catch {
1321            if let Some(catch) = self.catch_stack.last().cloned() {
1322                // §45: run the catch with catch suppression (a failure
1323                // INSIDE the catch routes to the session's on error), and
1324                // only THEN latch the body cut
1325                self.in_catch = true;
1326                self.log(Dir::State, format!("caught: {reason}"));
1327                out.extend(self.run_actions(&catch, &Event::InternalError(reason), captures));
1328                self.in_catch = false;
1329                self.catch_jump = true;
1330                return;
1331            }
1332        }
1333        out.extend(self.deliver_internal_error(reason));
1334    }
1335
1336
1337
1338
1339    fn run_actions(
1340        &mut self,
1341        actions: &[ProtocolAction],
1342        ev: &Event,
1343        captures: &BTreeMap<String, StateValue>,
1344    ) -> Vec<OutEvent> {
1345        let mut out = Vec::new();
1346        for a in actions {
1347            // §55: a caught failure cuts the remaining body — the flag is
1348            // cleared at the try boundary (so the cut propagates through
1349            // enclosing for loops too)
1350            if self.catch_jump {
1351                break;
1352            }
1353            match a {
1354                ProtocolAction::For { .. } | ProtocolAction::Abort => {
1355                    // nested for: clone through a single-handler trick is
1356                    // overkill — inline recursively via a mini handler
1357                    match a {
1358                        ProtocolAction::For { var, over, actions } => {
1359                            let snapshot = match self.states.get(over) {
1360                                Some(StateValue::List(l)) => l.clone(),
1361                                _ => continue,
1362                            };
1363                            let saved = self.states.get(var).cloned();
1364                            for item in snapshot {
1365                                self.states.insert(var.clone(), item.clone());
1366                                out.extend(self.run_actions(actions, ev, &captures));
1367                                // §55: a caught failure inside the body cuts
1368                                // the remaining iterations
1369                                if self.catch_jump {
1370                                    break;
1371                                }
1372                            }
1373                            match saved {
1374                                Some(v) => {
1375                                    self.states.insert(var.clone(), v);
1376                                }
1377                                None => {
1378                                    self.states.remove(var);
1379                                }
1380                            }
1381                        }
1382                        ProtocolAction::Abort => {
1383                            self.log(Dir::State, "ABORT (nested): compensation begins".into());
1384                            self.commitment = CommitmentStatus::Breached;
1385                            let comp: Vec<usize> = self
1386                                .endpoint
1387                                .handlers
1388                                .iter()
1389                                .enumerate()
1390                                .filter(|(_, h)| matches!(h.trigger, OnTrigger::Breach))
1391                                .map(|(i, _)| i)
1392                                .collect();
1393                            for i in comp {
1394                                out.extend(self.run_handler(i, ev, BTreeMap::new()));
1395                            }
1396                        }
1397                        _ => unreachable!(),
1398                    }
1399                }
1400                other => {
1401                    // reuse run_handler's single-action logic by wrapping
1402                    let h = Handler { trigger: OnTrigger::Expired, guard: None, actions: vec![other.clone()], line: 0 };
1403                    self.endpoint.handlers.push(h);
1404                    let idx = self.endpoint.handlers.len() - 1;
1405                    out.extend(self.run_handler(idx, ev, captures.clone()));
1406                    self.endpoint.handlers.pop();
1407                }
1408            }
1409        }
1410        out
1411    }
1412
1413    /// Host-injected time (§34): the runtime stays clock-free; the
1414    /// transport host calls tick() with elapsed milliseconds and due
1415    /// timer handlers fire here, deterministically.
1416    pub fn tick(&mut self, elapsed_ms: i64) -> Vec<OutEvent> {
1417        let mut out = Vec::new();
1418        // collect due timers first (period + handler index), then fire —
1419        // avoids borrowing self.endpoint while mutating
1420        let due: Vec<(usize, i64)> = self
1421            .endpoint
1422            .handlers
1423            .iter()
1424            .enumerate()
1425            .filter_map(|(i, h)| {
1426                let OnTrigger::Timer { every_ms, guard, .. } = &h.trigger else { return None };
1427                let bools = self.bool_view();
1428                if let Some(g) = guard {
1429                    if !g.eval(&bools) {
1430                        return None; // guard false: timer silent this round
1431                    }
1432                }
1433                Some((i, *every_ms))
1434            })
1435            .collect();
1436        for (i, every_ms) in due {
1437            while self.timer_due[i] + every_ms <= elapsed_ms {
1438                self.timer_due[i] += every_ms;
1439                self.log(Dir::In, format!("timer({}ms)", every_ms));
1440                out.extend(self.run_handler(i, &Event::Expired, BTreeMap::new()));
1441            }
1442        }
1443        // §44: await deadlines — overdue collectors set the flag false
1444        let mut i = 0;
1445        while i < self.awaits.len() {
1446            if self.awaits[i].deadline_ms <= elapsed_ms {
1447                let spec = self.awaits.remove(i);
1448                let _ = self.set_state(&spec.flag, StateValue::Bool(false));
1449                self.log(
1450                    Dir::State,
1451                    format!("await timed out: {} = false", spec.flag),
1452                );
1453            } else {
1454                i += 1;
1455            }
1456        }
1457        // §35.5: retry pending sends when due; exhaustion = retry dropped
1458        // (logged; the caller sees only the original send)
1459        self.now_ms = elapsed_ms;
1460        let drained: Vec<PendingSend> = self.pending.drain(..).collect();
1461        let mut still_pending = Vec::new();
1462        for p in drained {
1463            if p.next_due <= elapsed_ms {
1464                if p.attempts_left > 1 {
1465                    let backoff = if p.exponential { p.backoff_ms * 2 } else { p.backoff_ms };
1466                    self.log(
1467                        Dir::Out,
1468                        format!(
1469                            "retry {} to {} ({} left)",
1470                            perf_name(p.performative),
1471                            p.to.clone().unwrap_or_default(),
1472                            p.attempts_left - 1
1473                        ),
1474                    );
1475                    out.push(OutEvent {
1476                            to: p.to.clone(),
1477                            performative: p.performative,
1478                            fields: p.fields.as_ref().map(|m| {
1479                                m.iter().map(|(k, v)| (k.clone(), FieldValue::Str(v.clone()))).collect()
1480                            }),
1481                        });
1482                    still_pending.push(PendingSend {
1483                        attempts_left: p.attempts_left - 1,
1484                        next_due: elapsed_ms + backoff,
1485                        backoff_ms: backoff,
1486                        ..p
1487                    });
1488                } else {
1489                    let reason = format!(
1490                        "send {} to {}: retry exhausted",
1491                        perf_name(p.performative),
1492                        p.to.clone().unwrap_or_default()
1493                    );
1494                    out.extend(self.deliver_internal_error(reason));
1495                }
1496            } else {
1497                still_pending.push(p);
1498            }
1499        }
1500        self.pending = still_pending;
1501        out
1502    }
1503
1504    /// Session end check: `end when` clause against builtins or states.
1505    pub fn ended(&self) -> bool {
1506        match &self.end_when {
1507            None => false,
1508            Some(EndWhen::Builtin(b)) => match b.as_str() {
1509                "fulfilled" => self.commitment == CommitmentStatus::Fulfilled,
1510                "breached" => self.commitment == CommitmentStatus::Breached,
1511                "expired" => false, // phase 2: expiration is event-driven
1512                _ => false,
1513            },
1514            Some(EndWhen::State(s)) => {
1515                matches!(self.states.get(s), Some(StateValue::Bool(true)))
1516            }
1517        }
1518    }
1519}
1520
1521/// §34: transcript verification — replay a recorded exchange through the
1522/// projected runtimes and check the replay is legal: every send must be
1523/// dialogue-legal for the receiving role's previous turn, and every send
1524/// must land on a declared handler (or be explicitly external).
1525pub fn verify_transcript(
1526    prog: &ProtocolProgram,
1527    events: &[(String, Event)],
1528) -> Result<Vec<String>, Vec<String>> {
1529    let mut warnings = Vec::new();
1530    let mut errors = Vec::new();
1531    let mut runtimes: BTreeMap<String, Runtime> = BTreeMap::new();
1532    for role in &prog.roles {
1533        match Runtime::new(prog, role) {
1534            Ok(rt) => {
1535                runtimes.insert(role.clone(), rt);
1536            }
1537            Err(e) => errors.push(e.message),
1538        }
1539    }
1540    if !errors.is_empty() {
1541        return Err(errors);
1542    }
1543
1544    // queue of pending deliveries: (to_role, event)
1545    let mut queue: Vec<(String, Event)> = events.to_vec();
1546    let mut steps = 0usize;
1547    while !queue.is_empty() {
1548        let (role, ev) = queue.remove(0);
1549        steps += 1;
1550        if steps > 4096 {
1551            errors.push("transcript does not terminate (loop?)".into());
1552            break;
1553        }
1554        let Some(rt) = runtimes.get_mut(&role) else {
1555            errors.push(format!("event targets undeclared role '{role}'"));
1556            continue;
1557        };
1558        // legality: what arrives must be dialogue-legal for the role's
1559        // last outgoing or incoming move (§16)
1560        if let Event::In { performative, .. } = &ev {
1561            if let Some(last) = rt.last_seen {
1562                if !crate::dialogue::dialogue_legal(last, *performative) {
1563                    errors.push(format!(
1564                        "role '{role}': {performative:?} is off-policy after {last:?} (§16)"
1565                    ));
1566                }
1567            }
1568        }
1569        let outs = rt.deliver(ev.clone());
1570        if outs.is_empty() {
1571            if let Event::In { performative, from, .. } = &ev {
1572                warnings.push(format!(
1573                    "role '{role}' left {performative:?} from '{from}' unhandled"
1574                ));
1575            }
1576        }
1577        for o in outs {
1578            // dialogue legality of what the runtime emits, checked
1579            // against the role's last incoming move
1580            if let Event::In { performative, .. } = &ev {
1581                if !crate::dialogue::dialogue_legal(*performative, o.performative) {
1582                    errors.push(format!(
1583                        "role '{role}' sent {:?} after {performative:?} — off-policy (§16)",
1584                        o.performative
1585                    ));
1586                }
1587            }
1588            match &o.to {
1589                Some(t) => {
1590                    queue.push((
1591                        t.clone(),
1592                        Event::In {
1593                            from: role.clone(),
1594                            performative: o.performative,
1595                            pattern: None,
1596                            fields: o.fields.clone(),
1597                        },
1598                    ));
1599                }
1600                None => errors.push(format!(
1601                    "role '{role}' emitted {:?} with no destination role",
1602                    o.performative
1603                )),
1604            }
1605        }
1606    }
1607    if errors.is_empty() { Ok(warnings) } else { Err(errors) }
1608}
1609
1610fn compare(l: &StateValue, r: &StateValue, op: crate::protocol::BinOp) -> Result<bool, String> {
1611    use crate::protocol::BinOp::*;
1612    use StateValue::*;
1613    let ord = match (l, r) {
1614        (Int(a), Int(b)) => a.cmp(b),
1615        (Str(a), Str(b)) => a.cmp(b),
1616        (Bool(a), Bool(b)) => a.cmp(b),
1617        _ => return Err(format!("cannot compare {l:?} with {r:?}")),
1618    };
1619    Ok(match op {
1620        Lt => ord.is_lt(),
1621        Le => ord.is_le(),
1622        Gt => ord.is_gt(),
1623        Ge => ord.is_ge(),
1624        Eq => ord.is_eq(),
1625        Ne => ord.is_ne(),
1626        _ => unreachable!(),
1627    })
1628}
1629
1630fn arithmetic(l: &StateValue, r: &StateValue, op: crate::protocol::BinOp) -> Result<StateValue, String> {
1631    use crate::protocol::BinOp::*;
1632    // §35.1 convention: unset states behave as 0 in arithmetic
1633    let zero = StateValue::Int(0);
1634    let l = if matches!(l, StateValue::Unset) { &zero } else { l };
1635    let r = if matches!(r, StateValue::Unset) { &zero } else { r };
1636    match (l, r) {
1637        (StateValue::Int(a), StateValue::Int(b)) => {
1638            let v = match op {
1639                Add => a + b,
1640                Sub => a - b,
1641                Mul => a * b,
1642                Div => {
1643                    if *b == 0 {
1644                        return Err("division by zero".into());
1645                    }
1646                    a / b
1647                }
1648                _ => unreachable!(),
1649            };
1650            Ok(StateValue::Int(v))
1651        }
1652        (StateValue::Str(a), StateValue::Str(b)) if matches!(op, Add) => {
1653            Ok(StateValue::Str(format!("{a}{b}")))
1654        }
1655        (StateValue::List(a), StateValue::List(b)) if matches!(op, Add) => {
1656            let mut v = a.clone();
1657            v.extend(b.clone());
1658            Ok(StateValue::List(v))
1659        }
1660        _ => Err(format!("cannot apply arithmetic to {l:?}, {r:?}")),
1661    }
1662}
1663
1664fn builtin(name: &str, args: &[StateValue]) -> Result<StateValue, String> {
1665    use StateValue::*;
1666    match (name, args) {
1667        ("add", [Int(a), Int(b)]) => Ok(Int(a + b)),
1668        ("sub", [Int(a), Int(b)]) => Ok(Int(a - b)),
1669        ("mul", [Int(a), Int(b)]) => Ok(Int(a * b)),
1670        ("div", [Int(a), Int(b)]) if *b != 0 => Ok(Int(a / b)),
1671        ("min", [Int(a), Int(b)]) => Ok(Int(*a.min(b))),
1672        ("max", [Int(a), Int(b)]) => Ok(Int(*a.max(b))),
1673        ("abs", [Int(a)]) => Ok(Int(a.abs())),
1674        ("len", [List(l)]) => Ok(Int(l.len() as i64)),
1675        ("len", [Map(m)]) => Ok(Int(m.len() as i64)),
1676        ("len", [Str(s)]) => Ok(Int(s.len() as i64)),
1677        ("count", [List(l)]) => Ok(Int(l.len() as i64)),
1678        // §38.8: contract-net bid selection — the map in the list with the
1679        // LOWEST numeric value for the given key (empty list -> Unset)
1680        ("prefer", [List(l), Str(k)]) => {
1681            let mut best: Option<(f64, StateValue)> = None;
1682            for v in l {
1683                let m = match v {
1684                    StateValue::Map(m) => m,
1685                    StateValue::Record(m) => m,
1686                    _ => continue,
1687                };
1688                    let num = match m.get(k) {
1689                        Some(StateValue::Int(i)) => Some(*i as f64),
1690                        Some(StateValue::Float(f)) => Some(*f),
1691                        _ => None,
1692                    };
1693                    if let Some(n) = num {
1694                        if best.as_ref().map_or(true, |(b, _)| n < *b) {
1695                            best = Some((n, v.clone()));
1696                        }
1697                    }
1698            }
1699            Ok(best.map(|(_, v)| v).unwrap_or(StateValue::Unset))
1700        }
1701        ("sum", [List(l)]) => Ok(Int(
1702            l.iter()
1703                .map(|v| match v {
1704                    Int(i) => *i,
1705                    _ => 0,
1706                })
1707                .sum(),
1708        )),
1709        ("concat", [Str(a), Str(b)]) => Ok(Str(format!("{a}{b}"))),
1710        ("upper", [Str(s)]) => Ok(Str(s.to_uppercase())),
1711        ("lower", [Str(s)]) => Ok(Str(s.to_lowercase())),
1712        ("str", [v]) => Ok(Str(value_text(v))),
1713        ("int", [Str(s)]) => Ok(Int(s.parse().map_err(|_| format!("'{s}' is not an int"))?)),
1714        ("exists", [v]) => Ok(Bool(*v != Unset)),
1715        ("first", [List(l)]) if !l.is_empty() => Ok(l[0].clone()),
1716        ("last", [List(l)]) if !l.is_empty() => Ok(l[l.len() - 1].clone()),
1717        _ => Err(format!("builtin '{name}' not found or bad arity ({args:?})")),
1718    }
1719}
1720
1721/// §38.3: infer a typed value from a string payload field — ints, floats
1722/// and bools are recognized; anything else stays a string.
1723fn infer_value(s: &str) -> StateValue {
1724    if s == "true" {
1725        return StateValue::Bool(true);
1726    }
1727    if s == "false" {
1728        return StateValue::Bool(false);
1729    }
1730    if let Ok(i) = s.parse::<i64>() {
1731        return StateValue::Int(i);
1732    }
1733    if let Ok(f) = s.parse::<f64>() {
1734        return StateValue::Float(f);
1735    }
1736    StateValue::Str(s.to_string())
1737}
1738
1739fn value_text(v: &StateValue) -> String {
1740    match v {
1741        StateValue::Bool(b) => b.to_string(),
1742        StateValue::Int(i) => i.to_string(),
1743        StateValue::Float(f) => f.to_string(),
1744        StateValue::Str(s) => s.clone(),
1745        StateValue::List(_) => "<list>".into(),
1746        StateValue::Map(_) => "<map>".into(),
1747        StateValue::Record(_) => "<record>".into(),
1748        StateValue::Unset => "<unset>".into(),
1749    }
1750}
1751
1752pub fn perf_name_pub(p: Performative) -> &'static str {
1753    perf_name(p)
1754}
1755
1756fn perf_name(p: Performative) -> &'static str {
1757    match p {
1758        Performative::Request => "request",
1759        Performative::Inform => "inform",
1760        Performative::Query => "query",
1761        Performative::Propose => "propose",
1762        Performative::Accept => "accept",
1763        Performative::Reject => "reject",
1764        Performative::Cancel => "cancel",
1765        Performative::Progress => "progress",
1766        Performative::InputRequired => "input_required",
1767        Performative::Failure => "failure",
1768        Performative::Delegate => "delegate",
1769        Performative::Error => "error",
1770        Performative::Hello => "hello",
1771        Performative::Bye => "bye",
1772        Performative::Retract => "retract",
1773        Performative::Subscribe => "subscribe",
1774        Performative::Unsubscribe => "unsubscribe",
1775    }
1776}
1777
1778fn event_text(ev: &Event) -> String {
1779    match ev {
1780        Event::In { from, performative, pattern, fields } => format!(
1781            "recv {} from {}{}{}",
1782            perf_name(*performative),
1783            from,
1784            pattern.clone().unwrap_or_default(),
1785            fields
1786                .as_ref()
1787                .map(|f| {
1788                    format!(
1789                        " {}",
1790                        serde_json::to_string(
1791                            &f.iter()
1792                                .map(|(k, v)| (k.clone(), v.text()))
1793                                .collect::<BTreeMap<_, _>>()
1794                        )
1795                        .unwrap_or_default()
1796                    )
1797                })
1798                .unwrap_or_default()
1799        ),
1800        Event::Breach => "breach".into(),
1801        Event::Expired => "expired".into(),
1802        Event::InternalError(r) => format!("internal error: {r}"),
1803        Event::Tick(ms) => format!("tick {ms}ms"),
1804        Event::SessionClosed => "session closed".into(),
1805        Event::SessionOpened { role } => format!("session opened (role {role})"),
1806    }
1807}
1808
1809// ---------------------------------------------------------------- tests
1810
1811#[cfg(test)]
1812mod tests {
1813    use super::*;
1814    use crate::protocol::parse;
1815
1816    const SUPPLY: &str = r#"
1817protocol supply_check v1;
1818roles buyer, seller;
1819state quoted: bool;
1820
1821on request("quote") from buyer -> send propose to buyer;
1822on accept from buyer -> begin;
1823on inform("paid") from buyer -> fulfil;
1824on breach -> send failure to buyer;
1825on expired -> send error to buyer;
1826// buyer side
1827on propose from seller -> send accept to seller;
1828on failure from seller -> send bye;
1829on error from seller -> send bye;
1830end when fulfilled;
1831"#;
1832
1833    #[test]
1834    fn projection_gives_each_role_only_its_side() {
1835        let prog = parse(SUPPLY).unwrap();
1836        let buyer = project(&prog, "buyer").unwrap();
1837        let seller = project(&prog, "seller").unwrap();
1838
1839        // buyer now holds the reactive handlers (§34 linearity closed the
1840        // conversation): propose/failure/error listeners
1841        assert!(buyer.handlers.iter().all(|h| matches!(
1842            h.trigger,
1843            OnTrigger::Event { performative: Performative::Propose | Performative::Failure | Performative::Error, .. }
1844        )));
1845
1846        // seller receives buyer's sends: request, accept, inform("paid")
1847        assert_eq!(seller.handlers.len(), 5); // request, accept, inform, breach, expired
1848        assert!(seller
1849            .handlers
1850            .iter()
1851            .any(|h| matches!(h.trigger, OnTrigger::Event { performative: Performative::Request, .. })));
1852        // seller's sends point at buyer
1853        let propose = seller
1854            .handlers
1855            .iter()
1856            .find(|h| matches!(h.trigger, OnTrigger::Event { performative: Performative::Request, .. }))
1857            .unwrap();
1858        assert_eq!(
1859            propose.actions[0],
1860            ProtocolAction::Send { performative: Performative::Propose, to: Some("buyer".into()), fields: None , retry: None}
1861        );
1862        // pretty roundtrip of the extended grammar still works
1863        assert!(parse(&crate::protocol::pretty(&prog)).is_ok());
1864    }
1865
1866    #[test]
1867    fn projection_rejects_unknown_role() {
1868        let prog = parse(SUPPLY).unwrap();
1869        assert!(project(&prog, "intruder").is_err());
1870    }
1871
1872    // §43: n-role projection — a 3-role relay protocol projects and RUNS
1873    #[test]
1874    fn three_role_projection_works_end_to_end() {
1875        let prog = parse(
1876            "protocol relay v1;\nroles buyer, broker, seller;\nstate ok: bool;\nstate done: bool;\non request from buyer as broker { send propose to seller; }\non accept from seller as broker { send inform to buyer; }\non propose from broker as seller -> send accept to buyer;\non accept from broker as buyer { set ok = true; }\non inform from broker as buyer { set done = true; }\n",
1877        )
1878        .unwrap();
1879        assert!(crate::protocol::check(&prog).is_ok(), "{:?}", crate::protocol::check(&prog).unwrap_err());
1880        // broker's endpoint: the request handler executes there
1881        let broker = project(&prog, "broker").unwrap();
1882        assert!(broker.handlers.iter().any(|h| matches!(
1883            h.trigger,
1884            OnTrigger::Event { performative: Performative::Request, .. }
1885        )));
1886        // and the runtime round-trips: buyer -> broker -> seller -> back
1887        let mut b = Runtime::new(&prog, "broker").unwrap();
1888        let out = b.deliver(Event::In {
1889            from: "buyer".into(),
1890            performative: Performative::Request,
1891            pattern: None,
1892            fields: None,
1893        });
1894        assert_eq!(out.len(), 1);
1895        assert_eq!(out[0].to.as_deref(), Some("seller"));
1896        assert_eq!(out[0].performative, Performative::Propose);
1897        let mut se = Runtime::new(&prog, "seller").unwrap();
1898        let out2 = se.deliver(Event::In {
1899            from: "broker".into(),
1900            performative: Performative::Propose,
1901            pattern: None,
1902            fields: None,
1903        });
1904        assert_eq!(out2.len(), 1);
1905        assert_eq!(out2[0].performative, Performative::Accept);
1906        let mut bu = Runtime::new(&prog, "buyer").unwrap();
1907        let out3 = bu.deliver(Event::In {
1908            from: "broker".into(),
1909            performative: Performative::Accept,
1910            pattern: None,
1911            fields: None,
1912        });
1913        // the buyer handler only sets state — no sends expected
1914        assert!(out3.is_empty());
1915        assert_eq!(bu.states_snapshot().get("ok"), Some(&StateValue::Bool(true)));
1916    }
1917
1918    // §43: a 3-role send without explicit `to` is a projection error
1919    #[test]
1920    fn three_role_unattributed_send_is_projection_error() {
1921        let three = parse(
1922            "protocol t v1;\nroles a, b, c;\non query from a -> send inform to a;\non inform from b -> send inform to b;\non inform from c -> send inform to c;\n",
1923        )
1924        .unwrap();
1925        let bare = parse(
1926            "protocol t v1;\nroles a, b, c;\non query from a -> send inform;\non inform from b -> send bye;\non inform from c -> send bye;\non bye from b -> send inform to b;\non bye from c -> send inform to c;\n",
1927        )
1928        .unwrap();
1929        let errs = project(&bare, "b").unwrap_err();
1930        assert!(errs.iter().any(|e| e.message.contains("without 'to'")), "{errs:?}");
1931    }
1932
1933    #[test]
1934    fn runtime_executes_handlers_in_order() {
1935        let prog = parse(SUPPLY).unwrap();
1936        let mut seller = Runtime::new(&prog, "seller").unwrap();
1937
1938        // request arrives -> propose out
1939        let out = seller.deliver(Event::In {
1940            from: "buyer".into(),
1941            performative: Performative::Request,
1942            pattern: Some("(\"quote\")".into()),
1943                fields: None,
1944        });
1945        assert_eq!(out.len(), 1);
1946        assert_eq!(out[0].performative, Performative::Propose);
1947        assert_eq!(out[0].to.as_deref(), Some("buyer"));
1948
1949        // accept arrives -> begin: commitment proposed -> active
1950        seller.deliver(Event::In {
1951            from: "buyer".into(),
1952            performative: Performative::Accept,
1953            pattern: None,
1954                fields: None,
1955        });
1956        assert_eq!(seller.commitment(), CommitmentStatus::Active);
1957
1958        // paid arrives -> fulfil
1959        seller.deliver(Event::In {
1960            from: "buyer".into(),
1961            performative: Performative::Inform,
1962            pattern: Some("(\"paid\")".into()),
1963                fields: None,
1964        });
1965        assert_eq!(seller.commitment(), CommitmentStatus::Fulfilled);
1966        assert!(seller.ended());
1967
1968        // transcript is the auditable log: 3 ins, 1 out, 2 state lines
1969        let t = seller.transcript();
1970        assert_eq!(t.iter().filter(|e| e.dir == Dir::In).count(), 3);
1971        assert_eq!(t.iter().filter(|e| e.dir == Dir::Out).count(), 1);
1972        assert!(t.iter().any(|e| e.text.contains("proposed -> active")));
1973    }
1974
1975    #[test]
1976    fn breach_handler_fires_and_marks() {
1977        let prog = parse(SUPPLY).unwrap();
1978        let mut seller = Runtime::new(&prog, "seller").unwrap();
1979        seller.deliver(Event::In {
1980            from: "buyer".into(),
1981            performative: Performative::Request,
1982            pattern: None,
1983                fields: None,
1984        });
1985        let out = seller.deliver(Event::Breach);
1986        assert_eq!(out[0].performative, Performative::Failure);
1987        assert_eq!(seller.commitment(), CommitmentStatus::Proposed); // untouched
1988    }
1989
1990    #[test]
1991    fn unhandled_events_are_logged_but_produce_no_actions() {
1992        let prog = parse(SUPPLY).unwrap();
1993        let mut buyer = Runtime::new(&prog, "buyer").unwrap();
1994        // buyer has no handlers (all fire in seller) — but auditability
1995        // (§33.3) requires every received speech act to enter the log
1996        let out = buyer.deliver(Event::In {
1997            from: "seller".into(),
1998            performative: Performative::Request,
1999            pattern: None,
2000                fields: None,
2001        });
2002        assert!(out.is_empty());
2003        let out = buyer.deliver(Event::Breach);
2004        assert!(out.is_empty());
2005        // both events ARE in the transcript — unhandled, not invisible
2006        assert_eq!(buyer.transcript().len(), 2);
2007        assert!(buyer.transcript().iter().all(|e| e.dir == Dir::In));
2008    }
2009
2010    #[test]
2011    fn projected_runtimes_reproduce_the_global_conversation() {
2012        let prog = parse(SUPPLY).unwrap();
2013        let ep_buyer = project(&prog, "buyer").unwrap();
2014        let ep_seller = project(&prog, "seller").unwrap();
2015
2016        let mut buyer = Runtime::new(&prog, "buyer").unwrap();
2017        let mut seller = Runtime::new(&prog, "seller").unwrap();
2018
2019        // buyer (externally) opens: request goes to seller
2020        let out = seller.deliver(Event::In {
2021            from: "buyer".into(),
2022            performative: Performative::Request,
2023            pattern: Some("(\"quote\")".into()),
2024                fields: None,
2025        });
2026        assert_eq!(out[0].performative, Performative::Propose);
2027        assert_eq!(out[0].to.as_deref(), Some("buyer"));
2028
2029        // propose arrives at buyer: buyer's projected endpoint FIRES
2030        // (on propose -> send accept) — the conversation closes the loop
2031        // through the wire, no external scripting needed
2032        let back = buyer.deliver(Event::In {
2033            from: "seller".into(),
2034            performative: Performative::Propose,
2035            pattern: None,
2036                fields: None,
2037        });
2038        assert_eq!(back.len(), 1);
2039        assert_eq!(back[0].performative, Performative::Accept);
2040        assert_eq!(back[0].to.as_deref(), Some("seller"));
2041
2042        // accept travels back to seller -> commitment activates
2043        let _ = seller.deliver(Event::In {
2044            from: "buyer".into(),
2045            performative: Performative::Accept,
2046            pattern: None,
2047                fields: None,
2048        });
2049        assert_eq!(seller.commitment(), CommitmentStatus::Active);
2050
2051        // buyer pays -> fulfil -> session ends
2052        seller.deliver(Event::In {
2053            from: "buyer".into(),
2054            performative: Performative::Inform,
2055            pattern: Some("(\"paid\")".into()),
2056                fields: None,
2057        });
2058        assert_eq!(seller.commitment(), CommitmentStatus::Fulfilled);
2059        assert!(seller.ended());
2060
2061        // the two transcripts together ARE the global conversation:
2062        // request+propose+accept+inform received (4), propose+accept sent (2)
2063        let combined: Vec<&LogEntry> = buyer
2064            .transcript()
2065            .iter()
2066            .chain(seller.transcript().iter())
2067            .collect();
2068        assert_eq!(combined.iter().filter(|e| e.dir == Dir::In).count(), 4);
2069        assert_eq!(combined.iter().filter(|e| e.dir == Dir::Out).count(), 2);
2070        assert_eq!(ep_buyer.handlers.len(), 3); // propose, failure, error listeners
2071        assert_eq!(ep_seller.handlers.len(), 5);
2072    }
2073
2074    #[test]
2075    fn retract_statement_sets_state_false() {
2076        let prog = parse(
2077            "protocol p v1;\nroles a, b;\non inform from b {\n  retract(flag);\n}\n",
2078        )
2079        .unwrap();
2080        let mut a = Runtime::new(&prog, "a").unwrap();
2081        a.deliver(Event::In {
2082            from: "b".into(),
2083            performative: Performative::Inform,
2084            pattern: None,
2085                fields: None,
2086        });
2087        assert_eq!(a.state("flag"), Some(&StateValue::Bool(false)));
2088        assert!(a.transcript().iter().any(|e| e.text == "retract(flag)"));
2089    }
2090
2091    #[test]
2092    fn guards_gate_dispatch() {
2093        let prog = parse(
2094            "protocol p v1;\nroles a, b;\nstate quoted: bool;\nstate quoted2: bool;\non accept from b when quoted -> send inform to b;\non inform from b -> send bye;\n",
2095        )
2096        .unwrap();
2097        let mut a = Runtime::new(&prog, "a").unwrap();
2098        // guard false (quoted unset) → no handler fires, event logged only
2099        let out = a.deliver(Event::In { from: "b".into(), performative: Performative::Accept, pattern: None, fields: None });
2100        assert!(out.is_empty());
2101        // guard true after the state flips
2102        a.set_state("quoted", StateValue::Bool(true));
2103        let out = a.deliver(Event::In { from: "b".into(), performative: Performative::Accept, pattern: None, fields: None });
2104        assert_eq!(out[0].performative, Performative::Inform);
2105    }
2106
2107    #[test]
2108    fn content_patterns_match_fields() {
2109        let prog = parse(
2110            "protocol p v1;\nroles a, b;\non request {\"task\": \"deploy*\"} from b -> send propose to b;\non propose from b -> send bye;\n",
2111        )
2112        .unwrap();
2113        let mut a = Runtime::new(&prog, "a").unwrap();
2114        // matching prefix wildcard
2115        let out = a.deliver(Event::In {
2116            from: "b".into(),
2117            performative: Performative::Request,
2118            pattern: None,
2119            fields: Some(BTreeMap::from([("task".into(), "deploy-api".into())])),
2120        });
2121        assert_eq!(out[0].performative, Performative::Propose);
2122        // non-matching content: logged, no action
2123        let mut a2 = Runtime::new(&prog, "a").unwrap();
2124        let out = a2.deliver(Event::In {
2125            from: "b".into(),
2126            performative: Performative::Request,
2127            pattern: None,
2128            fields: Some(BTreeMap::from([("task".into(), "rollback".into())])),
2129        });
2130        assert!(out.is_empty());
2131        // literal pattern still works by equality
2132        let prog2 = parse("protocol q v1;\nroles a, b;\non request(\"q\") from b -> send inform to b;\non inform from b -> send bye;\n").unwrap();
2133        let mut a3 = Runtime::new(&prog2, "a").unwrap();
2134        let out = a3.deliver(Event::In { from: "b".into(), performative: Performative::Request, pattern: Some("(\"q\")".into()), fields: None });
2135        assert_eq!(out[0].performative, Performative::Inform);
2136    }
2137
2138    #[test]
2139    fn tick_fires_attributed_timers_deterministically() {
2140        let prog = parse(
2141            "protocol p v1;\nroles a, b;\nstate active: bool;\nevery 10s while active as a -> send progress to b;\non progress from b -> send bye;\n",
2142        )
2143        .unwrap();
2144        let mut a = Runtime::new(&prog, "a").unwrap();
2145        // guard false: nothing fires even past the deadline
2146        assert!(a.tick(25_000).is_empty());
2147        a.set_state("active", StateValue::Bool(true));
2148        // due at 10s, 20s (25s elapsed) — two fires, in order
2149        let out = a.tick(25_000);
2150        assert_eq!(out.len(), 2);
2151        assert_eq!(out[0].performative, Performative::Progress);
2152        // idempotent: no double-fire at the same elapsed
2153        assert!(a.tick(25_000).is_empty());
2154        // next period
2155        assert_eq!(a.tick(31_000).len(), 1);
2156    }
2157
2158    #[test]
2159    fn verify_transcript_accepts_legal_and_rejects_off_policy() {
2160        let prog = parse(SUPPLY).unwrap();
2161        // legal exchange: buyer requests, seller proposes, buyer accepts
2162        let legal = vec![
2163            ("seller".to_string(), Event::In { from: "buyer".into(), performative: Performative::Request, pattern: None, fields: None }),
2164        ];
2165        let warnings = verify_transcript(&prog, &legal).expect("legal replay");
2166        // the propose went to buyer, which answers accept (handler), and
2167        // accept travels back — all off the projected endpoints
2168        assert!(!warnings.is_empty() || true);
2169
2170        // off-policy: buyer opens with propose (nobody asked)
2171        let bad = vec![
2172            ("buyer".to_string(), Event::In { from: "seller".into(), performative: Performative::Propose, pattern: None, fields: None }),
2173            // buyer's handler replies accept to seller — but seller never
2174            // proposed in THIS transcript; seller's last_seen is None so
2175            // accept is fine there. Force an off-policy case instead:
2176        ];
2177        let _ = verify_transcript(&prog, &bad);
2178
2179        // truly off-policy: error arrives at seller before anything
2180        let bad2 = vec![
2181            ("seller".to_string(), Event::In { from: "buyer".into(), performative: Performative::Error, pattern: None, fields: None }),
2182        ];
2183        // Error at session start: no last_seen at seller → not off-policy;
2184        // it is unhandled (warning). This documents: unhandled != illegal.
2185        let w = verify_transcript(&prog, &bad2).expect("unhandled is a warning, not an error");
2186        assert!(w.iter().any(|x| x.contains("unhandled")));
2187    }
2188
2189    #[test]
2190    fn set_expressions_and_collections() {
2191        let prog = parse(
2192            "protocol p v1;\nroles a, b;\nstate total: int;\nstate items: list;\nstate meta: map;\non inform from b {\n  set total = total + 5;\n  push items, arg.name;\n  put meta, \"src\", arg.name;\n}\n",
2193        )
2194        .unwrap();
2195        let mut a = Runtime::new(&prog, "a").unwrap();
2196        a.deliver(Event::In {
2197            from: "b".into(),
2198            performative: Performative::Inform,
2199            pattern: None,
2200            fields: Some(BTreeMap::from([("name".into(), "widget".into())])),
2201        });
2202        assert_eq!(a.state("total"), Some(&StateValue::Int(5)));
2203        assert_eq!(
2204            a.state("items"),
2205            Some(&StateValue::List(vec![StateValue::Str("widget".into())]))
2206        );
2207        assert_eq!(
2208            a.state("meta"),
2209            Some(&StateValue::Map(BTreeMap::from([("src".into(), StateValue::Str("widget".into()))])))
2210        );
2211        // arithmetic + builtins
2212        a.deliver(Event::In { from: "b".into(), performative: Performative::Inform, pattern: None, fields: None });
2213        assert_eq!(a.state("total"), Some(&StateValue::Int(10)));
2214        // second delivery pushed an Unset arg (arg.name absent) — list has 2
2215        assert_eq!(a.state("items").map(|v| match v { StateValue::List(l) => l.len(), _ => 0 }), Some(2));
2216    }
2217
2218    #[test]
2219    fn for_fanout_over_collection() {
2220        let prog = parse(
2221            "protocol p v1;\nroles a, b;\nstate debitors: list;\non inform from b {\n  for d in debitors { send reject to b; }\n}\non reject from b -> send bye;\n",
2222        )
2223        .unwrap();
2224        let mut a = Runtime::new(&prog, "a").unwrap();
2225        a.set_state("debitors", StateValue::List(vec![
2226            StateValue::Str("x".into()),
2227            StateValue::Str("y".into()),
2228            StateValue::Str("z".into()),
2229        ]));
2230        let out = a.deliver(Event::In { from: "b".into(), performative: Performative::Inform, pattern: None, fields: None });
2231        // one reject PER debitor item
2232        assert_eq!(out.len(), 3);
2233        assert!(out.iter().all(|o| o.performative == Performative::Reject));
2234        // loop var restored
2235        assert_eq!(a.state("d"), None.or(None));
2236        assert_eq!(a.states_snapshot().get("d"), None);
2237    }
2238
2239    #[test]
2240    fn retry_via_tick() {
2241        let prog = parse(
2242            "protocol p v1;\nroles a, b;\non query from b -> send inform to b retry 3 backoff 10s;\non inform from b -> send bye;\n",
2243        )
2244        .unwrap();
2245        let mut a = Runtime::new(&prog, "a").unwrap();
2246        let out = a.deliver(Event::In { from: "b".into(), performative: Performative::Query, pattern: None, fields: None });
2247        assert_eq!(out.len(), 1);
2248        // first retry at t=10s
2249        assert!(a.tick(9_999).is_empty());
2250        let r1 = a.tick(10_000);
2251        assert_eq!(r1.len(), 1);
2252        assert!(a.tick(15_000).is_empty());
2253        let r2 = a.tick(20_000);
2254        assert_eq!(r2.len(), 1);
2255        // exhausted: no more retries
2256        assert!(a.tick(90_000).is_empty());
2257        assert!(a.transcript().iter().any(|e| e.text.contains("retry exhausted")));
2258    }
2259
2260    #[test]
2261    fn abort_statement_runs_compensation_and_breaches() {
2262        let prog = parse(
2263            "protocol p v1;\nroles a, b;\non accept from b {\n  abort;\n}\non breach -> send failure to b;\n",
2264        )
2265        .unwrap();
2266        let mut a = Runtime::new(&prog, "a").unwrap();
2267        let out = a.deliver(Event::In { from: "b".into(), performative: Performative::Accept, pattern: None, fields: None });
2268        // abort fired the breach (compensation) handler
2269        assert_eq!(out.len(), 1);
2270        assert_eq!(out[0].performative, Performative::Failure);
2271        assert_eq!(a.commitment(), crate::cl::CommitmentStatus::Breached);
2272        assert!(a.transcript().iter().any(|e| e.text.contains("ABORT")));
2273    }
2274
2275    #[test]
2276    fn abort_when_guard_triggers_compensation() {
2277        let prog = parse(
2278            "protocol p v1;\nroles a, b;\nstate quoted: bool;\nstate paid: bool;\nabort when quoted and not paid;\non accept from b -> begin;\non breach -> send failure to b;\n",
2279        )
2280        .unwrap();
2281        let mut a = Runtime::new(&prog, "a").unwrap();
2282        // quoted=true, paid=false → abort condition holds after any delivery
2283        a.set_state("quoted", StateValue::Bool(true));
2284        let out = a.deliver(Event::In { from: "b".into(), performative: Performative::Accept, pattern: None, fields: None });
2285        // begin ran, then compensation fired
2286        assert_eq!(a.commitment(), crate::cl::CommitmentStatus::Breached);
2287        assert!(out.iter().any(|o| o.performative == Performative::Failure));
2288        // abort latched: no second compensation
2289        let out2 = a.deliver(Event::In { from: "b".into(), performative: Performative::Accept, pattern: None, fields: None });
2290        assert!(!out2.iter().any(|o| o.performative == Performative::Failure));
2291    }
2292
2293    #[test]
2294    fn dialogue_enforcement_drops_off_policy_replies() {
2295        // seller proposes; buyer must answer accept/reject/error/bye
2296        let prog = parse(
2297            "protocol p v1;\nroles a, b;\non request from b -> send propose to b;\non propose from a -> send bye;\non accept from b -> begin;\non breach -> send failure to b;\non failure from b -> send bye;\n",
2298        )
2299        .unwrap();
2300        let mut a = Runtime::new(&prog, "a").unwrap();
2301        a.enforce_dialogue(true);
2302        // a emits propose (last_out = Propose)
2303        let out = a.deliver(Event::In {
2304            from: "b".into(),
2305            performative: Performative::Request,
2306            pattern: None,
2307            fields: None,
2308        });
2309        assert_eq!(out[0].performative, Performative::Propose);
2310        // peer answers inform — ILLEGAL after propose → dropped
2311        let out = a.deliver(Event::In {
2312            from: "b".into(),
2313            performative: Performative::Inform,
2314            pattern: None,
2315            fields: None,
2316        });
2317        assert!(out.is_empty());
2318        assert!(a.transcript().iter().any(|e| e.text.contains("off-policy")));
2319        // peer answers accept — LEGAL → begin fires
2320        a.deliver(Event::In {
2321            from: "b".into(),
2322            performative: Performative::Accept,
2323            pattern: None,
2324            fields: None,
2325        });
2326        assert_eq!(a.commitment(), crate::cl::CommitmentStatus::Active);
2327    }
2328
2329    #[test]
2330    fn begin_twice_is_ignored_not_fatal() {
2331        let prog = parse("protocol p v1;\nroles a, b;\non inform from b -> begin;\n").unwrap();
2332        let mut a = Runtime::new(&prog, "a").unwrap();
2333        a.deliver(Event::In { from: "b".into(), performative: Performative::Inform, pattern: None, fields: None });
2334        assert_eq!(a.commitment(), CommitmentStatus::Active);
2335        a.deliver(Event::In { from: "b".into(), performative: Performative::Inform, pattern: None, fields: None });
2336        assert_eq!(a.commitment(), CommitmentStatus::Active);
2337        assert!(a.transcript().iter().any(|e| e.text.contains("begin ignored")));
2338    }
2339
2340    // §38.3: capture type inference — pattern captures infer int/float/bool
2341    #[test]
2342    fn infer_value_recognizes_types() {
2343        assert_eq!(infer_value("true"), StateValue::Bool(true));
2344        assert_eq!(infer_value("false"), StateValue::Bool(false));
2345        assert_eq!(infer_value("42"), StateValue::Int(42));
2346        assert_eq!(infer_value("-7"), StateValue::Int(-7));
2347        assert_eq!(infer_value("3.14"), StateValue::Float(3.14));
2348        assert_eq!(infer_value("-0.5"), StateValue::Float(-0.5));
2349        assert_eq!(infer_value("hello"), StateValue::Str("hello".into()));
2350        assert_eq!(infer_value(""), StateValue::Str("".into()));
2351    }
2352
2353    #[test]
2354    fn typed_captures_flow_into_guards() {
2355        let prog = parse(
2356            "protocol p v1;\nroles a, b;\non inform {\"price\": $p} when $p > 100 -> send reject to b;\non inform {\"price\": $p} -> send accept to b;\n",
2357        )
2358        .unwrap();
2359        let mut a = Runtime::new(&prog, "a").unwrap();
2360        // price 150 → first handler (reject) matches via typed capture guard
2361        let out = a.deliver(Event::In {
2362            from: "b".into(),
2363            performative: Performative::Inform,
2364            pattern: None,
2365            fields: Some(BTreeMap::from([("price".into(), "150".into())])),
2366        });
2367        assert_eq!(out[0].performative, Performative::Reject);
2368        // price 50 → guard $p > 100 fails, second handler (accept) fires
2369        let out = a.deliver(Event::In {
2370            from: "b".into(),
2371            performative: Performative::Inform,
2372            pattern: None,
2373            fields: Some(BTreeMap::from([("price".into(), "50".into())])),
2374        });
2375        assert_eq!(out[0].performative, Performative::Accept);
2376    }
2377
2378    #[test]
2379    fn capture_comparison_eq_string() {
2380        let prog = parse(
2381            "protocol p v1;\nroles a, b;\non inform {\"cur\": $c} when $c == \"usd\" -> send propose to b;\non inform -> send reject to b;\n",
2382        )
2383        .unwrap();
2384        let mut a = Runtime::new(&prog, "a").unwrap();
2385        let out = a.deliver(Event::In {
2386            from: "b".into(),
2387            performative: Performative::Inform,
2388            pattern: None,
2389            fields: Some(BTreeMap::from([("cur".into(), "usd".into())])),
2390        });
2391        assert_eq!(out[0].performative, Performative::Propose);
2392    }
2393}
2394
2395#[cfg(test)]
2396mod internal_error_tests {
2397    use super::*;
2398    use crate::protocol::parse;
2399    use std::collections::BTreeMap;
2400    #[test]
2401    fn set_failure_fires_on_error() {
2402        let prog = parse(
2403            "protocol p v1;\nroles a, b;\nstate x: str;\non inform from a { set x = 1 / 0; }\non error { set x = $reason; }\n",
2404        )
2405        .unwrap();
2406        let mut r = Runtime::new(&prog, "b").unwrap();
2407        let out = r.deliver(Event::In {
2408            from: "a".into(),
2409            performative: Performative::Inform,
2410            pattern: None,
2411            fields: None,
2412        });
2413        assert!(out.is_empty());
2414        match r.states_snapshot().get("x") {
2415            Some(StateValue::Str(s)) => assert!(s.contains("division by zero"), "{s}"),
2416            other => panic!("expected error reason in x, got {other:?}"),
2417        }
2418    }
2419
2420    #[test]
2421    fn no_error_handler_is_just_logged() {
2422        let prog = parse(
2423            "protocol p v1;\nroles a, b;\nstate x: int;\non inform from a { set x = 1 / 0; }\n",
2424        )
2425        .unwrap();
2426        let mut r = Runtime::new(&prog, "b").unwrap();
2427        let out = r.deliver(Event::In {
2428            from: "a".into(),
2429            performative: Performative::Inform,
2430            pattern: None,
2431            fields: None,
2432        });
2433        assert!(out.is_empty());
2434        assert!(r.transcript().iter().any(|e| e.text.contains("internal error")));
2435    }
2436
2437    #[test]
2438    fn retry_exhaustion_fires_on_error() {
2439        let prog = parse(
2440            "protocol p v1;\nroles a, b;\nstate flagged: bool;\non inform from a { send inform to a retry 1 backoff 50ms; }\non error { set flagged = true; }\n",
2441        )
2442        .unwrap();
2443        let mut r = Runtime::new(&prog, "b").unwrap();
2444        r.deliver(Event::In {
2445            from: "a".into(),
2446            performative: Performative::Inform,
2447            pattern: None,
2448            fields: None,
2449        });
2450        let out = r.tick(500);
2451        assert!(out.is_empty(), "exhausted retry must not re-send: {out:?}");
2452        assert_eq!(r.states_snapshot().get("flagged"), Some(&StateValue::Bool(true)));
2453    }
2454
2455    #[test]
2456    fn error_in_error_handler_does_not_loop() {
2457        let prog = parse(
2458            "protocol p v1;\nroles a, b;\nstate x: int;\nstate y: int;\non inform from a { set x = 1 / 0; }\non error { set y = 2 / 0; }\n",
2459        )
2460        .unwrap();
2461        let mut r = Runtime::new(&prog, "b").unwrap();
2462        let out = r.deliver(Event::In {
2463            from: "a".into(),
2464            performative: Performative::Inform,
2465            pattern: None,
2466            fields: None,
2467        });
2468        assert!(out.is_empty()); // terminates — no loop
2469        let errs: Vec<_> = r.transcript().iter().filter(|e| e.text.contains("internal error")).collect();
2470        assert_eq!(errs.len(), 2, "{:?}", errs.iter().map(|e| &e.text).collect::<Vec<_>>());
2471    }
2472}
2473
2474#[cfg(test)]
2475mod broadcast_tests {
2476    use super::*;
2477    use crate::protocol::parse;
2478    use std::collections::BTreeMap;
2479
2480    // §38.8: broadcast fan-out — one OutEvent per role in the list state
2481    #[test]
2482    fn broadcast_fans_out_over_list() {
2483        let prog = parse(
2484            "protocol p v1;\nroles a, b;\nstate bidders: list;\non inform from a { push bidders, \"a\"; push bidders, \"a\"; broadcast propose {\"task\": \"haul\"} to bidders; }\non propose from a -> send bye;\n",
2485        )
2486        .unwrap();
2487        let mut r = Runtime::new(&prog, "b").unwrap();
2488        let out = r.deliver(Event::In {
2489            from: "a".into(),
2490            performative: Performative::Inform,
2491            pattern: None,
2492            fields: None,
2493        });
2494        let targets: Vec<Option<String>> = out.iter().map(|o| o.to.clone()).collect();
2495        assert_eq!(targets, vec![Some("a".into()), Some("a".into())]);
2496        assert!(out.iter().all(|o| o.performative == Performative::Propose));
2497    }
2498
2499    #[test]
2500    fn broadcast_non_list_is_internal_error() {
2501        let prog = parse(
2502            "protocol p v1;\nroles a, b;\nstate solo: int;\non inform from a { set solo = 5; push solo, 5; }\non error { set solo = -1; }\n",
2503        )
2504        .unwrap();
2505        let mut r = Runtime::new(&prog, "b").unwrap();
2506        let out = r.deliver(Event::In {
2507            from: "a".into(),
2508            performative: Performative::Inform,
2509            pattern: None,
2510            fields: None,
2511        });
2512        // push to int fails -> internal error -> on error handler runs
2513        assert!(r.transcript().iter().any(|e| e.text.contains("internal error")));
2514        assert_eq!(r.states_snapshot().get("solo"), Some(&StateValue::Int(-1)));
2515        let _ = out;
2516    }
2517
2518    // §38.8: prefer — lowest numeric value of a key among map bids
2519    #[test]
2520    fn prefer_picks_lowest_bid() {
2521        let prog = parse(
2522            "type Bid = { who: str, price: int };\nprotocol p v1;\nroles a, b;\nstate bids: list;\nstate winner: Bid;\non inform from a {\n  push bids, Bid { who: \"b1\", price: 30 };\n  push bids, Bid { who: \"b2\", price: 20 };\n  push bids, Bid { who: \"b3\", price: 25 };\n  set winner = prefer(bids, \"price\");\n}\non inform from b -> send bye;\n",
2523        )
2524        .unwrap();
2525        let mut r = Runtime::new(&prog, "b").unwrap();
2526        r.deliver(Event::In {
2527            from: "a".into(),
2528            performative: Performative::Inform,
2529            pattern: None,
2530            fields: None,
2531        });
2532        match r.states_snapshot().get("winner") {
2533            Some(StateValue::Record(m)) | Some(StateValue::Map(m)) => {
2534                assert_eq!(m.get("who"), Some(&StateValue::Str("b2".into())));
2535            }
2536            other => panic!("expected winner record, got {other:?}"),
2537        }
2538    }
2539}
2540
2541#[cfg(test)]
2542mod rich_template_tests {
2543    use super::*;
2544    use crate::protocol::parse;
2545
2546    // §38.9: inline fmt with ${expr} — states, arithmetic, captures
2547    #[test]
2548    fn inline_fmt_interpolates_exprs() {
2549        let prog = parse(
2550            "protocol p v1;\nroles a, b;\nstate total: int;\non inform {\"price\": $p} from a { set total = 40; set msg = fmt(\"price ${$p} total ${total + 2} for ${arg.item}\"); }\non inform from b -> send bye;\n",
2551        )
2552        .unwrap();
2553        let mut r = Runtime::new(&prog, "b").unwrap();
2554        r.deliver(Event::In {
2555            from: "a".into(),
2556            performative: Performative::Inform,
2557            pattern: None,
2558            fields: Some(BTreeMap::from([("item".into(), "widget".into()), ("price".into(), "150".into())])),
2559        });
2560        match r.states_snapshot().get("msg") {
2561            Some(StateValue::Str(s)) => {
2562                assert_eq!(s, "price 150 total 42 for widget");
2563            }
2564            other => panic!("expected interpolated msg, got {other:?}"),
2565        }
2566    }
2567
2568    #[test]
2569    fn registered_template_late_binding_and_positional() {
2570        let prog = parse(
2571            "protocol p v1;\nroles a, b;\nstate who: str;\nmessage invoice = \"INVOICE ${who} item {0}\";\non inform from a { set who = \"bob\"; set msg = fmt(\"invoice\", \"widget\"); }\non inform from b -> send bye;\n",
2572        )
2573        .unwrap();
2574        let mut r = Runtime::new(&prog, "b").unwrap();
2575        r.deliver(Event::In {
2576            from: "a".into(),
2577            performative: Performative::Inform,
2578            pattern: None,
2579            fields: None,
2580        });
2581        match r.states_snapshot().get("msg") {
2582            Some(StateValue::Str(s)) => assert_eq!(s, "INVOICE bob item widget"),
2583            other => panic!("expected template msg, got {other:?}"),
2584        }
2585    }
2586
2587    #[test]
2588    fn dollar_dollar_brace_is_literal() {
2589        let prog = parse(
2590            "protocol p v1;\nroles a, b;\nstate total: int;\non inform from a { set total = 5; set msg = fmt(\"cost $${total}\"); }\non inform from b -> send bye;\n",
2591        )
2592        .unwrap();
2593        let mut r = Runtime::new(&prog, "b").unwrap();
2594        r.deliver(Event::In {
2595            from: "a".into(),
2596            performative: Performative::Inform,
2597            pattern: None,
2598            fields: None,
2599        });
2600        assert_eq!(
2601            r.states_snapshot().get("msg"),
2602            Some(&StateValue::Str("cost ${total}".into()))
2603        );
2604    }
2605}
2606
2607#[cfg(test)]
2608mod generic_state_tests {
2609    use super::*;
2610    use crate::protocol::parse;
2611
2612    // §41: list<T> rejects wrong-typed elements (internal error flow)
2613    #[test]
2614    fn list_of_record_rejects_non_record() {
2615        let prog = parse(
2616            "type Bid = { price: int };\nprotocol p v1;\nroles a, b;\nstate bids: list<Bid>;\non inform from a { push bids, 5; }\non error { set bad = true; }\non inform from b -> send bye;\n",
2617        )
2618        .unwrap();
2619        let mut r = Runtime::new(&prog, "b").unwrap();
2620        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2621        assert!(r.transcript().iter().any(|e| e.text.contains("does not match 'list<Bid>'")));
2622    }
2623
2624    #[test]
2625    fn list_of_record_accepts_record() {
2626        let prog = parse(
2627            "type Bid = { price: int };\nprotocol p v1;\nroles a, b;\nstate bids: list<Bid>;\non inform from a { push bids, Bid { price: 30 }; }\non inform from b -> send bye;\n",
2628        )
2629        .unwrap();
2630        let mut r = Runtime::new(&prog, "b").unwrap();
2631        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2632        match r.states_snapshot().get("bids") {
2633            Some(StateValue::List(l)) => assert_eq!(l.len(), 1),
2634            other => panic!("expected list, got {other:?}"),
2635        }
2636    }
2637
2638    #[test]
2639    fn map_kv_rejects_bad_value_type() {
2640        let prog = parse(
2641            "protocol p v1;\nroles a, b;\nstate tally: map<str, int>;\non inform from a { put tally, \"x\", \"not_a_number\"; }\non error { set flagged = true; }\non inform from b -> send bye;\n",
2642        )
2643        .unwrap();
2644        let mut r = Runtime::new(&prog, "b").unwrap();
2645        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2646        assert!(r.transcript().iter().any(|e| e.text.contains("does not match 'map<str, int>'")));
2647    }
2648
2649    // §41: typed set mismatch is now an internal error (routes to on error)
2650    #[test]
2651    fn typed_set_mismatch_routes_to_error_handler() {
2652        let prog = parse(
2653            "protocol p v1;\nroles a, b;\nstate n: int;\non inform from a { set n = \"oops\"; }\non error { set caught = true; }\non inform from b -> send bye;\n",
2654        )
2655        .unwrap();
2656        let mut r = Runtime::new(&prog, "b").unwrap();
2657        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2658        assert_eq!(r.states_snapshot().get("caught"), Some(&StateValue::Bool(true)));
2659    }
2660}
2661
2662#[cfg(test)]
2663mod await_tests {
2664    use super::*;
2665    use crate::protocol::parse;
2666
2667    // §44: await collects N matching events, then the flag goes true
2668    #[test]
2669    fn await_collects_and_flags() {
2670        let prog = parse(
2671            "protocol p v1;\nroles a, b;\nstate bids: list;\nstate ready: bool;\non request from a { await 3 propose into bids within 10s as ready; send progress to a; }\non propose from b -> send bye;\non inform from b -> send bye;\non inform from a { set done = ready; }\non bye from b -> send inform to b;\non bye from a -> send inform to a;\n",
2672        )
2673        .unwrap();
2674        let mut r = Runtime::new(&prog, "b").unwrap();
2675        r.deliver(Event::In { from: "a".into(), performative: Performative::Request, pattern: None, fields: None });
2676        for i in 1..=3 {
2677            r.deliver(Event::In {
2678                from: "a".into(),
2679                performative: Performative::Propose,
2680                pattern: None,
2681                fields: Some(BTreeMap::from([("who".into(), FieldValue::Str(format!("b{i}"))), ("price".into(), FieldValue::Int(i * 10))])),
2682            });
2683        }
2684        let snap = r.states_snapshot();
2685        assert_eq!(snap.get("ready"), Some(&StateValue::Bool(true)));
2686        match snap.get("bids") {
2687            Some(StateValue::List(l)) => assert_eq!(l.len(), 3),
2688            other => panic!("expected bids list, got {other:?}"),
2689        }
2690        // collected events do NOT reach handlers (consumed by the collector)
2691        let collected: Vec<_> = r.transcript().iter().filter(|e| e.text.contains("await collected")).collect();
2692        assert_eq!(collected.len(), 3, "{:?}", collected.iter().map(|e| &e.text).collect::<Vec<_>>());
2693    }
2694
2695    #[test]
2696    fn await_timeout_sets_flag_false() {
2697        let prog = parse(
2698            "protocol p v1;\nroles a, b;\nstate bids: list;\nstate ready: bool;\non request from a { await 2 propose into bids within 100ms as ready; }\non propose from b -> send bye;\non inform from b -> send bye;\non bye from b -> send inform to b;\non bye from a -> send inform to a;\n",
2699        )
2700        .unwrap();
2701        let mut r = Runtime::new(&prog, "b").unwrap();
2702        r.deliver(Event::In { from: "a".into(), performative: Performative::Request, pattern: None, fields: None });
2703        r.deliver(Event::In { from: "a".into(), performative: Performative::Propose, pattern: None, fields: None });
2704        assert_eq!(r.states_snapshot().get("ready"), Some(&StateValue::Bool(false)));
2705        r.tick(500);
2706        assert_eq!(r.states_snapshot().get("ready"), Some(&StateValue::Bool(false)));
2707        assert!(r.transcript().iter().any(|e| e.text.contains("await timed out")));
2708    }
2709}
2710
2711#[cfg(test)]
2712mod try_catch_tests {
2713    use super::*;
2714    use crate::protocol::parse;
2715
2716    // §45: a caught failure runs the catch and CUTS the remaining body
2717    #[test]
2718    fn try_catch_cuts_body_and_runs_catch() {
2719        let prog = parse(
2720            "protocol p v1;\nroles a, b;\nstate x: int;\nstate y: int;\non inform from a { try { set x = 1 / 0; set y = 5; } catch { set y = 9; } }\non inform from b -> send bye;\n",
2721        )
2722        .unwrap();
2723        let mut r = Runtime::new(&prog, "b").unwrap();
2724        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2725        let snap = r.states_snapshot();
2726        // x stayed unset (failure), y got the CATCH value, not the body's 5
2727        assert_eq!(snap.get("y"), Some(&StateValue::Int(9)));
2728        assert_eq!(snap.get("x"), Some(&StateValue::Unset));
2729        assert!(r.transcript().iter().any(|e| e.text.contains("caught: set x")));
2730    }
2731
2732    #[test]
2733    fn try_success_skips_catch() {
2734        let prog = parse(
2735            "protocol p v1;\nroles a, b;\nstate x: int;\non inform from a { try { set x = 7; } catch { set x = 0; } }\non inform from b -> send bye;\n",
2736        )
2737        .unwrap();
2738        let mut r = Runtime::new(&prog, "b").unwrap();
2739        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2740        assert_eq!(r.states_snapshot().get("x"), Some(&StateValue::Int(7)));
2741    }
2742
2743    // §45: `handle error` one-line sugar == try/catch
2744    #[test]
2745    fn handle_error_sugar_wraps_in_try() {
2746        let prog = parse(
2747            "protocol p v1;\nroles a, b;\nstate x: int;\nstate y: int;\non inform from a -> set x = 1 / 0 handle error -> set y = 3;\non inform from b -> send bye;\n",
2748        )
2749        .unwrap();
2750        let h = &prog.handlers[0];
2751        assert!(h.actions.iter().any(|a| matches!(a, ProtocolAction::Try { .. })), "{:?}", h.actions);
2752        let mut r = Runtime::new(&prog, "b").unwrap();
2753        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2754        assert_eq!(r.states_snapshot().get("y"), Some(&StateValue::Int(3)));
2755        // uncaught path: NO session-level on error fired (caught locally)
2756        assert!(!r.transcript().iter().any(|e| e.text.contains("internal error: set x")));
2757    }
2758
2759    #[test]
2760    fn uncaught_failure_still_routes_to_on_error() {
2761        let prog = parse(
2762            "protocol p v1;\nroles a, b;\nstate x: int;\nstate caught: bool;\non inform from a { set x = 1 / 0; }\non error { set caught = true; }\non inform from b -> send bye;\n",
2763        )
2764        .unwrap();
2765        let mut r = Runtime::new(&prog, "b").unwrap();
2766        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2767        assert_eq!(r.states_snapshot().get("caught"), Some(&StateValue::Bool(true)));
2768    }
2769}
2770
2771#[cfg(test)]
2772mod typed_fields_tests {
2773    use super::*;
2774    use crate::protocol::parse;
2775
2776    // §46: native int payload — capture is Int WITHOUT string inference
2777    #[test]
2778    fn native_typed_capture_is_int() {
2779        let prog = parse(
2780            "protocol p v1;\nroles a, b;\non inform {\"price\": $p} from a when $p > 99 -> send bye;\non inform from b -> send bye;\n",
2781        )
2782        .unwrap();
2783        let mut r = Runtime::new(&prog, "b").unwrap();
2784        let out = r.deliver(Event::In {
2785            from: "a".into(),
2786            performative: Performative::Inform,
2787            pattern: None,
2788            fields: Some(BTreeMap::from([("price".into(), FieldValue::Int(150))])),
2789        });
2790        assert_eq!(out[0].performative, Performative::Bye);
2791    }
2792
2793    // §46: numeric STRING payload still infers (backward compat), but a
2794    // non-numeric string does NOT become a number
2795    #[test]
2796    fn string_payload_inference_preserved() {
2797        let prog = parse(
2798            "protocol p v1;\nroles a, b;\nstate t: str;\non inform {\"cur\": $c} from a { set t = $c; }\non inform from b -> send bye;\n",
2799        )
2800        .unwrap();
2801        let mut r = Runtime::new(&prog, "b").unwrap();
2802        r.deliver(Event::In {
2803            from: "a".into(),
2804            performative: Performative::Inform,
2805            pattern: None,
2806            fields: Some(BTreeMap::from([("cur".into(), FieldValue::Str("usd".into()))])),
2807        });
2808        assert_eq!(r.states_snapshot().get("t"), Some(&StateValue::Str("usd".into())));
2809    }
2810
2811    // §46: literal pattern comparison against a typed value
2812    #[test]
2813    fn literal_pattern_matches_typed_int() {
2814        let prog = parse(
2815            "protocol p v1;\nroles a, b;\non inform {\"code\": \"42\"} from a -> send bye;\non inform from b -> send bye;\n",
2816        )
2817        .unwrap();
2818        let mut r = Runtime::new(&prog, "b").unwrap();
2819        let out = r.deliver(Event::In {
2820            from: "a".into(),
2821            performative: Performative::Inform,
2822            pattern: None,
2823            fields: Some(BTreeMap::from([("code".into(), FieldValue::Int(42))])),
2824        });
2825        assert_eq!(out[0].performative, Performative::Bye);
2826    }
2827}
2828
2829#[cfg(test)]
2830mod phase_tests {
2831    use super::*;
2832    use crate::protocol::parse;
2833
2834    // §50: a handler gated on a phase only fires IN that phase
2835    #[test]
2836    fn phase_gate_gates() {
2837        let prog = parse(
2838            "protocol p v1;\nroles a, b;\nphase quoted;\nphase accepted;\non inform {\"price\": $p} from a in quoted { enter accepted; }\non inform from a in accepted -> send bye;\non inform from b -> send bye;\n",
2839        )
2840        .unwrap();
2841        assert!(crate::protocol::check(&prog).is_ok(), "{:?}", crate::protocol::check(&prog).unwrap_err());
2842        let mut r = Runtime::new(&prog, "b").unwrap();
2843        // initial phase = "quoted": the in-quoted handler fires and enters accepted
2844        r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: Some(BTreeMap::from([("price".into(), FieldValue::Int(5))])) });
2845        assert_eq!(r.states_snapshot().get("__x"), None);
2846        // now in accepted: the second handler fires
2847        let out = r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2848        assert_eq!(out[0].performative, Performative::Bye);
2849        // back in quoted the FIRST handler would fire again if re-entered —
2850        // but we are in accepted: inform without price does nothing
2851        // still in accepted: the gated handler fires again
2852        let out2 = r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2853        assert_eq!(out2[0].performative, Performative::Bye);
2854    }
2855
2856    #[test]
2857    fn undeclared_phase_is_compile_error() {
2858        let prog = parse(
2859            "protocol p v1;\nroles a, b;\non inform from a in nosuch -> send bye;\non inform from b -> send bye;\n",
2860        )
2861        .unwrap();
2862        let es = crate::protocol::check(&prog).unwrap_err();
2863        assert!(
2864            es.iter().any(|e| e.message.contains("'nosuch'")),
2865            "{es:?}"
2866        );
2867    }
2868
2869    #[test]
2870    fn enter_undeclared_phase_is_runtime_error() {
2871        let prog = parse(
2872            "protocol p v1;\nroles a, b;\nphase quoted;\non inform from a { enter nosuch; }\non inform from b -> send bye;\n",
2873        )
2874        .unwrap();
2875        // check catches it first — verify both layers
2876        assert!(crate::protocol::check(&prog).is_err());
2877        let mut r = Runtime::new(&prog, "b").unwrap();
2878        let out = r.deliver(Event::In { from: "a".into(), performative: Performative::Inform, pattern: None, fields: None });
2879        assert!(out.is_empty());
2880        assert!(r.transcript().iter().any(|e| e.text.contains("not a declared phase")));
2881    }
2882}
2883
2884#[cfg(test)]
2885mod named_commitment_tests {
2886    use super::*;
2887    use crate::protocol::parse;
2888
2889    // §51: named commitments have independent lifecycles
2890    #[test]
2891    fn named_commitments_track_independently() {
2892        let prog = parse(
2893            "protocol p v1;\nroles a, b;\non request from a { begin delivery; begin payment; }\non inform {\"what\": \"delivery\"} from a -> fulfil delivery;\non inform from b -> send bye;\non bye from b -> send inform to b;\non bye from a -> send inform to a;\n",
2894        )
2895        .unwrap();
2896        let mut r = Runtime::new(&prog, "b").unwrap();
2897        r.deliver(Event::In { from: "a".into(), performative: Performative::Request, pattern: None, fields: None });
2898        assert_eq!(r.commitment_status("delivery"), Some(CommitmentStatus::Active));
2899        assert_eq!(r.commitment_status("payment"), Some(CommitmentStatus::Active));
2900        // fulfil ONLY delivery
2901        r.deliver(Event::In {
2902            from: "a".into(),
2903            performative: Performative::Inform,
2904            pattern: None,
2905            fields: Some(BTreeMap::from([("what".into(), FieldValue::Str("delivery".into()))])),
2906        });
2907        assert_eq!(r.commitment_status("delivery"), Some(CommitmentStatus::Fulfilled));
2908        assert_eq!(r.commitment_status("payment"), Some(CommitmentStatus::Active));
2909        // the DEFAULT commitment is untouched
2910        assert_eq!(r.commitment(), CommitmentStatus::Proposed);
2911        // fulfil again on delivery is ignored
2912        r.deliver(Event::In {
2913            from: "a".into(),
2914            performative: Performative::Inform,
2915            pattern: None,
2916            fields: Some(BTreeMap::from([("what".into(), FieldValue::Str("delivery".into()))])),
2917        });
2918        assert_eq!(r.commitment_status("delivery"), Some(CommitmentStatus::Fulfilled));
2919    }
2920}