Skip to main content

bynk_ide/
sequence.rs

1//! #846: the sequence-diagram query.
2//!
3//! Classifies a handler body's calls into runtime-participant lifelines —
4//! consumed capabilities, calls into consumed contexts, and agents (including
5//! same-context agents) — for the "Show Sequence Diagram" VS Code feature.
6//! Everything else (commons fns, context-local fns, methods, constructors)
7//! folds into the entry participant's own activation: no message is emitted
8//! for the call, and — because this repo's resolver does not inline call
9//! bodies either — a lifeline call written inside a commons `fn`'s own body is
10//! invisible to this walk. That is a stated Tier-1 limitation, not a bug: see
11//! `design/pending/sequence-diagram-846.md`.
12//!
13//! A pure, read-only IDE query: it never touches the checker's hot path
14//! (`bynk_check::checker::check_handler_body`) and is built on the exhaustive
15//! `expr_children`/`statement_exprs` walkers only insofar as this module's own
16//! statement dispatch mirrors their coverage of [`Statement`] — a new
17//! `Statement` variant is a compile error here, in `Builder::walk_block`'s
18//! `match`, not a silent gap.
19//!
20//! #2194: in an agent's own handler, a write to the agent's state — a `:=`
21//! or a mutating store operation on one of its `store` fields — is not a
22//! lifeline either, but it is not folded away: it is a
23//! [`MessageKind::StateWrite`] from the entry to itself, rendered as a note.
24//!
25//! Cross-context/agent calls are boundary-stop (Decision C): one `Call` +
26//! one `Return` message: the callee's own body is never walked, even where
27//! reachable (an agent's handlers are visible via [`ContextSequenceInfo::agents`]).
28//! Model-diagrams slice 3 names the callee instead ([`Message::callee`]), so a
29//! client can open the callee's own diagram (a UML `ref`).
30//!
31//! Model-diagrams slice 3 (ADR 0858): the model is complete. Nesting is
32//! walked to [`MAX_BLOCK_DEPTH`], a safety cap far beyond real code, and each
33//! block carries its [`AltBlock::depth`]; how much to show is the client's
34//! call. A `?` at the top of a statement's value is an early return, modelled
35//! as an [`AltKind::Break`] block, and the model names its [`Trigger`].
36
37use std::collections::HashMap;
38
39use bynk_check::analysis::ContextSequenceInfo;
40use bynk_check::ast_text::{branch_outcome, pattern_summary, peel_paren};
41use bynk_syntax::ast::*;
42use bynk_syntax::span::Span;
43
44/// Which declaration owns the handler being diagrammed.
45#[derive(Debug, Clone, Copy)]
46pub enum HandlerOwner<'a> {
47    Service(&'a str),
48    Agent(&'a str),
49}
50
51/// A safety cap on `if`/`match` nesting, not a presentation choice (ADR 0858,
52/// model-diagrams slice 3): the model is complete to this depth and the client
53/// decides how much to show. It bounds the work and the payload for a
54/// pathological handler; real code never comes near it. Beyond it the walk
55/// emits a single [`AltKind::Collapsed`] marker instead of recursing further.
56/// (It was 2, a presentation cut, until slice 3.)
57pub const MAX_BLOCK_DEPTH: u32 = 16;
58
59#[derive(Debug, Clone, Default, PartialEq)]
60pub struct SequenceModel {
61    pub participants: Vec<Participant>,
62    pub messages: Vec<Message>,
63    pub blocks: Vec<AltBlock>,
64    /// Model-diagrams slice 3: what starts the handler. With a principal the
65    /// actor's inbound message already says so; without one (an `on call`,
66    /// `on cron`, `on event` …) a client draws a found message labelled by it.
67    pub trigger: Trigger,
68}
69
70/// What starts a handler (model-diagrams slice 3).
71#[derive(Debug, Clone, PartialEq)]
72pub struct Trigger {
73    pub kind: TriggerKind,
74    /// The handler's request descriptor: `GET /check/:client`, `hit`,
75    /// `cron "0 * * * *"`, `event` …
76    pub label: String,
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
80pub enum TriggerKind {
81    /// An HTTP request (`from http`).
82    Request,
83    /// An `on call` handler, called by another handler or context.
84    #[default]
85    Call,
86    /// An `on cron` schedule.
87    Schedule,
88    /// An `on event` subscription.
89    Event,
90    /// An `on message`: off a queue or a WebSocket (the service's protocol
91    /// says which; the model does not).
92    Message,
93    /// A WebSocket `on open` or `on close`.
94    Connection,
95    /// An `on rejected` handler.
96    Rejected,
97}
98
99impl Default for Trigger {
100    fn default() -> Self {
101        Trigger {
102            kind: TriggerKind::Call,
103            label: String::new(),
104        }
105    }
106}
107
108#[derive(Debug, Clone, PartialEq)]
109pub struct Participant {
110    pub id: u32,
111    pub kind: ParticipantKind,
112    pub name: String,
113    /// `None` for `Entry` — it has no single declaration site to jump to
114    /// (it *is* the handler).
115    pub span: Option<Span>,
116    /// Model-diagrams slice 3: an agent's key expression as written at the
117    /// call (`client` in `Limiter(client).hit(…)`), for a lifeline drawn
118    /// `Limiter[client]`. `None` for other kinds; [`MIXED_KEYS`] when calls in
119    /// one handler key the same agent differently.
120    pub key: Option<String>,
121}
122
123/// An agent participant's key when the handler's calls key it differently.
124pub const MIXED_KEYS: &str = "…";
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum ParticipantKind {
128    Entry,
129    Capability,
130    Context,
131    Agent,
132    /// The handler's **principal** — the `by <Actor>` role (v0.45) that
133    /// originates the request. Rendered leftmost, as the sender of the initial
134    /// inbound message into the entry, and the recipient of the handler's
135    /// replies. Present only for a handler that declares (or inherits) a `by`
136    /// clause — HTTP/WebSocket service handlers; agents have no principal.
137    Actor,
138}
139
140#[derive(Debug, Clone, PartialEq)]
141pub struct Message {
142    pub from: u32,
143    pub to: u32,
144    pub kind: MessageKind,
145    pub label: String,
146    pub span: Span,
147    pub block: Option<u32>,
148    /// Model-diagrams slice 3: the handler a boundary call reaches, for a
149    /// `Call` or `Send` to an agent or a consumed context — what a client
150    /// needs to open the callee's own diagram. `None` for every other message.
151    pub callee: Option<Callee>,
152}
153
154/// The handler a boundary-stop call reaches, named rather than walked
155/// (Decision C). The LSP layer resolves it to a location.
156#[derive(Debug, Clone, PartialEq, Eq, Hash)]
157pub struct Callee {
158    /// The consumed context's qualified name; `None` for an agent of the
159    /// handler's own context.
160    pub unit: Option<String>,
161    /// The agent or service declaring the handler.
162    pub owner: String,
163    /// The handler's method name (`hit` in `on call hit`); `None` for a
164    /// service's unnamed `on call`, which is what `platform.Pinger(n)` reaches.
165    pub method: Option<String>,
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum MessageKind {
170    Call,
171    Return,
172    /// `e.detach()` fire-and-forget — no paired `Return`.
173    Send,
174    /// #2194: an agent handler's write to its own state — a `:=` or a
175    /// mutating store operation (`items.put(…)`, `count.update(…)`). Not a
176    /// message across a boundary (the store is the agent's own storage, not an
177    /// ADR 0258 lifeline): `from == to ==` the entry, and a renderer draws it
178    /// as a note over the entry lifeline, in source order within its branch.
179    StateWrite,
180}
181
182#[derive(Debug, Clone, PartialEq)]
183pub struct AltBlock {
184    pub id: u32,
185    pub kind: AltKind,
186    /// Empty for `Collapsed`.
187    pub branches: Vec<Branch>,
188    pub span: Span,
189    pub parent: Option<u32>,
190    /// Which of `parent`'s branches this block is nested under — `None` iff
191    /// `parent` is `None`. Needed to render nesting correctly: a parent
192    /// branch can be entirely empty of messages (the rate-limiter's `if`/
193    /// `else` gating only a return, for one), so a renderer walking
194    /// `Message.block` alone would have no way to place a nested block whose
195    /// own branches are also message-free.
196    pub parent_branch: Option<u32>,
197    /// Model-diagrams slice 3: the block's nesting depth, 0 at the top level,
198    /// so a client can fold by depth (ADR 0858).
199    pub depth: u32,
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum AltKind {
204    If,
205    Match,
206    Collapsed,
207    /// Model-diagrams slice 3: a `?` — UML `break`. Its one branch is the
208    /// early return when the operand is `None` or `Err`, labelled by the
209    /// operand (`stored?`); the walk carries on after it, as the code does.
210    Break,
211}
212
213#[derive(Debug, Clone, PartialEq)]
214pub struct Branch {
215    pub label: String,
216    pub message_ids: Vec<usize>,
217    /// The value the handler yields on this branch — its rendered tail
218    /// expression (`Ok(view)`, `TooManyRequests(...)`). This is the "reply to
219    /// its own caller" ADR 0260 names as always present, but which the
220    /// original model never actually emitted: a return-gating `if`/`match`
221    /// whose branches call no lifeline produced two empty branches, and an
222    /// empty `alt` renders as a mangled zero-width box (issue: rate-limiter's
223    /// `GET /check/:client`). Carrying the outcome here gives the block real
224    /// content to render as a note over the entry lifeline.
225    ///
226    /// `None` when the tail carries no distinguishable signal: a unit `()`
227    /// tail (an else-less `if`'s synthesised branch), or control flow
228    /// (`if`/`match`/block) that is itself already rendered as nested
229    /// structure — a note duplicating it would be noise.
230    pub reply: Option<String>,
231    /// #3584: the source extent of the arm this branch came from, so a client
232    /// can link a branch to its source or project coverage onto it. For an
233    /// `if`, the `then` branch runs from the `if` keyword to the end of its
234    /// body, and the `else` branch is its block (the AST records no `else`
235    /// keyword span). For a `match`, the arm from its pattern to its end. An
236    /// else-less `if` emits only the `then` branch (an `opt`), so there is no
237    /// synthesised branch to span.
238    ///
239    /// #3599: in an `else if` chain the `else` branch's span starts at the
240    /// inner `if` keyword and covers the rest of the chain, because the parser
241    /// desugars `else if` into a block that reuses the inner `if`'s span. The
242    /// inner `if` is its own nested `AltBlock` with its own branch spans, so
243    /// the outer `else` range contains those.
244    pub span: Span,
245}
246
247/// Whether an expression sits directly under an effect operator
248/// (`<-`/`do`) — only then can it be a lifeline call, since a bare
249/// (pure) `let` cannot bind an `Effect[_]` value in this language.
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251enum Arrow {
252    /// `let x <- expr` / `do expr` — awaited; a Call+Return pair.
253    Awaited,
254    /// `expr.detach()` — fire-and-forget; a Send only.
255    FireAndForget,
256}
257
258const ENTRY_ID: u32 = 0;
259
260/// The block/branch a walk is currently nested inside — `None` at the
261/// handler-body top level. Threaded through every walk method so a nested
262/// block can record `parent_branch` and a message can record its `block`.
263#[derive(Debug, Clone, Copy)]
264struct BlockCtx {
265    id: u32,
266    branch: u32,
267}
268
269/// `default_given` is the owning service's service-level `given` default
270/// (v0.155, `ServiceDecl.default_given`) — a handler that declares no `given`
271/// of its own inherits it. This classifier walks a freshly-parsed AST that
272/// has *not* been through `bynk-emit`'s `inject_service_defaults`
273/// normalization pass (which is what mutates `handler.given` in the compile
274/// pipeline), so the fallback has to be applied here or a handler relying on
275/// the service default would drop every capability lifeline. Pass `&[]` when
276/// there is no default (always the case for `HandlerOwner::Agent` — agents
277/// have no service-level `given`).
278/// `default_by` is the owning service's service-level `by` default (v0.155,
279/// `ServiceDecl.default_by`) — a handler that declares no `by` of its own
280/// inherits it, exactly as it does the `given` default. Pass `None` for an
281/// agent (agents have no principal).
282pub fn sequence_model(
283    handler: &Handler,
284    owner: HandlerOwner<'_>,
285    default_given: &[CapRef],
286    default_by: Option<&ByClause>,
287    info: Option<&ContextSequenceInfo>,
288) -> SequenceModel {
289    let given = if handler.given.is_empty() {
290        default_given
291    } else {
292        &handler.given
293    };
294    let by = handler.by_clause.as_ref().or(default_by);
295    let mut b = Builder::new(entry_label(handler, owner, by.is_some()), given, info);
296    if let HandlerOwner::Agent(name) = owner
297        && let Some(agent) = info.and_then(|i| i.agents.get(name))
298    {
299        b.store = bynk_check::store_write::store_kinds(agent);
300        // A parameter named like a store field shadows it for the whole body.
301        b.bound = handler.params.iter().map(|p| p.name.name.clone()).collect();
302    }
303    if let Some(by) = by {
304        // The principal originates the request: a leftmost actor lifeline that
305        // sends the initial inbound message (the route/method) into the entry.
306        // The entry label is bare (`api`) in this case — the request descriptor
307        // rides on the message rather than doubling into the entry box.
308        b.add_actor(actor_name(by), by.span);
309        b.emit_request(discriminator(handler), handler.span);
310    }
311    // The whole body is in the handler's return position: its tail (and each
312    // return-gating branch's tail) is what the handler replies to the actor.
313    b.walk_block(&handler.body, None, 0, true);
314    let mut model = b.finish();
315    model.trigger = trigger(handler);
316    model
317}
318
319/// What starts `handler` (model-diagrams slice 3).
320fn trigger(handler: &Handler) -> Trigger {
321    use bynk_model::IrHandlerKind;
322    let kind = match bynk_model::lower_handler_kind_ir(&handler.kind) {
323        IrHandlerKind::Call => TriggerKind::Call,
324        IrHandlerKind::Http { .. } => TriggerKind::Request,
325        IrHandlerKind::Cron { .. } => TriggerKind::Schedule,
326        IrHandlerKind::Event => TriggerKind::Event,
327        IrHandlerKind::Message => TriggerKind::Message,
328        IrHandlerKind::Open | IrHandlerKind::Close => TriggerKind::Connection,
329        IrHandlerKind::Rejected => TriggerKind::Rejected,
330    };
331    Trigger {
332        kind,
333        label: discriminator(handler),
334    }
335}
336
337/// The handler's request descriptor — its method + path (`GET /check/:client`),
338/// method name, or lifecycle kind. Labels the initial actor→entry message, and
339/// (when there is no actor) the entry box's own discriminator suffix. Read from
340/// the system model's [`bynk_model::IrHandlerKind`] (M-1, crate-hygiene B1, #2939).
341fn discriminator(handler: &Handler) -> String {
342    use bynk_model::IrHandlerKind;
343    match bynk_model::lower_handler_kind_ir(&handler.kind) {
344        IrHandlerKind::Call => match handler.method_name.as_ref() {
345            Some(m) => m.name.clone(),
346            None => "call".to_string(),
347        },
348        IrHandlerKind::Http { method, path } => format!("{} {}", method.as_str(), path),
349        IrHandlerKind::Cron { expr } => format!("cron \"{expr}\""),
350        IrHandlerKind::Message => "message".to_string(),
351        IrHandlerKind::Open => "open".to_string(),
352        IrHandlerKind::Close => "close".to_string(),
353        IrHandlerKind::Event => "event".to_string(),
354        IrHandlerKind::Rejected => "rejected".to_string(),
355    }
356}
357
358/// The actor participant's name — the referenced actor contract(s). More than
359/// one (`by who: A | B`, an ordered sum of peer actors) joins with `|`.
360fn actor_name(by: &ByClause) -> String {
361    by.actors
362        .iter()
363        .map(|a| a.name.as_str())
364        .collect::<Vec<_>>()
365        .join(" | ")
366}
367
368/// The entry lifeline's label. With an actor present the request descriptor
369/// moves onto the initial message, so the entry is just its owner name
370/// (`api`); without one it keeps the self-describing combined form
371/// (`api GET /check/:client`, `Limiter.hit`).
372fn entry_label(handler: &Handler, owner: HandlerOwner<'_>, has_actor: bool) -> String {
373    match owner {
374        HandlerOwner::Service(name) if has_actor => name.to_string(),
375        HandlerOwner::Agent(name) if has_actor => name.to_string(),
376        HandlerOwner::Service(name) => format!("{name} {}", discriminator(handler)),
377        HandlerOwner::Agent(name) => format!("{name}.{}", discriminator(handler)),
378    }
379}
380
381struct Builder<'a> {
382    given: &'a [CapRef],
383    info: Option<&'a ContextSequenceInfo>,
384    participants: Vec<Participant>,
385    messages: Vec<Message>,
386    blocks: Vec<AltBlock>,
387    /// The principal's participant id, once [`Builder::add_actor`] has run.
388    /// Its presence is also the switch for reply routing: with an actor, a
389    /// return-position outcome is emitted as a `Return` message *to the actor*;
390    /// without one it stays a note on the branch (`Branch::reply`).
391    actor: Option<u32>,
392    /// #2194: the owning agent's store fields (name → kind head, `"Map"`,
393    /// `"Cell"`, …). Empty for a service, which emits no state writes.
394    store: HashMap<String, String>,
395    /// #2194: names bound in scope (handler parameters, `let`s, match-arm
396    /// bindings) — a store field shadowed by one is not a store operation.
397    bound: Vec<String>,
398}
399
400impl<'a> Builder<'a> {
401    fn new(
402        entry_label: String,
403        given: &'a [CapRef],
404        info: Option<&'a ContextSequenceInfo>,
405    ) -> Self {
406        Builder {
407            given,
408            info,
409            participants: vec![Participant {
410                id: ENTRY_ID,
411                kind: ParticipantKind::Entry,
412                name: entry_label,
413                span: None,
414                key: None,
415            }],
416            messages: Vec::new(),
417            blocks: Vec::new(),
418            actor: None,
419            store: HashMap::new(),
420            bound: Vec::new(),
421        }
422    }
423
424    /// Add the principal as the leftmost participant. Inserted at index 0 so it
425    /// renders left of the entry, while the entry keeps [`ENTRY_ID`] (`0`) —
426    /// participant ids are stable labels, independent of array position, so
427    /// every `from: ENTRY_ID` reference stays correct.
428    fn add_actor(&mut self, name: String, span: Span) {
429        let id = self.participants.len() as u32;
430        self.participants.insert(
431            0,
432            Participant {
433                id,
434                kind: ParticipantKind::Actor,
435                name,
436                span: Some(span),
437                key: None,
438            },
439        );
440        self.actor = Some(id);
441    }
442
443    /// The initial inbound request: a lone `Call` from the actor to the entry
444    /// (no paired `Return` — the handler's replies are the branch outcomes).
445    /// Spanned at the handler declaration so it sorts ahead of every body
446    /// message and click-navigates to the handler.
447    fn emit_request(&mut self, label: String, handler_span: Span) {
448        let Some(actor) = self.actor else { return };
449        self.messages.push(Message {
450            from: actor,
451            to: ENTRY_ID,
452            kind: MessageKind::Call,
453            label,
454            span: handler_span,
455            block: None,
456            callee: None,
457        });
458    }
459
460    /// A return-position outcome replied to the principal — a `Return` message
461    /// from the entry to the actor. A no-op when there is no actor (the outcome
462    /// stays a branch note instead).
463    fn emit_reply(&mut self, outcome: String, span: Span, current_block: Option<BlockCtx>) {
464        let Some(actor) = self.actor else { return };
465        self.messages.push(Message {
466            from: ENTRY_ID,
467            to: actor,
468            kind: MessageKind::Return,
469            label: outcome,
470            span,
471            block: current_block.map(|c| c.id),
472            callee: None,
473        });
474    }
475
476    fn finish(self) -> SequenceModel {
477        SequenceModel {
478            participants: self.participants,
479            messages: self.messages,
480            blocks: self.blocks,
481            trigger: Trigger::default(),
482        }
483    }
484
485    fn participant_id(&mut self, kind: ParticipantKind, name: &str, span: Span) -> u32 {
486        if let Some(p) = self
487            .participants
488            .iter()
489            .find(|p| p.kind == kind && p.name == name)
490        {
491            return p.id;
492        }
493        let id = self.participants.len() as u32;
494        self.participants.push(Participant {
495            id,
496            kind,
497            name: name.to_string(),
498            span: Some(span),
499            key: None,
500        });
501        id
502    }
503
504    /// Record the key an agent participant was called with: the first one
505    /// seen, or [`MIXED_KEYS`] once two calls disagree.
506    fn note_key(&mut self, id: u32, key: String) {
507        if let Some(p) = self.participants.iter_mut().find(|p| p.id == id) {
508            p.key = match p.key.take() {
509                None => Some(key),
510                Some(k) if k == key => Some(k),
511                Some(_) => Some(MIXED_KEYS.to_string()),
512            };
513        }
514    }
515
516    /// Walk a block's statements, then its tail — the traversal spine every
517    /// call site (top-level body, `if`/`match` branch) shares. `ret` is whether
518    /// this block sits in the handler's **return position**: only then is its
519    /// tail a value the handler replies to the caller. Statements are never in
520    /// return position (their values are bound or discarded); only the tail
521    /// inherits the block's `ret`.
522    fn walk_block(
523        &mut self,
524        block: &Block,
525        current_block: Option<BlockCtx>,
526        depth: u32,
527        ret: bool,
528    ) {
529        // A `let` binds for the rest of its own block only.
530        let scope = self.bound.len();
531        for stmt in &block.statements {
532            self.walk_stmt(stmt, current_block, depth);
533        }
534        self.walk_value(&block.tail, current_block, depth, None, ret);
535        self.bound.truncate(scope);
536    }
537
538    /// One statement of a block. A `par` block (#2640) walks its bindings in
539    /// source order, the order their effects are issued in.
540    fn walk_stmt(&mut self, stmt: &Statement, current_block: Option<BlockCtx>, depth: u32) {
541        match stmt {
542            Statement::EffectLet(l) => {
543                self.walk_value(&l.value, current_block, depth, Some(Arrow::Awaited), false);
544                self.bound.push(l.name.name.clone());
545            }
546            Statement::Do(d) => {
547                self.walk_value(&d.value, current_block, depth, Some(Arrow::Awaited), false)
548            }
549            Statement::Let(l) => {
550                self.walk_value(&l.value, current_block, depth, None, false);
551                self.bound.push(l.name.name.clone());
552            }
553            Statement::Expect(e) => self.walk_value(&e.value, current_block, depth, None, false),
554            Statement::Assign(a) => {
555                self.walk_value(&a.value, current_block, depth, None, false);
556                self.emit_assign(a, current_block);
557            }
558            Statement::Advance(a) => self.walk_value(&a.amount, current_block, depth, None, false),
559            Statement::Par(p) => {
560                for inner in &p.statements {
561                    self.walk_stmt(inner, current_block, depth);
562                }
563            }
564        }
565    }
566
567    /// Classify one expression reached directly under a statement (or a
568    /// block's tail): a lifeline call (only possible when `arrow.is_some()`,
569    /// since a pure `let`/tail cannot bind an `Effect[_]`), or `if`/`match`
570    /// control flow to recurse into. Anything else — plain computation,
571    /// constructors, nested calls buried in argument expressions — folds into
572    /// the current activation with no further descent (Tier-1 scope: only
573    /// handler-body-level control flow is diagrammed, not arbitrary
574    /// expression-level branching).
575    fn walk_value(
576        &mut self,
577        expr: &Expr,
578        current_block: Option<BlockCtx>,
579        depth: u32,
580        arrow: Option<Arrow>,
581        ret: bool,
582    ) {
583        let inner = peel_paren(expr);
584        // #3437: `e.detach()` is the asynchronous arrow, as the removed `~> e` was: the call it
585        // wraps is drawn without a return. Read from the shape (the walk has no
586        // types), and only under `do` or `<-`, where an effect is awaited.
587        if arrow == Some(Arrow::Awaited)
588            && let ExprKind::MethodCall {
589                receiver,
590                method,
591                args,
592                ..
593            } = &inner.kind
594            && method.name == "detach"
595            && args.is_empty()
596        {
597            self.walk_value(
598                receiver,
599                current_block,
600                depth,
601                Some(Arrow::FireAndForget),
602                false,
603            );
604            return;
605        }
606        match &inner.kind {
607            // Control flow in return position keeps the `ret` flag: each
608            // branch's own tail is what the handler ultimately returns.
609            ExprKind::If { .. } => self.walk_if(inner, current_block, depth, ret),
610            ExprKind::Match { arms, .. } => {
611                self.walk_match(inner.span, arms, current_block, depth, ret)
612            }
613            ExprKind::Block(b) => self.walk_block(b, current_block, depth, ret),
614            // Model-diagrams slice 3: `x?` returns early when `x` is `None` or
615            // `Err`. Only a `?` at the top of a statement's value (or a tail)
616            // is seen, as for calls; one inside a lambda returns from the
617            // lambda, and lambdas are not walked.
618            ExprKind::Question(operand) => {
619                self.walk_value(operand, current_block, depth, arrow, false);
620                self.push_break(inner, peel_paren(operand), current_block, depth);
621                self.maybe_reply(inner, current_block, ret);
622            }
623            ExprKind::Call { .. } | ExprKind::MethodCall { .. } => {
624                // A write to the agent's own store is a note, not a lifeline —
625                // under `<-`/`do`, or as a tail (`balance.update(…)` as a
626                // handler's last expression, `Ok(a) => items.put(a, n)`). Its
627                // value is `()`, so it is not also a reply.
628                if self.emit_store_op(inner, current_block) {
629                    return;
630                }
631                if let Some(arrow) = arrow {
632                    self.classify_call(inner, arrow, current_block);
633                }
634                self.maybe_reply(inner, current_block, ret);
635            }
636            _ => self.maybe_reply(inner, current_block, ret),
637        }
638    }
639
640    /// A value tail in return position is the handler's reply to the actor.
641    /// A no-op off the return path, on a signal-free outcome (unit), or with
642    /// no actor (`emit_reply` itself then does nothing).
643    fn maybe_reply(&mut self, expr: &Expr, current_block: Option<BlockCtx>, ret: bool) {
644        if !ret {
645            return;
646        }
647        if let Some(outcome) = branch_outcome(expr) {
648            self.emit_reply(outcome, expr.span, current_block);
649        }
650    }
651
652    /// `if_expr` is the (paren-peeled) `ExprKind::If` — destructured here rather
653    /// than in the caller to keep the argument list small.
654    fn walk_if(&mut self, if_expr: &Expr, current_block: Option<BlockCtx>, depth: u32, ret: bool) {
655        let ExprKind::If {
656            cond,
657            then_block,
658            else_block,
659        } = &if_expr.kind
660        else {
661            return;
662        };
663        let span = if_expr.span;
664        if depth >= MAX_BLOCK_DEPTH {
665            self.push_collapsed(span, current_block, depth);
666            return;
667        }
668        let id = self.blocks.len() as u32;
669        self.blocks.push(AltBlock {
670            id,
671            kind: AltKind::If,
672            branches: Vec::new(),
673            span,
674            parent: current_block.map(|c| c.id),
675            parent_branch: current_block.map(|c| c.branch),
676            depth,
677        });
678        let then_start = self.messages.len();
679        self.walk_block(then_block, Some(BlockCtx { id, branch: 0 }), depth + 1, ret);
680        let then_ids = (then_start..self.messages.len()).collect();
681        // The condition itself labels the `then` branch (`alt view.allowed`)
682        // rather than a bare "then" — the branch predicate is the signal.
683        let mut branches = vec![Branch {
684            label: bynk_fmt::expr_to_string(cond),
685            message_ids: then_ids,
686            reply: self.branch_reply(&then_block.tail),
687            span: Span {
688                end: then_block.span.end,
689                ..span
690            },
691        }];
692        // An else-less `if` has a synthesised `()` else block: no messages, no
693        // nested blocks, no outcome. Rendering it as a second (empty) branch
694        // gains nothing — a single-branch block renders as an `opt`, which is
695        // exactly the right shape for a guard with no alternative. A written
696        // `else` is always walked and always contributes its branch.
697        if !else_block.is_synth_unit() {
698            let else_start = self.messages.len();
699            self.walk_block(else_block, Some(BlockCtx { id, branch: 1 }), depth + 1, ret);
700            branches.push(Branch {
701                label: "otherwise".to_string(),
702                message_ids: (else_start..self.messages.len()).collect(),
703                reply: self.branch_reply(&else_block.tail),
704                span: else_block.span,
705            });
706        }
707        self.blocks[id as usize].branches = branches;
708    }
709
710    /// A branch's `reply` note — its outcome, but only when there is no actor.
711    /// With an actor the outcome is instead emitted as a `Return` message to it
712    /// (by the return-position walk of the branch tail), so a note would double
713    /// it.
714    fn branch_reply(&self, tail: &Expr) -> Option<String> {
715        if self.actor.is_some() || self.store_op_label(peel_paren(tail)).is_some() {
716            // A tail store write is already a state-write note.
717            None
718        } else {
719            branch_outcome(tail)
720        }
721    }
722
723    fn walk_match(
724        &mut self,
725        span: Span,
726        arms: &[MatchArm],
727        current_block: Option<BlockCtx>,
728        depth: u32,
729        ret: bool,
730    ) {
731        if depth >= MAX_BLOCK_DEPTH {
732            self.push_collapsed(span, current_block, depth);
733            return;
734        }
735        let id = self.blocks.len() as u32;
736        self.blocks.push(AltBlock {
737            id,
738            kind: AltKind::Match,
739            branches: Vec::new(),
740            span,
741            parent: current_block.map(|c| c.id),
742            parent_branch: current_block.map(|c| c.branch),
743            depth,
744        });
745        let mut branches = Vec::with_capacity(arms.len());
746        for (arm_index, arm) in arms.iter().enumerate() {
747            let start = self.messages.len();
748            let branch_ctx = Some(BlockCtx {
749                id,
750                branch: arm_index as u32,
751            });
752            // The arm's tail — the value it yields — is its outcome, whether
753            // the body is a bare expression or a block. It is in the match's
754            // own return position, so a return-position arm replies to the actor.
755            let scope = self.bound.len();
756            self.bound.extend(
757                arm.pattern
758                    .bound_names()
759                    .into_iter()
760                    .map(|n| n.name.clone()),
761            );
762            let reply = match &arm.body {
763                MatchBody::Expr(e) => {
764                    self.walk_value(e, branch_ctx, depth + 1, None, ret);
765                    self.branch_reply(e)
766                }
767                MatchBody::Block(b) => {
768                    self.walk_block(b, branch_ctx, depth + 1, ret);
769                    self.branch_reply(&b.tail)
770                }
771            };
772            self.bound.truncate(scope);
773            branches.push(Branch {
774                label: pattern_summary(&arm.pattern),
775                message_ids: (start..self.messages.len()).collect(),
776                reply,
777                span: arm.span,
778            });
779        }
780        self.blocks[id as usize].branches = branches;
781    }
782
783    /// #2194: a `:=` in an agent handler is a state write. The checker only
784    /// admits `:=` against a `store Cell` (`bynk.cell.invalid_target`), so the
785    /// target needs no resolution here.
786    fn emit_assign(&mut self, a: &AssignStmt, current_block: Option<BlockCtx>) {
787        // Only a known store field — the checker guarantees this for checked
788        // code, but a file with errors could carry any `:=`.
789        if !self.store.contains_key(&a.target.name) {
790            return;
791        }
792        let label = format!(
793            "{} := {}",
794            a.target.name,
795            truncate(&bynk_fmt::expr_to_string(&a.value))
796        );
797        self.push_state_write(label, a.span, current_block);
798    }
799
800    /// #2194: emit a state write for a mutating store operation on one of the
801    /// agent's own fields (`items.put(id, …)`) — a bare-name receiver that is
802    /// a store field, not shadowed, calling an op the registry marks as
803    /// mutating for that field's kind. Returns whether `expr` was one.
804    fn emit_store_op(&mut self, expr: &Expr, current_block: Option<BlockCtx>) -> bool {
805        let Some(label) = self.store_op_label(expr) else {
806            return false;
807        };
808        self.push_state_write(label, expr.span, current_block);
809        true
810    }
811
812    /// The state-write label for `expr` when it is a mutating store operation
813    /// on one of the agent's own, unshadowed fields; `None` otherwise.
814    fn store_op_label(&self, expr: &Expr) -> Option<String> {
815        let w = bynk_check::store_write::store_write(&self.store, &self.bound, expr)?;
816        Some(format!(
817            "{}.{}",
818            w.field.name,
819            op_call_label(&w.method.name, w.args)
820        ))
821    }
822
823    fn push_state_write(&mut self, label: String, span: Span, current_block: Option<BlockCtx>) {
824        self.messages.push(Message {
825            from: ENTRY_ID,
826            to: ENTRY_ID,
827            kind: MessageKind::StateWrite,
828            label,
829            span,
830            block: current_block.map(|c| c.id),
831            callee: None,
832        });
833    }
834
835    fn push_collapsed(&mut self, span: Span, current_block: Option<BlockCtx>, depth: u32) {
836        let id = self.blocks.len() as u32;
837        self.blocks.push(AltBlock {
838            id,
839            kind: AltKind::Collapsed,
840            branches: Vec::new(),
841            span,
842            parent: current_block.map(|c| c.id),
843            parent_branch: current_block.map(|c| c.branch),
844            depth,
845        });
846    }
847
848    /// Model-diagrams slice 3: a `?` is an early return — a UML `break`
849    /// whose one branch, labelled by the operand (`stored?`), replies an
850    /// early return: a `Return` to the principal when there is one, else the
851    /// branch's reply note. The operand is walked first (it is evaluated
852    /// first); the walk carries on after the block, as the code does.
853    fn push_break(
854        &mut self,
855        question: &Expr,
856        operand: &Expr,
857        current_block: Option<BlockCtx>,
858        depth: u32,
859    ) {
860        if depth >= MAX_BLOCK_DEPTH {
861            self.push_collapsed(question.span, current_block, depth);
862            return;
863        }
864        let id = self.blocks.len() as u32;
865        self.blocks.push(AltBlock {
866            id,
867            kind: AltKind::Break,
868            branches: Vec::new(),
869            span: question.span,
870            parent: current_block.map(|c| c.id),
871            parent_branch: current_block.map(|c| c.branch),
872            depth,
873        });
874        let start = self.messages.len();
875        self.emit_reply(
876            EARLY_RETURN.to_string(),
877            question.span,
878            Some(BlockCtx { id, branch: 0 }),
879        );
880        let reply = self.actor.is_none().then(|| EARLY_RETURN.to_string());
881        self.blocks[id as usize].branches = vec![Branch {
882            label: format!("{}?", bynk_fmt::expr_to_string(operand)),
883            message_ids: (start..self.messages.len()).collect(),
884            reply,
885            span: question.span,
886        }];
887    }
888
889    fn classify_call(&mut self, expr: &Expr, arrow: Arrow, current_block: Option<BlockCtx>) {
890        let callee = self.callee_of(expr);
891        let Some((target, label)) = self.classify_target(expr) else {
892            // Local computation (commons/context-local fn, plain method,
893            // constructor) — folds into the entry activation, no message.
894            return;
895        };
896        let block = current_block.map(|c| c.id);
897        match arrow {
898            Arrow::FireAndForget => {
899                self.messages.push(Message {
900                    from: ENTRY_ID,
901                    to: target,
902                    kind: MessageKind::Send,
903                    label,
904                    span: expr.span,
905                    block,
906                    callee,
907                });
908            }
909            Arrow::Awaited => {
910                self.messages.push(Message {
911                    from: ENTRY_ID,
912                    to: target,
913                    kind: MessageKind::Call,
914                    label,
915                    span: expr.span,
916                    block,
917                    callee,
918                });
919                self.messages.push(Message {
920                    from: target,
921                    to: ENTRY_ID,
922                    kind: MessageKind::Return,
923                    label: String::new(),
924                    span: expr.span,
925                    block,
926                    callee: None,
927                });
928            }
929        }
930    }
931
932    /// Model-diagrams slice 3: the handler a boundary call reaches, by name —
933    /// `Agent(key).method(…)` reaches the agent's `on call method`, and
934    /// `consumed.Service(…)` the consumed service's `on call`. Read from the
935    /// same shapes [`Builder::classify_target`] classifies; `None` for a
936    /// capability op or local computation. Must agree with that method on
937    /// which calls are boundary calls.
938    fn callee_of(&self, expr: &Expr) -> Option<Callee> {
939        let ExprKind::MethodCall {
940            receiver, method, ..
941        } = &expr.kind
942        else {
943            return None;
944        };
945        let info = self.info?;
946        match &receiver.kind {
947            ExprKind::Call { name, .. } if info.agents.contains_key(&name.name) => Some(Callee {
948                unit: None,
949                owner: name.name.clone(),
950                method: Some(method.name.clone()),
951            }),
952            ExprKind::Ident(id) if !self.given.iter().any(|c| c.key() == id.name) => {
953                let unit = info.cross_context.resolve_prefix(&id.name)?;
954                Some(Callee {
955                    unit: Some(unit),
956                    owner: method.name.clone(),
957                    method: None,
958                })
959            }
960            _ => None,
961        }
962    }
963
964    /// Resolve a call expression's target lifeline, per Decision A:
965    /// consumed Capability > Agent > consumed Context. Returns the
966    /// participant id and a rendered call label, or `None` when the call is
967    /// local computation.
968    ///
969    /// `TypeName.method(args)` (`Clock.now()`, a local capability op) and
970    /// `Consumed.service(args)` (a cross-context call) are syntactically
971    /// identical to an ordinary instance method call — the parser has no
972    /// static-vs-instance distinction at the receiver, so *every* qualified
973    /// call parses uniformly as `ExprKind::MethodCall` with an `Ident`
974    /// receiver (the resolver/checker make the static-vs-instance call from
975    /// context, which this classifier reimplements against `given`/`agents`/
976    /// `cross_context` instead). `Agent(key).method(args)` is the one
977    /// receiver shape that differs structurally: the receiver is itself an
978    /// `ExprKind::Call` (the agent construction), not a bare `Ident`.
979    fn classify_target(&mut self, expr: &Expr) -> Option<(u32, String)> {
980        match &expr.kind {
981            ExprKind::MethodCall {
982                receiver,
983                method,
984                args,
985                ..
986            } => match &receiver.kind {
987                ExprKind::Call {
988                    name,
989                    args: key_args,
990                    ..
991                } if self.info.is_some_and(|i| i.agents.contains_key(&name.name)) => {
992                    let id = self.participant_id(ParticipantKind::Agent, &name.name, name.span);
993                    let key: Vec<String> = key_args.iter().map(bynk_fmt::expr_to_string).collect();
994                    // No key arguments (a file mid-edit): no key, not `""`.
995                    if !key.is_empty() {
996                        self.note_key(id, key.join(", "));
997                    }
998                    Some((id, call_label(&method.name, args)))
999                }
1000                ExprKind::Ident(id) => self.classify_static(&id.name, &method.name, args, id.span),
1001                _ => None,
1002            },
1003            _ => None,
1004        }
1005    }
1006
1007    /// Classify a bare qualified call `Name.method(args)`: a local
1008    /// capability op when `Name` is in the handler's effective `given`,
1009    /// otherwise a cross-context call when `Name` resolves as a consumed
1010    /// context (or alias). Anything else (a static method on an ordinary
1011    /// type, a sum-type variant constructor) is local — `None`.
1012    fn classify_static(
1013        &mut self,
1014        name: &str,
1015        method: &str,
1016        args: &[Expr],
1017        span: Span,
1018    ) -> Option<(u32, String)> {
1019        if self.given.iter().any(|c| c.key() == name) {
1020            let id = self.participant_id(ParticipantKind::Capability, name, span);
1021            return Some((id, call_label(method, args)));
1022        }
1023        self.classify_cross_context(name, method, args, span)
1024    }
1025
1026    fn classify_cross_context(
1027        &mut self,
1028        prefix: &str,
1029        method: &str,
1030        args: &[Expr],
1031        span: Span,
1032    ) -> Option<(u32, String)> {
1033        let ctx_name = self.info?.cross_context.resolve_prefix(prefix)?;
1034        let id = self.participant_id(ParticipantKind::Context, &ctx_name, span);
1035        Some((id, call_label(method, args)))
1036    }
1037}
1038
1039/// The reply a `break` block (a `?`) gives: the handler returns early with the
1040/// operand's `None` or `Err` (a 404 under `HttpResult`, the error otherwise).
1041pub const EARLY_RETURN: &str = "early return";
1042
1043/// The longest rendered value a state-write note shows before eliding.
1044const WRITE_LABEL_MAX: usize = 32;
1045
1046/// Shorten a rendered value to [`WRITE_LABEL_MAX`] characters, ending in `…`.
1047fn truncate(text: &str) -> String {
1048    if text.chars().count() <= WRITE_LABEL_MAX {
1049        text.to_string()
1050    } else {
1051        let kept: String = text.chars().take(WRITE_LABEL_MAX - 1).collect();
1052        format!("{kept}…")
1053    }
1054}
1055
1056/// A store operation's label (#2194, DECISION B): the first argument when it
1057/// is a plain name or literal — usually the key (`put(id, …)`) or the item
1058/// (`add(x)`) — and every other argument elided to `…`, since values and
1059/// combiner lambdas are long and the note only has to say *what* is written.
1060fn op_call_label(method: &str, args: &[Expr]) -> String {
1061    let mut rendered = Vec::with_capacity(args.len());
1062    for (i, arg) in args.iter().enumerate() {
1063        let simple = matches!(
1064            peel_paren(arg).kind,
1065            ExprKind::Ident(_)
1066                | ExprKind::IntLit { .. }
1067                | ExprKind::StrLit(_)
1068                | ExprKind::BoolLit(_)
1069        );
1070        if i == 0 && simple {
1071            rendered.push(truncate(&bynk_fmt::expr_to_string(arg)));
1072        } else {
1073            rendered.push("…".to_string());
1074            break;
1075        }
1076    }
1077    format!("{method}({})", rendered.join(", "))
1078}
1079
1080fn call_label(method: &str, args: &[Expr]) -> String {
1081    let rendered: Vec<String> = args.iter().map(bynk_fmt::expr_to_string).collect();
1082    format!("{method}({})", rendered.join(", "))
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087    use super::*;
1088    use std::fs;
1089    use std::path::PathBuf;
1090
1091    /// Same convention as `symbols.rs`'s `setup_project`: a temp dir unique to
1092    /// the test name, populated with `(relative_path, contents)` files.
1093    /// Self-contained fixtures only (never `examples/`) — `bynk-ide` is
1094    /// published standalone, and a test reaching outside the crate would fail
1095    /// a `cargo test` on the released tarball.
1096    fn setup_project(test_name: &str, files: &[(&str, &str)]) -> PathBuf {
1097        let root = std::env::temp_dir().join(format!(
1098            "bynk-ide-sequence-test-{test_name}-{}",
1099            std::process::id()
1100        ));
1101        let _ = fs::remove_dir_all(&root);
1102        fs::create_dir_all(&root).expect("create test root");
1103        for (rel, contents) in files {
1104            let p = root.join(rel);
1105            if let Some(parent) = p.parent() {
1106                fs::create_dir_all(parent).expect("create parent");
1107            }
1108            fs::write(&p, contents).expect("write file");
1109        }
1110        root
1111    }
1112
1113    fn parse_context(text: &str) -> Context {
1114        let tokens = bynk_syntax::lexer::tokenize(text).expect("tokenize");
1115        let (unit, errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
1116        assert!(errs.is_empty(), "parse errors: {errs:?}");
1117        match unit.expect("parsed unit") {
1118            SourceUnit::Context(c) => c,
1119            _ => panic!("expected a context"),
1120        }
1121    }
1122
1123    fn find_service<'a>(ctx: &'a Context, name: &str) -> &'a ServiceDecl {
1124        ctx.items
1125            .iter()
1126            .find_map(|i| match i {
1127                CommonsItem::Service(s) if s.name.name == name => Some(s),
1128                _ => None,
1129            })
1130            .unwrap_or_else(|| panic!("service {name} not found"))
1131    }
1132
1133    // -- Fixture 1: examples/rate-limiter's `GET /check/:client`, reproduced
1134    // -- self-contained (not read from `examples/` — see `setup_project`).
1135    // -- Capability (Clock) + Agent (Limiter) + a return-gating `if` whose
1136    // -- branches call nothing lifeline-worthy — the regression fixture for
1137    // -- the corrected AltBlock rule (see the plan's "Corrected extractor
1138    // -- rule" note): the issue's own worked example renders this block.
1139    const RATELIMIT_SRC: &str = r#"context ratelimit
1140
1141consumes bynk { Clock }
1142
1143type ClientId = String where NonEmpty
1144
1145type RateView = {
1146  allowed:   Bool,
1147  remaining: Int,
1148  resetAt:   Int,
1149}
1150
1151agent Limiter {
1152  key client: ClientId
1153
1154  store count: Cell[Int]
1155
1156  on call hit(now: Int) -> Effect[RateView] {
1157    let _ <- count.update((c) => c + 1)
1158    RateView { allowed: count < 10, remaining: 10 - count, resetAt: now }
1159  }
1160}
1161
1162service api from http {
1163  on GET("/check/:client") (client: ClientId) -> Effect[HttpResult[RateView]] by Visitor given Clock {
1164    let now  <- Clock.now()
1165    let view <- Limiter(client).hit(now.toEpochMillis())
1166    if view.allowed {
1167      Ok(view)
1168    } else {
1169      TooManyRequests("rate limit exceeded")
1170    }
1171  }
1172}
1173"#;
1174
1175    #[test]
1176    fn rate_limiter_get_check_client_classifies_capability_and_agent_and_gates_the_return() {
1177        let root = setup_project("ratelimit", &[("ratelimit.bynk", RATELIMIT_SRC)]);
1178        let diag = crate::testkit::diagnose_project(&root);
1179        let info = diag
1180            .sequence_info
1181            .get("ratelimit")
1182            .expect("sequence_info entry for ratelimit");
1183
1184        let ctx = parse_context(RATELIMIT_SRC);
1185        let svc = find_service(&ctx, "api");
1186        let handler = &svc.handlers[0];
1187
1188        let model = sequence_model(
1189            handler,
1190            HandlerOwner::Service("api"),
1191            &svc.default_given,
1192            svc.default_by.as_ref(),
1193            Some(info),
1194        );
1195
1196        // The handler's `by Visitor` principal is the leftmost participant and
1197        // originates the request; the entry box drops to the bare owner name
1198        // (`api`) since the route now rides on the inbound message.
1199        let kinds: Vec<(ParticipantKind, &str)> = model
1200            .participants
1201            .iter()
1202            .map(|p| (p.kind, p.name.as_str()))
1203            .collect();
1204        assert_eq!(
1205            kinds,
1206            vec![
1207                (ParticipantKind::Actor, "Visitor"),
1208                (ParticipantKind::Entry, "api"),
1209                (ParticipantKind::Capability, "Clock"),
1210                (ParticipantKind::Agent, "Limiter"),
1211            ]
1212        );
1213        let actor_id = model.participants[0].id;
1214
1215        // The initial inbound request: Visitor -> api, labelled by the route.
1216        let req = &model.messages[0];
1217        assert_eq!(req.kind, MessageKind::Call);
1218        assert_eq!((req.from, req.to), (actor_id, ENTRY_ID));
1219        assert_eq!(req.label, "GET /check/:client");
1220
1221        // now() + reply, hit(...) + reply, then a reply-to-actor per branch.
1222        assert_eq!(
1223            model.messages.len(),
1224            7,
1225            "request + Clock Call/Return + Limiter Call/Return + a reply-to-actor per branch"
1226        );
1227
1228        assert_eq!(model.blocks.len(), 1);
1229        assert_eq!(model.blocks[0].kind, AltKind::If);
1230        assert_eq!(model.blocks[0].branches.len(), 2);
1231        // With an actor, each branch carries no *note* (`reply` is None) — its
1232        // outcome is instead a `Return` message back to the actor, which the
1233        // `then`/`else` branches own via their `message_ids`.
1234        let labels: Vec<&str> = model.blocks[0]
1235            .branches
1236            .iter()
1237            .map(|b| b.label.as_str())
1238            .collect();
1239        assert_eq!(labels, vec!["view.allowed", "otherwise"]);
1240        assert!(
1241            model.blocks[0].branches.iter().all(|b| b.reply.is_none()),
1242            "with an actor the outcome is a message, not a note"
1243        );
1244        let branch_replies: Vec<(MessageKind, u32, u32, &str)> = model.blocks[0]
1245            .branches
1246            .iter()
1247            .flat_map(|b| &b.message_ids)
1248            .map(|&i| {
1249                let m = &model.messages[i];
1250                (m.kind, m.from, m.to, m.label.as_str())
1251            })
1252            .collect();
1253        assert_eq!(
1254            branch_replies,
1255            vec![
1256                (MessageKind::Return, ENTRY_ID, actor_id, "Ok(view)"),
1257                (
1258                    MessageKind::Return,
1259                    ENTRY_ID,
1260                    actor_id,
1261                    "TooManyRequests(\"rate limit exceeded\")",
1262                ),
1263            ],
1264            "each branch replies its outcome to the actor"
1265        );
1266    }
1267
1268    // -- Fixture 2: a consumed-context call — boundary-stop (Decision C).
1269    const PLATFORM_SRC: &str = r#"context platform
1270
1271service Pinger {
1272  on call(n: Int) -> Effect[Int] {
1273    n
1274  }
1275}
1276"#;
1277    const CONSUMER_SRC: &str = r#"context consumer
1278
1279consumes platform
1280
1281service api {
1282  on call(n: Int) -> Effect[Int] {
1283    let v <- platform.Pinger(n)
1284    v
1285  }
1286}
1287"#;
1288
1289    #[test]
1290    fn cross_context_call_is_boundary_stop() {
1291        let root = setup_project(
1292            "crossctx",
1293            &[
1294                ("platform.bynk", PLATFORM_SRC),
1295                ("consumer.bynk", CONSUMER_SRC),
1296            ],
1297        );
1298        let diag = crate::testkit::diagnose_project(&root);
1299        let info = diag
1300            .sequence_info
1301            .get("consumer")
1302            .expect("sequence_info entry for consumer");
1303
1304        let ctx = parse_context(CONSUMER_SRC);
1305        let svc = find_service(&ctx, "api");
1306        let handler = &svc.handlers[0];
1307        let model = sequence_model(
1308            handler,
1309            HandlerOwner::Service("api"),
1310            &svc.default_given,
1311            svc.default_by.as_ref(),
1312            Some(info),
1313        );
1314
1315        assert_eq!(model.participants.len(), 2, "Entry + the consumed context");
1316        assert_eq!(model.participants[1].kind, ParticipantKind::Context);
1317        assert_eq!(model.participants[1].name, "platform");
1318        assert_eq!(
1319            model.messages.len(),
1320            2,
1321            "one Call + one Return — the consumed service's own body is never walked"
1322        );
1323        assert_eq!(model.messages[0].kind, MessageKind::Call);
1324        assert_eq!(model.messages[1].kind, MessageKind::Return);
1325    }
1326
1327    // -- Fixtures 3-5: fire-and-forget send, a degenerate (local-only)
1328    // -- handler, and 3-level-nested `if` past the depth budget.
1329    const MISC_SRC: &str = r#"context misc
1330
1331consumes bynk { Clock, Logger }
1332
1333fn double(x: Int) -> Int {
1334  x * 2
1335}
1336
1337service fireService {
1338  on call(n: Int) -> Effect[()] given Logger {
1339    do Logger.info("hi").detach()
1340    Effect.pure(())
1341  }
1342}
1343
1344service localService {
1345  on call(n: Int) -> Effect[Int] {
1346    double(n)
1347  }
1348}
1349
1350service nestedService {
1351  on call(n: Int) -> Effect[Int] given Clock {
1352    let now <- Clock.now()
1353    if n > 0 {
1354      if n > 10 {
1355        if n > 100 {
1356          now.toEpochMillis()
1357        } else {
1358          1
1359        }
1360      } else {
1361        2
1362      }
1363    } else {
1364      3
1365    }
1366  }
1367}
1368"#;
1369
1370    fn misc_info(diag: &crate::ProjectDiagnostics) -> bynk_check::analysis::ContextSequenceInfo {
1371        diag.sequence_info
1372            .get("misc")
1373            .cloned()
1374            .expect("sequence_info entry for misc")
1375    }
1376
1377    /// #3437: `do e.detach()` is the asynchronous arrow.
1378    #[test]
1379    fn fire_and_forget_send_has_no_paired_return() {
1380        let root = setup_project("misc-send", &[("misc.bynk", MISC_SRC)]);
1381        let diag = crate::testkit::diagnose_project(&root);
1382        let info = misc_info(&diag);
1383
1384        let ctx = parse_context(MISC_SRC);
1385        let svc = find_service(&ctx, "fireService");
1386        let handler = &svc.handlers[0];
1387        let model = sequence_model(
1388            handler,
1389            HandlerOwner::Service("fireService"),
1390            &svc.default_given,
1391            svc.default_by.as_ref(),
1392            Some(&info),
1393        );
1394
1395        assert_eq!(model.participants.len(), 2);
1396        assert_eq!(model.participants[1].kind, ParticipantKind::Capability);
1397        assert_eq!(model.participants[1].name, "Logger");
1398        assert_eq!(model.messages.len(), 1, "a Send has no paired Return");
1399        assert_eq!(model.messages[0].kind, MessageKind::Send);
1400    }
1401
1402    #[test]
1403    fn degenerate_handler_with_only_local_calls_has_no_lifelines() {
1404        let root = setup_project("misc-local", &[("misc.bynk", MISC_SRC)]);
1405        let diag = crate::testkit::diagnose_project(&root);
1406        let info = misc_info(&diag);
1407
1408        let ctx = parse_context(MISC_SRC);
1409        let svc = find_service(&ctx, "localService");
1410        let handler = &svc.handlers[0];
1411        let model = sequence_model(
1412            handler,
1413            HandlerOwner::Service("localService"),
1414            &svc.default_given,
1415            svc.default_by.as_ref(),
1416            Some(&info),
1417        );
1418
1419        assert_eq!(model.participants.len(), 1);
1420        assert_eq!(model.participants[0].kind, ParticipantKind::Entry);
1421        assert!(model.messages.is_empty());
1422        assert!(model.blocks.is_empty());
1423    }
1424
1425    #[test]
1426    fn nested_if_is_walked_in_full_with_depths() {
1427        let root = setup_project("misc-nested", &[("misc.bynk", MISC_SRC)]);
1428        let diag = crate::testkit::diagnose_project(&root);
1429        let info = misc_info(&diag);
1430
1431        let ctx = parse_context(MISC_SRC);
1432        let svc = find_service(&ctx, "nestedService");
1433        let handler = &svc.handlers[0];
1434        let model = sequence_model(
1435            handler,
1436            HandlerOwner::Service("nestedService"),
1437            &svc.default_given,
1438            svc.default_by.as_ref(),
1439            Some(&info),
1440        );
1441
1442        // Model-diagrams slice 3 (ADR 0858): all three levels are real blocks
1443        // — the old presentation cut at depth 2 is gone, and each block says
1444        // how deep it is so the client can fold by depth.
1445        let kinds: Vec<(AltKind, u32)> = model.blocks.iter().map(|b| (b.kind, b.depth)).collect();
1446        assert_eq!(
1447            kinds,
1448            vec![(AltKind::If, 0), (AltKind::If, 1), (AltKind::If, 2)]
1449        );
1450        // Regression: each nested block must record which branch of its
1451        // parent it sits under, not just the parent id — both the middle
1452        // and innermost `if` are nested in their parent's *first* ("then")
1453        // branch, and a renderer needs that even when the branch itself
1454        // carries no messages of its own (only the nested block does).
1455        assert_eq!(model.blocks[0].parent, None);
1456        assert_eq!(model.blocks[0].parent_branch, None);
1457        assert_eq!(model.blocks[1].parent, Some(0));
1458        assert_eq!(model.blocks[1].parent_branch, Some(0));
1459        assert_eq!(model.blocks[2].parent, Some(1));
1460        assert_eq!(model.blocks[2].parent_branch, Some(0));
1461    }
1462
1463    /// A handler whose body is `depth` nested `if`s around one value.
1464    fn deeply_nested_src(depth: usize) -> String {
1465        let mut body = String::from("n");
1466        for i in (0..depth).rev() {
1467            body = format!("if n > {i} {{ {body} }} else {{ 0 }}");
1468        }
1469        format!(
1470            "context deep\n\nservice api {{\n  on call(n: Int) -> Effect[Int] {{\n    {body}\n  }}\n}}\n"
1471        )
1472    }
1473
1474    #[test]
1475    fn nesting_past_the_safety_cap_collapses() {
1476        let src = deeply_nested_src(MAX_BLOCK_DEPTH as usize + 2);
1477        let ctx = parse_context(&src);
1478        let svc = find_service(&ctx, "api");
1479        let model = sequence_model(
1480            &svc.handlers[0],
1481            HandlerOwner::Service("api"),
1482            &[],
1483            None,
1484            None,
1485        );
1486        let ifs = model
1487            .blocks
1488            .iter()
1489            .filter(|b| b.kind == AltKind::If)
1490            .count();
1491        assert_eq!(
1492            ifs, MAX_BLOCK_DEPTH as usize,
1493            "walked in full up to the cap"
1494        );
1495        let collapsed: Vec<&AltBlock> = model
1496            .blocks
1497            .iter()
1498            .filter(|b| b.kind == AltKind::Collapsed)
1499            .collect();
1500        assert_eq!(collapsed.len(), 1, "one marker for everything past the cap");
1501        assert_eq!(collapsed[0].depth, MAX_BLOCK_DEPTH);
1502        assert!(collapsed[0].branches.is_empty());
1503    }
1504
1505    // -- Fixture 6 (#861 review): a service declares a service-level `given`
1506    // -- default (v0.155) and the handler omits its own `given`, inheriting it.
1507    // -- The classifier walks a freshly-parsed AST that never ran
1508    // -- `inject_service_defaults`, so it must apply the fallback itself — or
1509    // -- the Clock capability lifeline is silently dropped.
1510    const SERVICE_GIVEN_SRC: &str = r#"context svcgiven
1511
1512consumes bynk { Clock }
1513
1514service api from http by Visitor given Clock {
1515  on GET("/now") () -> Effect[HttpResult[Int]] {
1516    let now <- Clock.now()
1517    Ok(now.toEpochMillis())
1518  }
1519}
1520"#;
1521
1522    #[test]
1523    fn service_level_given_default_is_inherited_by_a_handler_without_its_own() {
1524        let root = setup_project("svcgiven", &[("svcgiven.bynk", SERVICE_GIVEN_SRC)]);
1525        let diag = crate::testkit::diagnose_project(&root);
1526        let info = diag
1527            .sequence_info
1528            .get("svcgiven")
1529            .expect("sequence_info entry for svcgiven");
1530
1531        let ctx = parse_context(SERVICE_GIVEN_SRC);
1532        let svc = find_service(&ctx, "api");
1533        let handler = &svc.handlers[0];
1534        // Precondition: the freshly-parsed handler carries no `given` of its
1535        // own — it relies entirely on the service-level default.
1536        assert!(
1537            handler.given.is_empty(),
1538            "fixture handler must omit its own `given`"
1539        );
1540        assert_eq!(svc.default_given.len(), 1, "service-level `given Clock`");
1541        assert!(
1542            handler.by_clause.is_none() && svc.default_by.is_some(),
1543            "fixture handler must inherit the service-level `by Visitor`"
1544        );
1545
1546        let model = sequence_model(
1547            handler,
1548            HandlerOwner::Service("api"),
1549            &svc.default_given,
1550            svc.default_by.as_ref(),
1551            Some(info),
1552        );
1553
1554        let kinds: Vec<(ParticipantKind, &str)> = model
1555            .participants
1556            .iter()
1557            .map(|p| (p.kind, p.name.as_str()))
1558            .collect();
1559        assert_eq!(
1560            kinds,
1561            vec![
1562                // Both service-level defaults are inherited: `by Visitor` (the
1563                // actor) and `given Clock` (the capability lifeline).
1564                (ParticipantKind::Actor, "Visitor"),
1565                (ParticipantKind::Entry, "api"),
1566                (ParticipantKind::Capability, "Clock"),
1567            ],
1568            "Clock must classify via the inherited `given`, and Visitor via the \
1569             inherited `by` — with only `handler.given`/`handler.by_clause` both \
1570             would be dropped"
1571        );
1572
1573        // A non-branching handler tail still replies to the actor: the last
1574        // message is the `Ok(...)` return, entry -> Visitor.
1575        let actor_id = model.participants[0].id;
1576        let last = model.messages.last().expect("at least one message");
1577        assert_eq!(last.kind, MessageKind::Return);
1578        assert_eq!((last.from, last.to), (ENTRY_ID, actor_id));
1579        assert_eq!(last.label, "Ok(now.toEpochMillis())");
1580    }
1581
1582    // -- Fixture 7 (issue): branch outcomes + else-less-if shape. An else-less
1583    // -- `if` renders as an `opt` (one branch, not an empty second branch), and
1584    // -- a `match` captures each arm's yielded value as its reply — the content
1585    // -- that keeps a return-gating block from rendering as an empty box.
1586    const OUTCOME_SRC: &str = r#"context outcome
1587
1588consumes bynk { Logger }
1589
1590service guardSvc {
1591  on call(flag: Bool) -> Effect[()] given Logger {
1592    if flag {
1593      do Logger.info("hi").detach()
1594    }
1595  }
1596}
1597
1598service routeSvc {
1599  on call(x: Int) -> Effect[Int] {
1600    match x {
1601      0 => 100
1602      _ => x
1603    }
1604  }
1605}
1606"#;
1607
1608    #[test]
1609    fn else_less_if_is_a_single_branch_opt_and_match_arms_capture_replies() {
1610        // `info` is `None` here: this fixture references only a capability
1611        // (`given Logger`) and control flow — no agent or cross-context call —
1612        // so classification needs no project table, and this stays a pure
1613        // parse-only test (the full project wouldn't type-check anyway).
1614        let ctx = parse_context(OUTCOME_SRC);
1615        let guard_svc = find_service(&ctx, "guardSvc");
1616        let route_svc = find_service(&ctx, "routeSvc");
1617
1618        // `guard`: an else-less `if` — one branch (an `opt`), labelled by its
1619        // condition. Its `then` carries the Send but its tail is unit, so it
1620        // has no reply of its own.
1621        let guard = &guard_svc.handlers[0];
1622        let gm = sequence_model(
1623            guard,
1624            HandlerOwner::Service("guardSvc"),
1625            &guard_svc.default_given,
1626            guard_svc.default_by.as_ref(),
1627            None,
1628        );
1629        assert_eq!(gm.blocks.len(), 1);
1630        assert_eq!(gm.blocks[0].kind, AltKind::If);
1631        assert_eq!(
1632            gm.blocks[0].branches.len(),
1633            1,
1634            "an else-less `if` renders as an `opt`, not an `alt` with an empty second branch"
1635        );
1636        assert_eq!(gm.blocks[0].branches[0].label, "flag");
1637        assert_eq!(
1638            gm.blocks[0].branches[0].reply, None,
1639            "a unit tail has no reply"
1640        );
1641        assert_eq!(
1642            gm.blocks[0].branches[0].message_ids.len(),
1643            1,
1644            "the `detach` Send"
1645        );
1646
1647        // `route`: a `match` whose arms yield distinct values — each captured
1648        // as that branch's reply.
1649        let route = &route_svc.handlers[0];
1650        let rm = sequence_model(
1651            route,
1652            HandlerOwner::Service("routeSvc"),
1653            &route_svc.default_given,
1654            route_svc.default_by.as_ref(),
1655            None,
1656        );
1657        assert_eq!(rm.blocks.len(), 1);
1658        assert_eq!(rm.blocks[0].kind, AltKind::Match);
1659        let replies: Vec<Option<&str>> = rm.blocks[0]
1660            .branches
1661            .iter()
1662            .map(|b| b.reply.as_deref())
1663            .collect();
1664        assert_eq!(replies, vec![Some("100"), Some("x")]);
1665    }
1666
1667    // -- #3584: each branch carries the source extent of its arm.
1668    const SPAN_SRC: &str = r#"context spans
1669
1670service spanSvc {
1671  on call(x: Int) -> Effect[Int] {
1672    if x > 0 {
1673      1
1674    } else {
1675      2
1676    }
1677  }
1678
1679  on call(y: Int) -> Effect[Int] {
1680    match y {
1681      0 => 100
1682      n if n > 5 => {
1683        n
1684      }
1685      _ => {}
1686    }
1687  }
1688
1689  on call(z: Bool) -> Effect[()] {
1690    if z {
1691      ()
1692    }
1693  }
1694
1695  on call(a: Bool, b: Bool) -> Effect[Int] {
1696    if a {
1697      1
1698    } else if b {
1699      2
1700    } else {
1701      3
1702    }
1703  }
1704}
1705"#;
1706
1707    fn branch_texts(src: &str, handler: usize) -> Vec<String> {
1708        let ctx = parse_context(src);
1709        let svc = find_service(&ctx, "spanSvc");
1710        let model = sequence_model(
1711            &svc.handlers[handler],
1712            HandlerOwner::Service("spanSvc"),
1713            &svc.default_given,
1714            svc.default_by.as_ref(),
1715            None,
1716        );
1717        model.blocks[0]
1718            .branches
1719            .iter()
1720            .map(|b| src[b.span.start..b.span.end].to_string())
1721            .collect()
1722    }
1723
1724    #[test]
1725    fn if_else_branches_span_their_arms() {
1726        let t = branch_texts(SPAN_SRC, 0);
1727        assert_eq!(t.len(), 2);
1728        assert!(
1729            t[0].starts_with("if x > 0 {") && t[0].ends_with('}'),
1730            "{t:?}"
1731        );
1732        assert!(t[0].contains('1') && !t[0].contains("else"), "{t:?}");
1733        assert!(t[1].starts_with('{') && t[1].contains('2'), "{t:?}");
1734    }
1735
1736    #[test]
1737    fn else_if_branch_spans_the_rest_of_the_chain() {
1738        // #3599: the outer `else` branch reuses the inner `if`'s span, so it
1739        // starts at the inner `if` keyword and covers the rest of the chain.
1740        let ctx = parse_context(SPAN_SRC);
1741        let svc = find_service(&ctx, "spanSvc");
1742        let model = sequence_model(
1743            &svc.handlers[3],
1744            HandlerOwner::Service("spanSvc"),
1745            &svc.default_given,
1746            svc.default_by.as_ref(),
1747            None,
1748        );
1749        let text = |b: &Branch| SPAN_SRC[b.span.start..b.span.end].to_string();
1750        let outer = &model.blocks[0];
1751        assert_eq!(outer.branches.len(), 2);
1752        assert!(
1753            text(&outer.branches[0]).starts_with("if a {")
1754                && !text(&outer.branches[0]).contains("else"),
1755            "{:?}",
1756            text(&outer.branches[0])
1757        );
1758        let else_text = text(&outer.branches[1]);
1759        assert!(
1760            else_text.starts_with("if b {") && else_text.ends_with('}'),
1761            "{else_text:?}"
1762        );
1763        assert!(
1764            else_text.contains("else") && else_text.contains('3'),
1765            "{else_text:?}"
1766        );
1767        // The nested `if` is its own block, whose branches sit inside that range.
1768        assert_eq!(model.blocks.len(), 2);
1769        let inner = &model.blocks[1];
1770        assert_eq!(inner.parent, Some(outer.id));
1771        assert_eq!(inner.parent_branch, Some(1));
1772        let inner_texts: Vec<String> = inner.branches.iter().map(text).collect();
1773        assert_eq!(inner_texts.len(), 2);
1774        assert!(
1775            inner_texts[0].starts_with("if b {") && !inner_texts[0].contains("else"),
1776            "{inner_texts:?}"
1777        );
1778        assert!(
1779            inner_texts[1].starts_with('{') && inner_texts[1].contains('3'),
1780            "{inner_texts:?}"
1781        );
1782        for b in &inner.branches {
1783            let o = &outer.branches[1];
1784            assert!(b.span.start >= o.span.start && b.span.end <= o.span.end);
1785        }
1786    }
1787
1788    #[test]
1789    fn match_arms_span_pattern_through_body() {
1790        let t = branch_texts(SPAN_SRC, 1);
1791        assert_eq!(t.len(), 3);
1792        assert_eq!(t[0], "0 => 100");
1793        assert!(
1794            t[1].starts_with("n if n > 5 => {") && t[1].ends_with('}'),
1795            "{t:?}"
1796        );
1797        // An empty arm still has a span, covering its pattern.
1798        assert_eq!(t[2], "_ => {}");
1799    }
1800
1801    #[test]
1802    fn else_less_if_has_one_branch_spanning_the_then_arm() {
1803        let t = branch_texts(SPAN_SRC, 2);
1804        assert_eq!(t.len(), 1, "no synthesised else branch is emitted");
1805        assert!(t[0].starts_with("if z {") && t[0].ends_with('}'), "{t:?}");
1806    }
1807
1808    // -- #2194: an agent's *own* handler — state writes as notes.
1809    const ORDER_SRC: &str = r#"context orders
1810
1811type OrderStatus = enum { Pending, Placed, Cancelled }
1812type OrderError  = enum { AlreadyPlaced, AlreadyCancelled }
1813
1814agent Counter {
1815  key id: String
1816
1817  store total: Cell[Int]
1818
1819  on call bump() -> Effect[Int] {
1820    total := total + 1
1821    total
1822  }
1823}
1824
1825agent Order {
1826  key id: String
1827
1828  store status: Cell[OrderStatus] = Pending
1829  store items:  Map[String, Int]
1830  store tally:  Cell[Int]
1831
1832  on call place() -> Effect[Result[(), OrderError]] {
1833    match status {
1834      Pending => {
1835        status := Placed
1836        Ok(())
1837      }
1838      Placed    => Err(AlreadyPlaced)
1839      Cancelled => Err(AlreadyCancelled)
1840    }
1841  }
1842
1843  on call add(sku: String, qty: Int) -> Effect[Bool] {
1844    let n <- Counter(sku).bump()
1845    let _ <- items.put(sku, qty + n)
1846    let _ <- tally.update((t) => t + qty)
1847    let known <- items.contains(sku)
1848    known
1849  }
1850
1851  on call bumpTally(n: Int) -> Effect[()] {
1852    tally.update((t) => t + n)
1853  }
1854
1855  on call putIfSome(k: String, found: Option[Int]) -> Effect[()] {
1856    match found {
1857      Some(v) => items.put(k, v),
1858      None    => Effect.pure(()),
1859    }
1860  }
1861}
1862"#;
1863
1864    fn find_agent<'a>(ctx: &'a Context, name: &str) -> &'a AgentDecl {
1865        ctx.items
1866            .iter()
1867            .find_map(|i| match i {
1868                CommonsItem::Agent(a) if a.name.name == name => Some(a),
1869                _ => None,
1870            })
1871            .unwrap_or_else(|| panic!("agent {name} not found"))
1872    }
1873
1874    fn agent_model(test_name: &str, handler_src: &str, agent: &str, method: &str) -> SequenceModel {
1875        let root = setup_project(test_name, &[("orders.bynk", ORDER_SRC)]);
1876        let diag = crate::testkit::diagnose_project(&root);
1877        let info = diag
1878            .sequence_info
1879            .get("orders")
1880            .expect("sequence_info for orders");
1881        let ctx = parse_context(handler_src);
1882        let a = find_agent(&ctx, agent);
1883        let h = a
1884            .handlers
1885            .iter()
1886            .find(|h| h.method_name.as_ref().is_some_and(|m| m.name == method))
1887            .expect("handler");
1888        sequence_model(h, HandlerOwner::Agent(agent), &[], None, Some(info))
1889    }
1890
1891    fn writes(model: &SequenceModel) -> Vec<(&str, Option<u32>)> {
1892        model
1893            .messages
1894            .iter()
1895            .filter(|m| m.kind == MessageKind::StateWrite)
1896            .map(|m| (m.label.as_str(), m.block))
1897            .collect()
1898    }
1899
1900    #[test]
1901    fn an_assignment_in_an_agent_handler_is_a_state_write_inside_its_branch() {
1902        let model = agent_model("assign", ORDER_SRC, "Order", "place");
1903        assert_eq!(writes(&model), [("status := Placed", Some(0))]);
1904        let w = &model.messages[0];
1905        assert_eq!((w.from, w.to), (ENTRY_ID, ENTRY_ID));
1906        // The write is a member of the `Pending` branch, ahead of its reply.
1907        let pending = &model.blocks[0].branches[0];
1908        assert_eq!(pending.label, "Pending");
1909        assert_eq!(pending.message_ids, [0]);
1910        assert_eq!(pending.reply.as_deref(), Some("Ok(())"));
1911        // The refusing branches write nothing.
1912        assert!(model.blocks[0].branches[1].message_ids.is_empty());
1913    }
1914
1915    #[test]
1916    fn mutating_store_ops_are_state_writes_in_order_and_reads_are_not() {
1917        let model = agent_model("storeops", ORDER_SRC, "Order", "add");
1918        let kinds: Vec<(MessageKind, &str)> = model
1919            .messages
1920            .iter()
1921            .map(|m| (m.kind, m.label.as_str()))
1922            .collect();
1923        assert_eq!(
1924            kinds,
1925            [
1926                (MessageKind::Call, "bump()"),
1927                (MessageKind::Return, ""),
1928                (MessageKind::StateWrite, "items.put(sku, …)"),
1929                (MessageKind::StateWrite, "tally.update(…)"),
1930            ],
1931            "the agent call keeps its lifeline; `contains` is a read and shows nothing"
1932        );
1933    }
1934
1935    #[test]
1936    fn an_assignment_in_another_agent_is_still_a_write_of_its_own() {
1937        let model = agent_model("counter", ORDER_SRC, "Counter", "bump");
1938        assert_eq!(writes(&model), [("total := total + 1", None)]);
1939    }
1940
1941    #[test]
1942    fn a_store_field_shadowed_by_a_parameter_or_let_is_not_a_store_op() {
1943        // Parsed only — the store fields come from ORDER_SRC's checked `Order`.
1944        let shadowing = r#"context orders
1945agent Order {
1946  key id: String
1947  store items: Map[String, Int]
1948  on call byParam(items: List[Int]) -> Effect[()] {
1949    let _ <- items.put("a", 1)
1950    ()
1951  }
1952  on call byLet() -> Effect[()] {
1953    let tally = Thing()
1954    let _ <- tally.update((t) => t)
1955    let _ <- items.remove("a")
1956    ()
1957  }
1958}
1959"#;
1960        assert!(writes(&agent_model("shadow-param", shadowing, "Order", "byParam")).is_empty());
1961        assert_eq!(
1962            writes(&agent_model("shadow-let", shadowing, "Order", "byLet")),
1963            [("items.remove(\"a\")", None)],
1964            "only the unshadowed field's write is a note"
1965        );
1966    }
1967
1968    #[test]
1969    fn a_long_right_hand_side_is_truncated() {
1970        assert_eq!(truncate("short"), "short");
1971        let long = "a".repeat(40);
1972        let t = truncate(&long);
1973        assert_eq!(t.chars().count(), WRITE_LABEL_MAX);
1974        assert!(t.ends_with('…'));
1975    }
1976
1977    #[test]
1978    fn a_service_handler_emits_no_state_writes() {
1979        let root = setup_project("svc-nowrites", &[("ratelimit.bynk", RATELIMIT_SRC)]);
1980        let diag = crate::testkit::diagnose_project(&root);
1981        let info = diag.sequence_info.get("ratelimit").expect("info");
1982        let ctx = parse_context(RATELIMIT_SRC);
1983        let svc = find_service(&ctx, "api");
1984        let model = sequence_model(
1985            &svc.handlers[0],
1986            HandlerOwner::Service("api"),
1987            &svc.default_given,
1988            svc.default_by.as_ref(),
1989            Some(info),
1990        );
1991        assert!(writes(&model).is_empty());
1992    }
1993
1994    #[test]
1995    fn the_rate_limiters_own_hit_handler_shows_its_cell_update() {
1996        let root = setup_project("limiter-hit", &[("ratelimit.bynk", RATELIMIT_SRC)]);
1997        let diag = crate::testkit::diagnose_project(&root);
1998        let info = diag.sequence_info.get("ratelimit").expect("info");
1999        let ctx = parse_context(RATELIMIT_SRC);
2000        let a = find_agent(&ctx, "Limiter");
2001        let model = sequence_model(
2002            &a.handlers[0],
2003            HandlerOwner::Agent("Limiter"),
2004            &[],
2005            None,
2006            Some(info),
2007        );
2008        assert_eq!(writes(&model), [("count.update(…)", None)]);
2009    }
2010
2011    #[test]
2012    fn a_store_write_in_tail_position_is_a_note_and_not_also_a_reply() {
2013        // `Wallet.topUp`'s shape: the write is the handler's last expression.
2014        let model = agent_model("tail-write", ORDER_SRC, "Order", "bumpTally");
2015        assert_eq!(writes(&model), [("tally.update(…)", None)]);
2016        assert_eq!(model.messages.len(), 1, "no reply duplicating the write");
2017    }
2018
2019    #[test]
2020    fn a_store_write_as_an_expression_match_arm_is_a_note_in_that_arm() {
2021        // `Ledger.open`'s shape: `Ok(acct) => balances.put(acct, n)`.
2022        let model = agent_model("arm-write", ORDER_SRC, "Order", "putIfSome");
2023        assert_eq!(writes(&model), [("items.put(k, …)", Some(0))]);
2024        let arms = &model.blocks[0].branches;
2025        assert_eq!(arms[0].message_ids, [0]);
2026        assert_eq!(
2027            arms[0].reply, None,
2028            "the write is the arm's note, not its reply"
2029        );
2030        assert!(arms[1].message_ids.is_empty());
2031        assert_eq!(arms[1].reply.as_deref(), Some("Effect.pure(())"));
2032    }
2033
2034    #[test]
2035    fn an_assignment_to_a_name_that_is_not_a_store_field_is_not_labelled() {
2036        // Parsed only: a file with errors can carry a `:=` the checker refuses.
2037        let src = r#"context orders
2038agent Order {
2039  key id: String
2040  store items: Map[String, Int]
2041  on call bad() -> Effect[()] {
2042    nope := 1
2043    ()
2044  }
2045}
2046"#;
2047        assert!(writes(&agent_model("bad-assign", src, "Order", "bad")).is_empty());
2048    }
2049
2050    // -- Model-diagrams slice 3: `?` as `break`, triggers, agent keys, callees.
2051
2052    const QUESTION_SRC: &str = r#"context q
2053
2054service web from http by Visitor {
2055  on GET("/links/:code") (code: String) -> Effect[HttpResult[String]] {
2056    let stored = lookup(code)
2057    let raw = stored?
2058    Ok(raw)
2059  }
2060}
2061
2062service calls {
2063  on call(n: Int) -> Effect[Int] {
2064    let v = parse(n)?
2065    v
2066  }
2067}
2068"#;
2069
2070    #[test]
2071    fn a_question_mark_is_a_break_that_returns_early_to_the_principal() {
2072        let ctx = parse_context(QUESTION_SRC);
2073        let svc = find_service(&ctx, "web");
2074        let model = sequence_model(
2075            &svc.handlers[0],
2076            HandlerOwner::Service("web"),
2077            &svc.default_given,
2078            svc.default_by.as_ref(),
2079            None,
2080        );
2081        assert_eq!(model.blocks.len(), 1);
2082        let brk = &model.blocks[0];
2083        assert_eq!((brk.kind, brk.depth, brk.parent), (AltKind::Break, 0, None));
2084        assert_eq!(brk.branches.len(), 1);
2085        assert_eq!(brk.branches[0].label, "stored?");
2086        // With a principal the early return is a `Return` to the actor, inside
2087        // the block, and not also a note.
2088        assert_eq!(brk.branches[0].reply, None);
2089        let early: Vec<&Message> = brk.branches[0]
2090            .message_ids
2091            .iter()
2092            .map(|&i| &model.messages[i])
2093            .collect();
2094        assert_eq!(early.len(), 1);
2095        assert_eq!(early[0].kind, MessageKind::Return);
2096        assert_eq!(early[0].label, EARLY_RETURN);
2097        assert_eq!(early[0].block, Some(0));
2098        // The walk carries on after the `?`: the handler's own reply follows.
2099        let last = model.messages.last().expect("a final reply");
2100        assert_eq!(
2101            (last.kind, last.label.as_str(), last.block),
2102            (MessageKind::Return, "Ok(raw)", None)
2103        );
2104    }
2105
2106    #[test]
2107    fn a_question_mark_without_a_principal_replies_with_a_note() {
2108        let ctx = parse_context(QUESTION_SRC);
2109        let svc = find_service(&ctx, "calls");
2110        let model = sequence_model(
2111            &svc.handlers[0],
2112            HandlerOwner::Service("calls"),
2113            &[],
2114            None,
2115            None,
2116        );
2117        assert_eq!(model.blocks.len(), 1);
2118        assert_eq!(model.blocks[0].kind, AltKind::Break);
2119        assert_eq!(model.blocks[0].branches[0].label, "parse(n)?");
2120        assert_eq!(
2121            model.blocks[0].branches[0].reply.as_deref(),
2122            Some(EARLY_RETURN)
2123        );
2124        assert!(model.blocks[0].branches[0].message_ids.is_empty());
2125    }
2126
2127    #[test]
2128    fn the_model_names_its_trigger() {
2129        let ctx = parse_context(QUESTION_SRC);
2130        let web = find_service(&ctx, "web");
2131        let model = sequence_model(
2132            &web.handlers[0],
2133            HandlerOwner::Service("web"),
2134            &web.default_given,
2135            web.default_by.as_ref(),
2136            None,
2137        );
2138        assert_eq!(
2139            model.trigger,
2140            Trigger {
2141                kind: TriggerKind::Request,
2142                label: "GET /links/:code".to_string()
2143            }
2144        );
2145        let calls = find_service(&ctx, "calls");
2146        let model = sequence_model(
2147            &calls.handlers[0],
2148            HandlerOwner::Service("calls"),
2149            &[],
2150            None,
2151            None,
2152        );
2153        assert_eq!(
2154            model.trigger,
2155            Trigger {
2156                kind: TriggerKind::Call,
2157                label: "call".to_string()
2158            }
2159        );
2160    }
2161
2162    #[test]
2163    fn an_agent_call_carries_its_key_and_names_its_callee() {
2164        let root = setup_project("ratelimit-callee", &[("ratelimit.bynk", RATELIMIT_SRC)]);
2165        let diag = crate::testkit::diagnose_project(&root);
2166        let info = diag.sequence_info.get("ratelimit").expect("sequence_info");
2167        let ctx = parse_context(RATELIMIT_SRC);
2168        let svc = find_service(&ctx, "api");
2169        let model = sequence_model(
2170            &svc.handlers[0],
2171            HandlerOwner::Service("api"),
2172            &svc.default_given,
2173            svc.default_by.as_ref(),
2174            Some(info),
2175        );
2176        let limiter = model
2177            .participants
2178            .iter()
2179            .find(|p| p.kind == ParticipantKind::Agent)
2180            .expect("the agent lifeline");
2181        assert_eq!(limiter.key.as_deref(), Some("client"));
2182        let hit = model
2183            .messages
2184            .iter()
2185            .find(|m| m.kind == MessageKind::Call && m.to == limiter.id)
2186            .expect("the agent call");
2187        assert_eq!(
2188            hit.callee,
2189            Some(Callee {
2190                unit: None,
2191                owner: "Limiter".to_string(),
2192                method: Some("hit".to_string())
2193            })
2194        );
2195        // A capability op is not a boundary call: no callee.
2196        let now = model
2197            .messages
2198            .iter()
2199            .find(|m| m.kind == MessageKind::Call && m.label.starts_with("now"))
2200            .expect("the Clock call");
2201        assert_eq!(now.callee, None);
2202        // Returns never name a callee.
2203        assert!(
2204            model
2205                .messages
2206                .iter()
2207                .filter(|m| m.kind == MessageKind::Return)
2208                .all(|m| m.callee.is_none())
2209        );
2210    }
2211
2212    #[test]
2213    fn an_agent_called_with_different_keys_has_mixed_keys() {
2214        const SRC: &str = r#"context mixed
2215
2216agent Book {
2217  key channel: String
2218
2219  store count: Cell[Int]
2220
2221  on call add() -> Effect[Int] {
2222    1
2223  }
2224}
2225
2226service api {
2227  on call(a: String, b: String) -> Effect[Int] {
2228    let x <- Book(a).add()
2229    let y <- Book(b).add()
2230    x
2231  }
2232}
2233"#;
2234        let root = setup_project("mixed-keys", &[("mixed.bynk", SRC)]);
2235        let diag = crate::testkit::diagnose_project(&root);
2236        let info = diag.sequence_info.get("mixed").expect("sequence_info");
2237        let ctx = parse_context(SRC);
2238        let svc = find_service(&ctx, "api");
2239        let model = sequence_model(
2240            &svc.handlers[0],
2241            HandlerOwner::Service("api"),
2242            &[],
2243            None,
2244            Some(info),
2245        );
2246        let book = model
2247            .participants
2248            .iter()
2249            .find(|p| p.kind == ParticipantKind::Agent)
2250            .expect("the agent lifeline");
2251        assert_eq!(book.key.as_deref(), Some(MIXED_KEYS));
2252    }
2253
2254    #[test]
2255    fn a_cross_context_call_names_the_consumed_service() {
2256        let root = setup_project(
2257            "crossctx-callee",
2258            &[
2259                ("platform.bynk", PLATFORM_SRC),
2260                ("consumer.bynk", CONSUMER_SRC),
2261            ],
2262        );
2263        let diag = crate::testkit::diagnose_project(&root);
2264        let info = diag.sequence_info.get("consumer").expect("sequence_info");
2265        let ctx = parse_context(CONSUMER_SRC);
2266        let svc = find_service(&ctx, "api");
2267        let model = sequence_model(
2268            &svc.handlers[0],
2269            HandlerOwner::Service("api"),
2270            &svc.default_given,
2271            svc.default_by.as_ref(),
2272            Some(info),
2273        );
2274        assert_eq!(
2275            model.messages[0].callee,
2276            Some(Callee {
2277                unit: Some("platform".to_string()),
2278                owner: "Pinger".to_string(),
2279                method: None
2280            })
2281        );
2282    }
2283
2284    // -- Review follow-ups (#3651): `?` inside a branch, a boundary call as a
2285    // -- `?` operand, and a `?` past the depth cap.
2286
2287    const QUESTION_EDGES_SRC: &str = r#"context qe
2288
2289agent Limiter {
2290  key client: String
2291
2292  store count: Cell[Int]
2293
2294  on call hit(n: Int) -> Effect[Result[Int, String]] {
2295    Ok(n)
2296  }
2297}
2298
2299service api {
2300  on call(c: String, n: Int) -> Effect[Int] {
2301    if n > 0 {
2302      let v = parse(n)?
2303      v
2304    } else {
2305      0
2306    }
2307  }
2308
2309  on call(c: String, n: Int) -> Effect[Int] {
2310    let x <- Limiter(c).hit(n)?
2311    x
2312  }
2313}
2314"#;
2315
2316    #[test]
2317    fn a_question_mark_inside_a_branch_nests_under_it() {
2318        let ctx = parse_context(QUESTION_EDGES_SRC);
2319        let svc = find_service(&ctx, "api");
2320        let model = sequence_model(
2321            &svc.handlers[0],
2322            HandlerOwner::Service("api"),
2323            &[],
2324            None,
2325            None,
2326        );
2327        let kinds: Vec<(AltKind, Option<u32>, Option<u32>, u32)> = model
2328            .blocks
2329            .iter()
2330            .map(|b| (b.kind, b.parent, b.parent_branch, b.depth))
2331            .collect();
2332        assert_eq!(
2333            kinds,
2334            vec![
2335                (AltKind::If, None, None, 0),
2336                (AltKind::Break, Some(0), Some(0), 1)
2337            ]
2338        );
2339    }
2340
2341    #[test]
2342    fn a_boundary_call_under_a_question_mark_comes_before_its_break() {
2343        let root = setup_project("question-edges", &[("qe.bynk", QUESTION_EDGES_SRC)]);
2344        let diag = crate::testkit::diagnose_project(&root);
2345        let info = diag.sequence_info.get("qe").expect("sequence_info");
2346        let ctx = parse_context(QUESTION_EDGES_SRC);
2347        let svc = find_service(&ctx, "api");
2348        let model = sequence_model(
2349            &svc.handlers[1],
2350            HandlerOwner::Service("api"),
2351            &[],
2352            None,
2353            Some(info),
2354        );
2355        assert_eq!(model.messages[0].kind, MessageKind::Call);
2356        assert_eq!(
2357            model.messages[0].block, None,
2358            "the call is evaluated before the `?`"
2359        );
2360        assert_eq!(
2361            model.messages[0].callee,
2362            Some(Callee {
2363                unit: None,
2364                owner: "Limiter".to_string(),
2365                method: Some("hit".to_string())
2366            })
2367        );
2368        assert_eq!(model.messages[1].kind, MessageKind::Return);
2369        assert_eq!(model.blocks.len(), 1);
2370        assert_eq!(model.blocks[0].kind, AltKind::Break);
2371        assert_eq!(model.blocks[0].branches[0].label, "Limiter(c).hit(n)?");
2372    }
2373
2374    #[test]
2375    fn a_question_mark_past_the_cap_collapses() {
2376        let mut body = String::from("let v = parse(n)?\n v");
2377        for i in (0..MAX_BLOCK_DEPTH as usize).rev() {
2378            body = format!("if n > {i} {{ {body} }} else {{ 0 }}");
2379        }
2380        let src = format!(
2381            "context deepq\n\nservice api {{\n  on call(n: Int) -> Effect[Int] {{\n    {body}\n  }}\n}}\n"
2382        );
2383        let ctx = parse_context(&src);
2384        let svc = find_service(&ctx, "api");
2385        let model = sequence_model(
2386            &svc.handlers[0],
2387            HandlerOwner::Service("api"),
2388            &[],
2389            None,
2390            None,
2391        );
2392        assert!(
2393            model.blocks.iter().all(|b| b.kind != AltKind::Break),
2394            "no break past the cap"
2395        );
2396        let last = model.blocks.last().expect("a marker");
2397        assert_eq!(
2398            (last.kind, last.depth),
2399            (AltKind::Collapsed, MAX_BLOCK_DEPTH)
2400        );
2401    }
2402}