Skip to main content

bynk_check/
agent_state.rs

1//! #2195: the agent state model — each agent's state machine, derived from its
2//! handlers (agent-state-views track, slice 1; retired-track
3//! summary in `design/archive/retired-tracks.md`, §3.1, §3.3, §3.7).
4//!
5//! The language leaves an agent's machine implicit: a `store` `Cell` of a
6//! user sum type (`enum { … }` or pipe form) *is* the machine, `match`/`is`
7//! read it and `:=` moves it. This query recovers, for every such field, the
8//! edges the handlers can produce — `(from-set, handler, guards, target,
9//! outcome, span)` — and the set of states reachable from the initialiser.
10//!
11//! **A dataflow pass, not path enumeration (§3.3 step 1).** Each handler body
12//! is walked over a set of abstract paths. A path carries the states it can
13//! have started in (the from-set), the field's *current* value, the last
14//! write, its opaque guards, and — once it reaches a tail — its outcome:
15//!
16//! - Before the first write, a `match <field>` arm or an `is`/`==` test
17//!   narrows the from-set. After a known write the same test is decided
18//!   statically (a read after a write sees the staged value — ADR 0125 D4),
19//!   pruning infeasible branches. After a computed write it narrows nothing
20//!   and becomes an opaque guard.
21//! - Any other condition is an opaque guard, labelled with its source text.
22//! - At each join, paths that agree on from-set, current value, last write
23//!   and outcome merge; their guards combine.
24//! - The last write on a path wins, since writes commit together at return.
25//!   A domain `Err` is a value, so a write before it still makes an edge.
26//! - Past [`PATH_BUDGET`] live paths a handler is truncated: its edges become
27//!   one [`Target::Unknown`] edge from every state, which keeps reachability
28//!   (and slice 3's overlay) sound.
29//!
30//! Reachability treats an [`Target::Unknown`] edge as reaching every state —
31//! a sound over-approximation, so a state outside [`StateMachine::reachable`]
32//! is truly unreachable from the handlers.
33//!
34//! **Placement (§3.7; #2220).** A pure function of an [`AgentDecl`] and the
35//! type table, taking no LSP or checker-internal type. It lives in
36//! `bynk-check` so the state view (`bynk-ide`, `bynk-lsp`) and a checker
37//! diagnostic read one model; `bynk-ide` re-exports it as
38//! `bynk_ide::agent_state`.
39//!
40//! Fault paths (a failing `expect` or `<-`) persist nothing and are not
41//! modelled as edges: the walk follows the success path of every statement.
42//!
43//! Out of scope, as in the sequence diagram (ADR 0259): control flow and
44//! writes nested inside an argument expression (`Ok(if c { … } else { … })`,
45//! a `field.update(f)` that is not the top of its expression) or a lambda.
46//! This costs guard and outcome precision, never edges: a `:=` is a
47//! statement, and a `field.update(f)` only runs when it is awaited (`<-`,
48//! `do`) or returned as a tail — an `Effect` buried in an argument is a value
49//! that never executes.
50
51use std::collections::{BTreeSet, HashMap};
52use std::sync::Arc;
53
54use bynk_syntax::CompileError;
55use bynk_syntax::ast::*;
56use bynk_syntax::span::Span;
57
58use crate::ast_text::{branch_outcome, pattern_summary, peel_paren};
59use crate::store_write::{store_kinds, store_write};
60
61/// The most live abstract paths one handler may carry before it is truncated
62/// (#2195 DECISION C) — a backstop against a pathological handler in a live
63/// view, far above anything in the corpus.
64pub const PATH_BUDGET: usize = 256;
65
66/// The state machines of one agent — one per state field.
67#[derive(Debug, Clone, PartialEq)]
68pub struct AgentStateModel {
69    pub agent: String,
70    pub machines: Vec<StateMachine>,
71    /// #3608: the agent's snapshot `invariant`s then its step `transition`s,
72    /// each in declaration order.
73    pub invariants: Vec<AgentInvariant>,
74}
75
76/// Which declaration an [`AgentInvariant`] came from.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum InvariantKind {
79    /// A snapshot `invariant`, over the committed state.
80    Invariant,
81    /// A step `transition`, over the `old`/`new` pair (ADR 0144).
82    Transition,
83}
84
85/// #3608: one declared `invariant` or `transition` of an agent. The predicate
86/// is source text printed by the expression printer, so two spellings of one
87/// predicate (whitespace, comments, layout) print alike and a client can
88/// compare revisions by `(kind, name, predicate)`.
89#[derive(Debug, Clone, PartialEq)]
90pub struct AgentInvariant {
91    pub kind: InvariantKind,
92    pub name: String,
93    pub predicate: String,
94    /// The declaration's documentation text, trailing whitespace trimmed,
95    /// when it has any.
96    pub doc: Option<String>,
97    /// From the `invariant`/`transition` keyword to the end of the predicate;
98    /// the leading documentation block is not included.
99    pub span: Span,
100}
101
102/// One state field's machine.
103#[derive(Debug, Clone, PartialEq)]
104pub struct StateMachine {
105    pub field: String,
106    pub field_span: Span,
107    /// The sum type's variant constructors, in declaration order.
108    pub states: Vec<String>,
109    /// The initialiser's variant; `None` when it is absent or not a variant
110    /// literal, in which case every state is treated as reachable.
111    pub initial: Option<String>,
112    pub edges: Vec<Edge>,
113    /// States reachable from `initial` over `edges` (sound: an `Unknown`
114    /// edge reaches every state), in declaration order.
115    pub reachable: Vec<String>,
116    /// #2219: the states the agent can be in *after a commit*, in declaration
117    /// order. A `transition` is checked from the second commit onward (the
118    /// genesis commit has no `old`), so only a move from one of these can
119    /// fault. Every reachable state but the initial one is here (reaching it
120    /// took a committing write); the initial state is here only when some
121    /// committing path leaves the agent in it. [`Self::reachable`] still
122    /// drives what the view dims.
123    pub reachable_after_commit: Vec<String>,
124    /// Handlers that exceeded [`PATH_BUDGET`].
125    pub truncated: Vec<String>,
126    /// #2197: `transition`s that mention this field but fall outside the
127    /// evaluated fragment — listed, never guessed.
128    pub not_evaluated: Vec<NotEvaluated>,
129}
130
131/// One way a handler can leave the field.
132#[derive(Debug, Clone, PartialEq)]
133pub struct Edge {
134    pub handler: String,
135    /// The states this path can start in, in declaration order.
136    pub from: Vec<String>,
137    /// Conditions on the path that don't constrain the field, as source text.
138    pub guards: Vec<String>,
139    pub to: Target,
140    /// The value the handler yields on this path (`Ok(())`); `None` for unit.
141    pub outcome: Option<String>,
142    /// The write, or for an unchanged path the tail, for click-to-code.
143    pub span: Span,
144    /// #2197: the `transition` step invariants this edge can violate.
145    pub violations: Vec<Violation>,
146    /// #2197: whether this edge's handler commits — the emitter wraps a
147    /// handler in the commit that runs `transition`s only when it writes some
148    /// store field (`bynk_model::body_writes_state`); a handler that doesn't
149    /// can violate none.
150    pub commits: bool,
151}
152
153/// #2197: an edge a `transition` would refuse at commit (`InvariantViolation`).
154#[derive(Debug, Clone, PartialEq)]
155pub struct Violation {
156    /// The `transition`'s name and declaration span.
157    pub transition: String,
158    pub span: Span,
159    pub certainty: Certainty,
160    /// The reachable start state from which it violates — one record per
161    /// start, so `certainty` and `targets` are that start's own.
162    pub from: Vec<String>,
163    /// The violating targets from that start: the edge's target, the start
164    /// itself for an unchanged path, or for a computed write the targets
165    /// that violate.
166    pub targets: Vec<String>,
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum Certainty {
171    /// Every way the edge can go violates (a known target always does).
172    Known,
173    /// A computed write may land on a violating target, or on one that isn't.
174    Possible,
175}
176
177/// #2197: a `transition` on the field outside the evaluated fragment.
178#[derive(Debug, Clone, PartialEq)]
179pub struct NotEvaluated {
180    pub transition: String,
181    pub span: Span,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum Target {
186    State(String),
187    /// A computed write (`status := next(x)`, `status.update(f)`).
188    Unknown,
189    /// No write to the field on this path.
190    Unchanged,
191}
192
193/// #2221: `bynk.transition.may_violate` — a warning for each move a handler
194/// can make that a `transition` refuses at commit (track §3.2–§3.5).
195///
196/// Only [`Certainty::Known`] violations fire, from start states the agent can
197/// be in after a commit (the overlay already filters on
198/// [`StateMachine::reachable_after_commit`]); a computed write that only *may*
199/// land badly, a truncated handler and a `transition` outside the evaluated
200/// fragment raise nothing. The warning sits on the write (or, for an unchanged
201/// path, its tail), names the path's guards, and carries the `transition` and
202/// one handler that makes the start state reachable as related information.
203/// The commit-time check is unchanged.
204pub fn may_violate_diagnostics(
205    agent: &AgentDecl,
206    types: &HashMap<String, Arc<TypeDecl>>,
207) -> Vec<CompileError> {
208    if agent.transitions.is_empty() {
209        return Vec::new();
210    }
211    let mut out = Vec::new();
212    for sm in agent_state_model(agent, types).machines {
213        let field = &sm.field;
214        for e in &sm.edges {
215            if sm.truncated.contains(&e.handler) {
216                continue;
217            }
218            for v in e
219                .violations
220                .iter()
221                .filter(|v| v.certainty == Certainty::Known)
222            {
223                for start in &v.from {
224                    let change = match &e.to {
225                        Target::State(t) => format!("move `{field}` from `{start}` to `{t}`"),
226                        Target::Unchanged => format!("leave `{field}` at `{start}`"),
227                        Target::Unknown => {
228                            format!("move `{field}` from `{start}` to a state it refuses")
229                        }
230                    };
231                    let when = if e.guards.is_empty() {
232                        String::new()
233                    } else {
234                        format!(" (when `{}`)", e.guards.join("` and `"))
235                    };
236                    let mut err = CompileError::new(
237                        "bynk.transition.may_violate",
238                        e.span,
239                        format!(
240                            "`{}()` can {change}{when}, which `{}` refuses at commit",
241                            e.handler, v.transition
242                        ),
243                    )
244                    .with_label(v.span, format!("`{}` is declared here", v.transition));
245                    if let Some((span, label)) = witness(&sm, start) {
246                        err = err.with_label(span, label);
247                    }
248                    out.push(err.with_note(
249                        "at run time this call faults with `InvariantViolation`; the \
250                         commit-time check is unchanged",
251                    ));
252                }
253            }
254        }
255    }
256    out
257}
258
259/// One handler path that leaves the agent in `state` after a commit — why the
260/// warning considers `state` reachable. `None` without a literal initialiser,
261/// where every state is assumed reachable.
262fn witness(sm: &StateMachine, state: &str) -> Option<(Span, String)> {
263    let field = &sm.field;
264    let initial = sm.initial.as_deref()?;
265    // Only a path that can start in a reachable state explains anything: an
266    // edge's `from` is what its pattern allows, not what is reachable.
267    let live = |e: &Edge| e.from.iter().any(|s| sm.reachable.contains(s));
268    let reaches = |e: &&Edge| {
269        live(e)
270            && match &e.to {
271                Target::State(t) => t == state,
272                Target::Unchanged => {
273                    state == initial && e.commits && e.from.iter().any(|s| s == state)
274                }
275                Target::Unknown => false,
276            }
277    };
278    if let Some(e) = sm.edges.iter().find(reaches) {
279        let label = match &e.to {
280            Target::Unchanged => {
281                format!(
282                    "`{}()` commits and leaves `{field}` at `{state}`",
283                    e.handler
284                )
285            }
286            _ => format!("`{}()` moves `{field}` to `{state}`", e.handler),
287        };
288        return Some((e.span, label));
289    }
290    sm.edges
291        .iter()
292        .find(|e| e.to == Target::Unknown && e.commits && live(e))
293        .map(|e| {
294            (
295                e.span,
296                format!("`{}()` can move `{field}` to any state", e.handler),
297            )
298        })
299}
300
301/// Derive every state machine of `agent`. `types` is the unit's combined type
302/// table (`ContextBoundaryInfo::types`); a state field whose type doesn't
303/// resolve to a sum in it is skipped, not guessed (#2195 DECISION A).
304pub fn agent_state_model(
305    agent: &AgentDecl,
306    types: &HashMap<String, Arc<TypeDecl>>,
307) -> AgentStateModel {
308    let store = store_kinds(agent);
309    let machines = agent
310        .store_fields
311        .iter()
312        .filter_map(|f| {
313            let states = state_variants(f, types)?;
314            Some(machine(agent, f, states, &store))
315        })
316        .collect();
317    AgentStateModel {
318        agent: agent.name.name.clone(),
319        machines,
320        invariants: declared_invariants(agent),
321    }
322}
323
324/// #3608: `agent`'s snapshot `invariant`s then its step `transition`s. An agent
325/// is one declaration in one file (`bynk.resolve.duplicate_agent`), so these
326/// are all of its declarations.
327fn declared_invariants(agent: &AgentDecl) -> Vec<AgentInvariant> {
328    let entry = |kind, name: &Ident, predicate: &Expr, doc: &Option<Doc>, span| AgentInvariant {
329        kind,
330        name: name.name.clone(),
331        predicate: bynk_syntax::print::expr_to_string(predicate),
332        doc: doc
333            .as_ref()
334            .map(|d| d.text.trim_end())
335            .filter(|t| !t.is_empty())
336            .map(str::to_string),
337        span,
338    };
339    let snapshots = agent.invariants.iter().map(|i| {
340        entry(
341            InvariantKind::Invariant,
342            &i.name,
343            &i.predicate,
344            &i.documentation,
345            i.span,
346        )
347    });
348    let steps = agent.transitions.iter().map(|t| {
349        entry(
350            InvariantKind::Transition,
351            &t.name,
352            &t.predicate,
353            &t.documentation,
354            t.span,
355        )
356    });
357    snapshots.chain(steps).collect()
358}
359
360/// The variant names of `field` when it is a `Cell` of a user sum type.
361fn state_variants(
362    field: &StoreField,
363    types: &HashMap<String, Arc<TypeDecl>>,
364) -> Option<Vec<String>> {
365    if field.kind.head.name != "Cell" {
366        return None;
367    }
368    let [TypeRef::Named(name)] = field.kind.args.as_slice() else {
369        return None;
370    };
371    let TypeBody::Sum(sum) = &types.get(&name.name)?.body else {
372        return None;
373    };
374    Some(sum.variants.iter().map(|v| v.name.name.clone()).collect())
375}
376
377fn machine(
378    agent: &AgentDecl,
379    field: &StoreField,
380    states: Vec<String>,
381    store: &HashMap<String, String>,
382) -> StateMachine {
383    let all: BTreeSet<usize> = (0..states.len()).collect();
384    let initial = field
385        .init
386        .as_ref()
387        .and_then(|e| variant_literal(e, &states));
388    let mut edges = Vec::new();
389    let mut truncated = Vec::new();
390    for handler in &agent.handlers {
391        let name = handler
392            .method_name
393            .as_ref()
394            .map_or_else(|| "call".to_string(), |m| m.name.clone());
395        let commits = handler_commits_in(handler, store);
396        let mut w = Walker {
397            field: &field.name.name,
398            states: &states,
399            store,
400            bound: handler.params.iter().map(|p| p.name.name.clone()).collect(),
401            truncated: false,
402        };
403        let start = Path {
404            from: all.clone(),
405            current: Cur::Pre,
406            write: None,
407            guards: BTreeSet::new(),
408            outcome: None,
409            outcome_span: None,
410        };
411        let paths = w.walk_block(&handler.body, vec![start], true);
412        if w.truncated {
413            truncated.push(name.clone());
414            edges.push(Edge {
415                handler: name,
416                from: states.clone(),
417                guards: Vec::new(),
418                to: Target::Unknown,
419                outcome: None,
420                span: handler.span,
421                violations: Vec::new(),
422                commits,
423            });
424            continue;
425        }
426        for p in paths {
427            let (to, span) = match p.write {
428                Some((Write::Known(i), span)) => (Target::State(states[i].clone()), span),
429                Some((Write::Unknown, span)) => (Target::Unknown, span),
430                None => (Target::Unchanged, p.outcome_span.unwrap_or(handler.span)),
431            };
432            edges.push(Edge {
433                handler: name.clone(),
434                from: p.from.iter().map(|&i| states[i].clone()).collect(),
435                guards: p.guards.into_iter().collect(),
436                to,
437                outcome: p.outcome,
438                span,
439                violations: Vec::new(),
440                commits,
441            });
442        }
443    }
444    let reachable = reachable(&states, initial, &edges);
445    let reachable_after_commit = reachable_after_commit(&states, initial, &reachable, &edges);
446    let not_evaluated = overlay(
447        agent,
448        &field.name.name,
449        &states,
450        &reachable_after_commit,
451        &mut edges,
452    );
453    StateMachine {
454        field: field.name.name.clone(),
455        field_span: field.name.span,
456        initial: initial.map(|i| states[i].clone()),
457        states,
458        edges,
459        reachable,
460        reachable_after_commit,
461        truncated,
462        not_evaluated,
463    }
464}
465
466/// #2197: flag each edge a `transition` would refuse at commit, and list the
467/// `transition`s on `field` the fragment can't evaluate (track §3.5).
468///
469/// - A known target `S → T` violates when the predicate is false for
470///   `old = S, new = T`.
471/// - An unchanged path is `S → S`, but only in a handler that commits — the
472///   emitter wraps a handler in the commit (where transitions are checked)
473///   only when it writes some store field (`bynk_model::body_writes_state`).
474/// - A computed write is checked against every target: all violating is
475///   [`Certainty::Known`], some is [`Certainty::Possible`].
476/// - Only start states the agent can be in after a commit count (#2219): a
477///   move only the genesis commit can make is never checked.
478fn overlay(
479    agent: &AgentDecl,
480    field: &str,
481    states: &[String],
482    after_commit: &[String],
483    edges: &mut [Edge],
484) -> Vec<NotEvaluated> {
485    let index = |name: &str| states.iter().position(|s| s == name);
486    let mut not_evaluated = Vec::new();
487    for t in &agent.transitions {
488        if !mentions_field(&t.predicate, field) {
489            continue;
490        }
491        let Some(pred) = compile(&t.predicate, field, states) else {
492            not_evaluated.push(NotEvaluated {
493                transition: t.name.name.clone(),
494                span: t.span,
495            });
496            continue;
497        };
498        for e in edges.iter_mut() {
499            // A handler that never commits runs no `transition` at all.
500            if !e.commits {
501                continue;
502            }
503            // One record per start state: certainty and targets differ by
504            // start (a computed write can be Known from one, Possible from
505            // another), and the view reads them per start.
506            for start in e.from.iter().filter(|s| after_commit.contains(s)) {
507                let Some(si) = index(start) else { continue };
508                let candidates: Vec<usize> = match &e.to {
509                    Target::State(t) => index(t).into_iter().collect(),
510                    Target::Unchanged => vec![si],
511                    Target::Unknown => (0..states.len()).collect(),
512                };
513                let bad: Vec<usize> = candidates
514                    .iter()
515                    .copied()
516                    .filter(|&ti| !pred.eval(si, ti))
517                    .collect();
518                if bad.is_empty() {
519                    continue;
520                }
521                e.violations.push(Violation {
522                    transition: t.name.name.clone(),
523                    span: t.span,
524                    certainty: if bad.len() == candidates.len() {
525                        Certainty::Known
526                    } else {
527                        Certainty::Possible
528                    },
529                    from: vec![start.clone()],
530                    targets: bad.into_iter().map(|i| states[i].clone()).collect(),
531                });
532            }
533        }
534    }
535    not_evaluated
536}
537
538/// Whether `handler` commits: whether its body writes any of `agent`'s store
539/// fields anywhere, the emitter's condition for wrapping it in the commit that
540/// checks `transition`s. This recomputes `bynk_model::body_writes_state`
541/// syntactically; `bynk-model`'s builder tests pin the two together (#2220).
542pub fn handler_commits(agent: &AgentDecl, handler: &Handler) -> bool {
543    handler_commits_in(handler, &store_kinds(agent))
544}
545
546fn handler_commits_in(handler: &Handler, store: &HashMap<String, String>) -> bool {
547    let mut bound: Vec<String> = handler.params.iter().map(|p| p.name.name.clone()).collect();
548    block_commits(&handler.body, store, &mut bound)
549}
550
551/// Whether a block writes any store field anywhere — see [`handler_commits`].
552/// `bound` is the names in scope that shadow a store field: the handler's
553/// parameters, and (#2220) every `let`, match-arm and lambda binding on the
554/// way down, so a local named like a field is never taken for it — the
555/// emitter decides over resolved callees, which can't be fooled that way.
556fn block_commits(b: &Block, store: &HashMap<String, String>, bound: &mut Vec<String>) -> bool {
557    let scope = bound.len();
558    let mut commits = false;
559    for s in &b.statements {
560        commits |= stmt_commits(s, store, bound);
561    }
562    commits |= expr_commits(&b.tail, store, bound);
563    bound.truncate(scope);
564    commits
565}
566
567fn stmt_commits(s: &Statement, store: &HashMap<String, String>, bound: &mut Vec<String>) -> bool {
568    match s {
569        Statement::Assign(_) => true,
570        Statement::Let(l) | Statement::EffectLet(l) => {
571            let c = expr_commits(&l.value, store, bound);
572            bound.push(l.name.name.clone());
573            c
574        }
575        Statement::Expect(a) => expr_commits(&a.value, store, bound),
576        Statement::Do(d) => expr_commits(&d.value, store, bound),
577        Statement::Advance(a) => expr_commits(&a.amount, store, bound),
578        Statement::Par(p) => p
579            .statements
580            .iter()
581            .fold(false, |c, s| c | stmt_commits(s, store, bound)),
582    }
583}
584
585fn expr_commits(e: &Expr, store: &HashMap<String, String>, bound: &mut Vec<String>) -> bool {
586    if store_write(store, bound, e).is_some() {
587        return true;
588    }
589    match &e.kind {
590        ExprKind::Block(b) => block_commits(b, store, bound),
591        ExprKind::If {
592            cond,
593            then_block,
594            else_block,
595        } => {
596            // Not short-circuited: each branch scopes its own bindings.
597            let c = expr_commits(cond, store, bound);
598            let t = block_commits(then_block, store, bound);
599            let f = block_commits(else_block, store, bound);
600            c || t || f
601        }
602        ExprKind::Match { discriminant, arms } => {
603            let mut commits = expr_commits(discriminant, store, bound);
604            for a in arms {
605                let scope = bound.len();
606                bound.extend(a.pattern.bound_names().into_iter().map(|n| n.name.clone()));
607                if let Some(g) = &a.guard {
608                    commits |= expr_commits(g, store, bound);
609                }
610                commits |= match &a.body {
611                    MatchBody::Expr(e) => expr_commits(e, store, bound),
612                    MatchBody::Block(b) => block_commits(b, store, bound),
613                };
614                bound.truncate(scope);
615            }
616            commits
617        }
618        ExprKind::Lambda(l) => {
619            let scope = bound.len();
620            bound.extend(l.params.iter().map(|p| p.name.name.clone()));
621            let commits = expr_commits(&l.body, store, bound);
622            bound.truncate(scope);
623            commits
624        }
625        _ => {
626            let mut commits = false;
627            for c in expr_children(e) {
628                commits |= expr_commits(c, store, bound);
629            }
630            commits
631        }
632    }
633}
634
635#[derive(Debug, Clone, Copy, PartialEq, Eq)]
636enum Side {
637    Old,
638    New,
639}
640
641/// A `transition` predicate in the evaluated fragment: `is`/`==`/`!=` tests
642/// of `old.f`/`new.f` against irrefutable patterns or nullary variants,
643/// composed with `!`, `&&`, `||` and `implies`.
644enum Pred {
645    Test(Side, BTreeSet<usize>),
646    Not(Box<Pred>),
647    And(Box<Pred>, Box<Pred>),
648    Or(Box<Pred>, Box<Pred>),
649    Implies(Box<Pred>, Box<Pred>),
650}
651
652impl Pred {
653    fn eval(&self, old: usize, new: usize) -> bool {
654        match self {
655            Pred::Test(Side::Old, s) => s.contains(&old),
656            Pred::Test(Side::New, s) => s.contains(&new),
657            Pred::Not(p) => !p.eval(old, new),
658            Pred::And(a, b) => a.eval(old, new) && b.eval(old, new),
659            Pred::Or(a, b) => a.eval(old, new) || b.eval(old, new),
660            Pred::Implies(a, b) => !a.eval(old, new) || b.eval(old, new),
661        }
662    }
663}
664
665/// `old.<field>` or `new.<field>`.
666fn side_of(expr: &Expr, field: &str) -> Option<Side> {
667    let ExprKind::FieldAccess { receiver, field: f } = &peel_paren(expr).kind else {
668        return None;
669    };
670    let ExprKind::Ident(r) = &receiver.kind else {
671        return None;
672    };
673    if f.name != field {
674        return None;
675    }
676    match r.name.as_str() {
677        "old" => Some(Side::Old),
678        "new" => Some(Side::New),
679        _ => None,
680    }
681}
682
683fn mentions_field(expr: &Expr, field: &str) -> bool {
684    side_of(expr, field).is_some()
685        || expr_children(expr)
686            .into_iter()
687            .any(|c| mentions_field(c, field))
688}
689
690fn compile(expr: &Expr, field: &str, states: &[String]) -> Option<Pred> {
691    let inner = peel_paren(expr);
692    match &inner.kind {
693        ExprKind::UnaryOp(UnaryOp::Not, e) => Some(Pred::Not(Box::new(compile(e, field, states)?))),
694        ExprKind::BinOp(op @ (BinOp::And | BinOp::Or | BinOp::Implies), l, r) => {
695            let (a, b) = (
696                Box::new(compile(l, field, states)?),
697                Box::new(compile(r, field, states)?),
698            );
699            Some(match op {
700                BinOp::And => Pred::And(a, b),
701                BinOp::Or => Pred::Or(a, b),
702                _ => Pred::Implies(a, b),
703            })
704        }
705        ExprKind::Is { value, pattern } => {
706            let side = side_of(value, field)?;
707            let m = pattern_sets(pattern, states);
708            // A refutable pattern can't be decided on constructors alone.
709            (m.may == m.must).then_some(Pred::Test(side, m.must))
710        }
711        ExprKind::BinOp(op @ (BinOp::Eq | BinOp::NotEq), l, r) => {
712            let (side, other) = match (side_of(l, field), side_of(r, field)) {
713                (Some(s), None) => (s, r),
714                (None, Some(s)) => (s, l),
715                _ => return None,
716            };
717            if has_payload(other) {
718                return None;
719            }
720            let test = Pred::Test(side, BTreeSet::from([variant_literal(other, states)?]));
721            Some(if *op == BinOp::Eq {
722                test
723            } else {
724                Pred::Not(Box::new(test))
725            })
726        }
727        _ => None,
728    }
729}
730
731/// States reachable from `initial` (every state when there is none), with an
732/// `Unknown` edge reaching every state.
733fn reachable(states: &[String], initial: Option<usize>, edges: &[Edge]) -> Vec<String> {
734    let index = |name: &str| states.iter().position(|s| s == name);
735    let mut seen: BTreeSet<usize> = match initial {
736        Some(i) => BTreeSet::from([i]),
737        None => (0..states.len()).collect(),
738    };
739    loop {
740        let before = seen.len();
741        for e in edges {
742            if !e
743                .from
744                .iter()
745                .filter_map(|s| index(s))
746                .any(|i| seen.contains(&i))
747            {
748                continue;
749            }
750            match &e.to {
751                Target::State(s) => seen.extend(index(s)),
752                Target::Unknown => seen.extend(0..states.len()),
753                Target::Unchanged => {}
754            }
755        }
756        if seen.len() == before {
757            break;
758        }
759    }
760    seen.into_iter().map(|i| states[i].clone()).collect()
761}
762
763/// #2219: the states the agent can be in after a commit (see
764/// [`StateMachine::reachable_after_commit`]). Without a literal initialiser
765/// every state counts, as for [`reachable`].
766fn reachable_after_commit(
767    states: &[String],
768    initial: Option<usize>,
769    reachable: &[String],
770    edges: &[Edge],
771) -> Vec<String> {
772    let Some(init) = initial else {
773        return reachable.to_vec();
774    };
775    let initial = &states[init];
776    // Back in the initial state after a commit: a committing path from a
777    // reachable start that ends there — an unchanged path from it, a move
778    // into it, or a computed write (which can land anywhere).
779    let returns = edges.iter().any(|e| {
780        e.commits
781            && e.from.iter().any(|s| {
782                reachable.contains(s)
783                    && match &e.to {
784                        Target::State(t) => t == initial,
785                        Target::Unchanged => s == initial,
786                        Target::Unknown => true,
787                    }
788            })
789    });
790    reachable
791        .iter()
792        .filter(|s| *s != initial || returns)
793        .cloned()
794        .collect()
795}
796
797/// A variant literal of the state type: `Placed`, `Square(1)`,
798/// `OrderStatus.Placed` or `OrderStatus.Square(1)`.
799/// Whether a variant literal carries a payload (`Square(1)`), so comparing
800/// against it pins the value, not just the constructor.
801fn has_payload(expr: &Expr) -> bool {
802    match &peel_paren(expr).kind {
803        ExprKind::Call { args, .. } | ExprKind::MethodCall { args, .. } => !args.is_empty(),
804        _ => false,
805    }
806}
807
808/// What a pattern says about the field's constructor (see
809/// [`Walker::pattern_states`]).
810#[derive(Default)]
811struct PatternStates {
812    may: BTreeSet<usize>,
813    must: BTreeSet<usize>,
814}
815
816fn variant_literal(expr: &Expr, states: &[String]) -> Option<usize> {
817    let name = match &peel_paren(expr).kind {
818        ExprKind::Ident(id) => &id.name,
819        ExprKind::Call { name, .. } => &name.name,
820        ExprKind::FieldAccess { field, .. } => &field.name,
821        ExprKind::MethodCall { method, .. } => &method.name,
822        _ => return None,
823    };
824    states.iter().position(|s| s == name)
825}
826
827#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
828enum Cur {
829    /// Not yet written on this path: the field holds the pre-state.
830    Pre,
831    Known(usize),
832    /// Written with a computed value.
833    Computed,
834}
835
836#[derive(Debug, Clone, Copy, PartialEq, Eq)]
837enum Write {
838    Known(usize),
839    Unknown,
840}
841
842#[derive(Debug, Clone)]
843struct Path {
844    from: BTreeSet<usize>,
845    current: Cur,
846    write: Option<(Write, Span)>,
847    guards: BTreeSet<String>,
848    outcome: Option<String>,
849    outcome_span: Option<Span>,
850}
851
852impl Path {
853    /// Paths with the same key produce the same edge, guards aside.
854    fn same_key(&self, other: &Path) -> bool {
855        self.from == other.from
856            && self.current == other.current
857            && self.write.map(|w| w.0) == other.write.map(|w| w.0)
858            && self.outcome == other.outcome
859    }
860}
861
862struct Walker<'a> {
863    field: &'a str,
864    states: &'a [String],
865    store: &'a HashMap<String, String>,
866    /// Names bound in scope; a binding named like the field shadows it.
867    bound: Vec<String>,
868    truncated: bool,
869}
870
871impl Walker<'_> {
872    fn walk_block(&mut self, block: &Block, mut paths: Vec<Path>, tail: bool) -> Vec<Path> {
873        let scope = self.bound.len();
874        for stmt in &block.statements {
875            if self.truncated {
876                return Vec::new();
877            }
878            paths = self.walk_stmt(stmt, paths);
879        }
880        let paths = self.walk_expr(&block.tail, paths, tail);
881        self.bound.truncate(scope);
882        paths
883    }
884
885    fn walk_stmt(&mut self, stmt: &Statement, paths: Vec<Path>) -> Vec<Path> {
886        match stmt {
887            Statement::Let(l) | Statement::EffectLet(l) => {
888                let paths = self.walk_expr(&l.value, paths, false);
889                self.bound.push(l.name.name.clone());
890                paths
891            }
892            Statement::Do(d) => self.walk_expr(&d.value, paths, false),
893            Statement::Expect(e) => self.walk_expr(&e.value, paths, false),
894            Statement::Advance(a) => self.walk_expr(&a.amount, paths, false),
895            Statement::Par(p) => p
896                .statements
897                .iter()
898                .fold(paths, |paths, s| self.walk_stmt(s, paths)),
899            Statement::Assign(a) => {
900                let mut paths = self.walk_expr(&a.value, paths, false);
901                // No shadowing check: `:=` only ever targets a `store Cell`
902                // (`bynk.cell.invalid_target`), never a local.
903                if a.target.name == self.field {
904                    let write = match variant_literal(&a.value, self.states) {
905                        Some(i) => Write::Known(i),
906                        None => Write::Unknown,
907                    };
908                    for p in &mut paths {
909                        Self::apply_write(p, write, a.span);
910                    }
911                }
912                paths
913            }
914        }
915    }
916
917    fn apply_write(p: &mut Path, write: Write, span: Span) {
918        p.current = match write {
919            Write::Known(i) => Cur::Known(i),
920            Write::Unknown => Cur::Computed,
921        };
922        p.write = Some((write, span));
923    }
924
925    fn walk_expr(&mut self, expr: &Expr, mut paths: Vec<Path>, tail: bool) -> Vec<Path> {
926        if self.truncated || paths.is_empty() {
927            return paths;
928        }
929        let inner = peel_paren(expr);
930        match &inner.kind {
931            ExprKind::If {
932                cond,
933                then_block,
934                else_block,
935            } => {
936                let then_paths = self.narrow(paths.clone(), cond, true);
937                let else_paths = self.narrow(paths, cond, false);
938                let mut out = self.walk_block(then_block, then_paths, tail);
939                out.extend(self.walk_block(else_block, else_paths, tail));
940                self.join(out)
941            }
942            ExprKind::Match { discriminant, arms } => {
943                self.walk_match(discriminant, arms, paths, tail)
944            }
945            ExprKind::Block(b) => self.walk_block(b, paths, tail),
946            _ => {
947                if let Some(w) = store_write(self.store, &self.bound, inner) {
948                    // `field.update(f)` on the state field: a computed write.
949                    if w.field.name == self.field {
950                        for p in &mut paths {
951                            Self::apply_write(p, Write::Unknown, inner.span);
952                        }
953                    }
954                    if tail {
955                        // A store write yields `()`, so it carries no outcome.
956                        for p in &mut paths {
957                            p.outcome = None;
958                            p.outcome_span = Some(inner.span);
959                        }
960                    }
961                } else if tail {
962                    let outcome = branch_outcome(inner);
963                    for p in &mut paths {
964                        p.outcome = outcome.clone();
965                        p.outcome_span = Some(inner.span);
966                    }
967                }
968                paths
969            }
970        }
971    }
972
973    fn walk_match(
974        &mut self,
975        scrutinee: &Expr,
976        arms: &[MatchArm],
977        paths: Vec<Path>,
978        tail: bool,
979    ) -> Vec<Path> {
980        let on_field = self.is_field(scrutinee);
981        // States taken by earlier unguarded arms — an arm only sees the rest.
982        let mut covered = BTreeSet::new();
983        let mut out = Vec::new();
984        for arm in arms {
985            let mut arm_paths = if on_field {
986                let m = self.pattern_states(&arm.pattern);
987                let states: BTreeSet<usize> = m.may.difference(&covered).copied().collect();
988                // Only a constructor the arm matches whatever its payload is
989                // taken from later arms: `Square(1) =>` leaves `Square(n) =>`
990                // its share.
991                if arm.guard.is_none() {
992                    covered.extend(m.must.iter().copied());
993                }
994                self.constrain(paths.clone(), &states)
995            } else {
996                let label = format!(
997                    "{} is {}",
998                    bynk_syntax::print::expr_to_string(scrutinee),
999                    pattern_summary(&arm.pattern)
1000                );
1001                Self::guarded(paths.clone(), label)
1002            };
1003            let scope = self.bound.len();
1004            self.bound.extend(
1005                arm.pattern
1006                    .bound_names()
1007                    .into_iter()
1008                    .map(|n| n.name.clone()),
1009            );
1010            if let Some(guard) = &arm.guard {
1011                arm_paths = self.narrow(arm_paths, guard, true);
1012            }
1013            let arm_out = match &arm.body {
1014                MatchBody::Expr(e) => self.walk_expr(e, arm_paths, tail),
1015                MatchBody::Block(b) => self.walk_block(b, arm_paths, tail),
1016            };
1017            self.bound.truncate(scope);
1018            out.extend(arm_out);
1019        }
1020        self.join(out)
1021    }
1022
1023    /// Keep the paths consistent with `cond` evaluating to `truth`.
1024    fn narrow(&mut self, paths: Vec<Path>, cond: &Expr, truth: bool) -> Vec<Path> {
1025        match self.facts(cond, truth) {
1026            Some(allowed) => self.constrain(paths, &allowed),
1027            None => {
1028                let text = bynk_syntax::print::expr_to_string(cond);
1029                let label = if truth { text } else { format!("!({text})") };
1030                Self::guarded(paths, label)
1031            }
1032        }
1033    }
1034
1035    /// Constrain each path's field to `allowed`: narrow the from-set before a
1036    /// write, decide statically after a known write, or record a guard after a
1037    /// computed one.
1038    fn constrain(&self, paths: Vec<Path>, allowed: &BTreeSet<usize>) -> Vec<Path> {
1039        paths
1040            .into_iter()
1041            .filter_map(|mut p| match p.current {
1042                Cur::Pre => {
1043                    p.from = p.from.intersection(allowed).copied().collect();
1044                    (!p.from.is_empty()).then_some(p)
1045                }
1046                Cur::Known(i) => allowed.contains(&i).then_some(p),
1047                Cur::Computed => {
1048                    let names: Vec<&str> =
1049                        allowed.iter().map(|&i| self.states[i].as_str()).collect();
1050                    p.guards
1051                        .insert(format!("{} is {}", self.field, names.join(" | ")));
1052                    Some(p)
1053                }
1054            })
1055            .collect()
1056    }
1057
1058    fn guarded(mut paths: Vec<Path>, label: String) -> Vec<Path> {
1059        for p in &mut paths {
1060            p.guards.insert(label.clone());
1061        }
1062        paths
1063    }
1064
1065    /// What `cond == truth` says about the field, when it says anything a
1066    /// state set can express: `is`, `==`/`!=` against a variant, `!`, and
1067    /// `&&`/`||` whose sides both speak about the field.
1068    fn facts(&self, cond: &Expr, truth: bool) -> Option<BTreeSet<usize>> {
1069        let all = || (0..self.states.len()).collect::<BTreeSet<usize>>();
1070        let complement = |s: BTreeSet<usize>| all().difference(&s).copied().collect();
1071        let inner = peel_paren(cond);
1072        match &inner.kind {
1073            // True: the field may be any constructor the pattern can match.
1074            // False: only a constructor it matches irrefutably is excluded —
1075            // `shape is Square(1)` false still allows `Square(2)`.
1076            ExprKind::Is { value, pattern } if self.is_field(value) => {
1077                let m = self.pattern_states(pattern);
1078                Some(if truth { m.may } else { complement(m.must) })
1079            }
1080            ExprKind::BinOp(op @ (BinOp::Eq | BinOp::NotEq), l, r) => {
1081                let other = if self.is_field(l) {
1082                    r
1083                } else if self.is_field(r) {
1084                    l
1085                } else {
1086                    return None;
1087                };
1088                let i = variant_literal(other, self.states)?;
1089                let s = BTreeSet::from([i]);
1090                // Equal to a nullary variant pins the constructor both ways;
1091                // unequal to `Square(1)` still allows `Square(2)`.
1092                let pinned = !has_payload(other);
1093                Some(if truth == (*op == BinOp::Eq) {
1094                    s
1095                } else if pinned {
1096                    complement(s)
1097                } else {
1098                    all()
1099                })
1100            }
1101            ExprKind::UnaryOp(UnaryOp::Not, e) => self.facts(e, !truth),
1102            ExprKind::BinOp(op @ (BinOp::And | BinOp::Or), l, r) => {
1103                let a = self.facts(l, truth)?;
1104                let b = self.facts(r, truth)?;
1105                // `a && b` true, or `a || b` false, needs both sides to hold.
1106                Some(if (*op == BinOp::And) == truth {
1107                    a.intersection(&b).copied().collect()
1108                } else {
1109                    a.union(&b).copied().collect()
1110                })
1111            }
1112            _ => None,
1113        }
1114    }
1115
1116    fn pattern_states(&self, pattern: &Pattern) -> PatternStates {
1117        pattern_sets(pattern, self.states)
1118    }
1119
1120    fn is_field(&self, expr: &Expr) -> bool {
1121        matches!(&peel_paren(expr).kind, ExprKind::Ident(id)
1122            if id.name == self.field && !self.bound.contains(&id.name))
1123    }
1124
1125    /// Merge paths that would produce the same edge, combining their guards,
1126    /// and enforce the budget.
1127    fn join(&mut self, paths: Vec<Path>) -> Vec<Path> {
1128        let mut out: Vec<Path> = Vec::new();
1129        for p in paths {
1130            match out.iter_mut().find(|q| q.same_key(&p)) {
1131                Some(q) => q.guards = combine_guards(&q.guards, &p.guards),
1132                None => out.push(p),
1133            }
1134        }
1135        if out.len() > PATH_BUDGET {
1136            self.truncated = true;
1137            return Vec::new();
1138        }
1139        out
1140    }
1141}
1142
1143/// The guards of two merged paths: either side holding is enough, so an
1144/// unconditional side makes the merge unconditional, and two different
1145/// conjunctions become one disjunction label.
1146pub fn combine_guards(a: &BTreeSet<String>, b: &BTreeSet<String>) -> BTreeSet<String> {
1147    if a == b {
1148        return a.clone();
1149    }
1150    if a.is_empty() || b.is_empty() {
1151        return BTreeSet::new();
1152    }
1153    // `c` on one side and `!(c)` on the other: together, no condition.
1154    if let ([x], [y]) = (
1155        a.iter().collect::<Vec<_>>().as_slice(),
1156        b.iter().collect::<Vec<_>>().as_slice(),
1157    ) && (**y == format!("!({x})") || **x == format!("!({y})"))
1158    {
1159        return BTreeSet::new();
1160    }
1161    let side = |s: &BTreeSet<String>| {
1162        let parts: Vec<&str> = s.iter().map(String::as_str).collect();
1163        if parts.len() == 1 {
1164            parts[0].to_string()
1165        } else {
1166            format!("({})", parts.join(" && "))
1167        }
1168    };
1169    BTreeSet::from([format!("{} || {}", side(a), side(b))])
1170}
1171
1172/// The constructors a pattern may match, and those it matches whatever
1173/// the payload: `Square(n)` must-matches `Square`, `Square(1)` only
1174/// may-match it, and a refined `_ where p` may match anything but must
1175/// match nothing.
1176fn pattern_sets(pattern: &Pattern, states: &[String]) -> PatternStates {
1177    let all = || (0..states.len()).collect::<BTreeSet<usize>>();
1178    match pattern {
1179        Pattern::Wildcard(_) | Pattern::Binding(_) => PatternStates {
1180            may: all(),
1181            must: all(),
1182        },
1183        Pattern::Variant {
1184            variant, bindings, ..
1185        } => {
1186            let may: BTreeSet<usize> = states
1187                .iter()
1188                .position(|s| *s == variant.name)
1189                .into_iter()
1190                .collect();
1191            let irrefutable = bindings
1192                .iter()
1193                .all(|b| matches!(b.pattern(), Pattern::Wildcard(_) | Pattern::Binding(_)));
1194            let must = if irrefutable {
1195                may.clone()
1196            } else {
1197                BTreeSet::new()
1198            };
1199            PatternStates { may, must }
1200        }
1201        Pattern::Refined { inner, .. } => PatternStates {
1202            may: pattern_sets(inner, states).may,
1203            must: BTreeSet::new(),
1204        },
1205        Pattern::Or(alts, _) => {
1206            let mut out = PatternStates::default();
1207            for a in alts {
1208                let m = pattern_sets(a, states);
1209                out.may.extend(m.may);
1210                out.must.extend(m.must);
1211            }
1212            out
1213        }
1214        // A record, a list or a range never matches a state sum.
1215        Pattern::Literal { .. }
1216        | Pattern::Range(_)
1217        | Pattern::Record { .. }
1218        | Pattern::List { .. } => PatternStates::default(),
1219    }
1220}
1221
1222#[cfg(test)]
1223mod tests {
1224    use super::*;
1225
1226    /// Parse a single-file context (parse only — the state model reads the
1227    /// AST) and derive the model of `agent`, with the type table built from
1228    /// the file's own `type` declarations. Sources are inline copies of the
1229    /// compiler's state-machine fixtures: `bynk-ide` tests stay self-contained.
1230    fn model(src: &str, agent: &str) -> AgentStateModel {
1231        let tokens = bynk_syntax::lexer::tokenize(src).expect("tokenize");
1232        let (unit, errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, src);
1233        assert!(errs.is_empty(), "parse errors: {errs:?}");
1234        let Some(SourceUnit::Context(ctx)) = unit else {
1235            panic!("expected a context")
1236        };
1237        let types = ctx
1238            .items
1239            .iter()
1240            .filter_map(|i| match i {
1241                CommonsItem::Type(t) => Some((t.name.name.clone(), Arc::new(t.clone()))),
1242                _ => None,
1243            })
1244            .collect();
1245        let a = ctx
1246            .items
1247            .iter()
1248            .find_map(|i| match i {
1249                CommonsItem::Agent(a) if a.name.name == agent => Some(a),
1250                _ => None,
1251            })
1252            .expect("agent");
1253        agent_state_model(a, &types)
1254    }
1255
1256    /// #2221: the `bynk.transition.may_violate` warnings for `agent`, as
1257    /// `(message, labels)`.
1258    fn warnings(src: &str, agent: &str) -> Vec<(String, Vec<String>)> {
1259        let tokens = bynk_syntax::lexer::tokenize(src).expect("tokenize");
1260        let (unit, errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, src);
1261        assert!(errs.is_empty(), "parse errors: {errs:?}");
1262        let Some(SourceUnit::Context(ctx)) = unit else {
1263            panic!("expected a context")
1264        };
1265        let types = ctx
1266            .items
1267            .iter()
1268            .filter_map(|i| match i {
1269                CommonsItem::Type(t) => Some((t.name.name.clone(), Arc::new(t.clone()))),
1270                _ => None,
1271            })
1272            .collect();
1273        let a = ctx
1274            .items
1275            .iter()
1276            .find_map(|i| match i {
1277                CommonsItem::Agent(a) if a.name.name == agent => Some(a),
1278                _ => None,
1279            })
1280            .expect("agent");
1281        may_violate_diagnostics(a, &types)
1282            .into_iter()
1283            .map(|e| {
1284                assert_eq!(e.category, "bynk.transition.may_violate");
1285                (e.message, e.labels.into_iter().map(|(_, l)| l).collect())
1286            })
1287            .collect()
1288    }
1289
1290    fn only(m: &AgentStateModel) -> &StateMachine {
1291        assert_eq!(m.machines.len(), 1, "one state field");
1292        &m.machines[0]
1293    }
1294
1295    /// `(handler, from, to, outcome)` per edge, for compact assertions.
1296    fn edges(sm: &StateMachine) -> Vec<(String, Vec<String>, Target, Option<String>)> {
1297        sm.edges
1298            .iter()
1299            .map(|e| {
1300                (
1301                    e.handler.clone(),
1302                    e.from.clone(),
1303                    e.to.clone(),
1304                    e.outcome.clone(),
1305                )
1306            })
1307            .collect()
1308    }
1309
1310    fn s(v: &[&str]) -> Vec<String> {
1311        v.iter().map(|x| x.to_string()).collect()
1312    }
1313
1314    fn to(state: &str) -> Target {
1315        Target::State(state.to_string())
1316    }
1317
1318    fn out(o: &str) -> Option<String> {
1319        Some(o.to_string())
1320    }
1321
1322    // 159_order_lifecycle
1323    const ORDER: &str = r#"context orders
1324
1325type OrderStatus = enum { Pending, Placed, Cancelled }
1326type OrderError = enum { AlreadyPlaced, AlreadyCancelled }
1327
1328agent Order {
1329  key id: String
1330
1331  store status: Cell[OrderStatus] = Pending
1332  store items: Cell[Int]
1333
1334  on call addItem(quantity: Int) -> Effect[Result[(), OrderError]] {
1335    let cur = items
1336    items := cur + quantity
1337    Ok(())
1338  }
1339
1340  on call place() -> Effect[Result[(), OrderError]] {
1341    match status {
1342      Pending => {
1343        status := Placed
1344        Ok(())
1345      }
1346      Placed    => Err(AlreadyPlaced)
1347      Cancelled => Err(AlreadyCancelled)
1348    }
1349  }
1350}
1351"#;
1352
1353    #[test]
1354    fn the_order_lifecycle_moves_pending_to_placed_and_refuses_the_rest() {
1355        let m = model(ORDER, "Order");
1356        let sm = only(&m);
1357        assert_eq!(sm.field, "status");
1358        assert_eq!(sm.states, s(&["Pending", "Placed", "Cancelled"]));
1359        assert_eq!(sm.initial.as_deref(), Some("Pending"));
1360        assert_eq!(
1361            edges(sm),
1362            [
1363                // `addItem` never touches `status`: unchanged from every state.
1364                (
1365                    "addItem".into(),
1366                    s(&["Pending", "Placed", "Cancelled"]),
1367                    Target::Unchanged,
1368                    out("Ok(())")
1369                ),
1370                ("place".into(), s(&["Pending"]), to("Placed"), out("Ok(())")),
1371                (
1372                    "place".into(),
1373                    s(&["Placed"]),
1374                    Target::Unchanged,
1375                    out("Err(AlreadyPlaced)")
1376                ),
1377                (
1378                    "place".into(),
1379                    s(&["Cancelled"]),
1380                    Target::Unchanged,
1381                    out("Err(AlreadyCancelled)")
1382                ),
1383            ]
1384        );
1385        // Nothing moves to `Cancelled`, so it is unreachable from `Pending`.
1386        assert_eq!(sm.reachable, s(&["Pending", "Placed"]));
1387        assert!(sm.truncated.is_empty());
1388        // The edge's span is the write, for click-to-code.
1389        let write_at = ORDER.find("status := Placed").unwrap();
1390        assert_eq!(sm.edges[1].span.start, write_at);
1391    }
1392
1393    // 245_transition_step_invariant
1394    const PAID: &str = r#"context commerce.order
1395
1396type AuthId = String where NonEmpty
1397type OrderStatus = enum { Pending, Placed, Paid }
1398
1399agent Order {
1400  key id: String
1401
1402  store status: Cell[OrderStatus] = Pending
1403  store paymentRef: Cell[Option[AuthId]]
1404
1405  invariant paid_has_payment_ref:
1406    status == Paid implies paymentRef.isSome()
1407
1408  transition paid_is_terminal:
1409    old.status is Paid implies new.status is Paid
1410
1411  on call place() -> Effect[()] {
1412    status := Placed
1413    Effect.pure(())
1414  }
1415
1416  on call pay(ref: AuthId) -> Effect[()] {
1417    status := Paid
1418    paymentRef := Some(ref)
1419    Effect.pure(())
1420  }
1421}
1422"#;
1423
1424    #[test]
1425    fn an_unguarded_write_is_an_edge_from_every_state_including_paid() {
1426        let m = model(PAID, "Order");
1427        let sm = only(&m);
1428        let all = s(&["Pending", "Placed", "Paid"]);
1429        assert_eq!(
1430            edges(sm),
1431            [
1432                (
1433                    "place".into(),
1434                    all.clone(),
1435                    to("Placed"),
1436                    out("Effect.pure(())")
1437                ),
1438                ("pay".into(), all, to("Paid"), out("Effect.pure(())")),
1439            ]
1440        );
1441        assert_eq!(sm.reachable, s(&["Pending", "Placed", "Paid"]));
1442    }
1443
1444    // 156_state_transition and 2018_history_transition_near_miss
1445    #[test]
1446    fn a_write_in_tail_or_single_statement_position_is_still_the_write() {
1447        let turnstile = r#"context turnstile
1448type Gate = enum { Locked, Unlocked }
1449agent Turnstile {
1450  key id: String
1451  store gate: Cell[Gate] = Locked
1452  on call unlock() -> Effect[Result[(), String]] {
1453    gate := Unlocked
1454    Ok(())
1455  }
1456}
1457"#;
1458        let m = model(turnstile, "Turnstile");
1459        assert_eq!(
1460            edges(only(&m)),
1461            [(
1462                "unlock".into(),
1463                s(&["Locked", "Unlocked"]),
1464                to("Unlocked"),
1465                out("Ok(())")
1466            )]
1467        );
1468        let door = r#"context demo.door
1469type Status = enum { Open, Closed }
1470agent Door {
1471  key id: String
1472  store status: Cell[Status] = Open
1473  transition closed_is_final: old.status is Closed implies new.status is Closed
1474  on call close() -> Effect[()] { status := Closed }
1475}
1476"#;
1477        let m = model(door, "Door");
1478        assert_eq!(
1479            edges(only(&m)),
1480            [("close".into(), s(&["Open", "Closed"]), to("Closed"), None)]
1481        );
1482    }
1483
1484    // 155_state_sum_machine
1485    #[test]
1486    fn a_read_only_handler_is_unchanged_and_a_comparison_is_not_a_write() {
1487        let src = r#"context signal
1488type Light = enum { Red, Green }
1489agent Signal {
1490  key id: String
1491  store colour: Cell[Light] = Red
1492  on call peek() -> Effect[Result[(), String]] {
1493    Ok(())
1494  }
1495  on call turnGreen() -> Effect[()] {
1496    colour := Green
1497  }
1498  on call isGreen() -> Effect[Bool] {
1499    colour == Green
1500  }
1501}
1502"#;
1503        let m = model(src, "Signal");
1504        let sm = only(&m);
1505        let both = s(&["Red", "Green"]);
1506        assert_eq!(
1507            edges(sm),
1508            [
1509                (
1510                    "peek".into(),
1511                    both.clone(),
1512                    Target::Unchanged,
1513                    out("Ok(())")
1514                ),
1515                ("turnGreen".into(), both.clone(), to("Green"), None),
1516                (
1517                    "isGreen".into(),
1518                    both,
1519                    Target::Unchanged,
1520                    out("colour == Green")
1521                ),
1522            ]
1523        );
1524        assert_eq!(sm.reachable, s(&["Red", "Green"]));
1525    }
1526
1527    // 1649_agent_state_round_trip: a sum with payloads, and computed writes.
1528    #[test]
1529    fn payloads_abstract_to_constructors_and_a_computed_write_is_unknown() {
1530        let src = r#"context demo
1531type Shape =
1532  | Circle(r: Int)
1533  | Square(side: Int)
1534agent Figure {
1535  key id: String
1536  store shape: Cell[Shape] = Square(1)
1537  on call set(s: Shape) -> Effect[()] { shape := s }
1538  on call circle(r: Int) -> Effect[()] { shape := Circle(r) }
1539  on call get() -> Effect[Shape] { shape }
1540}
1541"#;
1542        let m = model(src, "Figure");
1543        let sm = only(&m);
1544        assert_eq!(sm.states, s(&["Circle", "Square"]));
1545        assert_eq!(sm.initial.as_deref(), Some("Square"));
1546        let both = s(&["Circle", "Square"]);
1547        assert_eq!(
1548            edges(sm),
1549            [
1550                ("set".into(), both.clone(), Target::Unknown, None),
1551                ("circle".into(), both.clone(), to("Circle"), None),
1552                ("get".into(), both, Target::Unchanged, out("shape")),
1553            ]
1554        );
1555    }
1556
1557    #[test]
1558    fn option_result_records_and_scalars_are_not_state_fields() {
1559        let src = r#"context demo
1560type Light = enum { Red, Green }
1561type Rec = { n: Int }
1562agent Many {
1563  key id: String
1564  store n: Cell[Option[Int]]
1565  store r: Cell[Result[Int, String]] = Err("unset")
1566  store rec: Cell[Rec] = Rec { n: 0 }
1567  store count: Cell[Int]
1568  store lights: Map[String, Light]
1569  store light: Cell[Light] = Red
1570  on call get() -> Effect[Int] { count }
1571}
1572"#;
1573        let m = model(src, "Many");
1574        assert_eq!(only(&m).field, "light");
1575    }
1576
1577    #[test]
1578    fn a_field_whose_type_does_not_resolve_is_skipped() {
1579        // `Elsewhere` is not in this unit's type table.
1580        let src = r#"context demo
1581agent A {
1582  key id: String
1583  store s: Cell[Elsewhere]
1584  on call get() -> Effect[()] { () }
1585}
1586"#;
1587        assert!(model(src, "A").machines.is_empty());
1588    }
1589
1590    const LIFECYCLE: &str = r#"context demo
1591type Status = enum { Draft, Live, Closed }
1592type DocError = enum { NotDraft, Invalid }
1593agent Doc {
1594  key id: String
1595  store status: Cell[Status] = Draft
1596  store attempts: Cell[Int]
1597
1598  // A domain `Err` after a write still commits the write.
1599  on call publish(ok: Bool) -> Effect[Result[(), DocError]] {
1600    if status is Draft {
1601      status := Live
1602      if ok { Ok(()) } else { Err(Invalid) }
1603    } else {
1604      Err(NotDraft)
1605    }
1606  }
1607
1608  // A read after a write sees the write: the second `if` is decided.
1609  on call reopen() -> Effect[Bool] {
1610    status := Draft
1611    if status == Draft { true } else { false }
1612  }
1613
1614  // `update` on the state field is a computed write; a later test on the
1615  // field narrows nothing and becomes a guard.
1616  on call cycle() -> Effect[Int] {
1617    let _ <- status.update((s) => s)
1618    if status is Closed { 0 } else { 1 }
1619  }
1620
1621  // A guard that isn't about the field is kept as text.
1622  on call close(force: Bool) -> Effect[()] {
1623    if force && attempts > 3 { status := Closed } else { () }
1624  }
1625}
1626"#;
1627
1628    #[test]
1629    fn a_domain_err_after_a_write_is_still_an_edge() {
1630        let m = model(LIFECYCLE, "Doc");
1631        let publish: Vec<_> = edges(only(&m))
1632            .into_iter()
1633            .filter(|e| e.0 == "publish")
1634            .collect();
1635        assert_eq!(
1636            publish,
1637            [
1638                ("publish".into(), s(&["Draft"]), to("Live"), out("Ok(())")),
1639                (
1640                    "publish".into(),
1641                    s(&["Draft"]),
1642                    to("Live"),
1643                    out("Err(Invalid)")
1644                ),
1645                (
1646                    "publish".into(),
1647                    s(&["Live", "Closed"]),
1648                    Target::Unchanged,
1649                    out("Err(NotDraft)")
1650                ),
1651            ]
1652        );
1653        let guarded: Vec<_> = only(&m)
1654            .edges
1655            .iter()
1656            .filter(|e| e.handler == "publish")
1657            .map(|e| e.guards.clone())
1658            .collect();
1659        assert_eq!(guarded, [s(&["ok"]), s(&["!(ok)"]), vec![]]);
1660    }
1661
1662    #[test]
1663    fn a_read_after_a_write_is_decided_not_narrowed() {
1664        let m = model(LIFECYCLE, "Doc");
1665        let reopen: Vec<_> = only(&m)
1666            .edges
1667            .iter()
1668            .filter(|e| e.handler == "reopen")
1669            .collect();
1670        // One path: the `else` is infeasible after `status := Draft`, and the
1671        // from-set is not narrowed by the read.
1672        assert_eq!(reopen.len(), 1);
1673        assert_eq!(reopen[0].from, s(&["Draft", "Live", "Closed"]));
1674        assert_eq!(reopen[0].to, to("Draft"));
1675        assert_eq!(reopen[0].outcome.as_deref(), Some("true"));
1676        assert!(reopen[0].guards.is_empty());
1677    }
1678
1679    #[test]
1680    fn a_cell_update_on_the_state_field_is_unknown_and_later_tests_are_guards() {
1681        let m = model(LIFECYCLE, "Doc");
1682        let cycle: Vec<_> = only(&m)
1683            .edges
1684            .iter()
1685            .filter(|e| e.handler == "cycle")
1686            .collect();
1687        assert_eq!(cycle.len(), 2);
1688        assert!(cycle.iter().all(|e| e.to == Target::Unknown));
1689        assert!(
1690            cycle
1691                .iter()
1692                .all(|e| e.from == s(&["Draft", "Live", "Closed"]))
1693        );
1694        assert_eq!(cycle[0].guards, s(&["status is Closed"]));
1695        assert_eq!(cycle[1].guards, s(&["status is Draft | Live"]));
1696        // An `Unknown` edge reaches every state.
1697        assert_eq!(only(&m).reachable, s(&["Draft", "Live", "Closed"]));
1698    }
1699
1700    #[test]
1701    fn an_opaque_guard_is_kept_as_source_text() {
1702        let m = model(LIFECYCLE, "Doc");
1703        let close: Vec<_> = only(&m)
1704            .edges
1705            .iter()
1706            .filter(|e| e.handler == "close")
1707            .map(|e| (e.to.clone(), e.guards.clone()))
1708            .collect();
1709        assert_eq!(
1710            close,
1711            [
1712                (to("Closed"), s(&["force && attempts > 3"])),
1713                (Target::Unchanged, s(&["!(force && attempts > 3)"])),
1714            ]
1715        );
1716    }
1717
1718    #[test]
1719    fn paths_that_agree_merge_at_the_join_and_combine_guards() {
1720        let src = r#"context demo
1721type S = enum { A, B }
1722agent M {
1723  key id: String
1724  store s: Cell[S] = A
1725  on call go(x: Bool, y: Bool) -> Effect[()] {
1726    if x { s := B } else { if y { s := B } else { () } }
1727  }
1728}
1729"#;
1730        let m = model(src, "M");
1731        let sm = only(&m);
1732        // Both `s := B` paths merge into one edge whose guard is either side.
1733        assert_eq!(sm.edges.len(), 2);
1734        assert_eq!(sm.edges[0].to, to("B"));
1735        assert_eq!(sm.edges[0].guards, s(&["x || (!(x) && y)"]));
1736        assert_eq!(sm.edges[1].to, Target::Unchanged);
1737    }
1738
1739    #[test]
1740    fn a_condition_and_its_negation_merge_to_no_guard() {
1741        let src = r#"context demo
1742type S = enum { A, B }
1743agent M {
1744  key id: String
1745  store s: Cell[S] = A
1746  on call go(x: Bool) -> Effect[()] {
1747    if x { s := B } else { s := B }
1748  }
1749}
1750"#;
1751        let m = model(src, "M");
1752        let sm = only(&m);
1753        // Both branches reach `B`: one edge, with no condition rather than
1754        // `x || !(x)`.
1755        assert_eq!(sm.edges.len(), 1);
1756        assert_eq!(sm.edges[0].to, to("B"));
1757        assert!(sm.edges[0].guards.is_empty(), "{:?}", sm.edges[0].guards);
1758    }
1759
1760    #[test]
1761    fn a_shadowed_field_name_is_not_the_field() {
1762        let src = r#"context demo
1763type S = enum { A, B }
1764agent M {
1765  key id: String
1766  store s: Cell[S] = A
1767  on call go(s: S) -> Effect[Int] {
1768    match s {
1769      A => 1
1770      B => 2
1771    }
1772  }
1773}
1774"#;
1775        let m = model(src, "M");
1776        let sm = only(&m);
1777        // The parameter `s` is matched, not the field: both arms keep the
1778        // full from-set and record the match as a guard.
1779        assert!(sm.edges.iter().all(|e| e.from == s(&["A", "B"])));
1780        assert_eq!(sm.edges[0].guards, s(&["s is A"]));
1781    }
1782
1783    #[test]
1784    fn a_wildcard_arm_takes_only_the_states_earlier_arms_left() {
1785        let src = r#"context demo
1786type S = enum { A, B, C }
1787agent M {
1788  key id: String
1789  store s: Cell[S] = A
1790  on call go() -> Effect[Int] {
1791    match s {
1792      A => 1
1793      _ => 2
1794    }
1795  }
1796}
1797"#;
1798        let m = model(src, "M");
1799        let from: Vec<_> = only(&m).edges.iter().map(|e| e.from.clone()).collect();
1800        assert_eq!(from, [s(&["A"]), s(&["B", "C"])]);
1801    }
1802
1803    #[test]
1804    fn a_handler_past_the_budget_is_truncated_to_an_unknown_edge_from_every_state() {
1805        let arms: String = (0..=PATH_BUDGET)
1806            .map(|i| format!("      {i} => {i}\n"))
1807            .collect();
1808        let src = format!(
1809            "context demo\ntype S = enum {{ A, B }}\nagent M {{\n  key id: String\n  store s: Cell[S] = A\n  on call go(n: Int) -> Effect[Int] {{\n    match n {{\n{arms}      _ => 0\n    }}\n  }}\n}}\n"
1810        );
1811        let m = model(&src, "M");
1812        let sm = only(&m);
1813        assert_eq!(sm.truncated, s(&["go"]));
1814        assert_eq!(
1815            edges(sm),
1816            [("go".into(), s(&["A", "B"]), Target::Unknown, None)]
1817        );
1818        assert_eq!(sm.reachable, s(&["A", "B"]));
1819    }
1820
1821    #[test]
1822    fn several_state_fields_give_one_machine_each() {
1823        let src = r#"context demo
1824type S = enum { A, B }
1825type T = enum { X, Y }
1826agent M {
1827  key id: String
1828  store s: Cell[S] = A
1829  store t: Cell[T] = X
1830  on call go() -> Effect[()] {
1831    match s {
1832      A => { t := Y }
1833      B => { () }
1834    }
1835  }
1836}
1837"#;
1838        let m = model(src, "M");
1839        assert_eq!(m.machines.len(), 2);
1840        // On `t`'s machine, the match on `s` is a guard.
1841        let t = &m.machines[1];
1842        assert_eq!(t.field, "t");
1843        assert_eq!(t.edges[0].to, to("Y"));
1844        assert_eq!(t.edges[0].guards, s(&["s is A"]));
1845    }
1846
1847    const SHAPES: &str = r#"context demo
1848type Shape =
1849  | Circle(r: Int)
1850  | Square(side: Int)
1851agent Figure {
1852  key id: String
1853  store shape: Cell[Shape] = Square(1)
1854
1855  // A refutable arm leaves its constructor to the later arms.
1856  on call grow() -> Effect[Int] {
1857    match shape {
1858      Square(1) => 0
1859      Square(n) => {
1860        shape := Circle(n)
1861        1
1862      }
1863      Circle(_) => 2
1864    }
1865  }
1866
1867  // A refined pattern, or a payload literal, covers nothing for the arms
1868  // after it.
1869  on call guarded() -> Effect[Int] {
1870    match shape {
1871      _ where Positive => 0
1872      Circle(0) => 1
1873      Circle(_) => 2
1874      Square(_) => 3
1875    }
1876  }
1877
1878  // `is` / `!=` against a payload: the false side keeps the constructor.
1879  on call probe() -> Effect[Int] {
1880    if shape is Square(1) { 0 } else { 1 }
1881  }
1882  on call probeNe() -> Effect[Int] {
1883    if shape != Square(1) { 0 } else { 1 }
1884  }
1885
1886  // After a known write, a refutable test is not decided.
1887  on call reset() -> Effect[Int] {
1888    shape := Square(1)
1889    if shape is Square(2) { 0 } else { 1 }
1890  }
1891}
1892"#;
1893
1894    fn from_of(sm: &StateMachine, handler: &str) -> Vec<(Vec<String>, Option<String>)> {
1895        sm.edges
1896            .iter()
1897            .filter(|e| e.handler == handler)
1898            .map(|e| (e.from.clone(), e.outcome.clone()))
1899            .collect()
1900    }
1901
1902    #[test]
1903    fn a_refutable_arm_does_not_take_its_constructor_from_later_arms() {
1904        let m = model(SHAPES, "Figure");
1905        let sm = only(&m);
1906        let grow: Vec<_> = sm.edges.iter().filter(|e| e.handler == "grow").collect();
1907        assert_eq!(grow.len(), 3);
1908        // `Square(n)` still sees `Square`, so `Square → Circle` survives.
1909        assert_eq!(grow[1].from, s(&["Square"]));
1910        assert_eq!(grow[1].to, to("Circle"));
1911        assert_eq!(grow[2].from, s(&["Circle"]));
1912        assert_eq!(sm.reachable, s(&["Circle", "Square"]));
1913    }
1914
1915    #[test]
1916    fn a_refined_wildcard_arm_leaves_every_state_to_the_later_arms() {
1917        let m = model(SHAPES, "Figure");
1918        assert_eq!(
1919            from_of(only(&m), "guarded"),
1920            [
1921                (s(&["Circle", "Square"]), out("0")),
1922                (s(&["Circle"]), out("1")),
1923                (s(&["Circle"]), out("2")),
1924                (s(&["Square"]), out("3")),
1925            ]
1926        );
1927    }
1928
1929    #[test]
1930    fn the_false_side_of_a_refutable_test_keeps_the_constructor() {
1931        let m = model(SHAPES, "Figure");
1932        let both = s(&["Circle", "Square"]);
1933        assert_eq!(
1934            from_of(only(&m), "probe"),
1935            [(s(&["Square"]), out("0")), (both.clone(), out("1"))]
1936        );
1937        // `!= Square(1)` true allows anything; false is only `Square`.
1938        assert_eq!(
1939            from_of(only(&m), "probeNe"),
1940            [(both, out("0")), (s(&["Square"]), out("1"))]
1941        );
1942    }
1943
1944    #[test]
1945    fn a_refutable_test_after_a_known_write_keeps_both_branches() {
1946        let m = model(SHAPES, "Figure");
1947        let reset: Vec<_> = from_of(only(&m), "reset")
1948            .into_iter()
1949            .map(|e| e.1)
1950            .collect();
1951        assert_eq!(reset, [out("0"), out("1")]);
1952    }
1953
1954    // -- #2197: the `transition` overlay.
1955
1956    fn violations(
1957        sm: &StateMachine,
1958        handler: &str,
1959    ) -> Vec<(String, Certainty, Vec<String>, Vec<String>)> {
1960        sm.edges
1961            .iter()
1962            .filter(|e| e.handler == handler)
1963            .flat_map(|e| e.violations.iter())
1964            .map(|v| {
1965                (
1966                    v.transition.clone(),
1967                    v.certainty,
1968                    v.from.clone(),
1969                    v.targets.clone(),
1970                )
1971            })
1972            .collect()
1973    }
1974
1975    #[test]
1976    fn an_unguarded_write_from_paid_violates_paid_is_terminal() {
1977        let m = model(PAID, "Order");
1978        let sm = only(&m);
1979        assert_eq!(
1980            violations(sm, "place"),
1981            [(
1982                "paid_is_terminal".into(),
1983                Certainty::Known,
1984                s(&["Paid"]),
1985                s(&["Placed"])
1986            )]
1987        );
1988        // `pay` writes `Paid`, which the predicate allows from anywhere.
1989        assert!(violations(sm, "pay").is_empty());
1990        // The snapshot `invariant` is not a step invariant: nothing listed.
1991        assert!(sm.not_evaluated.is_empty());
1992        let v = &sm.edges[0].violations[0];
1993        assert_eq!(
1994            v.span.start,
1995            PAID.find("transition paid_is_terminal").unwrap()
1996        );
1997    }
1998
1999    const OVERLAY: &str = r#"context demo
2000type S = enum { A, B, C }
2001agent M {
2002  key id: String
2003  store s: Cell[S] = A
2004  store hits: Cell[Int]
2005
2006  transition must_advance: old.s is A implies new.s is B
2007
2008  // Writes another field, so it commits: the refused path is A -> A.
2009  on call refuse() -> Effect[Bool] {
2010    hits := hits + 1
2011    match s {
2012      A => false
2013      B => true
2014      C => true
2015    }
2016  }
2017
2018  // Writes nothing, so it never commits: transitions are not checked.
2019  on call peek() -> Effect[Bool] {
2020    match s {
2021      A => false
2022      B => true
2023      C => true
2024    }
2025  }
2026
2027  // A computed write from A may land on B (fine) or A/C (violating).
2028  on call spin() -> Effect[()] {
2029    let _ <- s.update((x) => x)
2030    ()
2031  }
2032}
2033"#;
2034
2035    #[test]
2036    fn an_unchanged_path_violates_only_in_a_handler_that_commits() {
2037        let m = model(OVERLAY, "M");
2038        let sm = only(&m);
2039        assert_eq!(
2040            violations(sm, "refuse"),
2041            [(
2042                "must_advance".into(),
2043                Certainty::Known,
2044                s(&["A"]),
2045                s(&["A"])
2046            )]
2047        );
2048        assert!(violations(sm, "peek").is_empty(), "peek never commits");
2049    }
2050
2051    /// #2219: `ship()` moves `A -> C`, which `must_advance` refuses, but
2052    /// nothing leaves the agent in `A` after a commit, so the move can only be
2053    /// the genesis commit — which the runtime never checks.
2054    fn genesis(extra: &str) -> String {
2055        format!(
2056            r#"context demo
2057type S = enum {{ A, B, C }}
2058agent M {{
2059  key id: String
2060  store s: Cell[S] = A
2061  store hits: Cell[Int]
2062
2063  transition must_advance: old.s is A implies new.s is B
2064
2065  on call ship() -> Effect[()] {{
2066    if s is A {{ s := C }} else {{ () }}
2067  }}
2068{extra}
2069}}
2070"#
2071        )
2072    }
2073
2074    #[test]
2075    fn a_move_only_the_genesis_commit_can_make_is_not_flagged() {
2076        let m = model(&genesis(""), "M");
2077        let sm = only(&m);
2078        assert_eq!(
2079            sm.reachable,
2080            s(&["A", "C"]),
2081            "A is still a state the agent is in"
2082        );
2083        assert_eq!(sm.reachable_after_commit, s(&["C"]));
2084        assert!(
2085            violations(sm, "ship").is_empty(),
2086            "{:?}",
2087            violations(sm, "ship")
2088        );
2089    }
2090
2091    #[test]
2092    fn a_committing_unchanged_path_from_the_initial_state_brings_it_back() {
2093        // `touch()` commits (it writes `hits`) and leaves `s` at `A`: the
2094        // genesis call is skipped, but a second call from `A` is checked.
2095        let m = model(
2096            &genesis("  on call touch() -> Effect[()] {\n    hits := hits + 1\n  }"),
2097            "M",
2098        );
2099        let sm = only(&m);
2100        assert_eq!(sm.reachable_after_commit, s(&["A", "C"]));
2101        assert_eq!(
2102            violations(sm, "ship"),
2103            [(
2104                "must_advance".into(),
2105                Certainty::Known,
2106                s(&["A"]),
2107                s(&["C"])
2108            )]
2109        );
2110    }
2111
2112    #[test]
2113    fn a_move_back_into_the_initial_state_brings_it_back() {
2114        let m = model(
2115            &genesis("  on call reset() -> Effect[()] {\n    s := A\n  }"),
2116            "M",
2117        );
2118        let sm = only(&m);
2119        assert_eq!(sm.reachable_after_commit, s(&["A", "C"]));
2120        assert_eq!(violations(sm, "ship").len(), 1);
2121    }
2122
2123    #[test]
2124    fn a_computed_write_can_land_back_in_the_initial_state() {
2125        let m = model(
2126            &genesis(
2127                "  on call spin() -> Effect[()] {\n    let _ <- s.update((x) => x)\n    ()\n  }",
2128            ),
2129            "M",
2130        );
2131        assert_eq!(only(&m).reachable_after_commit, s(&["A", "B", "C"]));
2132    }
2133
2134    #[test]
2135    fn a_non_committing_handler_never_brings_the_initial_state_back() {
2136        // `peek()` writes nothing, so it never commits: being in `A` after it
2137        // is still being in `A` before any commit.
2138        let m = model(
2139            &genesis(
2140                "  on call peek() -> Effect[Bool] {\n    match s {\n      A => false\n      B => true\n      C => true\n    }\n  }",
2141            ),
2142            "M",
2143        );
2144        let sm = only(&m);
2145        assert_eq!(sm.reachable_after_commit, s(&["C"]));
2146        assert!(violations(sm, "ship").is_empty());
2147    }
2148
2149    #[test]
2150    fn without_a_literal_initialiser_every_reachable_state_counts() {
2151        let src = genesis("").replace("store s: Cell[S] = A", "store s: Cell[S]");
2152        let m = model(&src, "M");
2153        let sm = only(&m);
2154        assert_eq!(sm.reachable_after_commit, sm.reachable);
2155        assert_eq!(violations(sm, "ship").len(), 1);
2156    }
2157
2158    #[test]
2159    fn a_computed_write_is_possible_when_some_targets_violate() {
2160        let m = model(OVERLAY, "M");
2161        assert_eq!(
2162            violations(only(&m), "spin"),
2163            [(
2164                "must_advance".into(),
2165                Certainty::Possible,
2166                s(&["A"]),
2167                s(&["A", "C"])
2168            )]
2169        );
2170    }
2171
2172    #[test]
2173    fn a_computed_write_is_known_when_every_target_violates() {
2174        let src = r#"context demo
2175type S = enum { A, B }
2176agent M {
2177  key id: String
2178  store s: Cell[S] = A
2179  transition frozen: old.s is A implies !(new.s is A || new.s == B)
2180  on call spin() -> Effect[()] {
2181    let _ <- s.update((x) => x)
2182    ()
2183  }
2184}
2185"#;
2186        let m = model(src, "M");
2187        assert_eq!(
2188            violations(only(&m), "spin"),
2189            [("frozen".into(), Certainty::Known, s(&["A"]), s(&["A", "B"]))]
2190        );
2191    }
2192
2193    #[test]
2194    fn an_edge_from_an_unreachable_state_is_not_flagged() {
2195        let src = r#"context demo
2196type S = enum { Pending, Placed, Cancelled }
2197agent M {
2198  key id: String
2199  store s: Cell[S] = Pending
2200  transition cancelled_is_final: old.s is Cancelled implies new.s is Cancelled
2201  on call place() -> Effect[()] { s := Placed }
2202}
2203"#;
2204        let m = model(src, "M");
2205        let sm = only(&m);
2206        assert!(!sm.reachable.contains(&"Cancelled".to_string()));
2207        assert!(violations(sm, "place").is_empty());
2208    }
2209
2210    #[test]
2211    fn predicates_outside_the_fragment_are_listed_and_others_ignored() {
2212        // 1374's hoisting predicate, a refutable pattern, and a numeric
2213        // transition that never mentions the state field.
2214        let src = r#"context demo
2215type Shape = | Circle(r: Int) | Square(side: Int)
2216agent M {
2217  key id: String
2218  store shape: Cell[Shape] = Circle(1)
2219  store count: Cell[Int]
2220  transition hoisting: if old.shape == old.shape { true } else { false }
2221  transition refutable: old.shape is Circle(1) implies new.shape is Circle(1)
2222  transition counting: new.count >= old.count
2223  on call go() -> Effect[()] { shape := Square(1) }
2224}
2225"#;
2226        let m = model(src, "M");
2227        let sm = only(&m);
2228        let names: Vec<&str> = sm
2229            .not_evaluated
2230            .iter()
2231            .map(|n| n.transition.as_str())
2232            .collect();
2233        assert_eq!(names, ["hoisting", "refutable"]);
2234        assert!(sm.edges.iter().all(|e| e.violations.is_empty()));
2235    }
2236
2237    #[test]
2238    fn a_truncated_handler_is_checked_as_a_computed_write_only_if_it_commits() {
2239        let arms: String = (0..=PATH_BUDGET)
2240            .map(|i| format!("      {i} => {i}\n"))
2241            .collect();
2242        let src = format!(
2243            "context demo\ntype S = enum {{ A, B }}\nagent M {{\n  key id: String\n  store s: Cell[S] = A\n  store hits: Cell[Int]\n  transition a_stays: old.s is A implies new.s is A\n  on call go(n: Int) -> Effect[Int] {{\n    hits := n\n    match n {{\n{arms}      _ => 0\n    }}\n  }}\n  on call peek(n: Int) -> Effect[Int] {{\n    match n {{\n{arms}      _ => 0\n    }}\n  }}\n}}\n"
2244        );
2245        let m = model(&src, "M");
2246        assert_eq!(only(&m).truncated, s(&["go", "peek"]));
2247        // `go` writes `hits`, so it commits: checked as a computed write.
2248        assert_eq!(
2249            violations(only(&m), "go"),
2250            [("a_stays".into(), Certainty::Possible, s(&["A"]), s(&["B"]))]
2251        );
2252        // `peek` writes nothing, so it never commits: no transition runs.
2253        assert!(violations(only(&m), "peek").is_empty());
2254    }
2255
2256    #[test]
2257    fn certainty_and_targets_are_per_start_state() {
2258        // From C every target violates (Known); from A only A and C do
2259        // (Possible) — B is fine from A.
2260        let src = r#"context demo
2261type S = enum { A, B, C }
2262agent M {
2263  key id: String
2264  store s: Cell[S] = A
2265  transition t: !(old.s is C) && (old.s is A implies new.s is B)
2266  on call reset() -> Effect[()] { s := C }
2267  on call spin() -> Effect[()] {
2268    let _ <- s.update((x) => x)
2269    ()
2270  }
2271}
2272"#;
2273        let m = model(src, "M");
2274        assert_eq!(
2275            violations(only(&m), "spin"),
2276            [
2277                ("t".into(), Certainty::Possible, s(&["A"]), s(&["A", "C"])),
2278                ("t".into(), Certainty::Known, s(&["C"]), s(&["A", "B", "C"])),
2279            ]
2280        );
2281    }
2282
2283    #[test]
2284    fn a_parameter_shadowing_a_store_field_does_not_make_a_handler_commit() {
2285        let src = r#"context demo
2286type S = enum { A, B }
2287agent M {
2288  key id: String
2289  store s: Cell[S] = A
2290  store log: Log[Int]
2291  transition a_moves: old.s is A implies new.s is B
2292  on call peek(log: List[Int]) -> Effect[Bool] {
2293    let _ <- log.append(1)
2294    true
2295  }
2296}
2297"#;
2298        let m = model(src, "M");
2299        // `log` is the parameter, not the store field: nothing commits, so
2300        // the unchanged A -> A path is not flagged.
2301        assert!(violations(only(&m), "peek").is_empty());
2302    }
2303
2304    #[test]
2305    fn a_local_shadowing_a_store_field_does_not_make_a_handler_commit() {
2306        // #2220: a `let`, a match binding and a lambda parameter shadow the
2307        // field just as a handler parameter does (found by the model builder's
2308        // agreement test against `body_writes_state`).
2309        let src = r#"context demo
2310type S = enum { A, B }
2311agent M {
2312  key id: String
2313  store s: Cell[S] = A
2314  store log: Log[Int]
2315  transition a_moves: old.s is A implies new.s is B
2316  on call byLet(xs: List[Int]) -> Effect[Bool] {
2317    let log = xs
2318    let _ <- log.append(1)
2319    true
2320  }
2321  on call byArm(o: Option[List[Int]]) -> Effect[()] {
2322    match o {
2323      Some(log) => log.append(1)
2324      None => Effect.pure(())
2325    }
2326  }
2327  on call byLambda(xss: List[List[Int]]) -> Effect[Bool] {
2328    let _ = xss.map((log) => log.append(1))
2329    true
2330  }
2331  on call byBlockLambda(xss: List[List[Int]]) -> Effect[Bool] {
2332    let _ = xss.map((x) => {
2333      let log = x
2334      log.append(1)
2335    })
2336    true
2337  }
2338}
2339"#;
2340        let m = model(src, "M");
2341        for h in ["byLet", "byArm", "byLambda", "byBlockLambda"] {
2342            assert!(violations(only(&m), h).is_empty(), "{h}");
2343        }
2344    }
2345
2346    #[test]
2347    fn a_known_violation_warns_at_the_write_with_the_transition_and_a_witness() {
2348        // Fixture 245: `place()` from `Paid`, reachable through `pay()`.
2349        let w = warnings(PAID, "Order");
2350        assert_eq!(
2351            w,
2352            [(
2353                "`place()` can move `status` from `Paid` to `Placed`, which `paid_is_terminal` refuses at commit"
2354                    .to_string(),
2355                vec![
2356                    "`paid_is_terminal` is declared here".to_string(),
2357                    "`pay()` moves `status` to `Paid`".to_string(),
2358                ],
2359            )]
2360        );
2361    }
2362
2363    #[test]
2364    fn a_refused_unchanged_path_in_a_committing_handler_warns() {
2365        let w = warnings(OVERLAY, "M");
2366        assert!(
2367            w.iter().any(|(m, l)| m
2368                == "`refuse()` can leave `s` at `A`, which `must_advance` refuses at commit"
2369                && l[1] == "`refuse()` commits and leaves `s` at `A`"),
2370            "{w:?}"
2371        );
2372        // `spin()`'s computed write only *may* land badly: no warning.
2373        assert!(!w.iter().any(|(m, _)| m.starts_with("`spin()`")), "{w:?}");
2374        // `peek()` never commits.
2375        assert!(!w.iter().any(|(m, _)| m.starts_with("`peek()`")), "{w:?}");
2376    }
2377
2378    #[test]
2379    fn the_witness_is_a_path_that_can_start_in_a_reachable_state() {
2380        // `C` is unreachable, so `x()`'s `C -> B` can't explain why `B` is
2381        // reachable even though it comes first; `y()` does.
2382        let src = r#"context demo
2383type S = enum { A, B, C }
2384agent M {
2385  key id: String
2386  store s: Cell[S] = A
2387  transition b_is_final: old.s is B implies new.s is B
2388  on call x() -> Effect[()] {
2389    match s {
2390      C => { s := B }
2391      _ => { () }
2392    }
2393  }
2394  on call y() -> Effect[()] { s := B }
2395  on call undo() -> Effect[()] { s := A }
2396}
2397"#;
2398        let w = warnings(src, "M");
2399        let undo = w
2400            .iter()
2401            .find(|(m, _)| m.starts_with("`undo()`"))
2402            .unwrap_or_else(|| panic!("{w:?}"));
2403        assert_eq!(undo.1[1], "`y()` moves `s` to `B`");
2404    }
2405
2406    #[test]
2407    fn a_warning_names_the_paths_guards() {
2408        let src = r#"context demo
2409type S = enum { A, B }
2410agent M {
2411  key id: String
2412  store s: Cell[S] = A
2413  transition b_is_final: old.s is B implies new.s is B
2414  on call finish() -> Effect[()] { s := B }
2415  on call undo(force: Bool) -> Effect[()] {
2416    if force { s := A } else { () }
2417  }
2418}
2419"#;
2420        assert_eq!(
2421            warnings(src, "M")[0].0,
2422            "`undo()` can move `s` from `B` to `A` (when `force`), which `b_is_final` refuses at commit"
2423        );
2424    }
2425
2426    #[test]
2427    fn a_move_only_the_genesis_commit_can_make_does_not_warn() {
2428        assert!(warnings(&genesis(""), "M").is_empty());
2429    }
2430
2431    #[test]
2432    fn a_not_evaluated_transition_does_not_warn() {
2433        let src = r#"context demo
2434type S = enum { A, B }
2435agent M {
2436  key id: String
2437  store s: Cell[S] = A
2438  store n: Cell[Int]
2439  transition counted: old.s is A implies new.n > old.n
2440  on call go() -> Effect[()] { s := B }
2441}
2442"#;
2443        assert!(only(&model(src, "M")).not_evaluated.len() == 1);
2444        assert!(warnings(src, "M").is_empty());
2445    }
2446
2447    #[test]
2448    fn a_truncated_handler_does_not_warn() {
2449        // Past the path budget, `go()` becomes one `?` edge from every state.
2450        // Every target from `A` violates `never_from_a`, so the overlay marks
2451        // it Known, but a truncated handler's edges aren't trustworthy enough
2452        // to warn on.
2453        let arms: String = (0..=PATH_BUDGET)
2454            .map(|i| format!("      {i} => {i}\n"))
2455            .collect();
2456        let src = format!(
2457            "context demo\ntype S = enum {{ A, B }}\nagent M {{\n  key id: String\n  store s: Cell[S] = A\n  store hits: Cell[Int]\n  transition never_from_a: !(old.s is A)\n  on call go(n: Int) -> Effect[Int] {{\n    hits := hits + 1\n    match n {{\n{arms}      _ => 0\n    }}\n  }}\n}}\n"
2458        );
2459        let m = model(&src, "M");
2460        assert_eq!(only(&m).truncated, s(&["go"]));
2461        assert!(
2462            !violations(only(&m), "go").is_empty(),
2463            "the overlay still flags it"
2464        );
2465        assert!(warnings(&src, "M").is_empty());
2466    }
2467
2468    #[test]
2469    fn an_agent_without_transitions_has_no_warnings() {
2470        let src = r#"context demo
2471type S = enum { A, B }
2472agent M {
2473  key id: String
2474  store s: Cell[S] = A
2475  on call go() -> Effect[()] { s := B }
2476}
2477"#;
2478        assert!(warnings(src, "M").is_empty());
2479    }
2480
2481    const INVARIANTS_SRC: &str = r#"context commerce
2482
2483type OrderStatus = enum { Pending, Placed, Paid }
2484
2485agent Order {
2486  key id: String
2487
2488  store status: Cell[OrderStatus] = Pending
2489  store paymentRef: Cell[Option[String]] = None
2490
2491  ---
2492  A paid order carries its payment reference.
2493  ---
2494  invariant paid_has_ref:
2495    status is Paid
2496      implies   paymentRef.isSome()
2497
2498  transition paid_is_terminal: old.status is Paid implies new.status is Paid
2499
2500  on call place() -> Effect[()] {
2501    status := Placed
2502  }
2503}
2504
2505agent Plain {
2506  key id: String
2507
2508  store total: Cell[Int]
2509
2510  on call bump() -> Effect[Int] {
2511    total := total + 1
2512    total
2513  }
2514}
2515"#;
2516
2517    /// #3608: both kinds are listed, snapshot invariants first, with the
2518    /// predicate printed by the expression printer (layout-independent), the
2519    /// documentation, and the declaration's span.
2520    #[test]
2521    fn declared_invariants_and_transitions_are_listed() {
2522        let m = model(INVARIANTS_SRC, "Order");
2523        let got: Vec<(InvariantKind, &str, &str)> = m
2524            .invariants
2525            .iter()
2526            .map(|i| (i.kind, i.name.as_str(), i.predicate.as_str()))
2527            .collect();
2528        assert_eq!(
2529            got,
2530            [
2531                (
2532                    InvariantKind::Invariant,
2533                    "paid_has_ref",
2534                    "status is Paid implies paymentRef.isSome()"
2535                ),
2536                (
2537                    InvariantKind::Transition,
2538                    "paid_is_terminal",
2539                    "old.status is Paid implies new.status is Paid"
2540                ),
2541            ]
2542        );
2543        assert_eq!(
2544            m.invariants[0].doc.as_deref(),
2545            Some("A paid order carries its payment reference.")
2546        );
2547        assert_eq!(m.invariants[1].doc, None);
2548        let span = m.invariants[1].span;
2549        assert!(INVARIANTS_SRC[span.start..span.end].contains("transition paid_is_terminal"));
2550    }
2551
2552    /// #3608: an agent that declares neither has an empty list.
2553    #[test]
2554    fn an_agent_with_neither_kind_lists_nothing() {
2555        assert!(model(INVARIANTS_SRC, "Plain").invariants.is_empty());
2556    }
2557
2558    /// #3608: comments inside a predicate do not change its printed text, and
2559    /// the span starts at the keyword, after the documentation block.
2560    #[test]
2561    fn comments_do_not_change_the_predicate_and_the_span_excludes_the_doc() {
2562        let src = INVARIANTS_SRC.replace(
2563            "status is Paid\n      implies   paymentRef.isSome()",
2564            "status is Paid // trailing\n      implies // inline\n      paymentRef.isSome()",
2565        );
2566        assert_ne!(src, INVARIANTS_SRC, "the fixture was rewritten");
2567        let m = model(&src, "Order");
2568        assert_eq!(
2569            m.invariants[0].predicate,
2570            "status is Paid implies paymentRef.isSome()"
2571        );
2572        let span = m.invariants[0].span;
2573        assert!(src[span.start..span.end].starts_with("invariant paid_has_ref"));
2574        assert!(src[span.start..span.end].ends_with("paymentRef.isSome()"));
2575    }
2576
2577    /// #3608: a documentation block holding only whitespace is no
2578    /// documentation, so `doc` is `None` (omitted on the wire), not `Some("")`.
2579    #[test]
2580    fn a_whitespace_only_doc_block_is_no_doc() {
2581        let src = INVARIANTS_SRC.replace(
2582            "  ---\n  A paid order carries its payment reference.\n  ---\n",
2583            "  ---\n   \n  ---\n",
2584        );
2585        assert_ne!(src, INVARIANTS_SRC, "the fixture was rewritten");
2586        let m = model(&src, "Order");
2587        assert_eq!(m.invariants[0].name, "paid_has_ref");
2588        assert_eq!(m.invariants[0].doc, None);
2589    }
2590}