Skip to main content

acl_core/
codegen.rs

1//! §34: endpoint codegen — `aclc gen agent py <file.aclp> <out_dir>`.
2//!
3//! Emits a RUNNABLE Python skeleton per role: the projected handlers as
4//! data, the dispatch loop, guard evaluation, and timer ticking. The
5//! generated agent has no ACL-specific dependencies — it speaks the
6//! protocol the program declares, exactly as compiled.
7
8use crate::protocol::{BinOp, Expr, Guard, OnTrigger, ProtocolAction, ProtocolProgram};
9use crate::runtime::{project, RoleEndpoint};
10use crate::Performative;
11
12fn py_perf(p: &Performative) -> String {
13    format!("{:?}", p).to_lowercase()
14}
15
16fn py_guard(g: &Guard) -> String {
17    match g {
18        Guard::Atom { name, neg } => {
19            format!("[\"atom\", \"{}\", {}]", name, neg)
20        }
21        Guard::And(a, b) => format!("[\"and\", {}, {}]", py_guard(a), py_guard(b)),
22        Guard::Or(a, b) => format!("[\"or\", {}, {}]", py_guard(a), py_guard(b)),
23        // §38.3: expression guards serialize as a nested expression node
24        Guard::ExprGuard(e) => format!("[\"expr\", {}]", py_expr(e)),
25    }
26}
27
28fn py_opt_guard(g: &Option<Guard>) -> String {
29    match g {
30        Some(g) => py_guard(g),
31        None => "None".into(),
32    }
33}
34
35fn py_action(a: &ProtocolAction) -> String {
36    match a {
37        ProtocolAction::Send { performative, to, fields, .. } => format!(
38            "{{\"kind\": \"send\", \"performative\": \"{}\", \"to\": {}, \"fields\": {}}}",
39            py_perf(performative),
40            match to {
41                Some(t) => format!("\"{t}\""),
42                None => "None".to_string(),
43            },
44            match fields {
45                Some(f) => {
46                    // §53: values with ${expr} become pre-parsed
47                    // interpolation segments (python has no expr parser)
48                    let entries: Vec<String> = f
49                        .iter()
50                        .map(|(k, v)| {
51                            let val = if v.contains("${") {
52                                let segs: Vec<String> = fmt_segments(v)
53                                    .into_iter()
54                                    .map(|seg| match seg {
55                                        FmtSeg::Text(t) => serde_json::json!({ "s": t }).to_string(),
56                                        FmtSeg::Expr(e) => serde_json::json!({
57                                            "e": serde_json::from_str::<serde_json::Value>(&py_expr(&e)).unwrap_or_default()
58                                        }).to_string(),
59                                    })
60                                    .collect();
61                                format!("{{\"interp\": [{}]}}", segs.join(", "))
62                            } else {
63                                serde_json::to_string(v).unwrap_or_default()
64                            };
65                            format!("\"{k}\": {val}")
66                        })
67                        .collect();
68                    format!("{{{}}}", entries.join(", "))
69                }
70                None => "None".into(),
71            }
72        ),
73        ProtocolAction::Enter { phase } => format!(
74            "{{\"kind\": \"enter\", \"phase\": \"{phase}\"}}",
75        ),
76        ProtocolAction::BeginId { id } => format!(
77            "{{\"kind\": \"begin_id\", \"id\": \"{id}\"}}",
78        ),
79        ProtocolAction::FulfilId { id } => format!(
80            "{{\"kind\": \"fulfil_id\", \"id\": \"{id}\"}}",
81        ),
82        ProtocolAction::Try { body, catch } => format!(
83            "{{\"kind\": \"try\", \"body\": [{}], \"catch\": [{}]}}",
84            body.iter().map(py_action).collect::<Vec<_>>().join(", "),
85            catch.iter().map(py_action).collect::<Vec<_>>().join(", ")
86        ),
87        ProtocolAction::Await { count, performative, into, within_ms, flag } => format!(
88            "{{\"kind\": \"await\", \"count\": {count}, \"performative\": \"{}\", \"into\": \"{into}\", \"within_ms\": {within_ms}, \"flag\": \"{flag}\"}}",
89            py_perf(performative)
90        ),
91        ProtocolAction::Broadcast { performative, fields, to } => format!(
92            "{{\"kind\": \"broadcast\", \"performative\": \"{}\", \"to\": \"{}\", \"fields\": {}}}",
93            py_perf(performative),
94            to,
95            match fields {
96                Some(f) => serde_json::to_string(f).unwrap_or_default(),
97                None => "None".into(),
98            }
99        ),
100        ProtocolAction::Begin => "{\"kind\": \"begin\"}".into(),
101        ProtocolAction::Fulfil => "{\"kind\": \"fulfil\"}".into(),
102        ProtocolAction::Retract { target } => {
103            format!("{{\"kind\": \"retract\", \"target\": \"{}\"}}", target)
104        }
105        ProtocolAction::Set { name, field, expr } => format!(
106            "{{\"kind\": \"set\", \"name\": \"{}\", \"field\": {}, \"expr\": {}}}",
107            name,
108            match field { Some(f) => format!("\"{f}\""), None => "None".into() },
109            py_expr(expr),
110        ),
111        ProtocolAction::Push { state, expr } => format!(
112            "{{\"kind\": \"push\", \"state\": \"{}\", \"expr\": {}}}", state, py_expr(expr)
113        ),
114        ProtocolAction::Put { state, key, expr } => format!(
115            "{{\"kind\": \"put\", \"state\": \"{}\", \"key\": \"{}\", \"expr\": {}}}", state, key, py_expr(expr)
116        ),
117        ProtocolAction::For { var, over, actions } => {
118            let inner: Vec<String> = actions.iter().map(py_action).collect();
119            format!(
120                "{{\"kind\": \"for\", \"var\": \"{}\", \"over\": \"{}\", \"actions\": [{}]}}",
121                var, over, inner.join(", ")
122            )
123        }
124        ProtocolAction::Abort => "{\"kind\": \"abort\"}".into(),
125        ProtocolAction::Return { expr } => format!(
126            "{{\"kind\": \"return\", \"expr\": {}}}",
127            py_expr(expr)
128        ),
129    }
130}
131
132/// §38.9: split a template text into literal/expr segments at `${...}`
133/// boundaries (brace-balanced); `$${` is the literal escape.
134enum FmtSeg {
135    Text(String),
136    Expr(Expr),
137}
138
139fn fmt_segments(txt: &str) -> Vec<FmtSeg> {
140    let esc = "\u{1}";
141    let cs: Vec<char> = txt.replace("$${", esc).chars().collect();
142    let mut out = Vec::new();
143    let mut lit = String::new();
144    let mut i = 0;
145    while i < cs.len() {
146        if cs[i] == '$' && i + 1 < cs.len() && cs[i + 1] == '{' {
147            let mut depth = 1i64;
148            let mut j = i + 2;
149            while j < cs.len() && depth > 0 {
150                match cs[j] {
151                    '{' => depth += 1,
152                    '}' => depth -= 1,
153                    _ => {}
154                }
155                j += 1;
156            }
157            if depth != 0 {
158                lit.push(cs[i]);
159                i += 1;
160                continue;
161            }
162            if !lit.is_empty() {
163                let t = std::mem::take(&mut lit).replace(esc, "${");
164                out.push(FmtSeg::Text(t));
165            }
166            let src: String = cs[i + 2..j - 1].iter().collect();
167            match Expr::parse_expr(src.trim()) {
168                Ok(e) => out.push(FmtSeg::Expr(e)),
169                Err(_) => {
170                    let t: String = cs[i..j].iter().collect();
171                    out.push(FmtSeg::Text(t.replace(esc, "${")));
172                }
173            }
174            i = j;
175        } else {
176            lit.push(cs[i]);
177            i += 1;
178        }
179    }
180    if !lit.is_empty() {
181        out.push(FmtSeg::Text(lit.replace(esc, "${")));
182    }
183    // escape restoration inside expr-preceding texts is handled by the
184    // final replacement below for already-pushed segments too
185    out
186}
187
188fn py_expr(e: &Expr) -> String {
189    match e {
190        Expr::LitInt(i) => format!("{{\"lit\": {}}}", i),
191        Expr::LitStr(s) => format!("{{\"lit\": {}}}", serde_json::to_string(s).unwrap_or_default()),
192        Expr::LitBool(b) => format!(
193            "{{\"lit\": {}}}",
194            if *b { "True" } else { "False" }
195        ),
196        Expr::State(n) => format!("{{\"state\": \"{}\"}}", n),
197        // §38.3: capture references serialize as a capture node
198        Expr::Capture(n) => format!("{{\"capture\": \"{}\"}}", n),
199        Expr::Field { base, name } => format!(
200            "{{\"field\": {{\"base\": {}, \"name\": \"{}\"}}}}",
201            py_expr(base), name
202        ),
203        Expr::RecLit { ty, fields } => {
204            let f: Vec<String> = fields.iter().map(|(n, e)| format!("\"{}\": {}", n, py_expr(e))).collect();
205            format!("{{\"rec\": \"{}\", \"fields\": {{{}}}}}", ty, f.join(", "))
206        }
207        Expr::Arg(a) => format!("{{\"arg\": \"{}\"}}", a),
208        Expr::Bin { op, l, r } => {
209            let o = match op {
210                BinOp::Add => "add", BinOp::Sub => "sub", BinOp::Mul => "mul", BinOp::Div => "div",
211                BinOp::Lt => "lt", BinOp::Le => "le", BinOp::Gt => "gt", BinOp::Ge => "ge",
212                BinOp::Eq => "eq", BinOp::Ne => "ne", BinOp::And => "and", BinOp::Or => "or",
213            };
214            format!("{{\"op\": \"{}\", \"l\": {}, \"r\": {}}}", o, py_expr(l), py_expr(r))
215        }
216        Expr::Not(x) => format!("{{\"not\": {}}}", py_expr(x)),
217        Expr::Call { name, args } if name == "fmt" && !args.is_empty() => {
218            // §38.9: fmt with an inline "${...}" literal is emitted as
219            // pre-parsed segments; fmt with a template name keeps the
220            // positional form (resolved against TEMPLATES at runtime)
221            if let Expr::LitStr(txt) = &args[0] {
222                if txt.contains("${") {
223                    let segs = fmt_segments(txt);
224                    let segs = segs
225                        .iter()
226                        .map(|seg| match seg {
227                            FmtSeg::Text(t) => format!("{{\"s\": {}}}", serde_json::to_string(t).unwrap_or_default()),
228                            FmtSeg::Expr(e) => format!("{{\"e\": {}}}", py_expr(e)),
229                        })
230                        .collect::<Vec<_>>()
231                        .join(", ");
232                    return format!("{{\"tmpl\": [{segs}]}}");
233                }
234            }
235            let a: Vec<String> = args.iter().map(py_expr).collect();
236            format!("{{\"fmtname\": {}, \"args\": [{}]}}", py_expr(&args[0]), a[1..].join(", "))
237        }
238        Expr::Call { name, args } => {
239            let a: Vec<String> = args.iter().map(py_expr).collect();
240            format!("{{\"call\": \"{}\", \"args\": [{}]}}", name, a.join(", "))
241        }
242    }
243}
244
245fn py_trigger(t: &OnTrigger) -> String {
246    match t {
247        OnTrigger::Event { performative, pattern, from, phase, .. } => format!(
248            "{{\"kind\": \"event\", \"performative\": \"{}\", \"pattern\": {}, \"from\": {}, {{\"phase\": {}}}",
249            py_perf(performative),
250            match pattern {
251                Some(p) => serde_json::to_string(p).unwrap_or_default(),
252                None => "None".into(),
253            },
254            match from {
255                Some(f) => format!("\"{f}\""),
256                None => "None".to_string(),
257            },
258            match phase {
259                Some(ph) => format!("\"{ph}\""),
260                None => "None".to_string(),
261            }
262        ),
263        OnTrigger::Breach => "{\"kind\": \"breach\"}".into(),
264        OnTrigger::Expired => "{\"kind\": \"expired\"}".into(),
265        OnTrigger::Timer { every_ms, guard, as_role } => format!(
266            "{{\"kind\": \"timer\", \"every_ms\": {}, \"guard\": {}, \"as_role\": {}}}",
267            every_ms,
268            py_opt_guard(guard),
269            match as_role { Some(r) => format!("\"{r}\""), None => "None".into() }
270        ),
271    }
272}
273
274/// Generate the Python agent skeleton for one role's endpoint.
275pub fn gen_agent_py(prog: &ProtocolProgram, role: &str) -> Result<String, Vec<crate::idl::IdlError>> {
276    let ep: RoleEndpoint = project(prog, role)?;
277    let mut out = String::new();
278    out.push_str(&format!(
279        "\"\"\"{} agent (role: {}) — generated from protocol '{}' v{} by aclc.\n\n\
280        The conversation is the program (ACL spec §33/§34): this class is the\n\
281        compiled protocol, not hand-written logic. Wire it to any transport\n\
282        by feeding deliver()/tick() and sending the returned dicts.\n\"\"\"\n\n",
283        prog.name, role, prog.name, prog.version
284    ));
285    out.push_str("class Agent:\n");
286    out.push_str(&format!("    ROLE = {}\n", serde_json::to_string(role).unwrap_or_default()));
287    out.push_str(&format!(
288        "    ROLES = {}\n",
289        serde_json::to_string(&prog.roles).unwrap_or_default()
290    ));
291    out.push_str(&format!(
292        "    STATES = {}\n",
293        serde_json::to_string(
294            &prog.states
295                .iter()
296                .map(|s| (s.name.clone(), s.ty.clone().unwrap_or_else(|| "bool".into())))
297                .collect::<std::collections::BTreeMap<_, _>>()
298        )
299        .unwrap_or_default()
300    ));
301    // §38.9: templates are pre-parsed into literal/expr segments
302    let templates: std::collections::BTreeMap<String, serde_json::Value> = prog
303        .templates
304        .iter()
305        .map(|(n, t)| {
306            let segs: Vec<serde_json::Value> = fmt_segments(t)
307                .into_iter()
308                .map(|seg| match seg {
309                    FmtSeg::Text(t) => serde_json::json!({ "s": t }),
310                    FmtSeg::Expr(e) => serde_json::json!({
311                        "e": serde_json::from_str::<serde_json::Value>(&py_expr(&e)).unwrap_or_default()
312                    }),
313                })
314                .collect();
315            (n.clone(), serde_json::json!(segs))
316        })
317        .collect();
318    out.push_str(&format!(
319        "    PHASES = {}\n",
320        serde_json::to_string(&prog.phases).unwrap_or_default()
321    ));
322    out.push_str(&format!(
323        "    TEMPLATES = {}\n",
324        serde_json::to_string(&templates).unwrap_or_default()
325    ));
326    out.push_str("    HANDLERS = [\n");
327    for h in &ep.handlers {
328        let (kind, base) = match &h.trigger {
329            OnTrigger::Event { performative, from, phase, .. } => {
330                ("event", format!("\"performative\": \"{}\", \"from\": {}, \"phase\": {}", py_perf(performative), match from { Some(f) => format!("\"{f}\""), None => "None".into() }, match phase { Some(ph) => format!("\"{ph}\""), None => "None".into() }))
331            }
332            OnTrigger::Breach => ("breach", String::new()),
333            OnTrigger::Expired => ("expired", String::new()),
334            OnTrigger::Timer { every_ms, guard, as_role } => ("timer", format!("\"every_ms\": {}, \"as_role\": {}", every_ms, match as_role { Some(r) => format!("\"{r}\""), None => "None".into() })),
335        };
336        let guard = match &h.trigger {
337            OnTrigger::Timer { guard, .. } => py_opt_guard(guard),
338            _ => py_opt_guard(&h.guard),
339        };
340        let pattern = match &h.trigger {
341            OnTrigger::Event { pattern, .. } => match pattern {
342                Some(p) => serde_json::to_string(p).unwrap_or_default(),
343                None => "None".into(),
344            },
345            _ => "None".into(),
346        };
347        let actions: Vec<String> = h.actions.iter().map(py_action).collect();
348        let mut parts = vec![format!("\"kind\": \"{}\"", kind)];
349        if !base.is_empty() {
350            parts.push(base);
351        }
352        parts.push(format!("\"pattern\": {}", pattern));
353        parts.push(format!("\"guard\": {}", guard));
354        parts.push(format!("\"actions\": [{}]", actions.join(", ")));
355        out.push_str(&format!("        {{{}}},\n", parts.join(", ")));
356    }
357    out.push_str("    ]\n\n");
358
359    // the runtime loop — mirrors src/runtime.rs semantics exactly
360    out.push_str(
361        r#"    def __init__(self):
362        self._arg = {}
363        self._caps = {}
364        self._awaits = []
365        self._catch = None
366        self._jump = False
367        self._phase = self.PHASES[0] if self.PHASES else ""
368        self.commitments = {}
369        self.states = {k: None for k in self.STATES}
370        self.commitment = "proposed"   # proposed -> active -> fulfilled/breached
371        self.timer_due = [0] * len([h for h in self.HANDLERS if h["kind"] == "timer"])
372        self._now = 0
373        self.transcript = []
374
375    # -- state helpers ------------------------------------------------
376    def _bool(self, name):
377        v = self.states.get(name)
378        if v is None:
379            return False
380        if isinstance(v, bool):
381            return v
382        if isinstance(v, int):
383            return v != 0
384        return len(v) > 0
385
386    def _eval_interp(self, node):
387        # §53: interpolation segments
388        out = ""
389        for seg in node["interp"]:
390            if "s" in seg:
391                out += seg["s"]
392            else:
393                out += self._text(self._eval(seg["e"]))
394        return out
395
396    def _text(self, v):
397        if v is True:
398            return "true"
399        if v is False:
400            return "false"
401        if v is None:
402            return "unset"
403        return str(v)
404
405    def _guard(self, g):
406        if g is None:
407            return True
408        kind = g[0]
409        if kind == "atom":
410            v = self._bool(g[1])
411            return (not v) if g[2] else v
412        if kind == "expr":
413            return self._truthy(self._eval(g[1]))
414        if kind == "and":
415            return self._guard(g[1]) and self._guard(g[2])
416        return self._guard(g[1]) or self._guard(g[2])
417
418    def _pattern_ok(self, want, got_pattern, got_fields):
419        if want is None:
420            return True
421        if want.startswith("("):
422            return want == got_pattern
423        if got_fields is None:
424            return False
425        import json
426        w = json.loads(want)
427        self._caps = {}
428        for k, wv in w.items():
429            gv = got_fields.get(k)
430            if gv is None:
431                return False
432            if wv.endswith("*"):
433                if not str(gv).startswith(wv[:-1]):
434                    return False
435            elif wv.startswith("$"):
436                # §46: native typed values pass through; strings infer
437                self._caps[wv[1:]] = gv if isinstance(gv, (int, float, bool)) else self._infer(gv)
438            elif str(gv) != wv:
439                return False
440        return True
441
442    def _infer(self, s):
443        # §38.3: capture type inference (int/float/bool, else string)
444        if s == "true":
445            return True
446        if s == "false":
447            return False
448        try:
449            return int(s)
450        except ValueError:
451            pass
452        try:
453            return float(s)
454        except ValueError:
455            return s
456
457    def _match(self, h, performative, pattern, fields):
458        if h["kind"] == "event":
459            if h["performative"] != performative:
460                return False
461            # §50: conversation phase gate
462            if h.get("phase") is not None and self._phase != h["phase"]:
463                return False
464            if not self._pattern_ok(h["pattern"], pattern, fields):
465                return False
466            return self._guard(h["guard"])
467        return False
468
469    def _eval(self, e):
470        if "tmpl" in e:
471            # §38.9 rich interpolation: pre-parsed segments
472            out = ""
473            for seg in e["tmpl"]:
474                if "s" in seg:
475                    out += seg["s"]
476                else:
477                    out += self._text(self._eval(seg["e"]))
478            return out
479        if "fmtname" in e:
480            tname = self._eval(e["fmtname"])
481            segs = self.TEMPLATES.get(tname)
482            if segs is None:
483                raise ValueError("no message template '%s'" % tname)
484            out = ""
485            for seg in segs:
486                if "s" in seg:
487                    out += seg["s"]
488                else:
489                    out += self._text(self._eval(seg["e"]))
490            for idx, a in enumerate(e["args"]):
491                out = out.replace("{%d}" % idx, self._text(self._eval(a)))
492            return out
493        if "lit" in e:
494            return e["lit"]
495        if "state" in e:
496            return self.states.get(e["state"])
497        if "capture" in e:
498            return self._caps.get(e["capture"])
499        if "arg" in e:
500            return self._arg.get(e["arg"])
501        if "not" in e:
502            return not self._truthy(self._eval(e["not"]))
503        if "op" in e:
504            l = self._eval(e["l"]); r = self._eval(e["r"])
505            op = e["op"]
506            if op == "and": return self._truthy(l) and self._truthy(r)
507            if op == "or": return self._truthy(l) or self._truthy(r)
508            # unset states behave as 0 in arithmetic (§35.1 convention)
509            if op == "add": return (l or 0) + (r or 0)
510            if op == "sub": return (l or 0) - (r or 0)
511            if op == "mul": return (l or 0) * (r or 0)
512            if op == "div": return (l or 0) // (r or 0)
513            if op == "eq": return l == r
514            if op == "ne": return l != r
515            if op == "lt": return l < r
516            if op == "le": return l <= r
517            if op == "gt": return l > r
518            if op == "ge": return l >= r
519        if "call" in e:
520            args = [self._eval(a) for a in e["args"]]
521            name = e["call"]
522            if name == "add": return (args[0] or 0) + (args[1] or 0)
523            if name == "sub": return (args[0] or 0) - (args[1] or 0)
524            if name == "mul": return (args[0] or 0) * (args[1] or 0)
525            if name == "div": return (args[0] or 0) // (args[1] or 0)
526            if name == "min": return min(args)
527            if name == "max": return max(args)
528            if name == "abs": return abs(args[0])
529            if name == "len": return len(args[0])
530            if name == "sum": return sum(args[0])
531            if name == "count": return len(args[0])
532            if name == "concat": return str(args[0]) + str(args[1])
533            if name == "upper": return str(args[0]).upper()
534            if name == "lower": return str(args[0]).lower()
535            if name == "str": return str(args[0])
536            if name == "int": return int(args[0])
537            if name == "exists": return args[0] is not None
538            if name == "prefer":
539                # §38.8: lowest value of args[1] among maps in args[0]
540                best = None; best_v = None
541                for m in (args[0] or []):
542                    v = (m or {}).get(args[1])
543                    if isinstance(v, (int, float)) and (best_v is None or v < best_v):
544                        best, best_v = m, v
545                return best
546            if name == "first": return args[0][0]
547            if name == "last": return args[0][-1]
548            if name == "fmt":
549                raise NotImplementedError("fmt requires template support")
550        raise ValueError("bad expression: %r" % e)
551
552    def _truthy(self, v):
553        if v is None: return False
554        if isinstance(v, bool): return v
555        if isinstance(v, (int, float)): return v != 0
556        if isinstance(v, (str, list, dict)): return len(v) > 0
557        return False
558
559    def _run(self, h):
560        out = []
561        for a in h["actions"]:
562            self._run_one(a, out)
563        return out
564
565    def deliver(self, from_role, performative, pattern=None, fields=None):
566        """Feed one incoming speech act; returns the outgoing ones."""
567        self._arg = fields or {}
568        # §44: an active await collector CONSUMES matching events
569        for aw in list(self._awaits):
570            if aw["performative"] == performative:
571                payload = dict(fields or {})
572                cur = self.states.get(aw["into"])
573                if isinstance(cur, list):
574                    cur.append(payload)
575                else:
576                    self.states[aw["into"]] = [payload]
577                aw["count_left"] -= 1
578                if aw["count_left"] <= 0:
579                    self._awaits.remove(aw)
580                    self.states[aw["flag"]] = True
581                return []
582        self.transcript.append(("in", performative, from_role))
583        for h in self.HANDLERS:
584            if h["kind"] == "breach" or h["kind"] == "expired":
585                continue
586            if h["kind"] == "event" and h["from"] is not None and h["from"] != from_role:
587                continue
588            if self._match(h, performative, pattern, fields):
589                return self._run(h)
590        return []   # logged, unhandled (§33.4 auditability)
591
592    def _run_one(self, a, out):
593        # ONE dispatcher for top-level AND nested execution — a failing
594        # action routes like the Rust runtime; caught failures jump
595        try:
596            if a["kind"] == "send":
597                self.transcript.append(("out", a["performative"]))
598                fields = a["fields"]
599                if isinstance(fields, dict):
600                    fields = {k: (self._eval_interp(v) if isinstance(v, dict) and "interp" in v else v) for k, v in fields.items()}
601                out.append({"to": a["to"], "performative": a["performative"], "fields": fields})
602            elif a["kind"] == "begin":
603                if self.commitment == "proposed":
604                    self.commitment = "active"
605                self.transcript.append(("state", "begin"))
606            elif a["kind"] == "fulfil":
607                if self.commitment == "active":
608                    self.commitment = "fulfilled"
609                self.transcript.append(("state", "fulfil"))
610            elif a["kind"] == "retract":
611                self.states[a["target"]] = False
612                self.transcript.append(("state", "retract:" + a["target"]))
613            elif a["kind"] == "set":
614                self.states[a["name"]] = self._eval(a["expr"])
615                self.transcript.append(("state", "set:" + a["name"]))
616            elif a["kind"] == "try":
617                # §45: handler-local error flow — a failing action in
618                # the body cuts it short and runs the catch actions
619                self._catch = a["catch"]
620                for b in a["body"]:
621                    self._run_one(b, out)
622                    if self._jump:
623                        break
624                self._catch = None
625                self._jump = False
626            elif a["kind"] == "begin_id":
627                # §51: named commitment lifecycle
628                cur = self.commitments.get(a["id"])
629                if cur in ("proposed", "active"):
630                    self.transcript.append(("state", "begin " + a["id"] + " ignored"))
631                else:
632                    self.commitments[a["id"]] = "active"
633                    self.transcript.append(("state", "commitment " + a["id"] + " -> active"))
634            elif a["kind"] == "fulfil_id":
635                if self.commitments.get(a["id"]) == "active":
636                    self.commitments[a["id"]] = "fulfilled"
637                    self.transcript.append(("state", "commitment " + a["id"] + " -> fulfilled"))
638                else:
639                    self.transcript.append(("state", "fulfil " + a["id"] + " ignored"))
640            elif a["kind"] == "enter":
641                # §50: conversation phase transition
642                self._phase = a["phase"]
643                self.transcript.append(("state", "phase:" + a["phase"]))
644            elif a["kind"] == "await":
645                # §44: arm the collector; flag starts False
646                self._awaits.append({
647                    "count_left": a["count"],
648                    "performative": a["performative"],
649                    "into": a["into"],
650                    "deadline_ms": self._now + a["within_ms"],
651                    "flag": a["flag"],
652                })
653                self.states[a["flag"]] = False
654            elif a["kind"] == "broadcast":
655                # §38.8: fan-out — one send per role in the list state
656                for r in (self.states.get(a["to"]) or []):
657                    self.transcript.append(("out", a["performative"]))
658                    out.append({"to": r, "performative": a["performative"], "fields": a["fields"]})
659            elif a["kind"] == "push":
660                cur = self.states.get(a["state"])
661                if cur is None:
662                    self.states[a["state"]] = [self._eval(a["expr"])]
663                elif isinstance(cur, list):
664                    cur.append(self._eval(a["expr"]))
665                self.transcript.append(("state", "push:" + a["state"]))
666            elif a["kind"] == "put":
667                cur = self.states.get(a["state"])
668                if cur is None:
669                    self.states[a["state"]] = {}
670                if isinstance(self.states[a["state"]], dict):
671                    key = self._eval({"lit": 0, "str": a["key"]}) if False else a["key"]
672                    self.states[a["state"]][key] = self._eval(a["expr"])
673                self.transcript.append(("state", "put:" + a["state"]))
674            elif a["kind"] == "for":
675                lst = list(self.states.get(a["over"]) or [])
676                saved = self.states.get(a["var"])
677                for item in lst:
678                    self.states[a["var"]] = item
679                    for sub in a["actions"]:
680                        # ONE dispatcher — nested execution is identical
681                        self._run_one(sub, out)
682                    if self._jump:
683                        # a caught failure cuts the remaining iterations
684                        break
685                if saved is None:
686                    self.states.pop(a["var"], None)
687                else:
688                    self.states[a["var"]] = saved
689            elif a["kind"] == "abort":
690                self.commitment = "breached"
691                self.transcript.append(("state", "abort"))
692        except Exception as e:
693            if self._catch:
694                catch = self._catch
695                self._catch = None
696                for c in catch:
697                    self._run_one(c, out)
698                self._jump = True
699            else:
700                self.transcript.append(("state", "internal error: %s" % e))
701
702    def fire(self, kind):
703        """Deliver 'breach' or 'expired' state events."""
704        self.transcript.append(("in", kind))
705        for h in self.HANDLERS:
706            if h["kind"] == kind:
707                return self._run(h)
708        return []
709
710    def tick(self, elapsed_ms):
711        """Host-injected time (§34): timers fire here, deterministically."""
712        self._now = elapsed_ms
713        # §44: await deadlines
714        for aw in list(self._awaits):
715            if aw["deadline_ms"] <= elapsed_ms:
716                self._awaits.remove(aw)
717                self.states[aw["flag"]] = False
718        timers = [h for h in self.HANDLERS if h["kind"] == "timer"]
719        out = []
720        for i, h in enumerate(timers):
721            if not self._guard(h["guard"]):
722                continue
723            while self.timer_due[i] + h["every_ms"] <= elapsed_ms:
724                self.timer_due[i] += h["every_ms"]
725                self.transcript.append(("in", "timer"))
726                out.extend(self._run(h))
727        return out
728
729    def ended(self):
730        if "fulfilled" == self.commitment:
731            return True
732        return False
733"#,
734    );
735    Ok(out)
736}