Skip to main content

logicaffeine_compile/
interpreter.rs

1//! Tree-walking interpreter for LOGOS imperative code.
2//!
3//! This module provides runtime execution of parsed LOGOS programs by
4//! walking the AST and executing statements/expressions directly. The
5//! interpreter is async-capable to support VFS operations.
6//!
7//! # Architecture
8//!
9//! ```text
10//! LOGOS AST
11//!     │
12//!     ▼
13//! ┌────────────┐
14//! │ Interpreter│ ──▶ Evaluate expressions
15//! │            │ ──▶ Execute statements
16//! │            │ ──▶ Manage scopes
17//! └────────────┘
18//!     │
19//!     ▼
20//! RuntimeValue results
21//! ```
22//!
23//! # Runtime Values
24//!
25//! The interpreter uses [`RuntimeValue`] to represent all values at runtime:
26//! - Primitives: `Int`, `Float`, `Bool`, `Text`, `Char`
27//! - Collections: `List`, `Tuple`, `Set`, `Map`
28//! - User types: `Struct`, `Inductive` (kernel-defined types)
29//!
30//! # Async Support
31//!
32//! The interpreter is async to support VFS file operations (OPFS on WASM,
33//! `tokio::fs` on native). All statement execution is `async fn`.
34
35use std::cell::RefCell;
36use std::collections::HashMap;
37use std::rc::Rc;
38use std::sync::Arc;
39
40use async_recursion::async_recursion;
41
42use crate::ast::stmt::{
43    BinaryOpKind, Block, ClosureBody, CompressionCodec, ExpectedOutput, Expr, Literal, MatchArm,
44    ReadSource, Stmt, TypeExpr,
45};
46
47/// The refusal for test-only statements reached outside the `largo test`
48/// runner's test mode (they are parser-gated to `## Test` bodies).
49const TEST_ONLY_STMT_ERR: &str =
50    "test-only statement outside the test runner — run it with `largo test`";
51
52/// Candidate shrinks for a value, smaller-first (toward the domain zero).
53fn shrink_candidates(v: &RuntimeValue) -> Vec<RuntimeValue> {
54    match v {
55        RuntimeValue::Int(0) => vec![],
56        RuntimeValue::Int(n) => {
57            let mut out = vec![RuntimeValue::Int(0), RuntimeValue::Int(n / 2)];
58            // step one toward zero (keeps a boundary counterexample minimal)
59            out.push(RuntimeValue::Int(if *n > 0 { n - 1 } else { n + 1 }));
60            out.retain(|c| c != v);
61            out
62        }
63        RuntimeValue::Bool(true) => vec![RuntimeValue::Bool(false)],
64        _ => vec![],
65    }
66}
67
68/// Map the language AST's observation category to the emission channel's.
69fn map_obs_category(c: logicaffeine_language::ast::stmt::ObsCategory) -> crate::observe::ObsCat {
70    use logicaffeine_language::ast::stmt::ObsCategory;
71    match c {
72        ObsCategory::Note => crate::observe::ObsCat::Note,
73        ObsCategory::Warn => crate::observe::ObsCat::Warn,
74        ObsCategory::Record => crate::observe::ObsCat::Record,
75    }
76}
77
78/// Format a failed `Expect` as a power-assert (Wave 5): the rendered condition,
79/// then each interesting subexpression annotated with its actual value, then an
80/// optional Socratic hint. Golden-locked by `failure_message_goldens`.
81fn format_expect_failure(
82    condition_text: &str,
83    annotations: &[(String, String)],
84    hint: Option<&str>,
85) -> String {
86    let mut s = format!("Expected that {condition_text}.");
87    for (text, value) in annotations {
88        s.push_str(&format!("\n    {text} → {value}"));
89    }
90    if let Some(h) = hint {
91        s.push_str(&format!("\n    Hint: {h}"));
92    }
93    s
94}
95use crate::intern::{Interner, Symbol};
96
97/// Map a surface `Send compressed with <codec>` choice to the wire codec.
98fn wire_compression_of(codec: CompressionCodec) -> crate::concurrency::marshal::WireCompression {
99    use crate::concurrency::marshal::WireCompression;
100    match codec {
101        CompressionCodec::Deflate => WireCompression::Deflate,
102        CompressionCodec::Lz4 => WireCompression::Lz4,
103        CompressionCodec::Zstd => WireCompression::Zstd,
104    }
105}
106use crate::analysis::{PolicyCondition, PolicyRegistry};
107
108// VFS imports for async file operations
109use crate::concurrency::bridge::{BlockingRequest, Yield, YieldFuture, YieldState};
110use crate::concurrency::driver::{ErrSink, InterpreterTask};
111use crate::concurrency::marshal;
112#[cfg(not(target_arch = "wasm32"))]
113use crate::semantics::world::PageWorld;
114use logicaffeine_runtime::{ChanId, RtPayload, SelectArm, TaskId};
115use logicaffeine_system::fs::Vfs;
116
117/// Callback type for streaming output from the interpreter.
118/// Called each time `Show` executes with the output line.
119pub type OutputCallback = Rc<RefCell<dyn FnMut(String)>>;
120
121/// Runtime values during LOGOS interpretation.
122///
123/// Represents all possible values that can exist at runtime when executing
124/// a LOGOS program. Includes primitives, collections, user-defined structs,
125/// and kernel inductive types.
126/// User-defined struct with named fields (boxed to reduce enum size).
127#[derive(Debug, Clone)]
128pub struct StructValue {
129    pub type_name: String,
130    pub fields: HashMap<String, RuntimeValue>,
131}
132
133/// A place a statement writes through: a binding (`xs`), or a path of fields and items rooted at
134/// one (`b's tape`, `item 2 of b's rows`, `b's inner's n`), its item keys already evaluated.
135struct Place {
136    root: Symbol,
137    steps: Vec<PlaceStep>,
138}
139
140/// One step from a value into a part of it.
141enum PlaceStep {
142    /// `b's tape`
143    Field(String),
144    /// `item k of xs` — a 1-based position in a list, a key in a map, a field name in a record.
145    Item(RuntimeValue),
146}
147
148/// A [`Place`] before its item keys are evaluated.
149enum PlaceShape<'e, 'a> {
150    Field(Symbol),
151    Item(&'e Expr<'a>),
152}
153
154/// The shape of `e` as a place — `None` for an expression that names no place (a call, a
155/// literal, arithmetic).
156fn place_shape<'e, 'a>(e: &'e Expr<'a>) -> Option<(Symbol, Vec<PlaceShape<'e, 'a>>)> {
157    match e {
158        Expr::Identifier(root) => Some((*root, Vec::new())),
159        Expr::FieldAccess { object, field } => {
160            let (root, mut steps) = place_shape(object)?;
161            steps.push(PlaceShape::Field(*field));
162            Some((root, steps))
163        }
164        Expr::Index { collection, index } => {
165            let (root, mut steps) = place_shape(collection)?;
166            steps.push(PlaceShape::Item(index));
167            Some((root, steps))
168        }
169        _ => None,
170    }
171}
172
173/// Copy-on-write: a collection another binding shares is replaced by a copy of its own before a
174/// write reaches it. The copy is one level deep; a collection nested inside it is still shared
175/// until a write reaches THAT, which copies it in turn.
176fn own_collection(value: &mut RuntimeValue) {
177    fn shared<T>(rc: &Rc<T>) -> bool {
178        Rc::strong_count(rc) > 1 || Rc::weak_count(rc) > 0
179    }
180    match value {
181        RuntimeValue::List(rc) if shared(rc) => {
182            let own = Rc::new(RefCell::new(rc.borrow().clone()));
183            *rc = own;
184        }
185        RuntimeValue::Map(rc) if shared(rc) => {
186            let own = Rc::new(RefCell::new(rc.borrow().clone()));
187            *rc = own;
188        }
189        RuntimeValue::Set(rc) if shared(rc) => {
190            let own = Rc::new(RefCell::new(rc.borrow().clone()));
191            *rc = own;
192        }
193        _ => {}
194    }
195}
196
197/// The part of `value` one step names, to write through — `None` when there is no such part or
198/// the collection is shared. A packed list is materialized before lending an element, since
199/// its slot must hold `Nothing` until the mutable parameter returns.
200fn step_into<'v>(value: &'v mut RuntimeValue, step: &PlaceStep) -> Option<&'v mut RuntimeValue> {
201    match (value, step) {
202        (RuntimeValue::Struct(s), PlaceStep::Field(name)) => s.fields.get_mut(name),
203        (RuntimeValue::Struct(s), PlaceStep::Item(RuntimeValue::Text(name))) => {
204            s.fields.get_mut(name.as_str())
205        }
206        (RuntimeValue::List(rc), PlaceStep::Item(RuntimeValue::Int(k))) => {
207            let items = Rc::get_mut(rc)?.get_mut();
208            let position = logicaffeine_data::logos_offset(*k, items.len())?;
209            items.make_boxed().get_mut(position)
210        }
211        (RuntimeValue::Map(rc), PlaceStep::Item(key)) => Rc::get_mut(rc)?.get_mut().get_mut(key),
212        _ => None,
213    }
214}
215
216/// The value a declared type starts at, when a slot names a type and supplies no value of its own.
217///
218/// ★ ONE TABLE, EVERY READER. This was written out TWICE verbatim — once on the sync `new` path and
219/// once on the async one — which is the same shape as the two copies of the event vocabulary that
220/// drifted apart in both directions (`SELECTOR_EVENTS`: "it is one vocabulary, so it is one table,
221/// and both readers ask it"). Two copies of a type table disagree the first time somebody adds a
222/// type to one of them, and a CRDT field that silently defaults to `Nothing` on one path is a
223/// replica that never converges.
224pub fn default_for_declared_type(type_name: &str) -> RuntimeValue {
225    if let Some(c) = crdt_for_declared_type(type_name) {
226        return c;
227    }
228    match type_name {
229        "Int" | "Element" | "Event" | "View" | "Byte" => RuntimeValue::Int(0),
230        "Float" => RuntimeValue::Float(0.0),
231        "Bool" => RuntimeValue::Bool(false),
232        "Text" | "String" => RuntimeValue::Text(Rc::new(String::new())),
233        "Char" => RuntimeValue::Char('\0'),
234        "Seq" | "List" => RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(Vec::new())))),
235        "Set" | "HashSet" => RuntimeValue::Set(Rc::new(RefCell::new(vec![]))),
236        "Map" | "HashMap" => RuntimeValue::Map(Rc::new(RefCell::new(MapStorage::default()))),
237        _ => RuntimeValue::Nothing,
238    }
239}
240
241/// A fresh, empty CRDT replica for a declared CRDT type name, or `None` for a type that is not one.
242///
243/// A `Shared` struct's CRDT fields default to an empty LIVE CRDT, mirroring the compiled tier's
244/// `ORSet`/`RGA` field. Counter fields are per-replica CRDTs too (`GCounter`/`PNCounter`), so their
245/// merge is idempotent — a bare Int would merge by overwrite and lose concurrent increments.
246///
247/// Split out from [`default_for_declared_type`] because the CRDT half has a SECOND question to
248/// answer that the scalar half does not: "is this name a CRDT at all?" — which is what lets a
249/// declared type decide whether a slot holds a converging value, without that decision being
250/// spelled out again at every site that needs it.
251pub fn crdt_for_declared_type(type_name: &str) -> Option<RuntimeValue> {
252    let kind = crate::semantics::crdt::CrdtKind::of_type_name(type_name)?;
253    Some(RuntimeValue::Crdt(Rc::new(RefCell::new(kind.fresh()))))
254}
255
256/// Whether a declared type name is a COUNTER CRDT — one whose readable value is an Int total.
257///
258/// The counters are the CRDTs an Int literal can initialize: `Let n: Tally be 5.` is a counter at
259/// five, and the reference tier already projects a counter to its Int total on the wire. A set or
260/// a sequence has no such reading, so an Int beside one stays an error.
261pub fn is_counter_type(type_name: &str) -> bool {
262    matches!(
263        type_name,
264        "ConvergentCount" | "GCounter" | "Tally" | "PNCounter"
265    )
266}
267
268/// Kernel inductive value (boxed to reduce enum size).
269#[derive(Debug, Clone)]
270pub struct InductiveValue {
271    pub inductive_type: String,
272    pub constructor: String,
273    pub args: Vec<RuntimeValue>,
274}
275
276/// A present Option: a real two-constructor inductive, not the payload itself.
277///
278/// One constructor for every producer, because the tag each backend derives its discriminant from
279/// is the CONSTRUCTOR NAME — a typo here would be a silent tier divergence, not a compile error.
280pub(crate) fn option_some(inner: RuntimeValue) -> RuntimeValue {
281    RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
282        inductive_type: "Option".to_string(),
283        constructor: "Some".to_string(),
284        args: vec![inner],
285    }))
286}
287
288/// An absent Option. Equal to `nothing` by R2, so every `x is equal to nothing` still holds.
289pub(crate) fn option_none() -> RuntimeValue {
290    RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
291        inductive_type: "Option".to_string(),
292        constructor: "None".to_string(),
293        args: Vec::new(),
294    }))
295}
296
297/// First-class closure value (boxed to reduce enum size).
298#[derive(Debug, Clone)]
299pub struct ClosureValue {
300    pub body_index: usize,
301    pub captured_env: HashMap<Symbol, RuntimeValue>,
302    pub param_names: Vec<Symbol>,
303    /// A SHIPPED pure function carries its sandboxed generator body directly (self-
304    /// contained — no `body_index` into any arena), so it can cross the wire and be
305    /// invoked on a receiver that never compiled it. `None` for ordinary closures, whose
306    /// body lives in `closure_bodies[body_index]`. Set only by `T_FUNC` decode (and the
307    /// gated `Send computed` lowering); the call path evaluates it via the sandbox.
308    pub generated: Option<std::rc::Rc<crate::concurrency::marshal::GenExpr>>,
309}
310
311/// The Map payload behind `RuntimeValue::Map`. INSERTION-ORDERED (`IndexMap`):
312/// iteration, display, and marshaling follow the order keys were first
313/// inserted — the LOGOS `Map` contract, identical across the tree-walker, the
314/// VM, the AOT `LogosMap`, and the direct-WASM linear map. FxHash instead of
315/// the standard library's SipHash: map-heavy programs hash on every
316/// get/insert, and the keys here are small values (ints, short texts) where
317/// Fx is several times faster — with no DoS-resistance requirement (a
318/// single-program interpreter hashing its own program's keys). NOTE: removal
319/// must go through `shift_remove` (order-preserving), never `swap_remove`.
320pub type MapStorage = indexmap::IndexMap<
321    RuntimeValue,
322    RuntimeValue,
323    std::hash::BuildHasherDefault<rustc_hash::FxHasher>,
324>;
325
326fn apply_capacity_hint(value: RuntimeValue, capacity: i64) -> RuntimeValue {
327    let capacity = capacity.max(0) as usize;
328    match &value {
329        RuntimeValue::List(list) => list.borrow_mut().reserve_hint(capacity),
330        RuntimeValue::Set(set) => {
331            let _ = set.borrow_mut().try_reserve(capacity);
332        }
333        RuntimeValue::Map(map) => {
334            let _ = map.borrow_mut().try_reserve(capacity);
335        }
336        _ => {}
337    }
338    match value {
339        RuntimeValue::Text(text) if text.capacity() < capacity => {
340            let mut reserved = String::with_capacity(capacity);
341            reserved.push_str(&text);
342            RuntimeValue::Text(Rc::new(reserved))
343        }
344        other => other,
345    }
346}
347
348/// The List payload behind `RuntimeValue::List`: homogeneous all-Int and
349/// all-Float lists store UNBOXED vectors (cache-dense, and the JIT can pin a
350/// raw pointer to them); anything else boxes. The repr lives INSIDE the
351/// `Rc<RefCell<…>>`, so promotion re-tags the payload in place and every
352/// alias observes it — reference semantics and Rc identity are untouched.
353/// An EMPTY list is vacuously `Ints` and re-tags freely on its first push.
354///
355/// Hot paths take `&self`/`&mut self` borrows only — no Rc refcount traffic.
356/// `Clone` snapshots a buffer's contents for the region deopt-rollback of an
357/// in-place-mutated array (see `crate::vm::native_tier::ArrayPin::mutated`).
358#[derive(Debug, Clone)]
359pub enum ListRepr {
360    Boxed(Vec<RuntimeValue>),
361    Ints(Vec<i64>),
362    /// A proven-narrowable Int buffer stored half-width: every element fits
363    /// `i32` (the narrowing proof in `codegen::narrow`), so the buffer is
364    /// `Vec<i32>` — half the footprint and cache pressure. Reads SIGN-EXTEND
365    /// (`x as i64`, lossless); writes TRUNCATE (`x as i32`, lossless *because*
366    /// of the proof, debug-asserted in range). A write outside `i32` range
367    /// PROMOTES the buffer back to a full-width `Ints` (the proof was wrong —
368    /// soundness over speed), so observable values never differ from `Ints`.
369    /// Created only behind `LOGOS_NARROW_VM` for narrowable declarations.
370    IntsI32(Vec<i32>),
371    Floats(Vec<f64>),
372    Bools(Vec<bool>),
373    /// A packed `Word32` ring list — each element the MASKED value (`0 ≤ x < 2³²`) stored in an `i64`, so the
374    /// forge pins it with the EXACT IntList buffer machinery (8-byte loads); the ONLY difference from `Ints`
375    /// is that a read yields a `Word(W32)` (and the forge tags an indexed load `Kind::Word32`), never an Int.
376    /// This is what lets a `Seq of Word32` (a sha256 message schedule / round-constant table) pin + tier.
377    /// Cold paths (wire codec, WASM lowering, structural mutation) de-optimize via `make_boxed`.
378    Words32(Vec<i64>),
379    /// A flat string array (Arrow-style): all element bytes concatenated in one
380    /// `data` buffer, with `ends[i]` the exclusive end offset of element `i` (so
381    /// element `i` is `data[ends[i-1]..ends[i]]`, `ends.len()` == the count). This
382    /// is the columnar layout that lets a string list pack and load as two bulk
383    /// copies instead of one heap allocation per string — the same treatment the
384    /// numeric variants already get. It is read-optimized: an element materializes
385    /// to `Text` only when accessed, and any mutation promotes the buffer to
386    /// `Boxed`. The wire decoder builds it directly; normal code paths are
387    /// unaffected (a string *literal* stays `Boxed`).
388    ///
389    /// `cache` is a LAZY memo: empty until the first `get`, so ship/load/iterate
390    /// pay nothing, and repeated indexing of the same element returns a cheap `Rc`
391    /// clone instead of re-materializing — best of both worlds (flat to move,
392    /// boxed-cheap to re-read).
393    Strings {
394        data: Vec<u8>,
395        ends: Vec<u32>,
396        cache: RefCell<Vec<Option<Rc<String>>>>,
397    },
398    /// A homogeneous struct list stored COLUMNAR (struct-of-arrays): instead of N
399    /// boxed `StructValue`s (each a heap `Box` + a `HashMap`), the schema is held
400    /// once (`type_name` + canonical sorted `field_names`) and each field becomes a
401    /// packed column — itself a `ListRepr`, so an int field is a `Vec<i64>`, a bool
402    /// field is bit-packed, a nested struct field is recursively columnar. Zero
403    /// per-row `Box`/`HashMap`; field access is a column index; the wire encoder
404    /// memcpy-streams the columns. Reads reconstruct a `StructValue` on demand
405    /// (`get`); ANY mutation de-columnarizes to `Boxed` first (`make_boxed`), so
406    /// reference semantics are exactly those of a boxed list. Built by `from_values`
407    /// for genuinely-homogeneous struct lists (same type, same field set); ragged
408    /// lists stay `Boxed`. `columns` are all the same length (the row count).
409    Structs {
410        type_name: String,
411        field_names: Vec<String>,
412        columns: Vec<ListRepr>,
413    },
414    /// A homogeneous inductive (enum/ADT) list stored COLUMNAR as a tagged union:
415    /// instead of N boxed `InductiveValue`s, the type name is held once, the distinct
416    /// constructor names are dictionaried (`ctor_dict`), each row carries a small
417    /// constructor index (`ctors`), and the constructor ARGUMENTS are packed DENSE
418    /// per constructor — `arg_cols[c][j]` is the column of argument `j` across only
419    /// the rows whose constructor is `c` (so `arg_cols[c].len()` is constructor `c`'s
420    /// arity, and each inner column's length is the count of rows with constructor
421    /// `c`). `ranks[i]` is row `i`'s rank within its constructor, so `get` is O(1).
422    /// A nullary enum collapses to just the dictionary + index column (no arg cols).
423    /// Built by `from_values` for same-type enum lists; ragged/mixed-type lists stay
424    /// `Boxed`. Any mutation de-columnarizes via `make_boxed`.
425    Inductives {
426        inductive_type: String,
427        ctor_dict: Vec<String>,
428        ctors: Vec<u32>,
429        ranks: Vec<u32>,
430        arg_cols: Vec<Vec<ListRepr>>,
431    },
432    /// A received record-list held as RAW WIRE BYTES, decoded LAZILY — the production zero-copy
433    /// receive (Cap'n Proto's "read in place, only what you touch"). `bytes` is the full received
434    /// frame whose top-level value is a `T_STRUCTS_VIEW` record list; the schema (`type_name`,
435    /// `field_names`, `len`) is read ONCE from the header, so `len` and shape are O(1) with ZERO
436    /// rows decoded. Field access reads a single cell in place via `WireView::structs_row_field`
437    /// (O(1), no allocation for the untouched rows/fields); `get(i)` reconstructs one `StructValue`
438    /// on demand. ANY mutation de-lazies to `Boxed` first (`make_boxed`), so reference semantics are
439    /// exactly those of a boxed list. Built only by the `view` receive path; normal code is
440    /// unaffected.
441    WireStructs {
442        bytes: Rc<Vec<u8>>,
443        type_name: String,
444        field_names: Vec<String>,
445        len: usize,
446    },
447    /// A received NUMERIC column (`T_INTS_ALIGNED`/`T_FLOATS_ALIGNED`) held as RAW WIRE BYTES and
448    /// read ZERO-COPY: the 8-byte-aligned blob is the array. `len` is O(1) from the header (no
449    /// decode); `get(i)` reads element `i` straight out of the borrowed `&[i64]`/`&[f64]` (capnp's
450    /// `List<i64>` read-in-place); a partial read touches only what it reads. ANY mutation
451    /// materializes to `Ints`/`Floats` first. Built only by the `view` receive path for an aligned
452    /// column whose blob is 8-aligned in the received buffer (else the caller decodes eagerly).
453    WireColumn {
454        bytes: Rc<Vec<u8>>,
455        len: usize,
456        floats: bool,
457    },
458}
459
460impl ListRepr {
461    fn reserve_hint(&mut self, capacity: usize) {
462        match self {
463            ListRepr::Boxed(v) => {
464                let _ = v.try_reserve(capacity.saturating_sub(v.len()));
465            }
466            ListRepr::Ints(v) => {
467                let _ = v.try_reserve(capacity.saturating_sub(v.len()));
468            }
469            ListRepr::IntsI32(v) => {
470                let _ = v.try_reserve(capacity.saturating_sub(v.len()));
471            }
472            ListRepr::Floats(v) => {
473                let _ = v.try_reserve(capacity.saturating_sub(v.len()));
474            }
475            ListRepr::Bools(v) => {
476                let _ = v.try_reserve(capacity.saturating_sub(v.len()));
477            }
478            ListRepr::Words32(v) => {
479                let _ = v.try_reserve(capacity.saturating_sub(v.len()));
480            }
481            ListRepr::Strings { ends, .. } => {
482                let _ = ends.try_reserve(capacity.saturating_sub(ends.len()));
483            }
484            _ => {}
485        }
486    }
487
488    /// Wrap a received record-list frame (`T_STRUCTS_VIEW` top-level) as a lazy zero-copy backing.
489    /// `None` if the bytes are not a self-describing record-list view (the caller decodes eagerly).
490    pub fn from_record_list_view(bytes: Rc<Vec<u8>>) -> Option<ListRepr> {
491        let (type_name, field_names, len) = {
492            let view = crate::concurrency::marshal::view_message(&bytes)?;
493            view.structs_schema()?
494        };
495        Some(ListRepr::WireStructs {
496            bytes,
497            type_name,
498            field_names,
499            len,
500        })
501    }
502
503    /// Wrap a received aligned numeric column (`T_INTS_ALIGNED`/`T_FLOATS_ALIGNED`) as a lazy
504    /// zero-copy backing. `None` unless the blob reads as an 8-aligned `&[i64]`/`&[f64]` in this
505    /// buffer (so every later read is a sound slice cast); the caller then decodes eagerly.
506    pub fn from_aligned_column_view(bytes: Rc<Vec<u8>>) -> Option<ListRepr> {
507        let view = crate::concurrency::marshal::view_message(&bytes)?;
508        if let Some(s) = view.as_i64_slice() {
509            return Some(ListRepr::WireColumn {
510                len: s.len(),
511                floats: false,
512                bytes,
513            });
514        }
515        if let Some(s) = view.as_f64_slice() {
516            return Some(ListRepr::WireColumn {
517                len: s.len(),
518                floats: true,
519                bytes,
520            });
521        }
522        None
523    }
524
525    /// Wrap ANY received self-describing view (record list OR aligned numeric column) as a lazy
526    /// zero-copy backing, or `None` for anything else (the caller decodes eagerly).
527    pub fn from_received_view(bytes: Rc<Vec<u8>>) -> Option<ListRepr> {
528        Self::from_record_list_view(bytes.clone()).or_else(|| Self::from_aligned_column_view(bytes))
529    }
530
531    fn wire_column_get(bytes: &[u8], floats: bool, i: usize) -> Option<RuntimeValue> {
532        let view = crate::concurrency::marshal::view_message(bytes)?;
533        if floats {
534            view.as_f64_slice()?.get(i).map(|&f| RuntimeValue::Float(f))
535        } else {
536            view.as_i64_slice()?.get(i).map(|&n| RuntimeValue::Int(n))
537        }
538    }
539
540    fn wire_column_to_values(bytes: &[u8], floats: bool) -> Vec<RuntimeValue> {
541        let Some(view) = crate::concurrency::marshal::view_message(bytes) else {
542            return Vec::new();
543        };
544        if floats {
545            view.as_f64_slice()
546                .map(|s| s.iter().map(|&f| RuntimeValue::Float(f)).collect())
547                .unwrap_or_default()
548        } else {
549            view.as_i64_slice()
550                .map(|s| s.iter().map(|&n| RuntimeValue::Int(n)).collect())
551                .unwrap_or_default()
552        }
553    }
554
555    /// Materialize a single row of a lazy `WireStructs` into an owned `StructValue` by reading each
556    /// field cell in place. Shared by `get` and `make_boxed`.
557    fn wire_struct_row(
558        bytes: &[u8],
559        type_name: &str,
560        field_names: &[String],
561        len: usize,
562        i: usize,
563    ) -> Option<RuntimeValue> {
564        if i >= len {
565            return None;
566        }
567        let view = crate::concurrency::marshal::view_message(bytes)?;
568        let mut fields = HashMap::with_capacity(field_names.len());
569        for name in field_names {
570            let cell = view.structs_row_field_value(i, name)?;
571            fields.insert(name.clone(), cell);
572        }
573        Some(RuntimeValue::Struct(Box::new(StructValue {
574            type_name: type_name.to_string(),
575            fields,
576        })))
577    }
578}
579
580impl ListRepr {
581    pub fn from_values(values: Vec<RuntimeValue>) -> ListRepr {
582        if values.iter().all(|v| matches!(v, RuntimeValue::Int(_))) {
583            ListRepr::Ints(
584                values
585                    .into_iter()
586                    .map(|v| match v {
587                        RuntimeValue::Int(n) => n,
588                        _ => unreachable!(),
589                    })
590                    .collect(),
591            )
592        } else if values.iter().all(|v| matches!(v, RuntimeValue::Float(_))) {
593            ListRepr::Floats(
594                values
595                    .into_iter()
596                    .map(|v| match v {
597                        RuntimeValue::Float(f) => f,
598                        _ => unreachable!(),
599                    })
600                    .collect(),
601            )
602        } else if values.iter().all(|v| matches!(v, RuntimeValue::Bool(_))) {
603            ListRepr::Bools(
604                values
605                    .into_iter()
606                    .map(|v| match v {
607                        RuntimeValue::Bool(b) => b,
608                        _ => unreachable!(),
609                    })
610                    .collect(),
611            )
612        } else if !values.is_empty()
613            && values
614                .iter()
615                .all(|v| matches!(v, RuntimeValue::Word(logicaffeine_base::WordVal::W32(_))))
616        {
617            // A homogeneous `Word32` list packs to `Vec<i64>` (masked), so the forge pins it as an IntList
618            // buffer and tags reads `Word32` — a `Seq of Word32` (sha256 schedule/constants) becomes tierable.
619            ListRepr::Words32(
620                values
621                    .into_iter()
622                    .map(|v| match v {
623                        RuntimeValue::Word(logicaffeine_base::WordVal::W32(w)) => w.0 as i64,
624                        _ => unreachable!(),
625                    })
626                    .collect(),
627            )
628        } else if !values.is_empty() && values.iter().all(|v| matches!(v, RuntimeValue::Text(_))) {
629            // A homogeneous string list de-boxes to one flat contiguous buffer (bytes + end
630            // offsets). It encodes as a single memcpy of the bytes — and the wire form is
631            // byte-identical to the boxed path — instead of one scattered copy per string.
632            let mut data = Vec::new();
633            let mut ends = Vec::with_capacity(values.len());
634            for v in &values {
635                if let RuntimeValue::Text(s) = v {
636                    data.extend_from_slice(s.as_bytes());
637                    ends.push(data.len() as u32);
638                }
639            }
640            ListRepr::strings(data, ends)
641        } else if let Some((type_name, field_names)) = Self::struct_schema(&values) {
642            // A homogeneous struct list de-boxes to columns: one packed `ListRepr`
643            // per field (recursively, so nested structs stay columnar too).
644            let columns = field_names
645                .iter()
646                .map(|fname| {
647                    ListRepr::from_values(
648                        values
649                            .iter()
650                            .map(|v| match v {
651                                RuntimeValue::Struct(sv) => sv.fields.get(fname).cloned().unwrap(),
652                                _ => unreachable!("struct_schema guaranteed all-struct"),
653                            })
654                            .collect(),
655                    )
656                })
657                .collect();
658            ListRepr::Structs {
659                type_name,
660                field_names,
661                columns,
662            }
663        } else if let Some(inductives) = Self::build_inductives(&values) {
664            inductives
665        } else {
666            ListRepr::Boxed(values)
667        }
668    }
669
670    /// Build a columnar [`ListRepr::Inductives`] from a homogeneous enum list (all
671    /// the same `inductive_type`, each constructor used at a consistent arity).
672    /// `None` if not a uniform enum list (the list stays boxed). Arguments are
673    /// grouped DENSE per constructor and each group packed via `from_values`.
674    pub(crate) fn build_inductives(values: &[RuntimeValue]) -> Option<ListRepr> {
675        let inductive_type = match values.first()? {
676            RuntimeValue::Inductive(i) => i.inductive_type.clone(),
677            _ => return None,
678        };
679        let mut ctor_dict: Vec<String> = Vec::new();
680        let mut ctors: Vec<u32> = Vec::with_capacity(values.len());
681        let mut ranks: Vec<u32> = Vec::with_capacity(values.len());
682        let mut counts: Vec<u32> = Vec::new();
683        // grouped[c][j] = the j-th argument across rows whose constructor is `c`.
684        let mut grouped: Vec<Vec<Vec<RuntimeValue>>> = Vec::new();
685        for v in values {
686            let iv = match v {
687                RuntimeValue::Inductive(i) if i.inductive_type == inductive_type => i,
688                _ => return None,
689            };
690            let c = match ctor_dict.iter().position(|n| n == &iv.constructor) {
691                Some(c) => {
692                    if grouped[c].len() != iv.args.len() {
693                        return None; // a constructor used at inconsistent arity
694                    }
695                    c
696                }
697                None => {
698                    ctor_dict.push(iv.constructor.clone());
699                    counts.push(0);
700                    grouped.push(vec![Vec::new(); iv.args.len()]);
701                    ctor_dict.len() - 1
702                }
703            };
704            ctors.push(c as u32);
705            ranks.push(counts[c]);
706            counts[c] += 1;
707            for (j, a) in iv.args.iter().enumerate() {
708                grouped[c][j].push(a.clone());
709            }
710        }
711        let arg_cols: Vec<Vec<ListRepr>> = grouped
712            .into_iter()
713            .map(|cols| cols.into_iter().map(ListRepr::from_values).collect())
714            .collect();
715        Some(ListRepr::Inductives {
716            inductive_type,
717            ctor_dict,
718            ctors,
719            ranks,
720            arg_cols,
721        })
722    }
723
724    /// Reconstruct row `i` of a columnar enum store as a boxed `InductiveValue`.
725    fn inductive_row(
726        inductive_type: &str,
727        ctor_dict: &[String],
728        ctors: &[u32],
729        ranks: &[u32],
730        arg_cols: &[Vec<ListRepr>],
731        i: usize,
732    ) -> Option<RuntimeValue> {
733        let c = *ctors.get(i)? as usize;
734        let r = ranks[i] as usize;
735        let mut args = Vec::with_capacity(arg_cols[c].len());
736        for col in &arg_cols[c] {
737            args.push(col.get(r)?);
738        }
739        Some(RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
740            inductive_type: inductive_type.to_string(),
741            constructor: ctor_dict[c].clone(),
742            args,
743        })))
744    }
745
746    /// If `values` is a non-empty run of structs that all share one `type_name` and
747    /// the same field-name set, return `(type_name, sorted_field_names)` — the schema
748    /// for a columnar [`ListRepr::Structs`]. `None` otherwise (the list stays boxed).
749    /// Fields are sorted so the columnar order is canonical and stable.
750    fn struct_schema(values: &[RuntimeValue]) -> Option<(String, Vec<String>)> {
751        let first = match values.first()? {
752            RuntimeValue::Struct(s) => s,
753            _ => return None,
754        };
755        let mut names: Vec<String> = first.fields.keys().cloned().collect();
756        names.sort();
757        // A columnar store needs ≥1 column to carry the row count — a zero-field
758        // struct list stays boxed.
759        if names.is_empty() {
760            return None;
761        }
762        for item in values {
763            match item {
764                RuntimeValue::Struct(s)
765                    if s.type_name == first.type_name
766                        && s.fields.len() == names.len()
767                        && names.iter().all(|n| s.fields.contains_key(n)) => {}
768                _ => return None,
769            }
770        }
771        Some((first.type_name.clone(), names))
772    }
773
774    /// Reconstruct row `i` of a columnar struct store as a boxed `StructValue`.
775    fn struct_row(
776        type_name: &str,
777        field_names: &[String],
778        columns: &[ListRepr],
779        i: usize,
780    ) -> Option<RuntimeValue> {
781        if i >= columns.first().map_or(0, |c| c.len()) {
782            return None;
783        }
784        let mut fields = std::collections::HashMap::with_capacity(field_names.len());
785        for (j, fname) in field_names.iter().enumerate() {
786            fields.insert(fname.clone(), columns[j].get(i)?);
787        }
788        Some(RuntimeValue::Struct(Box::new(StructValue {
789            type_name: type_name.to_string(),
790            fields,
791        })))
792    }
793
794    /// A flat string buffer with an empty (lazy) materialization cache.
795    pub fn strings(data: Vec<u8>, ends: Vec<u32>) -> ListRepr {
796        ListRepr::Strings {
797            data,
798            ends,
799            cache: RefCell::new(Vec::new()),
800        }
801    }
802
803    /// Element `i` of a flat `Strings` buffer as an owned `String` (UTF-8 was
804    /// validated when the buffer was built, but we re-check rather than risk UB).
805    fn string_at(data: &[u8], ends: &[u32], i: usize) -> Option<String> {
806        let end = *ends.get(i)? as usize;
807        let start = if i == 0 { 0 } else { ends[i - 1] as usize };
808        std::str::from_utf8(data.get(start..end)?)
809            .ok()
810            .map(str::to_string)
811    }
812
813    pub fn len(&self) -> usize {
814        match self {
815            ListRepr::Boxed(v) => v.len(),
816            ListRepr::Ints(v) => v.len(),
817            ListRepr::IntsI32(v) => v.len(),
818            ListRepr::Words32(v) => v.len(),
819            ListRepr::Floats(v) => v.len(),
820            ListRepr::Bools(v) => v.len(),
821            ListRepr::Strings { ends, .. } => ends.len(),
822            ListRepr::Structs { columns, .. } => columns.first().map_or(0, |c| c.len()),
823            ListRepr::Inductives { ctors, .. } => ctors.len(),
824            ListRepr::WireStructs { len, .. } | ListRepr::WireColumn { len, .. } => *len,
825        }
826    }
827
828    pub fn is_empty(&self) -> bool {
829        self.len() == 0
830    }
831
832    /// A human label for the underlying storage layout — for the debugger's memory
833    /// view. It teaches that a list of ints is a *packed* `Vec<i64>` (not boxed
834    /// values), a struct list is columnar (struct-of-arrays), and so on: the dense
835    /// representations the VM picks automatically.
836    pub fn storage_label(&self) -> &'static str {
837        match self {
838            ListRepr::Boxed(_) => "boxed values",
839            ListRepr::Ints(_) => "packed Vec<i64>",
840            ListRepr::IntsI32(_) => "packed Vec<i32> (narrowed)",
841            ListRepr::Words32(_) => "packed Vec<i64> (word32)",
842            ListRepr::Floats(_) => "packed Vec<f64>",
843            ListRepr::Bools(_) => "packed Vec<bool>",
844            ListRepr::Strings { .. } => "flat string buffer",
845            ListRepr::Structs { .. } => "columnar (struct-of-arrays)",
846            ListRepr::Inductives { .. } => "columnar tagged-union",
847            ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => "wire view (lazy)",
848        }
849    }
850
851    /// Drop every element past `n` (no-op when already `<= n`). The region
852    /// deopt path uses this to roll a pushed buffer back to its entry length
853    /// so discard-and-replay re-pushes cleanly instead of duplicating.
854    pub fn truncate(&mut self, n: usize) {
855        match self {
856            ListRepr::Boxed(v) => v.truncate(n),
857            ListRepr::Ints(v) => v.truncate(n),
858            ListRepr::IntsI32(v) => v.truncate(n),
859            ListRepr::Words32(v) => v.truncate(n),
860            ListRepr::Floats(v) => v.truncate(n),
861            ListRepr::Bools(v) => v.truncate(n),
862            ListRepr::Strings { data, ends, cache } => {
863                if n < ends.len() {
864                    let cut = if n == 0 { 0 } else { ends[n - 1] as usize };
865                    data.truncate(cut);
866                    ends.truncate(n);
867                    let mut c = cache.borrow_mut();
868                    if !c.is_empty() {
869                        c.truncate(n);
870                    }
871                }
872            }
873            ListRepr::Structs { columns, .. } => {
874                for c in columns.iter_mut() {
875                    c.truncate(n);
876                }
877            }
878            // The union's arg columns are dense (not row-aligned), so a row-range
879            // truncate de-columnarizes first (a rare path — region rollback).
880            ListRepr::Inductives { .. } => {
881                if n < self.len() {
882                    self.make_boxed().truncate(n);
883                }
884            }
885            // A structural mutation de-lazies the received view first.
886            ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => {
887                if n < self.len() {
888                    self.make_boxed().truncate(n);
889                }
890            }
891        }
892    }
893
894    /// 0-based read; boxes the scalar (stack-only — no heap, no Rc traffic).
895    pub fn get(&self, i: usize) -> Option<RuntimeValue> {
896        match self {
897            ListRepr::Boxed(v) => v.get(i).cloned(),
898            ListRepr::Ints(v) => v.get(i).map(|&n| RuntimeValue::Int(n)),
899            ListRepr::IntsI32(v) => v.get(i).map(|&n| RuntimeValue::Int(n as i64)),
900            ListRepr::Words32(v) => v.get(i).map(|&x| {
901                RuntimeValue::Word(logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
902                    x as u32,
903                )))
904            }),
905            ListRepr::Floats(v) => v.get(i).map(|&f| RuntimeValue::Float(f)),
906            ListRepr::Bools(v) => v.get(i).map(|&b| RuntimeValue::Bool(b)),
907            ListRepr::Strings { data, ends, cache } => {
908                if i >= ends.len() {
909                    return None;
910                }
911                let mut c = cache.borrow_mut();
912                // Lazily size the memo on first access — ship/load/iterate never
913                // touch it, so they pay nothing.
914                if c.is_empty() {
915                    c.resize(ends.len(), None);
916                }
917                if c[i].is_none() {
918                    c[i] = Some(Rc::new(Self::string_at(data, ends, i)?));
919                }
920                c[i].clone().map(RuntimeValue::Text)
921            }
922            ListRepr::Structs {
923                type_name,
924                field_names,
925                columns,
926            } => Self::struct_row(type_name, field_names, columns, i),
927            ListRepr::Inductives {
928                inductive_type,
929                ctor_dict,
930                ctors,
931                ranks,
932                arg_cols,
933            } => Self::inductive_row(inductive_type, ctor_dict, ctors, ranks, arg_cols, i),
934            ListRepr::WireStructs {
935                bytes,
936                type_name,
937                field_names,
938                len,
939            } => Self::wire_struct_row(bytes, type_name, field_names, *len, i),
940            ListRepr::WireColumn { bytes, floats, .. } => Self::wire_column_get(bytes, *floats, i),
941        }
942    }
943
944    /// Read field `name` of row `i` from a columnar struct list by indexing ONE
945    /// column directly — no `StructValue` reconstruction. `None` for a non-columnar
946    /// repr or a missing field/row. This is the zero-alloc read path that makes a
947    /// field scan over a columnar struct list run at array speed.
948    pub fn get_field(&self, i: usize, name: &str) -> Option<RuntimeValue> {
949        match self {
950            ListRepr::Structs {
951                field_names,
952                columns,
953                ..
954            } => {
955                let j = field_names.iter().position(|f| f == name)?;
956                columns[j].get(i)
957            }
958            // The lazy zero-copy receive: locate and decode JUST this cell in place — no row
959            // reconstruction, no decode of the other rows/fields.
960            ListRepr::WireStructs { bytes, .. } => {
961                crate::concurrency::marshal::view_message(bytes)?.structs_row_field_value(i, name)
962            }
963            _ => None,
964        }
965    }
966
967    /// Direct access to a struct field's whole packed column (the array behind a
968    /// field), for aggregating one field across the list at array speed. `None` for
969    /// a non-columnar repr or a missing field.
970    pub fn column(&self, name: &str) -> Option<&ListRepr> {
971        match self {
972            ListRepr::Structs {
973                field_names,
974                columns,
975                ..
976            } => {
977                let j = field_names.iter().position(|f| f == name)?;
978                Some(&columns[j])
979            }
980            _ => None,
981        }
982    }
983
984    /// Re-tag to Boxed in place (aliases see it — same Rc).
985    fn make_boxed(&mut self) -> &mut Vec<RuntimeValue> {
986        match self {
987            ListRepr::Boxed(v) => v,
988            ListRepr::Ints(v) => {
989                let boxed = v.drain(..).map(RuntimeValue::Int).collect();
990                *self = ListRepr::Boxed(boxed);
991                match self {
992                    ListRepr::Boxed(v) => v,
993                    _ => unreachable!(),
994                }
995            }
996            ListRepr::Floats(v) => {
997                let boxed = v.drain(..).map(RuntimeValue::Float).collect();
998                *self = ListRepr::Boxed(boxed);
999                match self {
1000                    ListRepr::Boxed(v) => v,
1001                    _ => unreachable!(),
1002                }
1003            }
1004            ListRepr::IntsI32(v) => {
1005                let boxed = v.drain(..).map(|n| RuntimeValue::Int(n as i64)).collect();
1006                *self = ListRepr::Boxed(boxed);
1007                match self {
1008                    ListRepr::Boxed(v) => v,
1009                    _ => unreachable!(),
1010                }
1011            }
1012            ListRepr::Words32(v) => {
1013                let boxed = v
1014                    .drain(..)
1015                    .map(|x| {
1016                        RuntimeValue::Word(logicaffeine_base::WordVal::W32(
1017                            logicaffeine_base::Word32(x as u32),
1018                        ))
1019                    })
1020                    .collect();
1021                *self = ListRepr::Boxed(boxed);
1022                match self {
1023                    ListRepr::Boxed(v) => v,
1024                    _ => unreachable!(),
1025                }
1026            }
1027            ListRepr::Bools(v) => {
1028                let boxed = v.drain(..).map(RuntimeValue::Bool).collect();
1029                *self = ListRepr::Boxed(boxed);
1030                match self {
1031                    ListRepr::Boxed(v) => v,
1032                    _ => unreachable!(),
1033                }
1034            }
1035            ListRepr::Strings { data, ends, .. } => {
1036                let boxed = (0..ends.len())
1037                    .filter_map(|i| {
1038                        Self::string_at(data, ends, i).map(|s| RuntimeValue::Text(Rc::new(s)))
1039                    })
1040                    .collect();
1041                *self = ListRepr::Boxed(boxed);
1042                match self {
1043                    ListRepr::Boxed(v) => v,
1044                    _ => unreachable!(),
1045                }
1046            }
1047            ListRepr::Structs {
1048                type_name,
1049                field_names,
1050                columns,
1051            } => {
1052                let n = columns.first().map_or(0, |c| c.len());
1053                // Invariant (held by `from_values` and the wire decoder): every column
1054                // is the same length, so no row is silently dropped on de-columnarize.
1055                debug_assert!(
1056                    columns.iter().all(|c| c.len() == n),
1057                    "columnar struct columns must share one length"
1058                );
1059                let boxed = (0..n)
1060                    .filter_map(|i| Self::struct_row(type_name, field_names, columns, i))
1061                    .collect();
1062                *self = ListRepr::Boxed(boxed);
1063                match self {
1064                    ListRepr::Boxed(v) => v,
1065                    _ => unreachable!(),
1066                }
1067            }
1068            ListRepr::Inductives {
1069                inductive_type,
1070                ctor_dict,
1071                ctors,
1072                ranks,
1073                arg_cols,
1074            } => {
1075                let n = ctors.len();
1076                debug_assert_eq!(ranks.len(), n, "ranks and ctors must agree");
1077                let boxed = (0..n)
1078                    .filter_map(|i| {
1079                        Self::inductive_row(inductive_type, ctor_dict, ctors, ranks, arg_cols, i)
1080                    })
1081                    .collect();
1082                *self = ListRepr::Boxed(boxed);
1083                match self {
1084                    ListRepr::Boxed(v) => v,
1085                    _ => unreachable!(),
1086                }
1087            }
1088            // A mutation forces the lazy receive to fully decode (read every row in place) and
1089            // re-tag to `Boxed`, so reference semantics match a boxed list from that point on.
1090            ListRepr::WireStructs {
1091                bytes,
1092                type_name,
1093                field_names,
1094                len,
1095            } => {
1096                let len = *len;
1097                let boxed: Vec<RuntimeValue> = {
1098                    let view = crate::concurrency::marshal::view_message(bytes);
1099                    (0..len)
1100                        .filter_map(|i| {
1101                            view.as_ref().and_then(|v| {
1102                                let mut fields = HashMap::with_capacity(field_names.len());
1103                                for name in field_names.iter() {
1104                                    let cell = v.structs_row_field_value(i, name)?;
1105                                    fields.insert(name.clone(), cell);
1106                                }
1107                                Some(RuntimeValue::Struct(Box::new(StructValue {
1108                                    type_name: type_name.clone(),
1109                                    fields,
1110                                })))
1111                            })
1112                        })
1113                        .collect()
1114                };
1115                *self = ListRepr::Boxed(boxed);
1116                match self {
1117                    ListRepr::Boxed(v) => v,
1118                    _ => unreachable!(),
1119                }
1120            }
1121            ListRepr::WireColumn { bytes, floats, .. } => {
1122                let boxed = Self::wire_column_to_values(bytes, *floats);
1123                *self = ListRepr::Boxed(boxed);
1124                match self {
1125                    ListRepr::Boxed(v) => v,
1126                    _ => unreachable!(),
1127                }
1128            }
1129        }
1130    }
1131
1132    /// Re-tag a half-width `IntsI32` buffer to full-width `Ints` in place — the
1133    /// soundness fallback when a value outside `i32` range reaches a narrowed
1134    /// buffer (the narrowing proof was unsound for that store). Sign-extends
1135    /// every existing element losslessly. After this the buffer behaves exactly
1136    /// like a buffer that was never narrowed.
1137    fn widen_to_ints(&mut self) -> &mut Vec<i64> {
1138        match self {
1139            ListRepr::IntsI32(v) => {
1140                let wide: Vec<i64> = v.drain(..).map(|n| n as i64).collect();
1141                *self = ListRepr::Ints(wide);
1142                match self {
1143                    ListRepr::Ints(v) => v,
1144                    _ => unreachable!(),
1145                }
1146            }
1147            ListRepr::Ints(v) => v,
1148            _ => unreachable!("widen_to_ints called on a non-Int buffer"),
1149        }
1150    }
1151
1152    /// 0-based write (bounds already validated by the caller); promotes on a
1153    /// kind mismatch.
1154    pub fn set(&mut self, i: usize, value: RuntimeValue) {
1155        match (&mut *self, &value) {
1156            (ListRepr::Ints(v), RuntimeValue::Int(n)) => v[i] = *n,
1157            (ListRepr::IntsI32(v), RuntimeValue::Int(n)) => {
1158                if let Ok(narrow) = i32::try_from(*n) {
1159                    v[i] = narrow;
1160                } else {
1161                    // The proof said every store fits i32; this one did not.
1162                    // Widen the whole buffer rather than truncate (which would
1163                    // silently change the observable value). Soundness wins.
1164                    self.widen_to_ints()[i] = *n;
1165                }
1166            }
1167            (ListRepr::Floats(v), RuntimeValue::Float(f)) => v[i] = *f,
1168            (ListRepr::Bools(v), RuntimeValue::Bool(b)) => v[i] = *b,
1169            (ListRepr::Boxed(v), _) => v[i] = value,
1170            _ => self.make_boxed()[i] = value,
1171        }
1172    }
1173
1174    pub fn push(&mut self, value: RuntimeValue) {
1175        match (&mut *self, &value) {
1176            (ListRepr::Ints(v), RuntimeValue::Int(n)) => v.push(*n),
1177            (ListRepr::IntsI32(v), RuntimeValue::Int(n)) => match i32::try_from(*n) {
1178                Ok(narrow) => v.push(narrow),
1179                Err(_) => self.widen_to_ints().push(*n),
1180            },
1181            (ListRepr::Floats(v), RuntimeValue::Float(f)) => v.push(*f),
1182            (ListRepr::Bools(v), RuntimeValue::Bool(b)) => v.push(*b),
1183            (ListRepr::Words32(v), RuntimeValue::Word(logicaffeine_base::WordVal::W32(w))) => {
1184                v.push(w.0 as i64)
1185            }
1186            // An empty list (Boxed or numeric) receiving its FIRST `Word32` specializes to the packed
1187            // `Words32` lane — this is what makes a `Push word32(x)`-built `Seq of Word32` (a sha256 table)
1188            // pin-eligible. A non-W32 into a Words32 (mixed) de-optimizes to Boxed via the fallthrough.
1189            (ListRepr::Boxed(v), RuntimeValue::Word(logicaffeine_base::WordVal::W32(w)))
1190                if v.is_empty() =>
1191            {
1192                let mut out = Vec::with_capacity(v.capacity().max(1));
1193                out.push(w.0 as i64);
1194                *self = ListRepr::Words32(out);
1195            }
1196            (ListRepr::Ints(v), RuntimeValue::Word(logicaffeine_base::WordVal::W32(w)))
1197                if v.is_empty() =>
1198            {
1199                let mut out = Vec::with_capacity(v.capacity().max(1));
1200                out.push(w.0 as i64);
1201                *self = ListRepr::Words32(out);
1202            }
1203            (ListRepr::Boxed(v), _) => v.push(value),
1204            (ListRepr::Ints(v), RuntimeValue::Float(f)) if v.is_empty() => {
1205                let mut out = Vec::with_capacity(v.capacity().max(1));
1206                out.push(*f);
1207                *self = ListRepr::Floats(out);
1208            }
1209            (ListRepr::Ints(v), RuntimeValue::Bool(b)) if v.is_empty() => {
1210                let mut out = Vec::with_capacity(v.capacity().max(1));
1211                out.push(*b);
1212                *self = ListRepr::Bools(out);
1213            }
1214            (ListRepr::Floats(v), RuntimeValue::Int(n)) if v.is_empty() => {
1215                let mut out = Vec::with_capacity(v.capacity().max(1));
1216                out.push(*n);
1217                *self = ListRepr::Ints(out);
1218            }
1219            (ListRepr::Floats(v), RuntimeValue::Bool(b)) if v.is_empty() => {
1220                let mut out = Vec::with_capacity(v.capacity().max(1));
1221                out.push(*b);
1222                *self = ListRepr::Bools(out);
1223            }
1224            (ListRepr::Bools(v), RuntimeValue::Int(n)) if v.is_empty() => {
1225                let mut out = Vec::with_capacity(v.capacity().max(1));
1226                out.push(*n);
1227                *self = ListRepr::Ints(out);
1228            }
1229            (ListRepr::Bools(v), RuntimeValue::Float(f)) if v.is_empty() => {
1230                let mut out = Vec::with_capacity(v.capacity().max(1));
1231                out.push(*f);
1232                *self = ListRepr::Floats(out);
1233            }
1234            _ => self.make_boxed().push(value),
1235        }
1236    }
1237
1238    pub fn pop(&mut self) -> Option<RuntimeValue> {
1239        match self {
1240            ListRepr::Boxed(v) => v.pop(),
1241            ListRepr::Ints(v) => v.pop().map(RuntimeValue::Int),
1242            ListRepr::IntsI32(v) => v.pop().map(|n| RuntimeValue::Int(n as i64)),
1243            ListRepr::Words32(v) => v.pop().map(|x| {
1244                RuntimeValue::Word(logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
1245                    x as u32,
1246                )))
1247            }),
1248            ListRepr::Floats(v) => v.pop().map(RuntimeValue::Float),
1249            ListRepr::Bools(v) => v.pop().map(RuntimeValue::Bool),
1250            ListRepr::Strings { data, ends, cache } => {
1251                let last = ends.len().checked_sub(1)?;
1252                let s = Self::string_at(data, ends, last)?;
1253                let start = if last == 0 {
1254                    0
1255                } else {
1256                    ends[last - 1] as usize
1257                };
1258                data.truncate(start);
1259                ends.pop();
1260                let mut c = cache.borrow_mut();
1261                if !c.is_empty() {
1262                    c.pop();
1263                }
1264                Some(RuntimeValue::Text(Rc::new(s)))
1265            }
1266            // Removing from a columnar store: de-columnarize, then pop.
1267            ListRepr::Structs { .. } => self.make_boxed().pop(),
1268            ListRepr::Inductives { .. } => self.make_boxed().pop(),
1269            ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => self.make_boxed().pop(),
1270        }
1271    }
1272
1273    pub fn insert(&mut self, i: usize, value: RuntimeValue) {
1274        match (&mut *self, &value) {
1275            (ListRepr::Ints(v), RuntimeValue::Int(n)) => v.insert(i, *n),
1276            (ListRepr::IntsI32(v), RuntimeValue::Int(n)) => match i32::try_from(*n) {
1277                Ok(narrow) => v.insert(i, narrow),
1278                Err(_) => self.widen_to_ints().insert(i, *n),
1279            },
1280            (ListRepr::Floats(v), RuntimeValue::Float(f)) => v.insert(i, *f),
1281            (ListRepr::Bools(v), RuntimeValue::Bool(b)) => v.insert(i, *b),
1282            (ListRepr::Boxed(v), _) => v.insert(i, value),
1283            _ => self.make_boxed().insert(i, value),
1284        }
1285    }
1286
1287    pub fn remove_at(&mut self, i: usize) -> RuntimeValue {
1288        match self {
1289            ListRepr::Boxed(v) => v.remove(i),
1290            ListRepr::Ints(v) => RuntimeValue::Int(v.remove(i)),
1291            ListRepr::IntsI32(v) => RuntimeValue::Int(v.remove(i) as i64),
1292            ListRepr::Words32(v) => RuntimeValue::Word(logicaffeine_base::WordVal::W32(
1293                logicaffeine_base::Word32(v.remove(i) as u32),
1294            )),
1295            ListRepr::Floats(v) => RuntimeValue::Float(v.remove(i)),
1296            ListRepr::Bools(v) => RuntimeValue::Bool(v.remove(i)),
1297            // Removal in the middle is O(n) on a flat buffer; promote and remove.
1298            ListRepr::Strings { .. } => self.make_boxed().remove(i),
1299            ListRepr::Structs { .. } => self.make_boxed().remove(i),
1300            ListRepr::Inductives { .. } => self.make_boxed().remove(i),
1301            ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => {
1302                self.make_boxed().remove(i)
1303            }
1304        }
1305    }
1306
1307    /// Index of the first element `values_equal` to `needle` (the kernel's
1308    /// equality: epsilon floats, cross-type never equal).
1309    pub fn position(&self, needle: &RuntimeValue) -> Option<usize> {
1310        match (self, needle) {
1311            (ListRepr::Ints(v), RuntimeValue::Int(n)) => v.iter().position(|x| x == n),
1312            (ListRepr::Ints(_), _) => None,
1313            (ListRepr::IntsI32(v), RuntimeValue::Int(n)) => i32::try_from(*n)
1314                .ok()
1315                .and_then(|nn| v.iter().position(|x| *x == nn)),
1316            (ListRepr::IntsI32(_), _) => None,
1317            (ListRepr::Words32(v), RuntimeValue::Word(logicaffeine_base::WordVal::W32(w))) => {
1318                v.iter().position(|x| *x == w.0 as i64)
1319            }
1320            (ListRepr::Words32(_), _) => None,
1321            (ListRepr::Floats(v), RuntimeValue::Float(f)) => {
1322                v.iter().position(|x| (x - f).abs() < f64::EPSILON)
1323            }
1324            (ListRepr::Floats(_), _) => None,
1325            (ListRepr::Bools(v), RuntimeValue::Bool(b)) => v.iter().position(|x| x == b),
1326            (ListRepr::Bools(_), _) => None,
1327            (ListRepr::Strings { data, ends, .. }, RuntimeValue::Text(t)) => (0..ends.len())
1328                .find(|&i| Self::string_at(data, ends, i).as_deref() == Some(t.as_str())),
1329            (ListRepr::Strings { .. }, _) => None,
1330            (ListRepr::Boxed(v), _) => v
1331                .iter()
1332                .position(|x| crate::semantics::compare::values_equal(x, needle)),
1333            // A struct never equals a scalar needle, but a needle could be a struct;
1334            // reconstruct row-by-row and compare (rare path — search over structs).
1335            (ListRepr::Structs { .. }, _) => (0..self.len()).find(|&i| {
1336                self.get(i)
1337                    .is_some_and(|v| crate::semantics::compare::values_equal(&v, needle))
1338            }),
1339            (ListRepr::Inductives { .. }, _) => (0..self.len()).find(|&i| {
1340                self.get(i)
1341                    .is_some_and(|v| crate::semantics::compare::values_equal(&v, needle))
1342            }),
1343            // The lazy receive: reconstruct rows/elements on demand and compare.
1344            (ListRepr::WireStructs { .. }, _) | (ListRepr::WireColumn { .. }, _) => (0..self.len())
1345                .find(|&i| {
1346                    self.get(i)
1347                        .is_some_and(|v| crate::semantics::compare::values_equal(&v, needle))
1348                }),
1349        }
1350    }
1351
1352    pub fn contains(&self, needle: &RuntimeValue) -> bool {
1353        self.position(needle).is_some()
1354    }
1355
1356    /// Materialize boxed values (snapshots, display, deep clones).
1357    pub fn to_values(&self) -> Vec<RuntimeValue> {
1358        match self {
1359            ListRepr::Boxed(v) => v.clone(),
1360            ListRepr::Ints(v) => v.iter().map(|&n| RuntimeValue::Int(n)).collect(),
1361            ListRepr::IntsI32(v) => v.iter().map(|&n| RuntimeValue::Int(n as i64)).collect(),
1362            ListRepr::Words32(v) => v
1363                .iter()
1364                .map(|&x| {
1365                    RuntimeValue::Word(logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
1366                        x as u32,
1367                    )))
1368                })
1369                .collect(),
1370            ListRepr::Floats(v) => v.iter().map(|&f| RuntimeValue::Float(f)).collect(),
1371            ListRepr::Bools(v) => v.iter().map(|&b| RuntimeValue::Bool(b)).collect(),
1372            ListRepr::Strings { data, ends, .. } => (0..ends.len())
1373                .filter_map(|i| {
1374                    Self::string_at(data, ends, i).map(|s| RuntimeValue::Text(Rc::new(s)))
1375                })
1376                .collect(),
1377            ListRepr::Structs {
1378                type_name,
1379                field_names,
1380                columns,
1381            } => {
1382                let n = columns.first().map_or(0, |c| c.len());
1383                (0..n)
1384                    .filter_map(|i| Self::struct_row(type_name, field_names, columns, i))
1385                    .collect()
1386            }
1387            ListRepr::Inductives {
1388                inductive_type,
1389                ctor_dict,
1390                ctors,
1391                ranks,
1392                arg_cols,
1393            } => (0..ctors.len())
1394                .filter_map(|i| {
1395                    Self::inductive_row(inductive_type, ctor_dict, ctors, ranks, arg_cols, i)
1396                })
1397                .collect(),
1398            ListRepr::WireStructs {
1399                bytes,
1400                type_name,
1401                field_names,
1402                len,
1403            } => (0..*len)
1404                .filter_map(|i| Self::wire_struct_row(bytes, type_name, field_names, *len, i))
1405                .collect(),
1406            ListRepr::WireColumn { bytes, floats, .. } => {
1407                Self::wire_column_to_values(bytes, *floats)
1408            }
1409        }
1410    }
1411
1412    /// 0-based inclusive-range slice as a fresh payload of the same repr.
1413    pub fn slice(&self, start: usize, end: usize) -> ListRepr {
1414        match self {
1415            ListRepr::Boxed(v) => ListRepr::Boxed(v[start..=end].to_vec()),
1416            ListRepr::Ints(v) => ListRepr::Ints(v[start..=end].to_vec()),
1417            ListRepr::IntsI32(v) => ListRepr::IntsI32(v[start..=end].to_vec()),
1418            ListRepr::Words32(v) => ListRepr::Words32(v[start..=end].to_vec()),
1419            ListRepr::Floats(v) => ListRepr::Floats(v[start..=end].to_vec()),
1420            ListRepr::Bools(v) => ListRepr::Bools(v[start..=end].to_vec()),
1421            ListRepr::Strings { data, ends, .. } => ListRepr::Boxed(
1422                (start..=end)
1423                    .filter_map(|i| {
1424                        Self::string_at(data, ends, i).map(|s| RuntimeValue::Text(Rc::new(s)))
1425                    })
1426                    .collect(),
1427            ),
1428            // Slicing stays columnar — slice each column to the same range.
1429            ListRepr::Structs {
1430                type_name,
1431                field_names,
1432                columns,
1433            } => ListRepr::Structs {
1434                type_name: type_name.clone(),
1435                field_names: field_names.clone(),
1436                columns: columns.iter().map(|c| c.slice(start, end)).collect(),
1437            },
1438            // The union's arg columns are dense, so re-columnarize the sliced rows.
1439            ListRepr::Inductives { .. } => {
1440                ListRepr::from_values((start..=end).filter_map(|i| self.get(i)).collect())
1441            }
1442            // Reconstruct just the sliced rows/elements from the received view.
1443            ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => {
1444                ListRepr::from_values((start..=end).filter_map(|i| self.get(i)).collect())
1445            }
1446        }
1447    }
1448
1449    /// Direct unboxed views for the JIT's region pinning.
1450    pub fn as_ints_mut(&mut self) -> Option<&mut Vec<i64>> {
1451        match self {
1452            ListRepr::Ints(v) => Some(v),
1453            _ => None,
1454        }
1455    }
1456
1457    pub fn as_floats_mut(&mut self) -> Option<&mut Vec<f64>> {
1458        match self {
1459            ListRepr::Floats(v) => Some(v),
1460            _ => None,
1461        }
1462    }
1463}
1464
1465/// The empty value of whatever type `current` already holds — what a `Load` of a key that is not
1466/// there gives back.
1467///
1468/// ★ ABSENCE MUST NOT RETYPE THE TARGET. A miss used to answer empty TEXT whatever the field was,
1469/// so a `Load` into an Int field left a Text behind and the next `+ 1` CONCATENATED instead of
1470/// adding. The bytecode tier decodes a tagged default and answered the field's zero, so the two
1471/// tiers disagreed about a forgotten key — a page that behaves one way in a test and another in a
1472/// browser. Shaping the miss like the value already in the variable needs no type table and gives
1473/// both tiers the same answer.
1474fn empty_like(current: Option<&RuntimeValue>) -> RuntimeValue {
1475    match current {
1476        Some(RuntimeValue::Int(_)) => RuntimeValue::Int(0),
1477        Some(RuntimeValue::Float(_)) => RuntimeValue::Float(0.0),
1478        Some(RuntimeValue::Bool(_)) => RuntimeValue::Bool(false),
1479        _ => RuntimeValue::Text(Rc::new(String::new())),
1480    }
1481}
1482
1483#[derive(Debug, Clone)]
1484pub enum RuntimeValue {
1485    Int(i64),
1486    /// A CALLBACK a parent handed a child: the parent's instance path and the action to run on
1487    /// it. This is the only direction data flows back up — a child never reaches into a
1488    /// parent's record, it calls what the parent gave it, and the turn runs on the PARENT.
1489    /// Behind one `Rc` so `RuntimeValue` stays 16 bytes (`nanbox_runtime_value_is_16_bytes`).
1490    Action(Rc<ActionRef>),
1491    /// A rendered VIEW: the handle of a detached fragment holding its nodes. `View` is a real
1492    /// value — a `-> View` function returns one, a prop carries one, a Seq holds several — and
1493    /// placing one in a template moves its nodes into the page. Distinct from `Int` so a text
1494    /// hole can tell "a view to place" from "a number to print".
1495    View(i64),
1496    /// An exact integer that does NOT fit `i64` — the overflow-safe continuation of
1497    /// `Int`. INVARIANT: `b.to_i64().is_none()` always holds (build via
1498    /// [`RuntimeValue::from_bigint`], which downsizes any in-range result back to
1499    /// `Int`), so there is exactly one representation per integer value and `Eq`/
1500    /// `Hash`/ordering never need a cross-`Int` arm. `Rc` keeps `Clone` O(1).
1501    BigInt(Rc<logicaffeine_base::BigInt>),
1502    /// An exact rational number — the result of an integer division that does NOT
1503    /// divide evenly (`7 / 2 → 7/2`), the way `Int` "overflows" into `BigInt`.
1504    /// INVARIANT: never a whole number — build via [`RuntimeValue::from_rational`],
1505    /// which downsizes an integer-valued rational to `Int`/`BigInt`, so a value has
1506    /// one canonical representation and `Eq`/`Hash` need no cross-`Int` arm.
1507    Rational(Rc<logicaffeine_base::Rational>),
1508    /// An exact base-10 fixed-point number — money's type. Distinct from `Rational`:
1509    /// it carries a *scale* (decimal places) for faithful display (`19.99`, not
1510    /// `1999/100`), and unlike `Int`/`BigInt`/`Rational` it does NOT downsize on a
1511    /// whole value (`20.00` stays `Decimal`, not `Int`), because the scale is meaning.
1512    /// `+ − ×` are exact and keep it `Decimal`; `÷` and a `Rational` operand promote to
1513    /// the exact `Rational` (base-10 division need not terminate). `Rc` keeps `Clone` O(1).
1514    Decimal(Rc<logicaffeine_base::Decimal>),
1515    /// An exact complex number `re + im·i`, each part a `Rational`. The field that closes
1516    /// the tower for `√` of a negative and for EE/signal math: `i·i = −1` exactly. NOT
1517    /// ordered (complex numbers have no total order), so it never appears in `compare`.
1518    Complex(Rc<logicaffeine_base::Complex>),
1519    /// A floating-point complex `re + im·i` (each part `f64`) — LAPACK's `Z`, the INEXACT dual of
1520    /// `Complex`. Unlike the exact Gaussian rationals it has a `sqrt`, so the sqrt-based complex
1521    /// decompositions (Cholesky/QR/eig/SVD) can run. Any exact operand mixed with a float promotes
1522    /// here, the way `Rational` promotes into `Float`.
1523    ComplexF(Rc<logicaffeine_base::ComplexF>),
1524    /// An element of the ring ℤ/nℤ — an integer modulo a fixed modulus (the arbitrary-modulus
1525    /// generalisation of `Word`). Arithmetic wraps into `[0, modulus)`; the crypto/number-theory
1526    /// substrate (modular exponentiation, inverse). Equal only at the same value AND modulus.
1527    Modular(Rc<logicaffeine_base::Modular>),
1528    /// A real algebraic number that is not rational (a rational is held as `Int`, `BigInt` or
1529    /// `Rational`): `√2`, `(1 + √5)/2`, a root of `x^3 - x - 1`. Ordered and compared exactly.
1530    Algebraic(Rc<logicaffeine_base::algebraic::Algebraic>),
1531    /// A computable real that is not algebraic: an exponential or `π` form, whose equality is
1532    /// decided exactly, or a general expression compared by refinement under a budget.
1533    ExactReal(Rc<logicaffeine_base::exact_real::ExactReal>),
1534    /// A hyperreal with a nonzero infinitesimal part, written in the program's infinitesimal
1535    /// (`3 + dt`, `1/dt`); one with none is its standard value.
1536    Hyperreal(Rc<crate::semantics::exact::HyperValue>),
1537    /// An infinite integer: a polynomial in the generator `⌈1/dt⌉`, the trip count of a loop
1538    /// that runs infinitely many times.
1539    Hypernatural(Rc<crate::semantics::exact::NaturalValue>),
1540    /// An infinite ordinal below ε₀ (a finite one is a natural number).
1541    Ordinal(Rc<logicaffeine_base::ordinal::Ordinal>),
1542    /// A value that depends on the residue of `⌈1/dt⌉`: `0 when ⌈1/dt⌉ is even, 1 when it is odd`.
1543    Depends(Rc<crate::semantics::exact::DependsValue>),
1544    /// The answer of a search over every natural number: settled by a certificate, or provisional
1545    /// with the cases it checked.
1546    Converging(Rc<logicaffeine_base::limit_value::Converging<RuntimeValue>>),
1547    Float(f64),
1548    Bool(bool),
1549    Text(Rc<String>),
1550    Char(char),
1551    List(Rc<RefCell<ListRepr>>),
1552    Tuple(Rc<Vec<RuntimeValue>>),
1553    Set(Rc<RefCell<Vec<RuntimeValue>>>),
1554    Map(Rc<RefCell<MapStorage>>),
1555    Struct(Box<StructValue>),
1556    /// Shared, never changed in place: a variant's arguments are fixed when it is built, so a binding, an argument
1557    /// or an `Inspect` arm takes another handle to the same value rather than a copy of the tree below it.
1558    Inductive(Rc<InductiveValue>),
1559    Function(Box<ClosureValue>),
1560    Nothing,
1561    Duration(i64),
1562    Date(i32),
1563    Moment(i64),
1564    Span {
1565        months: i32,
1566        days: i32,
1567    },
1568    Time(i64),
1569    /// A channel handle (a `Pipe`) — an opaque token into the scheduler.
1570    Chan(ChanId),
1571    /// A spawned-task handle — an opaque token into the scheduler.
1572    TaskHandle(TaskId),
1573    /// A remote peer handle — its canonical relay topic. `Send … to <peer>`
1574    /// publishes on this topic; the peer receives it on its own inbox.
1575    Peer(Rc<String>),
1576    /// A live CRDT (observed-remove set, replicated sequence, or multi-value register)
1577    /// held by the tree-walker. Wraps the real `logicaffeine_data` type the compiled tier
1578    /// uses, so merge converges identically across tiers. `Rc<RefCell<_>>` gives the same
1579    /// interior-mutation/aliasing semantics as `Set`/`List`/`Map`, so mutating a struct's
1580    /// CRDT field through a field access updates the shared value in place.
1581    Crdt(Rc<RefCell<crate::semantics::crdt::CrdtValue>>),
1582    /// A fixed-width wrapping integer (`Word32`/`Word64`) — the ring ℤ/2ᵏ the bit-twiddling
1583    /// primitives (ChaCha20 over `Word32`, Keccak over `Word64`) compute over. Distinct from
1584    /// `Int`: its arithmetic wraps and it never promotes to `BigInt`.
1585    Word(logicaffeine_base::WordVal),
1586    /// A SIMD lane vector (`Lanes8Word32` = 8×`Word32` = one `__m256i`) — a fixed-width vector over
1587    /// the Word ring. The tree-walker carries the scalar-lane representation and computes each op as
1588    /// independent scalar lanes (the spec); AOT lowers the same op to an AVX2 intrinsic. Boxed in `Rc`
1589    /// so the 256-bit lane payload stays out of the 16-byte `RuntimeValue` (the NaN-box invariant).
1590    Lanes(Rc<logicaffeine_base::LanesVal>),
1591    /// A physical quantity — an exact magnitude carrying a `Dimension` and a display unit
1592    /// (`2 inches`, `9.8 m/s²`). The magnitude rides the exact rational tower, so unit conversion
1593    /// is lossless (`2 inches + 5 cm in feet = 42/127 ft`); `+ −` and comparison require the SAME
1594    /// dimension (else a typed error, like Word width-mismatch), `× ÷` combine dimensions. The
1595    /// display unit travels with the value so `Show` renders it faithfully.
1596    Quantity(Rc<QuantityValue>),
1597    /// An exact monetary amount in a currency (`19.99 USD`). The amount rides the Decimal tower so it
1598    /// never float-drifts; `+ −` and comparison require the SAME currency (else a typed error, like a
1599    /// dimension mismatch), `× ÷` scale by a number. The currency travels with the value.
1600    Money(Rc<logicaffeine_base::Money>),
1601    /// A 128-bit UUID (RFC 9562). `Ord` by bytes — so v6/v7 ids sort chronologically — and a stable
1602    /// canonical text form. `Rc`-boxed to keep `RuntimeValue` at 16 bytes (the value itself is a
1603    /// `Copy [u8;16]`; the compiled tier carries it unboxed).
1604    Uuid(Rc<logicaffeine_base::Uuid>),
1605}
1606
1607/// The payload of a [`RuntimeValue::Quantity`]: the physical quantity (magnitude in SI base +
1608/// dimension) plus the unit it should be displayed in. Equality/hashing are by physical value
1609/// (SI magnitude + dimension) — the display unit is presentation only, so `2 inches` equals
1610/// `5.08 centimetres`.
1611#[derive(Clone, Debug)]
1612pub struct QuantityValue {
1613    pub q: logicaffeine_base::Quantity,
1614    pub unit: logicaffeine_base::Unit,
1615}
1616
1617impl QuantityValue {
1618    /// The faithful display: the magnitude expressed in the carried unit, then its symbol —
1619    /// `42/127 ft`, `2 in`, `20 °C`. A synthetic SI unit (empty symbol, produced by a
1620    /// dimension-combining `× ÷`) shows the dimension signature instead (`12 L^2`).
1621    pub fn display(&self) -> String {
1622        let magnitude = self
1623            .q
1624            .in_unit(&self.unit)
1625            .expect("a Quantity's display unit always shares its dimension");
1626        if self.unit.symbol.is_empty() {
1627            format!("{} {}", magnitude, self.q.dimension())
1628        } else {
1629            format!("{} {}", magnitude, self.unit.symbol)
1630        }
1631    }
1632}
1633
1634impl PartialEq for RuntimeValue {
1635    /// ONE equality: delegates to [`crate::semantics::compare::values_equal`],
1636    /// so map-key lookup, set membership, and the language's `==` can never
1637    /// disagree. Structural for collections/structs, EXACT across numeric
1638    /// types (`1 == 1.0`), IEEE for floats — coherent with the unified
1639    /// numeric `Hash` below (equal values hash equal).
1640    fn eq(&self, other: &Self) -> bool {
1641        crate::semantics::compare::values_equal(self, other)
1642    }
1643}
1644
1645/// NOTE: `eq` is IEEE on floats, so `NaN != NaN` — strictly this bends `Eq`'s
1646/// reflexivity for the one value IEEE defines as not equal to itself. The
1647/// trade is deliberate: map keys behave exactly like the language's own `==`
1648/// (a NaN key is unfindable, as IEEE intends) instead of maps and `==`
1649/// silently disagreeing about float identity. Everything else is a total
1650/// equivalence.
1651impl Eq for RuntimeValue {}
1652
1653impl std::hash::Hash for RuntimeValue {
1654    /// The hash/equality coherence law: values that compare equal MUST hash
1655    /// equal. Numeric types are cross-type equal (`1 == 1.0 == 1/1`), so they
1656    /// share ONE hash stream — the unified numeric hash (value mod 2^61 − 1,
1657    /// `base::numeric`) with NO discriminant prefix. Everything else keeps
1658    /// its discriminant-prefixed per-type hash (collisions between UNEQUAL
1659    /// values are always allowed; only equal ⇒ equal-hash is required).
1660    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1661        use logicaffeine_base::numeric;
1662        match self {
1663            // ── The unified numeric stream (no discriminant) ─────────────
1664            RuntimeValue::Int(n) => state.write_u64(numeric::numeric_hash_i64(*n)),
1665            RuntimeValue::BigInt(b) => state.write_u64(numeric::numeric_hash_bigint(b)),
1666            RuntimeValue::Float(f) => state.write_u64(numeric::numeric_hash_f64(*f)),
1667            RuntimeValue::Rational(r) => state.write_u64(numeric::numeric_hash_rational(r)),
1668            // ── Discriminant-prefixed per-type hashes ────────────────────
1669            other => {
1670                std::mem::discriminant(other).hash(state);
1671                match other {
1672                    RuntimeValue::Int(_)
1673                    | RuntimeValue::BigInt(_)
1674                    | RuntimeValue::Float(_)
1675                    | RuntimeValue::Rational(_) => unreachable!("handled above"),
1676                    RuntimeValue::Decimal(d) => d.hash(state),
1677                    RuntimeValue::Complex(c) => c.hash(state),
1678                    RuntimeValue::ComplexF(c) => {
1679                        state.write_u64(numeric::numeric_hash_f64(c.re()));
1680                        state.write_u64(numeric::numeric_hash_f64(c.im()));
1681                    }
1682                    RuntimeValue::Modular(m) => m.hash(state),
1683                    RuntimeValue::Algebraic(a) => a.hash(state),
1684                    RuntimeValue::ExactReal(x) => x.describe().hash(state),
1685                    RuntimeValue::Hyperreal(h) => h.value.hash(state),
1686                    RuntimeValue::Hypernatural(n) => n.value.hash(state),
1687                    RuntimeValue::Ordinal(o) => o.hash(state),
1688                    RuntimeValue::Depends(_) | RuntimeValue::Converging(_) => {
1689                        other.to_display_string().hash(state)
1690                    }
1691                    RuntimeValue::Bool(b) => b.hash(state),
1692                    RuntimeValue::Text(s) => s.hash(state),
1693                    RuntimeValue::Char(c) => c.hash(state),
1694                    RuntimeValue::Nothing => {}
1695                    RuntimeValue::Duration(d) => d.hash(state),
1696                    RuntimeValue::Date(d) => d.hash(state),
1697                    RuntimeValue::Moment(m) => m.hash(state),
1698                    RuntimeValue::Span { months, days } => {
1699                        months.hash(state);
1700                        days.hash(state);
1701                    }
1702                    RuntimeValue::Time(t) => t.hash(state),
1703                    // Tuples are VALUE keys: content-hashed, in order —
1704                    // coherent with their structural equality.
1705                    RuntimeValue::Tuple(items) => {
1706                        items.len().hash(state);
1707                        for v in items.iter() {
1708                            v.hash(state);
1709                        }
1710                    }
1711                    // Structs are VALUE keys: type + an ORDER-INSENSITIVE
1712                    // field fold (the fields map iterates nondeterministically,
1713                    // and equal structs must hash equal).
1714                    RuntimeValue::Struct(s) => {
1715                        s.type_name.hash(state);
1716                        let mut fold: u64 = 0;
1717                        for (k, v) in &s.fields {
1718                            let mut h = rustc_hash::FxHasher::default();
1719                            std::hash::Hash::hash(k, &mut h);
1720                            std::hash::Hash::hash(v, &mut h);
1721                            fold = fold.wrapping_add(std::hash::Hasher::finish(&h));
1722                        }
1723                        state.write_u64(fold);
1724                    }
1725                    // Mutable containers hash by LENGTH — consistent with
1726                    // structural equality (equal ⇒ equal length), and they
1727                    // are rejected as map keys at insert anyway.
1728                    RuntimeValue::List(items) => items.borrow().len().hash(state),
1729                    RuntimeValue::Set(items) => items.borrow().len().hash(state),
1730                    RuntimeValue::Map(m) => m.borrow().len().hash(state),
1731                    RuntimeValue::Inductive(i) => {
1732                        i.inductive_type.hash(state);
1733                        i.constructor.hash(state);
1734                    }
1735                    RuntimeValue::Function(f) => f.body_index.hash(state),
1736                    // A view hashes by the fragment it holds — two views are the same value
1737                    // only when they are the same rendered nodes.
1738                    RuntimeValue::View(h) => h.hash(state),
1739                    RuntimeValue::Action(a) => {
1740                        a.instance.hash(state);
1741                        a.name.hash(state);
1742                    }
1743                    RuntimeValue::Chan(c) => c.0.hash(state),
1744                    RuntimeValue::TaskHandle(t) => t.0.hash(state),
1745                    RuntimeValue::Peer(topic) => topic.hash(state),
1746                    RuntimeValue::Crdt(c) => c.borrow().len().hash(state),
1747                    RuntimeValue::Word(w) => w.hash(state),
1748                    RuntimeValue::Lanes(v) => v.hash(state),
1749                    // Hash the physical value (SI magnitude + dimension), consistent with `eq`
1750                    // ignoring the display unit.
1751                    RuntimeValue::Quantity(qv) => {
1752                        qv.q.magnitude_si().hash(state);
1753                        qv.q.dimension().hash(state);
1754                    }
1755                    // Hash by value (currency + amount), consistent with `eq`.
1756                    RuntimeValue::Money(m) => m.hash(state),
1757                    RuntimeValue::Uuid(u) => u.hash(state),
1758                }
1759            }
1760        }
1761    }
1762}
1763
1764impl RuntimeValue {
1765    /// Build an integer value from a `BigInt`, DOWNSIZING to [`RuntimeValue::Int`]
1766    /// whenever the value fits `i64`. This is the single chokepoint that maintains
1767    /// the `BigInt`-is-always-out-of-range invariant, so every integer has one
1768    /// canonical representation — the "downsize when it provably fits" rule, applied
1769    /// unconditionally on every result.
1770    pub fn from_bigint(b: logicaffeine_base::BigInt) -> RuntimeValue {
1771        match b.to_i64() {
1772            Some(i) => RuntimeValue::Int(i),
1773            None => RuntimeValue::BigInt(Rc::new(b)),
1774        }
1775    }
1776
1777    /// Build a number from a `Rational`, DOWNSIZING to an exact integer
1778    /// (`Int`/`BigInt`) whenever the denominator reduces to `1`. This is the single
1779    /// chokepoint that maintains the `Rational`-is-never-whole invariant, so an
1780    /// integer-valued result (`6 / 2 → 3`) is an `Int`, not a `Rational` — exactly the
1781    /// "downsize when it provably fits" rule `from_bigint` applies for integers.
1782    pub fn from_rational(r: logicaffeine_base::Rational) -> RuntimeValue {
1783        match r.to_bigint() {
1784            Some(whole) => RuntimeValue::from_bigint(whole),
1785            None => RuntimeValue::Rational(Rc::new(r)),
1786        }
1787    }
1788
1789    /// Returns the type name of this value as a string slice.
1790    ///
1791    /// Used for error messages and type checking at runtime.
1792    pub fn type_name(&self) -> &str {
1793        match self {
1794            RuntimeValue::Int(_) => "Int",
1795            // A BigInt is an exact integer too — same logical type, wider repr — so it
1796            // reports "Int", keeping the type stable across promotion/downsizing.
1797            RuntimeValue::BigInt(_) => "Int",
1798            RuntimeValue::Rational(_) => "Rational",
1799            RuntimeValue::Decimal(_) => "Decimal",
1800            RuntimeValue::Complex(_) => "Complex",
1801            RuntimeValue::ComplexF(_) => "ComplexF",
1802            RuntimeValue::Modular(_) => "Modular",
1803            RuntimeValue::Algebraic(_) => "Algebraic",
1804            RuntimeValue::ExactReal(_) => "ExactReal",
1805            RuntimeValue::Hyperreal(_) => "Hyperreal",
1806            RuntimeValue::Hypernatural(_) => "Hypernatural",
1807            RuntimeValue::Ordinal(_) => "Ordinal",
1808            RuntimeValue::Depends(_) => "Depends",
1809            RuntimeValue::Converging(_) => "Converging",
1810            RuntimeValue::Float(_) => "Float",
1811            RuntimeValue::Bool(_) => "Bool",
1812            RuntimeValue::Text(_) => "Text",
1813            RuntimeValue::Char(_) => "Char",
1814            RuntimeValue::List(_) => "List",
1815            RuntimeValue::Tuple(_) => "Tuple",
1816            RuntimeValue::Set(_) => "Set",
1817            RuntimeValue::Map(_) => "Map",
1818            RuntimeValue::Struct(s) => &s.type_name,
1819            RuntimeValue::Inductive(ind) => ind.inductive_type.as_str(),
1820            RuntimeValue::Function(_) => "Function",
1821            RuntimeValue::View(_) => "View",
1822            RuntimeValue::Action(_) => "Action",
1823            RuntimeValue::Nothing => "Nothing",
1824            RuntimeValue::Duration(_) => "Duration",
1825            RuntimeValue::Date(_) => "Date",
1826            RuntimeValue::Moment(_) => "Moment",
1827            RuntimeValue::Span { .. } => "Span",
1828            RuntimeValue::Time(_) => "Time",
1829            RuntimeValue::Chan(_) => "Channel",
1830            RuntimeValue::TaskHandle(_) => "Task",
1831            RuntimeValue::Peer(_) => "PeerAgent",
1832            RuntimeValue::Crdt(c) => c.borrow().kind(),
1833            RuntimeValue::Word(w) => w.type_name(),
1834            RuntimeValue::Lanes(v) => v.type_name(),
1835            RuntimeValue::Quantity(_) => "Quantity",
1836            RuntimeValue::Money(_) => "Money",
1837            RuntimeValue::Uuid(_) => "Uuid",
1838        }
1839    }
1840
1841    /// The truth of a value that decides a branch. A residue-dependent or provisional answer is an
1842    /// error here: no branch may silently take it as true or false.
1843    pub fn decided_truth(&self) -> Result<bool, String> {
1844        if let Some(why) = crate::semantics::exact::undecided_branch(self) {
1845            return Err(why);
1846        }
1847        Ok(self.is_truthy())
1848    }
1849
1850    /// Checks if this value evaluates to true in a boolean context.
1851    ///
1852    /// - `Bool(true)` → true
1853    /// - `Int(n)` → true if n ≠ 0
1854    /// - `Nothing` → false
1855    /// - All other values → true
1856    pub fn deep_clone(&self) -> RuntimeValue {
1857        match self {
1858            RuntimeValue::List(items) => {
1859                let cloned: Vec<RuntimeValue> = items
1860                    .borrow()
1861                    .to_values()
1862                    .iter()
1863                    .map(|v| v.deep_clone())
1864                    .collect();
1865                RuntimeValue::List(Rc::new(RefCell::new(ListRepr::from_values(cloned))))
1866            }
1867            RuntimeValue::Set(items) => {
1868                let cloned = items.borrow().iter().map(|v| v.deep_clone()).collect();
1869                RuntimeValue::Set(Rc::new(RefCell::new(cloned)))
1870            }
1871            RuntimeValue::Map(m) => {
1872                let cloned = m
1873                    .borrow()
1874                    .iter()
1875                    .map(|(k, v)| (k.deep_clone(), v.deep_clone()))
1876                    .collect();
1877                RuntimeValue::Map(Rc::new(RefCell::new(cloned)))
1878            }
1879            RuntimeValue::Tuple(items) => {
1880                let cloned = items.iter().map(|v| v.deep_clone()).collect();
1881                RuntimeValue::Tuple(Rc::new(cloned))
1882            }
1883            RuntimeValue::Struct(s) => {
1884                let cloned_fields = s
1885                    .fields
1886                    .iter()
1887                    .map(|(k, v)| (k.clone(), v.deep_clone()))
1888                    .collect();
1889                RuntimeValue::Struct(Box::new(StructValue {
1890                    type_name: s.type_name.clone(),
1891                    fields: cloned_fields,
1892                }))
1893            }
1894            RuntimeValue::Inductive(ind) => {
1895                let cloned_args = ind.args.iter().map(|v| v.deep_clone()).collect();
1896                RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
1897                    inductive_type: ind.inductive_type.clone(),
1898                    constructor: ind.constructor.clone(),
1899                    args: cloned_args,
1900                }))
1901            }
1902            RuntimeValue::Function(f) => {
1903                let cloned_env = f
1904                    .captured_env
1905                    .iter()
1906                    .map(|(k, v)| (k.clone(), v.deep_clone()))
1907                    .collect();
1908                RuntimeValue::Function(Box::new(ClosureValue {
1909                    body_index: f.body_index,
1910                    captured_env: cloned_env,
1911                    param_names: f.param_names.clone(),
1912                    generated: f.generated.clone(),
1913                }))
1914            }
1915            // A value-copy of a CRDT is an INDEPENDENT replica — deep-copy the inner state
1916            // so a later mutation of one copy does not alias the other (a shallow `Rc`
1917            // share would make a struct copy mutate the original's CRDT field).
1918            RuntimeValue::Crdt(c) => RuntimeValue::Crdt(Rc::new(RefCell::new(c.borrow().clone()))),
1919            other => other.clone(),
1920        }
1921    }
1922
1923    /// Falsy: `false`, numeric zero (Int/Float/BigInt/Rational/Decimal/Complex/Word),
1924    /// `nothing`, and empty Text/List/Set/Map. Everything else is truthy.
1925    /// (`-0.0` is zero; NaN is nonzero and therefore truthy.)
1926    pub fn is_truthy(&self) -> bool {
1927        match self {
1928            RuntimeValue::Bool(b) => *b,
1929            RuntimeValue::Int(n) => *n != 0,
1930            RuntimeValue::Float(f) => *f != 0.0,
1931            RuntimeValue::BigInt(b) => !b.is_zero(),
1932            RuntimeValue::Rational(r) => !r.is_zero(),
1933            RuntimeValue::Decimal(d) => !d.is_zero(),
1934            RuntimeValue::Complex(c) => !c.is_zero(),
1935            RuntimeValue::ComplexF(c) => !c.is_zero(),
1936            RuntimeValue::Word(w) => w.to_u64() != 0,
1937            RuntimeValue::Text(s) => !s.is_empty(),
1938            RuntimeValue::List(l) => l.borrow().len() != 0,
1939            RuntimeValue::Set(s) => !s.borrow().is_empty(),
1940            RuntimeValue::Map(m) => !m.borrow().is_empty(),
1941            RuntimeValue::Nothing => false,
1942            _ => true,
1943        }
1944    }
1945
1946    /// Converts this value to a human-readable string for display.
1947    ///
1948    /// Used by the `show()` built-in function and for debugging output.
1949    /// Formats collections with brackets, structs with field names, and
1950    /// inductive values with constructor notation.
1951    pub fn to_display_string(&self) -> String {
1952        match self {
1953            RuntimeValue::Int(n) => n.to_string(),
1954            RuntimeValue::Word(w) => w.to_string(),
1955            // A lane vector renders like a Seq of its lanes — `[l0, l1, ...]` of unsigned values.
1956            RuntimeValue::Lanes(v) => {
1957                let parts: Vec<String> = (0..v.lanes()).map(|i| v.lane(i).to_string()).collect();
1958                format!("[{}]", parts.join(", "))
1959            }
1960            RuntimeValue::BigInt(b) => b.to_string(),
1961            RuntimeValue::Rational(r) => r.to_string(),
1962            RuntimeValue::Decimal(d) => d.to_string(),
1963            RuntimeValue::Complex(c) => c.to_string(),
1964            RuntimeValue::ComplexF(c) => {
1965                // Render like `Complex` (unit coefficient omitted) but with `fmt_f64` parts, so
1966                // `2.0 + 1.0i` shows as `2+i` and `4.0 + 6.0i` as `4+6i`.
1967                let fmt = logicaffeine_data::fmt::fmt_f64;
1968                let (re, im) = (c.re(), c.im());
1969                if im == 0.0 {
1970                    fmt(re)
1971                } else {
1972                    let mag = im.abs();
1973                    let icoef = if mag == 1.0 { String::new() } else { fmt(mag) };
1974                    if re == 0.0 {
1975                        format!("{}{}i", if im < 0.0 { "-" } else { "" }, icoef)
1976                    } else {
1977                        format!("{}{}{}i", fmt(re), if im < 0.0 { "-" } else { "+" }, icoef)
1978                    }
1979                }
1980            }
1981            RuntimeValue::Modular(m) => m.to_string(),
1982            RuntimeValue::Algebraic(_)
1983            | RuntimeValue::ExactReal(_)
1984            | RuntimeValue::Hyperreal(_)
1985            | RuntimeValue::Hypernatural(_)
1986            | RuntimeValue::Ordinal(_)
1987            | RuntimeValue::Depends(_)
1988            | RuntimeValue::Converging(_) => {
1989                crate::semantics::exact::display(self).expect("an exact value displays")
1990            }
1991            RuntimeValue::Quantity(qv) => qv.display(),
1992            RuntimeValue::Money(m) => m.to_string(),
1993            RuntimeValue::Uuid(u) => u.to_string(),
1994            RuntimeValue::Float(f) => logicaffeine_data::fmt::fmt_f64(*f),
1995            RuntimeValue::Bool(b) => if *b { "true" } else { "false" }.to_string(),
1996            RuntimeValue::Text(s) => s.as_str().to_string(),
1997            RuntimeValue::Char(c) => c.to_string(),
1998            RuntimeValue::List(items) => {
1999                let items = items.borrow();
2000                let parts: Vec<String> = items
2001                    .to_values()
2002                    .iter()
2003                    .map(|v| v.to_display_string())
2004                    .collect();
2005                format!("[{}]", parts.join(", "))
2006            }
2007            RuntimeValue::Tuple(items) => {
2008                let parts: Vec<String> = items.iter().map(|v| v.to_display_string()).collect();
2009                format!("({})", parts.join(", "))
2010            }
2011            RuntimeValue::Set(items) => {
2012                let items = items.borrow();
2013                let parts: Vec<String> = items.iter().map(|v| v.to_display_string()).collect();
2014                format!("{{{}}}", parts.join(", "))
2015            }
2016            RuntimeValue::Map(m) => {
2017                let m = m.borrow();
2018                let pairs: Vec<String> = m
2019                    .iter()
2020                    .map(|(k, v)| format!("{}: {}", k.to_display_string(), v.to_display_string()))
2021                    .collect();
2022                format!("{{{}}}", pairs.join(", "))
2023            }
2024            RuntimeValue::Struct(s) => {
2025                if s.fields.is_empty() {
2026                    s.type_name.clone()
2027                } else {
2028                    // `fields` is a `HashMap` (random iteration order), so sort by field NAME to make
2029                    // the display DETERMINISTIC — otherwise `TypeName { … }` order varies per run and
2030                    // can't be a byte-identical target for the VM/AOT tiers.
2031                    let mut field_strs: Vec<(&str, String)> = s
2032                        .fields
2033                        .iter()
2034                        .map(|(k, v)| (k.as_str(), v.to_display_string()))
2035                        .collect();
2036                    field_strs.sort_by(|a, b| a.0.cmp(b.0));
2037                    let joined: Vec<String> = field_strs
2038                        .iter()
2039                        .map(|(k, v)| format!("{k}: {v}"))
2040                        .collect();
2041                    format!("{} {{ {} }}", s.type_name, joined.join(", "))
2042                }
2043            }
2044            RuntimeValue::Inductive(ind) => {
2045                // ★ R1 — AN OPTION DISPLAYS AS ITS PAYLOAD, never as its wrapper.
2046                //
2047                // `Option` is a real two-constructor inductive in the value model, but it must not
2048                // LOOK like one: `Show some 42` has always printed `42` and `Show none` has always
2049                // printed `nothing`, on every tier. Rendering it as `Some(42)` would silently
2050                // rewrite the output of every program that shows one, which is the one thing a
2051                // representation change is not allowed to do. Pinned by
2052                // `option_tier_lock::showing_an_option_prints_its_payload_not_its_wrapper` and by
2053                // `semantic_probes_lock`'s five-tier `option_some_is_transparent` probe.
2054                if ind.inductive_type == "Option" {
2055                    return match ind.args.first() {
2056                        Some(inner) => inner.to_display_string(),
2057                        None => "nothing".to_string(),
2058                    };
2059                }
2060                if ind.args.is_empty() {
2061                    ind.constructor.clone()
2062                } else {
2063                    let arg_strs: Vec<String> =
2064                        ind.args.iter().map(|v| v.to_display_string()).collect();
2065                    format!("{}({})", ind.constructor, arg_strs.join(", "))
2066                }
2067            }
2068            RuntimeValue::Function(_) => "<closure>".to_string(),
2069            // Showing a view renders it: the HTML of the fragment it holds. That is what makes
2070            // `Show html of card("Hi")` and a server-rendered page the same one walk.
2071            RuntimeValue::View(h) => crate::semantics::dom::render_children(*h),
2072            // A callback is behavior, not text: showing one says so rather than inventing a
2073            // rendering for it.
2074            RuntimeValue::Action(_) => "<action>".to_string(),
2075            RuntimeValue::Chan(_) => "<channel>".to_string(),
2076            RuntimeValue::TaskHandle(_) => "<task>".to_string(),
2077            RuntimeValue::Peer(topic) => format!("<peer {topic}>"),
2078            RuntimeValue::Crdt(c) => c.borrow().render(),
2079            RuntimeValue::Nothing => "nothing".to_string(),
2080            RuntimeValue::Duration(nanos) => {
2081                // Format durations nicely based on magnitude
2082                let abs_nanos = nanos.unsigned_abs();
2083                let sign = if *nanos < 0 { "-" } else { "" };
2084                if abs_nanos >= 3_600_000_000_000 {
2085                    // Hours
2086                    format!("{}{}h", sign, abs_nanos / 3_600_000_000_000)
2087                } else if abs_nanos >= 60_000_000_000 {
2088                    // Minutes
2089                    format!("{}{}min", sign, abs_nanos / 60_000_000_000)
2090                } else if abs_nanos >= 1_000_000_000 {
2091                    // Seconds
2092                    format!("{}{}s", sign, abs_nanos / 1_000_000_000)
2093                } else if abs_nanos >= 1_000_000 {
2094                    // Milliseconds
2095                    format!("{}{}ms", sign, abs_nanos / 1_000_000)
2096                } else if abs_nanos >= 1_000 {
2097                    // Microseconds
2098                    format!("{}{}μs", sign, abs_nanos / 1_000)
2099                } else {
2100                    // Nanoseconds
2101                    format!("{}{}ns", sign, abs_nanos)
2102                }
2103            }
2104            RuntimeValue::Date(days) => {
2105                // Convert days since epoch to YYYY-MM-DD format
2106                // Using Howard Hinnant's algorithm
2107                let z = *days as i64 + 719468; // shift epoch
2108                let era = if z >= 0 { z } else { z - 146096 } / 146097;
2109                let doe = z - era * 146097;
2110                let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2111                let y = yoe + era * 400;
2112                let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2113                let mp = (5 * doy + 2) / 153;
2114                let d = doy - (153 * mp + 2) / 5 + 1;
2115                let m = mp + if mp < 10 { 3 } else { -9 };
2116                let year = y + if m <= 2 { 1 } else { 0 };
2117                format!("{:04}-{:02}-{:02}", year, m, d)
2118            }
2119            RuntimeValue::Moment(nanos) => {
2120                // Convert nanoseconds since epoch to ISO-8601-like datetime.
2121                // Use floored (Euclidean) division so a pre-epoch (negative)
2122                // Moment yields the correct date and a 0..86399 time-of-day,
2123                // not a negative hour/minute.
2124                let total_seconds = nanos.div_euclid(1_000_000_000);
2125                let days = total_seconds.div_euclid(86400) as i32;
2126                let day_seconds = total_seconds.rem_euclid(86400);
2127                let hours = day_seconds / 3600;
2128                let minutes = (day_seconds % 3600) / 60;
2129
2130                // Convert days since epoch to YYYY-MM-DD using Howard Hinnant's algorithm
2131                let z = days as i64 + 719468;
2132                let era = if z >= 0 { z } else { z - 146096 } / 146097;
2133                let doe = z - era * 146097;
2134                let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2135                let y = yoe + era * 400;
2136                let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2137                let mp = (5 * doy + 2) / 153;
2138                let d = doy - (153 * mp + 2) / 5 + 1;
2139                let m = mp + if mp < 10 { 3 } else { -9 };
2140                let year = y + if m <= 2 { 1 } else { 0 };
2141
2142                format!("{:04}-{:02}-{:02} {:02}:{:02}", year, m, d, hours, minutes)
2143            }
2144            RuntimeValue::Span { months, days } => {
2145                // Format span with years, months, and days
2146                let mut parts = Vec::new();
2147
2148                // Extract years from months
2149                let years = *months / 12;
2150                let remaining_months = *months % 12;
2151
2152                if years != 0 {
2153                    parts.push(if years.abs() == 1 {
2154                        format!("{} year", years)
2155                    } else {
2156                        format!("{} years", years)
2157                    });
2158                }
2159
2160                if remaining_months != 0 {
2161                    parts.push(if remaining_months.abs() == 1 {
2162                        format!("{} month", remaining_months)
2163                    } else {
2164                        format!("{} months", remaining_months)
2165                    });
2166                }
2167
2168                if *days != 0 || parts.is_empty() {
2169                    parts.push(if days.abs() == 1 {
2170                        format!("{} day", days)
2171                    } else {
2172                        format!("{} days", days)
2173                    });
2174                }
2175
2176                parts.join(" and ")
2177            }
2178            RuntimeValue::Time(nanos) => {
2179                // The wall-clock time-of-day, lossless to the nanosecond (HH:MM:SS[.frac]).
2180                logicaffeine_base::temporal::format_time_of_day(*nanos)
2181            }
2182        }
2183    }
2184}
2185
2186/// Control flow signals returned from statement execution.
2187///
2188/// These signals allow the interpreter to handle early exits from blocks,
2189/// function returns, and loop breaks without exceptions.
2190pub enum ControlFlow {
2191    /// Continue normal execution to the next statement.
2192    Continue,
2193    /// Return from the current function with a value.
2194    Return(RuntimeValue),
2195    /// Break out of the current loop.
2196    Break,
2197}
2198
2199/// Where a callback runs: the instance that owns the action, and which action it is.
2200#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2201pub struct ActionRef {
2202    pub instance: String,
2203    pub name: Symbol,
2204}
2205
2206/// Stored function definition for user-defined functions.
2207///
2208/// Captures the parameter list, body statements, and optional return type
2209/// for later invocation when the function is called.
2210#[derive(Clone)]
2211pub struct FunctionDef<'a> {
2212    /// Parameter names paired with their type expressions.
2213    pub params: Vec<(Symbol, &'a TypeExpr<'a>)>,
2214    /// Statements comprising the function body.
2215    pub body: Block<'a>,
2216    /// Optional declared return type.
2217    pub return_type: Option<&'a TypeExpr<'a>>,
2218    /// A `## To native` declaration: no body to run, so a call reaches the engine's own
2219    /// implementation of the name or is refused by name.
2220    pub is_native: bool,
2221    /// The Rust function a native declaration names (`is native "crate::module::function"`).
2222    pub native_path: Option<Symbol>,
2223}
2224
2225/// Tree-walking interpreter for LOGOS programs.
2226///
2227/// Phase 55: Now async with optional VFS for file operations.
2228/// Phase 102: Kernel context for inductive type support.
2229/// Flat environment with O(1) lookup and undo-log scoping.
2230/// LEXICALLY scoped environment.
2231///
2232/// Main's top-level bindings are globals, visible (and assignable) everywhere.
2233/// Each function call swaps in a fresh `locals` frame — a callee sees its
2234/// parameters, its own bindings, and the globals, but NEVER its caller's
2235/// locals. Block scopes (If/While/Repeat bodies, Zone, Inspect arms) are
2236/// undo-logged: `define`s inside a block are reverted when it ends, while
2237/// `assign`s persist (mutation is not binding).
2238struct Environment {
2239    /// Main TOP-LEVEL bindings — the program's globals, visible everywhere.
2240    globals: HashMap<Symbol, RuntimeValue>,
2241    /// Main BLOCK-scoped bindings (Let inside an If/While/Repeat at Main
2242    /// level). Lexically NOT visible to called functions.
2243    main_block: HashMap<Symbol, RuntimeValue>,
2244    /// The current function frame's bindings.
2245    locals: HashMap<Symbol, RuntimeValue>,
2246    save_stack: Vec<Vec<(Symbol, Option<RuntimeValue>)>>,
2247    // Shelved (locals, save_stack) of each caller. The save stack is shelved
2248    // WITH the locals so a callee's defines can never be recorded into a
2249    // caller's undo frame.
2250    frame_stack: Vec<(
2251        HashMap<Symbol, RuntimeValue>,
2252        Vec<Vec<(Symbol, Option<RuntimeValue>)>>,
2253    )>,
2254}
2255
2256impl Environment {
2257    fn new() -> Self {
2258        Environment {
2259            globals: HashMap::new(),
2260            main_block: HashMap::new(),
2261            locals: HashMap::new(),
2262            save_stack: Vec::new(),
2263            frame_stack: Vec::new(),
2264        }
2265    }
2266
2267    fn in_function(&self) -> bool {
2268        !self.frame_stack.is_empty()
2269    }
2270
2271    /// The map `define` writes to in the current context: function locals, or
2272    /// at Main level the block map (inside a block) vs the globals (at root).
2273    fn define_map(&mut self) -> &mut HashMap<Symbol, RuntimeValue> {
2274        if !self.frame_stack.is_empty() {
2275            &mut self.locals
2276        } else if !self.save_stack.is_empty() {
2277            &mut self.main_block
2278        } else {
2279            &mut self.globals
2280        }
2281    }
2282
2283    /// Enter a function frame: the caller's locals and undo log are shelved;
2284    /// the callee starts with neither (the lexical barrier).
2285    fn push_frame(&mut self) {
2286        self.frame_stack.push((
2287            std::mem::take(&mut self.locals),
2288            std::mem::take(&mut self.save_stack),
2289        ));
2290    }
2291
2292    /// Leave a function frame, restoring the caller's locals and undo log.
2293    fn pop_frame(&mut self) {
2294        let (locals, saves) = self.frame_stack.pop().unwrap_or_default();
2295        self.locals = locals;
2296        self.save_stack = saves;
2297    }
2298
2299    fn push_scope(&mut self) {
2300        self.save_stack.push(Vec::new());
2301    }
2302
2303    fn pop_scope(&mut self) {
2304        if let Some(saves) = self.save_stack.pop() {
2305            let map = if !self.frame_stack.is_empty() {
2306                &mut self.locals
2307            } else {
2308                // Main level: block-scoped defines live in main_block (a
2309                // define at Main ROOT records no undo — save_stack was empty).
2310                &mut self.main_block
2311            };
2312            for (sym, old_val) in saves.into_iter().rev() {
2313                match old_val {
2314                    Some(val) => {
2315                        map.insert(sym, val);
2316                    }
2317                    None => {
2318                        map.remove(&sym);
2319                    }
2320                }
2321            }
2322        }
2323    }
2324
2325    fn define(&mut self, name: Symbol, value: RuntimeValue) {
2326        let map = self.define_map();
2327        let old = map.insert(name, value);
2328        if let Some(frame) = self.save_stack.last_mut() {
2329            frame.push((name, old));
2330        }
2331    }
2332
2333    fn lookup(&self, name: Symbol) -> Option<&RuntimeValue> {
2334        if self.in_function() {
2335            self.locals.get(&name).or_else(|| self.globals.get(&name))
2336        } else {
2337            self.main_block
2338                .get(&name)
2339                .or_else(|| self.globals.get(&name))
2340        }
2341    }
2342
2343    /// The binding `name` resolves to, as [`Environment::lookup`] resolves it, to write through.
2344    fn lookup_mut(&mut self, name: Symbol) -> Option<&mut RuntimeValue> {
2345        let scoped = if self.in_function() {
2346            &mut self.locals
2347        } else {
2348            &mut self.main_block
2349        };
2350        if scoped.contains_key(&name) {
2351            return scoped.get_mut(&name);
2352        }
2353        self.globals.get_mut(&name)
2354    }
2355
2356    /// The current function frame's own binding of `name`, taken out of the frame.
2357    fn take_local(&mut self, name: Symbol) -> Option<RuntimeValue> {
2358        self.locals.remove(&name)
2359    }
2360
2361    fn assign(&mut self, name: Symbol, value: RuntimeValue) -> bool {
2362        if self.in_function() {
2363            if self.locals.contains_key(&name) {
2364                self.locals.insert(name, value);
2365                return true;
2366            }
2367        } else if self.main_block.contains_key(&name) {
2368            self.main_block.insert(name, value);
2369            return true;
2370        }
2371        if self.globals.contains_key(&name) {
2372            self.globals.insert(name, value);
2373            true
2374        } else {
2375            false
2376        }
2377    }
2378}
2379
2380/// Side-table entry storing a closure body AST reference.
2381/// The index into the `closure_bodies` Vec on the interpreter is stored
2382/// in `ClosureValue::body_index`.
2383#[derive(Clone)]
2384pub enum ClosureBodyRef<'a> {
2385    Expression(&'a Expr<'a>),
2386    Block(Block<'a>),
2387}
2388
2389/// `Send redundant` FEC parameters: split into `REDUNDANT_K` data shards plus
2390/// `REDUNDANT_N − REDUNDANT_K` parity shards, so a receiver reconstructs from any
2391/// `REDUNDANT_K` and tolerates losing up to `REDUNDANT_N − REDUNDANT_K` of the `REDUNDANT_N`
2392/// (here 2 of 6 — a 33% loss budget at 1.5× bandwidth).
2393const REDUNDANT_K: usize = 4;
2394const REDUNDANT_N: usize = 6;
2395
2396pub struct Interpreter<'a> {
2397    /// Shared, mostly-immutable context — interner, function/struct tables,
2398    /// platform handles, pre-interned builtin symbols. Held directly for the
2399    /// single-task case; wrapped in `Rc<SharedCtx>` and shared across per-task
2400    /// `Interpreter` instances once the scheduler spawns concurrent tasks.
2401    ctx: SharedCtx<'a>,
2402    /// Per-task execution state — owned per task so the cooperative scheduler can
2403    /// run multiple task continuations without aliasing the interpreter.
2404    task: TaskState,
2405    /// The program's output lines. Public API consumed by `ui_bridge`.
2406    pub output: Vec<String>,
2407    /// The `id` of the last `Stmt::Site` marker this task passed through (Wave 3: "runtime
2408    /// failures carry a location") — `None` before the first one, or outside any component's
2409    /// action/handler (`## Main`/`## Test`'s own top-level statements carry no marker; their
2410    /// location already comes from `Parser::stmt_spans`). A runtime error renders with whichever
2411    /// site is current when it is raised; see `Stmt::Site`'s own doc comment for why "current site"
2412    /// alone is enough with no call stack. Public API consumed by `ui_bridge`/`compile.rs`, same as
2413    /// `output` above, once the failure-site table itself reaches them (`FailureSite::render` needs
2414    /// this id plus `Parser::failure_sites()[id]`, not this crate's to build alone yet).
2415    pub current_site: Option<u32>,
2416    /// Set when this interpreter is a scheduled concurrent task: the side-channel
2417    /// to the scheduler. `None` for ordinary single-task execution.
2418    yield_state: Option<crate::concurrency::bridge::Yield<'a>>,
2419    /// Where a scheduled task's failure goes: the run's one sink, shared with every task it launches,
2420    /// so a launched task that fails fails the run (first failure kept), as it does on the VM. `None`
2421    /// outside a scheduled run.
2422    err_sink: Option<ErrSink>,
2423    /// All peer-messaging state — the relay handle, this node's inbox topic, the received-message
2424    /// buffer, the wire schema caches, and the FEC shard buffer — lifted into one shared
2425    /// [`crate::concurrency::net_inbox::NetInbox`] so the bytecode VM's task driver owns the SAME
2426    /// inbox and networking runs byte-identically on both tiers (no tier silently differs).
2427    netbox: crate::concurrency::net_inbox::NetInbox,
2428    /// Open tcp.lg client connections (async tiers) — the VM driver owns its own
2429    /// instance; both funnel through the ONE `exec_values` so semantics match.
2430    tcpbox: crate::concurrency::tcp_registry::TcpRegistry,
2431    /// Test mode (the `largo test` runner, constitution Wave 3): when armed,
2432    /// `Expect` records-and-continues into this sink instead of erroring, and
2433    /// every executed statement counts against a deterministic op budget.
2434    test_mode: bool,
2435    /// Recorded expectation failures (record-and-continue: one run reports all).
2436    test_failures: Vec<String>,
2437    /// Statements executed under test mode — deterministic, identical across
2438    /// machines and parallelism (the flake-proof timeout's clock).
2439    test_ops: u64,
2440    /// How many ASSERTIONS this test executed — every `Expect`/`Expect this to
2441    /// fail`/`Expect output:`/`For all` property. A test that finishes with zero
2442    /// is VACUOUS (G13): the runner fails it rather than reporting a green that
2443    /// checked nothing.
2444    test_assertions: u64,
2445    /// The op budget; exceeding it fails the test at the identical op, always.
2446    test_budget: u64,
2447    /// Property-generation stream (SplitMix64), seeded per test — the recorded
2448    /// entropy behind `For all` (constitution §1.5).
2449    gen_rng: u64,
2450    /// `--prove` mode: over a FINITE domain, run every case exhaustively — a
2451    /// proof, not a sample (constitution §1.6).
2452    prove_mode: bool,
2453    /// How many properties this run PROVED by exhaustion (finite domains).
2454    properties_proven: u64,
2455    /// General engine fuel (`largo run --max-steps`, the MCP `step_budget`):
2456    /// one shared cell spans every interpreter of the run — the main task,
2457    /// spawned tasks, closure children — so a runaway anywhere stops the
2458    /// whole cohort at a deterministic op. `None` (every existing path) costs
2459    /// one branch per statement.
2460    fuel: Option<FuelHandles>,
2461    /// The wall-clock budget for the request currently being served, armed only
2462    /// while a `Serve` handler is running.
2463    ///
2464    /// The compiled tier races its handler against a timer by moving it to a
2465    /// blocking thread; this one cannot, because the handler borrows `&mut self`
2466    /// and runs inline on the single loop thread. So the budget is enforced from
2467    /// the inside, at the same per-statement checkpoint the op budget uses.
2468    ///
2469    /// The granularity is honest and worth stating: the deadline is observed
2470    /// BETWEEN statements, so a single long-running builtin still runs to
2471    /// completion. It bounds a runaway loop, not a runaway primitive.
2472    request_deadline: Option<std::time::Instant>,
2473    /// Counts statements between clock reads, so an armed deadline costs a
2474    /// wrapping increment per statement rather than a syscall.
2475    deadline_tick: u32,
2476    /// The `--tiers all` replay profile: test-only statements (`Expect`/
2477    /// `ForAll`/…) execute as NO-OPS — the exact mirror of the VM compiler's
2478    /// `compile_tiers`, so the cross-tier comparison runs TWO ENGINES on ONE
2479    /// program (the computation around the assertions).
2480    tiers_noop: bool,
2481    /// Who carries out this run's driving statements (`Click`, `Mount`, `Navigate`, …).
2482    page: PageSeat<'a>,
2483    /// Called with its index after each top-level statement of `run`/`run_sync` finishes — lets
2484    /// a caller driving a page through [`Interpreter::with_page`] observe the page once per test
2485    /// statement in the course of ONE run, rather than re-running a growing prefix from scratch.
2486    statement_observer: Option<Box<dyn FnMut(usize) + 'a>>,
2487    /// The page's own program, as [`Interpreter::run_page_main`] ran it — what a reload
2488    /// ([`crate::page_host::LoweredCalls::reload`]) runs again. `None` until the page's main has
2489    /// run, and a host cannot call into a page that never loaded.
2490    page_main: Option<Vec<Stmt<'a>>>,
2491    /// The failure site in force when the most recent failed host call trapped
2492    /// ([`crate::page_host::LoweredCalls::failure_site`]).
2493    failed_call_site: Option<u32>,
2494    /// The run real numbers the program defines by a function read their functions in, opened the
2495    /// first time the program defines one ([`Interpreter::open_defined_run`]).
2496    defined_run: Option<crate::semantics::defined::RunScope<'a>>,
2497}
2498
2499/// Who carries out a run's driving statements.
2500enum PageSeat<'a> {
2501    /// No page: a task launched beside the test runs its function and drives nothing.
2502    Unseated,
2503    /// A page another engine executes — the bytecode VM's lowered page, or a real browser.
2504    Driven(std::rc::Rc<std::cell::RefCell<dyn crate::page_host::DrivenPage + 'a>>),
2505    /// The page's lowered program, run by this interpreter itself, through the one driver every
2506    /// lowered tier shares.
2507    Here(HostedPage),
2508}
2509
2510/// A lowered page this interpreter runs itself ([`Interpreter::host_lowered_page`]).
2511struct HostedPage {
2512    /// The page's host; lent out (`None`) for as long as it is carrying a statement out on this
2513    /// interpreter.
2514    host: Option<crate::page_host::LoweredHost>,
2515    /// The first driving statement the page could not carry at all, and why — a statement this
2516    /// tier refuses, as opposed to one the page answered with a failure.
2517    refused: Option<(crate::page_host::Drive, String)>,
2518}
2519
2520impl HostedPage {
2521    /// The seat of a page whose `## Page` component `page` names, if it mounts one by itself.
2522    fn of(page: Option<String>) -> Self {
2523        HostedPage {
2524            host: Some(crate::page_host::LoweredHost::of_page(page)),
2525            refused: None,
2526        }
2527    }
2528}
2529
2530/// The shared fuel cell for one budgeted run, and its structured verdict.
2531///
2532/// Install with [`install_fuel`] before starting an engine, read
2533/// `exhausted`/`remaining` after it returns, and [`clear_fuel`] when done.
2534/// The boundary never string-sniffs: `exhausted` IS the budget-exceeded
2535/// signal.
2536#[derive(Clone)]
2537pub struct FuelHandles {
2538    /// The installed budget, for messages and `steps_used` accounting.
2539    pub budget: u64,
2540    /// Steps left; zero once exhausted.
2541    pub remaining: std::rc::Rc<std::cell::Cell<u64>>,
2542    /// Set at the deterministic op where the budget ran dry.
2543    pub exhausted: std::rc::Rc<std::cell::Cell<bool>>,
2544}
2545
2546impl FuelHandles {
2547    /// The engine-agnostic exhaustion story (tree-walker and VM agree).
2548    pub fn exhaust_message(&self) -> String {
2549        format!(
2550            "step budget of {} exhausted — the program was stopped at a deterministic op; \
2551             raise --max-steps (or the MCP step_budget) to allow more",
2552            self.budget
2553        )
2554    }
2555}
2556
2557thread_local! {
2558    /// The fuel active on this thread, picked up by every [`Interpreter::new`]
2559    /// (the tree-walker's cooperative concurrency is single-threaded, so one
2560    /// thread-local spans the whole task cohort) and consulted by the VM's
2561    /// straight-line run path.
2562    static ACTIVE_FUEL: std::cell::RefCell<Option<FuelHandles>> = const { std::cell::RefCell::new(None) };
2563}
2564
2565/// Arm a step budget for every engine started on this thread until
2566/// [`clear_fuel`]. Returns the handles the caller reads after the run.
2567pub fn install_fuel(budget: u64) -> FuelHandles {
2568    let handles = FuelHandles {
2569        budget,
2570        remaining: std::rc::Rc::new(std::cell::Cell::new(budget)),
2571        exhausted: std::rc::Rc::new(std::cell::Cell::new(false)),
2572    };
2573    ACTIVE_FUEL.with(|cell| *cell.borrow_mut() = Some(handles.clone()));
2574    handles
2575}
2576
2577/// Disarm the thread's fuel (always paired with [`install_fuel`]).
2578pub fn clear_fuel() {
2579    ACTIVE_FUEL.with(|cell| *cell.borrow_mut() = None);
2580}
2581
2582/// The fuel currently armed on this thread, if any.
2583pub fn active_fuel() -> Option<FuelHandles> {
2584    ACTIVE_FUEL.with(|cell| cell.borrow().clone())
2585}
2586
2587/// The shared interpreter context: function definitions, type metadata, platform
2588/// handles, and pre-interned builtin symbols. Immutable-after-setup, so multiple
2589/// per-task [`Interpreter`]s can share one `Rc<SharedCtx>` while each owns its own
2590/// [`TaskState`] — the basis of the tree-walker's re-entrancy for concurrency.
2591#[derive(Clone)]
2592struct SharedCtx<'a> {
2593    interner: &'a Interner,
2594    functions: HashMap<Symbol, FunctionDef<'a>>,
2595    /// `## Component` / `## Page` / `## Store` definitions by name — what the lowering's gate reads
2596    /// to explain a `Mount` the lowered page refused, what a route's server walk places, and what
2597    /// says whether the program needs the relay.
2598    components: HashMap<Symbol, crate::ast::component::ComponentDef<'a>>,
2599    /// The program's type registry, as `with_type_registry` was given it — what the lowering's
2600    /// own gate asks when it explains a `Mount` the lowered page refused.
2601    types: Option<crate::analysis::TypeRegistry>,
2602    struct_defs: HashMap<Symbol, Vec<(Symbol, Symbol, bool)>>,
2603    /// Enum type → its constructor names in declaration order. Feeds the wire type
2604    /// registry so `Send shared` elides enum type/constructor names (T_INDUCTIVE_TID),
2605    /// the enum analog of struct name elision.
2606    enum_defs: HashMap<Symbol, Vec<Symbol>>,
2607    /// A variant's OWN field names, in DECLARATION order — the enum analog of `struct_defs`,
2608    /// keyed by `(enum name, constructor name)`. Keyed by the constructor alone until this session:
2609    /// two enums declaring a same-named variant with DIFFERENT field shapes (`a new Failure from
2610    /// Outcome`/`a new Failure from Status`, made constructible together for the first time by the
2611    /// `from`-qualification lang5 landed) would collide on one shared entry, whichever registered
2612    /// second in the discovery pass's own `HashMap` iteration order silently winning — a real,
2613    /// order-dependent wrong-field-order bug, not a cosmetic one, since `from`-qualification is
2614    /// exactly what makes both enums' same-named variants constructible in one program. `Expr::
2615    /// NewVariant`'s construction is written field-name-first and is documented as ORDER-INDEPENDENT
2616    /// (`a new X with b 2 and a 1` is legal), but `RuntimeValue::Inductive` stores its payload
2617    /// POSITIONALLY (`args: Vec<RuntimeValue>`) — this table is what lets construction re-seat each
2618    /// evaluated value at its DECLARED index regardless of the order it was written in, so a later
2619    /// positional read (`ind.args[i]`, `Inspect`'s destructuring bindings) always means "the i-th
2620    /// DECLARED field", never "the i-th WRITTEN field". Only ever consulted AT CONSTRUCTION
2621    /// (`Expr::NewVariant` already names its own enum), never at `Inspect`/match time — a match
2622    /// binds positionally into whatever `args` construction already seated correctly, needing no
2623    /// enum resolution of its own.
2624    variant_fields: HashMap<(Symbol, Symbol), Vec<Symbol>>,
2625    vfs: Option<Arc<dyn Vfs>>,
2626    kernel_ctx: Option<Arc<crate::kernel::Context>>,
2627    policy_registry: Option<PolicyRegistry>,
2628    output_callback: Option<OutputCallback>,
2629    /// Side-table for closure body AST references.
2630    /// Indexed by `ClosureValue::body_index`.
2631    closure_bodies: Vec<ClosureBodyRef<'a>>,
2632    // Pre-interned builtin function symbols for O(1) dispatch
2633    sym_show: Option<Symbol>,
2634    sym_length: Option<Symbol>,
2635    sym_format: Option<Symbol>,
2636    sym_parse_int: Option<Symbol>,
2637    sym_parse_float: Option<Symbol>,
2638    sym_abs: Option<Symbol>,
2639    sym_sqrt: Option<Symbol>,
2640    sym_min: Option<Symbol>,
2641    sym_max: Option<Symbol>,
2642    sym_floor: Option<Symbol>,
2643    sym_ceil: Option<Symbol>,
2644    sym_round: Option<Symbol>,
2645    sym_pow: Option<Symbol>,
2646    sym_copy: Option<Symbol>,
2647    sym_chr: Option<Symbol>,
2648    sym_count_ones: Option<Symbol>,
2649    sym_args: Option<Symbol>,
2650    /// Program arguments for the `args()` system native — full argv, index 0 is
2651    /// the program name (mirrors the compiled binary's `env::args()`).
2652    program_args: Vec<String>,
2653}
2654
2655/// The per-task execution state the cooperative scheduler owns for each task.
2656/// Splitting it out of [`Interpreter`] lets multiple task continuations coexist —
2657/// each with its own `&mut TaskState` over one shared interpreter context — which
2658/// is what makes the tree-walker re-entrant for concurrency.
2659struct TaskState {
2660    /// Variable bindings / scopes for this task.
2661    env: Environment,
2662    /// Live LOGOS call depth, bounded by `semantics::MAX_CALL_DEPTH`.
2663    call_depth: usize,
2664    /// The user function whose body the SYNC path is currently executing. A
2665    /// `Return self(args)` (or the `Set/Let x to self(args); Return x` pair) of
2666    /// THIS function is a self-tail-call: `call_function_sync` reassigns the
2667    /// parameters and loops to the body's start instead of recursing, so tail
2668    /// recursion runs in constant stack — matching the VM and the AOT TCE.
2669    tco_fn_sync: Option<Symbol>,
2670    /// Set by a recognized self-tail-call: the already-evaluated arguments for
2671    /// the next loop iteration, consumed by `call_function_sync`.
2672    pending_tail_call: Option<Vec<RuntimeValue>>,
2673    /// `Repeat` (for-each) nesting on the SYNC path within the current function
2674    /// body. A `Repeat` owns a live iterator, so — exactly like the VM's
2675    /// `is_repeat` guard — a self-tail-call detected inside one stays an ordinary
2676    /// recursive call, keeping the two engines bit-identical. Reset at call boundaries.
2677    repeat_depth_sync: usize,
2678    /// `tco_fn_sync` for the ASYNC execution path; same constant-stack TCO semantics.
2679    tco_fn_async: Option<Symbol>,
2680    /// `pending_tail_call` for the ASYNC path.
2681    pending_tail_call_async: Option<Vec<RuntimeValue>>,
2682    /// `repeat_depth_sync` for the ASYNC path.
2683    repeat_depth_async: usize,
2684}
2685
2686impl TaskState {
2687    fn new() -> Self {
2688        TaskState {
2689            env: Environment::new(),
2690            call_depth: 0,
2691            tco_fn_sync: None,
2692            pending_tail_call: None,
2693            repeat_depth_sync: 0,
2694            tco_fn_async: None,
2695            pending_tail_call_async: None,
2696            repeat_depth_async: 0,
2697        }
2698    }
2699}
2700
2701/// The message a request that outran its wall-clock budget carries. The serve
2702/// loop matches on it to answer `503` (the peer should retry) rather than the
2703/// `500` an ordinary handler failure gets.
2704pub(crate) const REQUEST_TIMED_OUT: &str = "request exceeded its time budget";
2705
2706impl<'a> Interpreter<'a> {
2707    pub fn new(interner: &'a Interner) -> Self {
2708        Interpreter {
2709            ctx: SharedCtx {
2710                interner,
2711                functions: HashMap::new(),
2712                components: HashMap::new(),
2713                types: None,
2714                struct_defs: HashMap::new(),
2715                enum_defs: HashMap::new(),
2716                variant_fields: HashMap::new(),
2717                vfs: None,
2718                kernel_ctx: None,
2719                policy_registry: None,
2720                output_callback: None,
2721                closure_bodies: Vec::new(),
2722                sym_show: interner.lookup("show"),
2723                sym_length: interner.lookup("length"),
2724                sym_format: interner.lookup("format"),
2725                sym_parse_int: interner.lookup("parseInt"),
2726                sym_parse_float: interner.lookup("parseFloat"),
2727                sym_abs: interner.lookup("abs"),
2728                sym_sqrt: interner.lookup("sqrt"),
2729                sym_min: interner.lookup("min"),
2730                sym_max: interner.lookup("max"),
2731                sym_floor: interner.lookup("floor"),
2732                sym_ceil: interner.lookup("ceil"),
2733                sym_round: interner.lookup("round"),
2734                sym_pow: interner.lookup("pow"),
2735                sym_copy: interner.lookup("copy"),
2736                sym_chr: interner.lookup("chr"),
2737                sym_count_ones: interner.lookup("count_ones"),
2738                sym_args: interner.lookup("args"),
2739                program_args: crate::semantics::argv_with_program_name(Vec::new()),
2740            },
2741            task: TaskState::new(),
2742            output: Vec::new(),
2743            current_site: None,
2744            yield_state: None,
2745            err_sink: None,
2746            netbox: crate::concurrency::net_inbox::NetInbox::new(),
2747            tcpbox: crate::concurrency::tcp_registry::TcpRegistry::new(),
2748            test_mode: false,
2749            test_failures: Vec::new(),
2750            test_ops: 0,
2751            test_assertions: 0,
2752            test_budget: u64::MAX,
2753            gen_rng: 0,
2754            prove_mode: false,
2755            properties_proven: 0,
2756            fuel: active_fuel(),
2757            request_deadline: None,
2758            deadline_tick: 0,
2759            tiers_noop: false,
2760            page: PageSeat::Here(HostedPage::of(None)),
2761            statement_observer: None,
2762            page_main: None,
2763            failed_call_site: None,
2764            defined_run: None,
2765        }
2766    }
2767
2768    /// Arm test mode (the `largo test` runner): `Expect` records-and-continues
2769    /// and every statement counts against the deterministic op `budget`.
2770    pub fn enable_test_mode(&mut self, budget: u64) {
2771        self.test_mode = true;
2772        self.test_budget = budget;
2773    }
2774
2775    /// Arm the `--tiers all` replay profile: test-only statements execute as
2776    /// no-ops (the interpreter twin of the VM's `compile_tiers`), so the tier
2777    /// differential compares the COMPUTATION on two engines, one program.
2778    pub fn set_tiers_noop(&mut self, on: bool) {
2779        self.tiers_noop = on;
2780    }
2781
2782    /// Seed the property-generation stream (the runner keys this by test
2783    /// identity so counterexamples are stable across runs).
2784    pub fn set_gen_seed(&mut self, seed: u64) {
2785        self.gen_rng = seed;
2786    }
2787
2788    /// Enable `--prove` — finite-domain properties run exhaustively (a proof).
2789    pub fn set_prove_mode(&mut self, on: bool) {
2790        self.prove_mode = on;
2791    }
2792
2793    /// How many properties were PROVED by exhaustion this run.
2794    pub fn properties_proven(&self) -> u64 {
2795        self.properties_proven
2796    }
2797
2798    /// Next SplitMix64 draw from the property stream.
2799    fn draw_u64(&mut self) -> u64 {
2800        self.gen_rng = self.gen_rng.wrapping_add(0x9E37_79B9_7F4A_7C15);
2801        let mut z = self.gen_rng;
2802        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
2803        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
2804        z ^ (z >> 31)
2805    }
2806
2807    /// Draw one value for a property domain (bounded so display and shrinking
2808    /// stay tractable; integers in [-1000, 1000], naturals in [0, 1000]).
2809    fn draw_domain(&mut self, domain: crate::ast::stmt::PropDomain) -> RuntimeValue {
2810        use crate::ast::stmt::PropDomain;
2811        let r = self.draw_u64();
2812        match domain {
2813            PropDomain::Integers => RuntimeValue::Int((r % 2001) as i64 - 1000),
2814            PropDomain::Naturals => RuntimeValue::Int((r % 1001) as i64),
2815            PropDomain::Booleans => RuntimeValue::Bool(r & 1 == 0),
2816        }
2817    }
2818
2819    /// Run a `For all` property: generate seeded cases, and on the first
2820    /// failure shrink to a minimal counterexample and record it (§1.5/§1.6).
2821    /// Pure-body statements run on the sync path (properties are pure), so this
2822    /// one implementation serves both the async and sync `ForAll` arms.
2823    fn run_property(
2824        &mut self,
2825        vars: &[Symbol],
2826        domain: crate::ast::stmt::PropDomain,
2827        constraint: Option<&'a Expr<'a>>,
2828        body: &[Stmt<'a>],
2829    ) -> Result<(), String> {
2830        use crate::ast::stmt::PropDomain;
2831        // A `For all` property is an assertion (G13 non-vacuity) — a test whose
2832        // only check is a property is NOT vacuous.
2833        self.test_assertions += 1;
2834        // `--prove` over a FINITE domain: enumerate EVERY case — a proof, not a
2835        // sample. Booleans^k is 2^k cases; small enough to exhaust for k≤16.
2836        if self.prove_mode && domain == PropDomain::Booleans && vars.len() <= 16 {
2837            let total = 1usize << vars.len();
2838            let mut counterexample: Option<Vec<RuntimeValue>> = None;
2839            for mask in 0..total {
2840                let vals: Vec<RuntimeValue> = (0..vars.len())
2841                    .map(|i| RuntimeValue::Bool(mask & (1 << i) != 0))
2842                    .collect();
2843                if self.property_fails(vars, constraint, body, &vals)? {
2844                    counterexample = Some(vals);
2845                    break;
2846                }
2847            }
2848            if let Some(vals) = counterexample {
2849                self.record_counterexample(vars, constraint, body, vals)?;
2850            } else {
2851                self.properties_proven += 1; // exhausted with no failure = PROVED
2852            }
2853            return Ok(());
2854        }
2855
2856        const RUNS: u32 = 256;
2857        let mut counterexample: Option<Vec<RuntimeValue>> = None;
2858        for _ in 0..RUNS {
2859            let vals: Vec<RuntimeValue> =
2860                (0..vars.len()).map(|_| self.draw_domain(domain)).collect();
2861            if self.property_fails(vars, constraint, body, &vals)? {
2862                counterexample = Some(vals);
2863                break;
2864            }
2865        }
2866        if let Some(vals) = counterexample {
2867            self.record_counterexample(vars, constraint, body, vals)?;
2868        }
2869        Ok(())
2870    }
2871
2872    /// Shrink a failing case to its minimum and record it as a failure.
2873    fn record_counterexample(
2874        &mut self,
2875        vars: &[Symbol],
2876        constraint: Option<&'a Expr<'a>>,
2877        body: &[Stmt<'a>],
2878        vals: Vec<RuntimeValue>,
2879    ) -> Result<(), String> {
2880        let shrunk = self.shrink_property(vars, constraint, body, vals)?;
2881        let binding = vars
2882            .iter()
2883            .zip(shrunk.iter())
2884            .map(|(v, val)| {
2885                format!(
2886                    "{} = {}",
2887                    self.ctx.interner.resolve(*v),
2888                    val.to_display_string()
2889                )
2890            })
2891            .collect::<Vec<_>>()
2892            .join(", ");
2893        self.test_failures
2894            .push(format!("Property failed. Counterexample: {binding}"));
2895        Ok(())
2896    }
2897
2898    /// Bind `vals`, apply the filter, run the body, and report whether it FAILED
2899    /// — never leaking the probe's own expectation failures.
2900    fn property_fails(
2901        &mut self,
2902        vars: &[Symbol],
2903        constraint: Option<&'a Expr<'a>>,
2904        body: &[Stmt<'a>],
2905        vals: &[RuntimeValue],
2906    ) -> Result<bool, String> {
2907        for (v, val) in vars.iter().zip(vals.iter()) {
2908            self.define(*v, val.clone());
2909        }
2910        if let Some(c) = constraint {
2911            if !self.evaluate_expr_sync(c)?.decided_truth()? {
2912                return Ok(false); // filtered out — a non-case, never a failure
2913            }
2914        }
2915        let before = self.test_failures.len();
2916        for s in body.iter() {
2917            self.execute_stmt_sync(s)?;
2918        }
2919        let failed = self.test_failures.len() > before;
2920        self.test_failures.truncate(before);
2921        Ok(failed)
2922    }
2923
2924    /// Greedily shrink each value toward its domain zero, keeping the smallest
2925    /// still-failing case (internal shrinking, §1.5).
2926    fn shrink_property(
2927        &mut self,
2928        vars: &[Symbol],
2929        constraint: Option<&'a Expr<'a>>,
2930        body: &[Stmt<'a>],
2931        mut vals: Vec<RuntimeValue>,
2932    ) -> Result<Vec<RuntimeValue>, String> {
2933        let mut improved = true;
2934        let mut guard = 0;
2935        while improved && guard < 1000 {
2936            improved = false;
2937            guard += 1;
2938            for i in 0..vals.len() {
2939                for cand in shrink_candidates(&vals[i]) {
2940                    let mut trial = vals.clone();
2941                    trial[i] = cand;
2942                    if self.property_fails(vars, constraint, body, &trial)? {
2943                        vals = trial;
2944                        improved = true;
2945                        break;
2946                    }
2947                }
2948            }
2949        }
2950        Ok(vals)
2951    }
2952
2953    /// Take the recorded expectation failures (empties the sink).
2954    pub fn take_test_failures(&mut self) -> Vec<String> {
2955        std::mem::take(&mut self.test_failures)
2956    }
2957
2958    /// Statements executed under test mode — the deterministic op count.
2959    pub fn test_ops(&self) -> u64 {
2960        self.test_ops
2961    }
2962
2963    /// How many assertions (`Expect`/`ForAll`) this test executed. Zero = a
2964    /// VACUOUS test the runner must fail (G13).
2965    pub fn test_assertions(&self) -> u64 {
2966        self.test_assertions
2967    }
2968
2969    /// Count one statement against the test budget; `Err` when exhausted —
2970    /// at the identical op on every run (the timeout that cannot flake).
2971    /// Also drains the general [`FuelHandles`] cell when one is armed
2972    /// (`--max-steps` / MCP `step_budget`), which spans the whole cohort.
2973    fn tick_test_budget(&mut self) -> Result<(), String> {
2974        // A served request's wall-clock budget. Sampled every 512 statements so an
2975        // ordinary program pays one branch and a served request cannot run away.
2976        if let Some(deadline) = self.request_deadline {
2977            self.deadline_tick = self.deadline_tick.wrapping_add(1);
2978            if self.deadline_tick % 512 == 0 && std::time::Instant::now() > deadline {
2979                return Err(REQUEST_TIMED_OUT.to_string());
2980            }
2981        }
2982        if let Some(fuel) = &self.fuel {
2983            let left = fuel.remaining.get();
2984            if left == 0 {
2985                fuel.exhausted.set(true);
2986                return Err(fuel.exhaust_message());
2987            }
2988            fuel.remaining.set(left - 1);
2989        }
2990        if !self.test_mode {
2991            return Ok(());
2992        }
2993        self.test_ops += 1;
2994        if self.test_ops > self.test_budget {
2995            return Err(format!(
2996                "op budget of {} steps exhausted — a runaway test fails at the identical op \
2997                 on every run; a test that legitimately needs more declares it: \
2998                 `This test may run up to {} steps.`",
2999                self.test_budget,
3000                self.test_budget.saturating_mul(10)
3001            ));
3002        }
3003        Ok(())
3004    }
3005
3006    /// A Socratic hint keyed on a failed expectation's SHAPE (Wave 5). Float
3007    /// equality is the classic trap: `x is 0.3` where `x` drifted.
3008    fn expect_socratic_hint(condition: &Expr<'a>) -> Option<&'static str> {
3009        if let Expr::BinaryOp {
3010            op: BinaryOpKind::Eq,
3011            left,
3012            right,
3013        } = condition
3014        {
3015            let floaty = |e: &Expr<'a>| matches!(e, Expr::Literal(Literal::Float(_)));
3016            if floaty(left) || floaty(right) {
3017                return Some(
3018                    "floats drift — did you mean `is approximately X within <eps>`? (bare `is` is IEEE bit-exact)",
3019                );
3020            }
3021        }
3022        None
3023    }
3024
3025    /// Supply the program arguments read by the `args()` system native. The
3026    /// vector is the full argv (index 0 is the program name), matching the
3027    /// compiled binary's `env::args()`.
3028    pub fn with_program_args(mut self, args: Vec<String>) -> Self {
3029        self.ctx.program_args = crate::semantics::argv_with_program_name(args);
3030        self
3031    }
3032
3033    /// Phase 55: Set the VFS for file operations.
3034    pub fn with_vfs(mut self, vfs: Arc<dyn Vfs>) -> Self {
3035        self.ctx.vfs = Some(vfs);
3036        self
3037    }
3038
3039    /// Phase 102: Set the kernel context for inductive type support.
3040    ///
3041    /// When set, the interpreter can query the kernel for inductive types
3042    /// and constructors, enabling unified type system.
3043    pub fn with_kernel(mut self, ctx: Arc<crate::kernel::Context>) -> Self {
3044        self.ctx.kernel_ctx = Some(ctx);
3045        self
3046    }
3047
3048    /// Set the policy registry for security checks.
3049    pub fn with_policies(mut self, registry: PolicyRegistry) -> Self {
3050        self.ctx.policy_registry = Some(registry);
3051        self
3052    }
3053
3054    /// Populate struct_defs from a TypeRegistry (DiscoveryPass results).
3055    /// This allows the interpreter to initialize default field values for
3056    /// structs created with `new Point` (no explicit fields).
3057    pub fn with_type_registry(mut self, registry: &crate::analysis::TypeRegistry) -> Self {
3058        use crate::analysis::registry::{FieldType, TypeDef};
3059        self.ctx.types = Some(registry.clone());
3060        for (name_sym, type_def) in registry.iter_types() {
3061            if let TypeDef::Struct { fields, .. } = type_def {
3062                let field_defs: Vec<(Symbol, Symbol, bool)> = fields
3063                    .iter()
3064                    .map(|f| {
3065                        let type_sym = match &f.ty {
3066                            FieldType::Primitive(s)
3067                            | FieldType::Named(s)
3068                            | FieldType::TypeParam(s) => *s,
3069                            FieldType::Generic { base, .. } => *base,
3070                            // A tuple names no type with a scalar default.
3071                            FieldType::Tuple(_) | FieldType::Record(_) => Symbol::EMPTY,
3072                        };
3073                        (f.name, type_sym, f.is_public)
3074                    })
3075                    .collect();
3076                self.ctx.struct_defs.insert(*name_sym, field_defs);
3077            } else if let TypeDef::Enum { variants, .. } = type_def {
3078                // Constructor names in declaration order — the order is the wire's ctor
3079                // index, so both peers (deriving from the same program) agree.
3080                let ctors: Vec<Symbol> = variants.iter().map(|v| v.name).collect();
3081                self.ctx.enum_defs.insert(*name_sym, ctors);
3082                // Each variant's OWN field names, in declaration order — see `variant_fields`'s
3083                // own doc comment for why construction needs this, and why the key is
3084                // `(enum, variant)` rather than the variant alone.
3085                for v in variants {
3086                    let field_names: Vec<Symbol> = v.fields.iter().map(|f| f.name).collect();
3087                    self.ctx
3088                        .variant_fields
3089                        .insert((*name_sym, v.name), field_names);
3090                }
3091            }
3092        }
3093        self
3094    }
3095
3096    /// Set a callback for streaming output.
3097    /// The callback is called each time `Show` executes, with the output line.
3098    pub fn with_output_callback(mut self, callback: OutputCallback) -> Self {
3099        self.ctx.output_callback = Some(callback);
3100        self
3101    }
3102
3103    /// Drive this run's page through `p` — the bytecode VM's lowered page, or a real browser —
3104    /// instead of hosting the page's lowered program here. The seam a host uses to run a
3105    /// `## Test`'s statements ONCE and carry every driving verb (`Click`, `Mount`, `Navigate`, …)
3106    /// to whichever tier `p` fronts; every other statement (`Let`, `Set`, `Expect`, …) still runs
3107    /// here, against the interpreter's own evaluator.
3108    pub fn with_page(
3109        mut self,
3110        p: std::rc::Rc<std::cell::RefCell<dyn crate::page_host::DrivenPage + 'a>>,
3111    ) -> Self {
3112        self.page = PageSeat::Driven(p);
3113        self
3114    }
3115
3116    /// Observe each top-level statement of `run`/`run_sync` by index, right after it finishes.
3117    pub fn with_statement_observer(mut self, f: Box<dyn FnMut(usize) + 'a>) -> Self {
3118        self.statement_observer = Some(f);
3119        self
3120    }
3121
3122    /// Host `program` as this run's page, LOWERED, on this very interpreter: the page's main
3123    /// (`program`) runs once and settles, and from then on every driving statement this
3124    /// interpreter meets is carried out on the page by the driver every lowered tier shares
3125    /// ([`crate::page_host::LoweredHost`]), with this interpreter as the engine it calls into —
3126    /// exactly as a browser drives the page's module. `auto_mounted` names the `## Page` component
3127    /// the program mounts by itself, if any. A failing main is the page's failure; the page is
3128    /// hosted either way, as a browser can still call into a module whose `main` trapped.
3129    pub fn host_lowered_page(
3130        &mut self,
3131        program: &[Stmt<'a>],
3132        auto_mounted: Option<String>,
3133    ) -> Result<(), crate::page_host::DriveError> {
3134        self.page = PageSeat::Here(HostedPage::of(auto_mounted));
3135        let ran = self.run_page_main(program);
3136        self.with_hosted_page(|host, me| host.settle(me));
3137        ran.map_err(crate::page_host::DriveError::Failed)
3138    }
3139
3140    /// Lend the page hosted here to `f` together with this interpreter, its engine — `None` when no
3141    /// page is hosted here, or when its host is already carrying a statement out.
3142    fn with_hosted_page<R>(
3143        &mut self,
3144        f: impl FnOnce(&mut crate::page_host::LoweredHost, &mut Self) -> R,
3145    ) -> Option<R> {
3146        let PageSeat::Here(hosted) = &mut self.page else {
3147            return None;
3148        };
3149        let mut host = hosted.host.take()?;
3150        let out = f(&mut host, self);
3151        if let PageSeat::Here(hosted) = &mut self.page {
3152            hosted.host = Some(host);
3153        }
3154        Some(out)
3155    }
3156
3157    /// The first action failure the page hosted here ([`Interpreter::host_lowered_page`]) left
3158    /// unabsorbed by any handler — the page's own failure to report.
3159    pub fn hosted_page_failure(&self) -> Option<String> {
3160        match &self.page {
3161            PageSeat::Here(HostedPage {
3162                host: Some(host), ..
3163            }) => host.unhandled_failure().map(str::to_string),
3164            _ => None,
3165        }
3166    }
3167
3168    /// Where the page's first unabsorbed failure happened (its `Stmt::Site`), when the page is
3169    /// hosted here — the site a located error names, since the host's call has since returned.
3170    pub fn page_failure_site(&self) -> Option<u32> {
3171        match &self.page {
3172            PageSeat::Here(HostedPage {
3173                host: Some(host), ..
3174            }) => host.unhandled_failure_site(),
3175            _ => None,
3176        }
3177    }
3178
3179    /// The first action failure no handler absorbed, taken — whichever tier carried the page. A
3180    /// program that ran to the end reports it as its own failure: the page went on answering, and
3181    /// the failure still happened.
3182    pub fn take_page_failure(&mut self) -> Option<String> {
3183        match &mut self.page {
3184            PageSeat::Unseated => None,
3185            PageSeat::Driven(page) => page.borrow().unhandled_failure(),
3186            PageSeat::Here(hosted) => hosted
3187                .host
3188                .as_mut()
3189                .and_then(|h| h.take_unhandled_failure()),
3190        }
3191    }
3192
3193    /// The first driving statement the page hosted here could not carry at all, and why — `None`
3194    /// while every statement has been carried (or answered with a failure of the page's own).
3195    pub fn hosted_page_refusal(&self) -> Option<(&crate::page_host::Drive, &str)> {
3196        match &self.page {
3197            PageSeat::Here(HostedPage {
3198                refused: Some((d, why)),
3199                ..
3200            }) => Some((d, why.as_str())),
3201            _ => None,
3202        }
3203    }
3204
3205    /// Run `stmts` as the next top-level statements of the program this interpreter is already
3206    /// running — no fresh program start: definitions stay registered, globals stay bound, a hosted
3207    /// page stays hosted — until one returns or breaks, and answer that flow. What a host that
3208    /// walks a test body one step at a time runs each step with.
3209    pub fn run_statements(&mut self, stmts: &[Stmt<'a>]) -> Result<ControlFlow, String> {
3210        for stmt in stmts {
3211            match self.execute_stmt_sync(stmt)? {
3212                ControlFlow::Continue => {}
3213                flow => return Ok(flow),
3214            }
3215        }
3216        Ok(ControlFlow::Continue)
3217    }
3218
3219    /// [`Interpreter::run_statements`] on the async executor, for statements that need it.
3220    pub async fn run_statements_async(
3221        &mut self,
3222        stmts: &[Stmt<'a>],
3223    ) -> Result<ControlFlow, String> {
3224        for stmt in stmts {
3225            match self.execute_stmt(stmt).await? {
3226                ControlFlow::Continue => {}
3227                flow => return Ok(flow),
3228            }
3229        }
3230        Ok(ControlFlow::Continue)
3231    }
3232
3233    /// Carry the driving statement `d` out on the page seated here — the lowered program this
3234    /// interpreter hosts, or the page another engine executes — with the driver every lowered tier
3235    /// shares. A statement the page refuses or fails is this statement's failure.
3236    fn drive_page(&mut self, d: crate::page_host::Drive) -> Result<ControlFlow, String> {
3237        let outcome = match &mut self.page {
3238            PageSeat::Unseated => {
3239                return Err(format!(
3240                "`{}` drives the page, and a task launched beside the test has no page to drive",
3241                d.verb()
3242            ))
3243            }
3244            PageSeat::Driven(page) => {
3245                let page = page.clone();
3246                let outcome = page.borrow_mut().drive(&d);
3247                outcome
3248            }
3249            PageSeat::Here(_) => {
3250                let Some(mut outcome) = self.with_hosted_page(|host, me| host.drive(me, &d)) else {
3251                    return Err(format!(
3252                        "`{}` drives the page, and the page's own code cannot drive the page it \
3253                         is running in",
3254                        d.verb()
3255                    ));
3256                };
3257                if let (
3258                    crate::page_host::Drive::Mount { component, .. },
3259                    Err(crate::page_host::DriveError::Refused(why)),
3260                ) = (&d, &mut outcome)
3261                {
3262                    if let Some(reason) = self.why_not_lowered(component) {
3263                        *why = reason;
3264                    }
3265                }
3266                if let (PageSeat::Here(hosted), Err(crate::page_host::DriveError::Refused(why))) =
3267                    (&mut self.page, &outcome)
3268                {
3269                    hosted
3270                        .refused
3271                        .get_or_insert_with(|| (d.clone(), why.clone()));
3272                }
3273                outcome
3274            }
3275        };
3276        outcome.map_err(|e| match e {
3277            crate::page_host::DriveError::Failed(m) | crate::page_host::DriveError::Refused(m) => m,
3278        })?;
3279        Ok(ControlFlow::Continue)
3280    }
3281
3282    /// Why the lowering left `component` without a mount entry, in the lowering's own words: the
3283    /// compiler emits a program whole, and a component it cannot carry (a store shared across
3284    /// replicas, an event modifier with no lowered dispatch, …) is left without its entry rather
3285    /// than failing the program.
3286    fn why_not_lowered(&self, component: &str) -> Option<String> {
3287        let all: Vec<crate::ast::component::ComponentDef<'a>> =
3288            self.ctx.components.values().cloned().collect();
3289        let def = all
3290            .iter()
3291            .find(|d| self.ctx.interner.resolve(d.name) == component)?;
3292        logicaffeine_language::parser::lgx_lower::lowerable(
3293            def,
3294            &all,
3295            self.ctx.types.as_ref(),
3296            self.ctx.interner,
3297        )
3298        .err()
3299        .map(|why| {
3300            format!(
3301                "`Mount {component}` cannot run on this tier: {}",
3302                why.message
3303            )
3304        })
3305    }
3306
3307    /// `Serve fetches with routes.` — the single execution site for both statement executors.
3308    fn serve_fetches_sync(&mut self) -> Result<ControlFlow, String> {
3309        self.drive_page(crate::page_host::Drive::ServeFetchesWithRoutes)
3310    }
3311
3312    /// `Given that METHOD "url" answers STATUS with BODY.` — the single execution site for both
3313    /// statement executors.
3314    fn given_fetch_sync(
3315        &mut self,
3316        method: Symbol,
3317        url: &'a Expr<'a>,
3318        status: &'a Expr<'a>,
3319        body: &'a Expr<'a>,
3320    ) -> Result<ControlFlow, String> {
3321        let u = self.evaluate_expr_sync(url)?.to_display_string();
3322        let st = match self.evaluate_expr_sync(status)? {
3323            RuntimeValue::Int(n) => n,
3324            other => {
3325                return Err(format!(
3326                    "`Given that … answers …` wants a numeric status, got {}.",
3327                    other.type_name()
3328                ))
3329            }
3330        };
3331        let b = self.evaluate_expr_sync(body)?.to_display_string();
3332        self.drive_page(crate::page_host::Drive::AnswerFetch {
3333            method: self.ctx.interner.resolve(method).to_string(),
3334            url: u,
3335            status: st,
3336            body: b,
3337        })
3338    }
3339
3340    /// `Advance time by N.` — the shared tail once `ms` is evaluated (the async executor awaits
3341    /// it, the sync one does not; everything from here on is identical, and the single execution
3342    /// site for both).
3343    fn advance_time_ms(&mut self, ms: u64) -> Result<ControlFlow, String> {
3344        self.drive_page(crate::page_host::Drive::AdvanceTime { ms })
3345    }
3346
3347    /// Install the scheduler side-channel and the run's error sink, marking this interpreter as a
3348    /// scheduled concurrent task (used by the scheduler-driven run path).
3349    pub(crate) fn install_yield_state(
3350        &mut self,
3351        ys: crate::concurrency::bridge::Yield<'a>,
3352        err_sink: ErrSink,
3353    ) {
3354        self.yield_state = Some(ys);
3355        self.err_sink = Some(err_sink);
3356    }
3357
3358    /// Internal helper to emit output (calls callback if set, always adds to output vec)
3359    fn emit_output(&mut self, line: String) {
3360        if let Some(ref callback) = self.ctx.output_callback {
3361            (callback.borrow_mut())(line.clone());
3362        }
3363        self.output.push(line);
3364    }
3365
3366    /// Phase 102: Check if a name is a kernel inductive type.
3367    pub fn is_kernel_inductive(&self, name: &str) -> bool {
3368        self.ctx
3369            .kernel_ctx
3370            .as_ref()
3371            .map(|ctx| ctx.is_inductive(name))
3372            .unwrap_or(false)
3373    }
3374
3375    /// Phase 102: Get constructors for a kernel inductive type.
3376    ///
3377    /// Returns a vector of (constructor_name, arity) pairs.
3378    pub fn get_kernel_constructors(&self, name: &str) -> Vec<(String, usize)> {
3379        self.ctx
3380            .kernel_ctx
3381            .as_ref()
3382            .map(|ctx| {
3383                ctx.get_constructors(name)
3384                    .iter()
3385                    .map(|(ctor_name, ty)| {
3386                        // Count Pi types to determine arity
3387                        let arity = count_pi_args(ty);
3388                        (ctor_name.to_string(), arity)
3389                    })
3390                    .collect()
3391            })
3392            .unwrap_or_default()
3393    }
3394
3395    /// `Replay these actions: a, b.` — run each named action against the mounted page, in order.
3396    ///
3397    /// Each is a REAL TURN, so the transaction rule holds under replay: one that traps rolls back
3398    /// and the actions AFTER it still run. A replay that stopped at the first trap could not
3399    /// reproduce a sequence whose whole point is what happens after one.
3400    ///
3401    /// The single execution site for both statement executors, and a driving statement like any
3402    /// other: the page this interpreter hosts, or one attached ([`Interpreter::with_page`]),
3403    /// replays them.
3404    fn replay_actions(&mut self, actions: &[Symbol]) -> Result<(), String> {
3405        let named = actions
3406            .iter()
3407            .map(|a| self.ctx.interner.resolve(*a).to_string())
3408            .collect();
3409        self.drive_page(crate::page_host::Drive::Replay { actions: named })
3410            .map(|_| ())
3411    }
3412
3413    /// `value`'s JSON wire form for storage — the encode half of `Save`'s Seq/record codec. Returns
3414    /// `None` for anything neither a JSON scalar, array, nor object can carry.
3415    fn json_of_value(value: &RuntimeValue) -> Option<serde_json::Value> {
3416        use serde_json::Value;
3417        Some(match value {
3418            RuntimeValue::Text(s) => Value::String(s.to_string()),
3419            RuntimeValue::Int(n) => serde_json::json!(n),
3420            RuntimeValue::Float(f) => serde_json::json!(f),
3421            RuntimeValue::Bool(b) => Value::Bool(*b),
3422            RuntimeValue::Char(c) => Value::String(c.to_string()),
3423            RuntimeValue::List(items) => {
3424                let elems: Option<Vec<Value>> = items
3425                    .borrow()
3426                    .to_values()
3427                    .iter()
3428                    .map(Self::json_of_value)
3429                    .collect();
3430                Value::Array(elems?)
3431            }
3432            RuntimeValue::Struct(s) => {
3433                let mut map = serde_json::Map::new();
3434                for (k, v) in &s.fields {
3435                    map.insert(k.clone(), Self::json_of_value(v)?);
3436                }
3437                Value::Object(map)
3438            }
3439            _ => return None,
3440        })
3441    }
3442
3443    /// A JSON value with no shape to match it against — read off its OWN tag: what `Load` reads
3444    /// back with no field to shape it by. A JSON object with no shape cannot become a properly
3445    /// NAMED record, so it is refused rather than guessed at.
3446    fn value_from_json_untyped(json: &serde_json::Value) -> Option<RuntimeValue> {
3447        use serde_json::Value;
3448        match json {
3449            Value::String(s) => Some(RuntimeValue::Text(Rc::new(s.clone()))),
3450            Value::Bool(b) => Some(RuntimeValue::Bool(*b)),
3451            Value::Number(n) => match n.as_i64() {
3452                Some(i) => Some(RuntimeValue::Int(i)),
3453                None => n.as_f64().map(RuntimeValue::Float),
3454            },
3455            Value::Array(arr) => {
3456                let values: Option<Vec<RuntimeValue>> =
3457                    arr.iter().map(Self::value_from_json_untyped).collect();
3458                Some(RuntimeValue::List(Rc::new(RefCell::new(
3459                    ListRepr::from_values(values?),
3460                ))))
3461            }
3462            _ => None,
3463        }
3464    }
3465
3466    /// `Save`'s durable-storage wire form, byte-for-byte the same scheme the lowered tier's own
3467    /// `tagged_value` (`parser/lgx_lower/elements.rs`) writes: a one-letter tag, a colon, then the
3468    /// value — `i`/`f`/`b`/`t` for the scalars, `j` (JSON, [`Self::json_of_value`]) for a Seq or a
3469    /// record. `None` for anything the scheme cannot carry (a Chan, a Crdt, …), which `Save`
3470    /// refuses by name.
3471    fn tagged_storage_text(value: &RuntimeValue) -> Option<String> {
3472        let tag = match value {
3473            RuntimeValue::Int(_) => 'i',
3474            RuntimeValue::Float(_) => 'f',
3475            RuntimeValue::Bool(_) => 'b',
3476            RuntimeValue::Text(_) | RuntimeValue::Char(_) => 't',
3477            RuntimeValue::List(_) | RuntimeValue::Struct(_) => 'j',
3478            _ => return None,
3479        };
3480        let body = if tag == 'j' {
3481            Self::json_of_value(value)?.to_string()
3482        } else {
3483            value.to_display_string()
3484        };
3485        Some(format!("{tag}:{body}"))
3486    }
3487
3488    /// The inverse of [`Self::tagged_storage_text`] — `Load`'s read of whatever EITHER tier's
3489    /// `Save` wrote. A `j:`-tagged array/object has no field to shape it by here, so it decodes with
3490    /// [`Self::value_from_json_untyped`]'s Int-if-whole/Float-if-fractional rule.
3491    fn value_from_tagged_storage(text: &str) -> Option<RuntimeValue> {
3492        let (tag, body) = text.split_once(':')?;
3493        Some(match tag {
3494            "i" => RuntimeValue::Int(body.parse().ok()?),
3495            "f" => RuntimeValue::Float(body.parse().ok()?),
3496            "b" => match body {
3497                "true" => RuntimeValue::Bool(true),
3498                "false" => RuntimeValue::Bool(false),
3499                _ => return None,
3500            },
3501            "t" => RuntimeValue::Text(Rc::new(body.to_string())),
3502            "j" => Self::value_from_json_untyped(&serde_json::from_str(body).ok()?)?,
3503            _ => return None,
3504        })
3505    }
3506
3507    /// Answer a question about the rendered page. Reading the DOM is the same on every engine
3508    /// that has one, so this is the ONE implementation the tiers share.
3509    fn evaluate_dom_query(
3510        &mut self,
3511        query: &crate::ast::stmt::DomQuery<'a>,
3512    ) -> Result<RuntimeValue, String> {
3513        use crate::ast::stmt::DomQuery;
3514        use crate::semantics::dom;
3515        let selector = match query.selector() {
3516            Some(sel) => Some(self.evaluate_expr_sync(sel)?),
3517            None => None,
3518        };
3519        // `the count of xs` over a collection is its size — the same English, the reading the
3520        // VALUE settles, since neither reading is decidable from the sentence alone. Answered by
3521        // `length_of`, the one place the language decides what a collection's size is, so the two
3522        // spellings of one question cannot drift apart.
3523        //
3524        // ★ ONLY A TEXT IS A SELECTOR. `the count of ".row"` asks how many elements of the page
3525        // match, and reading it as a string length would answer a different question with an
3526        // equally plausible-looking number. Every other value is a collection or an error — asking
3527        // a Set for its selector reading gave 0 for a set with anything in it, which is the worst
3528        // wrong answer available, because an empty set really does count 0.
3529        if let (DomQuery::Count { .. }, Some(v)) = (query, &selector) {
3530            if !matches!(v, RuntimeValue::Text(_)) {
3531                return crate::semantics::collections::length_of(v);
3532            }
3533        }
3534        let sel = selector
3535            .as_ref()
3536            .map(|v| v.to_display_string())
3537            .unwrap_or_default();
3538        let one = |q: &str| -> Result<i64, String> {
3539            let node = dom::query_selector(&sel);
3540            if node < 0 {
3541                return Err(format!(
3542                    "No element matches {sel:?}, so it has no {q}. Mount the component first, and \
3543                     check the selector against the ids and classes its view renders."
3544                ));
3545            }
3546            Ok(node)
3547        };
3548        Ok(match query {
3549            DomQuery::Text { .. } => RuntimeValue::Text(Rc::new(dom::text_content(one("text")?))),
3550            DomQuery::Value { .. } => RuntimeValue::Text(Rc::new(dom::get_value(one("value")?))),
3551            DomQuery::Count { .. } => RuntimeValue::Int(dom::query_selector_all(&sel).len() as i64),
3552            // ★ SEEN, NOT MERELY PRESENT. This was `query_selector(&sel) >= 0`, so an element
3553            // that exists and is not shown answered "visible" — which made the one question a
3554            // page test asks about a toggle unable to fail, since `hidden={flag}` and
3555            // `class:hidden={flag}` both leave the element in the document. See `Dom::shown` for
3556            // exactly what is decided and what is not.
3557            DomQuery::Visible { .. } => RuntimeValue::Bool(dom::is_shown(&sel)),
3558            // The complement, written from the same fact so the two can never disagree about an
3559            // element that is somehow neither.
3560            // The exact complement, so an element is never both and never neither.
3561            DomQuery::Hidden { .. } => RuntimeValue::Bool(!dom::is_shown(&sel)),
3562            // PRESENCE, not value — `disabled=""` is disabled, and comparing against a string
3563            // would answer "false" for a control that really is disabled.
3564            DomQuery::Disabled { .. } => {
3565                let node = dom::query_selector(&sel);
3566                RuntimeValue::Bool(node >= 0 && dom::has_attribute(node, "disabled"))
3567            }
3568            // The LIVE property (see `DomOp::SetChecked`), so this follows a click rather than
3569            // reporting the markup the page started as.
3570            DomQuery::Checked { .. } => {
3571                let node = dom::query_selector(&sel);
3572                RuntimeValue::Bool(node >= 0 && dom::get_checked(node))
3573            }
3574            DomQuery::Focused { .. } => {
3575                let node = dom::query_selector(&sel);
3576                RuntimeValue::Bool(node >= 0 && dom::focused() == node)
3577            }
3578            // The ACTIONS that have run, in order — including the ones that rolled back, because
3579            // a turn that failed still HAPPENED and a test asking what the page did must see it.
3580            DomQuery::Journal => {
3581                let names: Vec<RuntimeValue> = crate::semantics::world::journal()
3582                    .into_iter()
3583                    .map(|e| RuntimeValue::Text(Rc::new(e.action)))
3584                    .collect();
3585                RuntimeValue::List(Rc::new(RefCell::new(crate::interpreter::ListRepr::Boxed(
3586                    names,
3587                ))))
3588            }
3589            // Did `first` run and `second` run AFTER it? "After", not "immediately after": a
3590            // test that pinned adjacency would break the moment an unrelated turn appeared in
3591            // between. `A then A` therefore needs a SECOND occurrence, never the same one twice.
3592            DomQuery::JournalShows { first, second } => {
3593                let want_first = self.ctx.interner.resolve(*first);
3594                let want_second = self.ctx.interner.resolve(*second);
3595                let entries = crate::semantics::world::journal();
3596                let found = entries
3597                    .iter()
3598                    .position(|e| e.action == want_first)
3599                    .is_some_and(|at| entries.iter().skip(at + 1).any(|e| e.action == want_second));
3600                RuntimeValue::Bool(found)
3601            }
3602            DomQuery::Title => RuntimeValue::Text(Rc::new(dom::title())),
3603            DomQuery::Url => RuntimeValue::Text(Rc::new(dom::route_path())),
3604        })
3605    }
3606
3607    /// The one element a selector names, or a message saying what to check. Every element verb
3608    /// goes through here, so they all fail the same way.
3609    fn require_element(&mut self, selector: &'a Expr<'a>, verb: &str) -> Result<i64, String> {
3610        let sel = self.evaluate_expr_sync(selector)?.to_display_string();
3611        let node = crate::semantics::dom::query_selector(&sel);
3612        if node < 0 {
3613            return Err(crate::semantics::drive::element_required(verb, &sel));
3614        }
3615        Ok(node)
3616    }
3617
3618    /// Register every top-level `FunctionDef`/`StructDef` BEFORE any statement
3619    /// runs, so a `## Main` that precedes a definition still resolves it — the
3620    /// forward-reference semantics the VM already has via its Pass 1 (`fn_index`
3621    /// over the whole program). Re-registration by the inline arms is an idempotent
3622    /// re-insert, so ordering-dependent shadowing (a later redefinition) is
3623    /// unaffected — the last definition still wins at its point of execution.
3624    fn preregister_definitions(&mut self, stmts: &[Stmt<'a>]) {
3625        for stmt in stmts {
3626            match stmt {
3627                Stmt::FunctionDef {
3628                    name,
3629                    params,
3630                    body,
3631                    return_type,
3632                    is_native,
3633                    native_path,
3634                    ..
3635                } => {
3636                    self.ctx
3637                        .functions
3638                        .entry(*name)
3639                        .or_insert_with(|| FunctionDef {
3640                            params: params.clone(),
3641                            body: *body,
3642                            return_type: *return_type,
3643                            is_native: *is_native,
3644                            native_path: *native_path,
3645                        });
3646                }
3647                Stmt::StructDef { name, fields, .. } => {
3648                    self.ctx
3649                        .struct_defs
3650                        .entry(*name)
3651                        .or_insert_with(|| fields.clone());
3652                }
3653                Stmt::ComponentDef(def) => {
3654                    self.ctx
3655                        .components
3656                        .entry(def.name)
3657                        .or_insert_with(|| (**def).clone());
3658                }
3659                _ => {}
3660            }
3661        }
3662    }
3663
3664    /// Execute a program (list of statements), on the async executor.
3665    pub async fn run(&mut self, stmts: &[Stmt<'a>]) -> Result<(), String> {
3666        self.begin_program(stmts);
3667        for (i, stmt) in stmts.iter().enumerate() {
3668            let flow = self.execute_stmt(stmt).await?;
3669            if let Some(f) = self.statement_observer.as_mut() {
3670                f(i);
3671            }
3672            match flow {
3673                ControlFlow::Return(_) => break,
3674                ControlFlow::Break => break,
3675                ControlFlow::Continue => {}
3676            }
3677        }
3678        Ok(())
3679    }
3680
3681    /// Activate the PNP one-time-pad session for a `Connect`/`Listen` `with pad "<path>" as <role>`
3682    /// clause: read the pad file, build the quality-gated pool, and install the directional session on
3683    /// the channel so every subsequent `Send`/receive on this thread is sealed. Fail-closed on any
3684    /// error (unreadable or non-random pad) — the caller propagates it as a program error, never
3685    /// proceeding to send plaintext.
3686    #[cfg(not(target_arch = "wasm32"))]
3687    async fn activate_pnp_session(
3688        &mut self,
3689        bind: &crate::ast::SecurePad<'a>,
3690    ) -> Result<(), String> {
3691        let path = self.evaluate_expr(bind.pad).await?.to_display_string();
3692        let bytes = std::fs::read(&path)
3693            .map_err(|e| format!("one-time pad '{path}' could not be read: {e}"))?;
3694        let pool = crate::concurrency::pnp::PadPool::shared(bytes).map_err(|e| {
3695            format!("one-time pad '{path}' rejected (not truly random / too small): {e:?}")
3696        })?;
3697        let role = match bind.role {
3698            crate::ast::SecureRole::Initiator => crate::concurrency::pnp::Role::Initiator,
3699            crate::ast::SecureRole::Responder => crate::concurrency::pnp::Role::Responder,
3700        };
3701        // Every run reads the same pad file, so its position is kept beside it: a run resumes past
3702        // every byte an earlier run handed out, and a ledger it cannot read stops the connect.
3703        let ledger = crate::concurrency::pnp::FileLedger::beside(std::path::Path::new(&path), role);
3704        use crate::concurrency::pnp::PadLedgerStore;
3705        ledger.update(&mut |_| false).map_err(|e| e.to_string())?;
3706        let session: std::rc::Rc<dyn crate::concurrency::channel::ActiveSession> =
3707            std::rc::Rc::new(pool.session_with_ledger(role, std::sync::Arc::new(ledger)));
3708        crate::concurrency::channel::install_session(Some(session));
3709        Ok(())
3710    }
3711
3712    /// On wasm the pad is provisioned through the VFS handle rather than host files (a future wiring);
3713    /// the clause is accepted but installs no session, matching the offline single-node tiers.
3714    #[cfg(target_arch = "wasm32")]
3715    async fn activate_pnp_session(
3716        &mut self,
3717        _bind: &crate::ast::SecurePad<'a>,
3718    ) -> Result<(), String> {
3719        Ok(())
3720    }
3721
3722    /// The single execution site for every `UiStmt` verb — driving (`Click`, `Navigate`,
3723    /// `Hover`, …) and imperative (`Save`, `Toggle`, `CallStore`, `Mount`, …) alike. Both
3724    /// statement executors — the async one and its sync twin — dispatch here instead of each
3725    /// carrying its own copy of this match.
3726    fn execute_ui(&mut self, ui: &crate::ast::stmt::UiStmt<'a>) -> Result<ControlFlow, String> {
3727        use crate::page_host::Drive;
3728        match ui {
3729            crate::ast::stmt::UiStmt::Click { selector } => {
3730                let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3731                self.drive_page(Drive::Click { selector })
3732            }
3733            // `Submit "#form".` — the same shape as a click, on the event a form answers. A test
3734            // that could only click would have to know which BUTTON submits a form, which is the
3735            // page's business rather than the test's.
3736            crate::ast::stmt::UiStmt::Submit { selector } => {
3737                let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3738                self.drive_page(Drive::Submit { selector })
3739            }
3740            // `Press "Enter" in "#draft".` — a key press on an element, or on the page when no
3741            // element is named, so a page-level `When the user presses Escape:` is reachable.
3742            crate::ast::stmt::UiStmt::Press { key, selector } => {
3743                let key = self.evaluate_expr_sync(key)?.to_display_string();
3744                let selector = match selector {
3745                    Some(e) => self.evaluate_expr_sync(e)?.to_display_string(),
3746                    None => "body".to_string(),
3747                };
3748                self.drive_page(Drive::Press { key, selector })
3749            }
3750            crate::ast::stmt::UiStmt::Choose { value, selector } => {
3751                let value = self.evaluate_expr_sync(value)?.to_display_string();
3752                let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3753                self.drive_page(Drive::Choose { value, selector })
3754            }
3755            crate::ast::stmt::UiStmt::TypeInto { text, selector } => {
3756                let text = self.evaluate_expr_sync(text)?.to_display_string();
3757                let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3758                self.drive_page(Drive::Type { text, selector })
3759            }
3760            crate::ast::stmt::UiStmt::SetTitle { title } => {
3761                let t = self.evaluate_expr_sync(title)?.to_display_string();
3762                crate::semantics::dom::set_title(&t);
3763                Ok(ControlFlow::Continue)
3764            }
3765            // ★ `Scroll to "#card".` / `Select the text in "#draft".` — neither is a change to the
3766            // document: scrolling and selecting are things a browser does TO a document that stays
3767            // the same, which is why they are recorder STATE rather than ops, and why a test asks
3768            // `dom::scrolled_to()` rather than reading the markup.
3769            // ★ A tier with no browser cannot put anything on a real clipboard, hand the viewer a
3770            // file, or raise a notification — but it can RECORD that the page asked, which is the
3771            // part a test needs and the only part that is honest to claim.
3772            crate::ast::stmt::UiStmt::CopyToClipboard { text } => {
3773                let t = self.evaluate_expr_sync(text)?.to_display_string();
3774                crate::semantics::dom::write_clipboard(&t);
3775                Ok(ControlFlow::Continue)
3776            }
3777            crate::ast::stmt::UiStmt::Download { bytes, name } => {
3778                let content = self.evaluate_expr_sync(bytes)?.to_display_string();
3779                let n = self.evaluate_expr_sync(name)?.to_display_string();
3780                crate::semantics::dom::offer_download(&n, &content);
3781                Ok(ControlFlow::Continue)
3782            }
3783            crate::ast::stmt::UiStmt::Notify { message, tone } => {
3784                let m = self.evaluate_expr_sync(message)?.to_display_string();
3785                // The tone is the author's word for it (`Notify "Saved." as a success.`); a page
3786                // that names none says so with the empty string rather than with a guess.
3787                let t = tone.map(|t| self.ctx.interner.resolve(t).to_string()).unwrap_or_default();
3788                crate::semantics::dom::notify(&m, &t);
3789                Ok(ControlFlow::Continue)
3790            }
3791            crate::ast::stmt::UiStmt::ScrollTo { selector } => {
3792                let node = self.require_element(selector, "Scroll to")?;
3793                crate::semantics::dom::scroll_to(node);
3794                Ok(ControlFlow::Continue)
3795            }
3796            crate::ast::stmt::UiStmt::SelectText { selector } => {
3797                let node = self.require_element(selector, "Select the text in")?;
3798                crate::semantics::dom::select_text(node);
3799                Ok(ControlFlow::Continue)
3800            }
3801            crate::ast::stmt::UiStmt::Focus { selector } => {
3802                let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3803                self.drive_page(Drive::Focus { selector })
3804            }
3805            crate::ast::stmt::UiStmt::Blur { selector } => {
3806                let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3807                self.drive_page(Drive::Blur { selector })
3808            }
3809            crate::ast::stmt::UiStmt::Hover { selector } => {
3810                let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3811                self.drive_page(Drive::Hover { selector })
3812            }
3813            crate::ast::stmt::UiStmt::AddClass { class, selector } => {
3814                let node = self.require_element(selector, "Add class")?;
3815                let c = self.evaluate_expr_sync(class)?.to_display_string();
3816                crate::semantics::dom::add_class(node, &c);
3817                Ok(ControlFlow::Continue)
3818            }
3819            crate::ast::stmt::UiStmt::RemoveClass { class, selector } => {
3820                let node = self.require_element(selector, "Remove class")?;
3821                let c = self.evaluate_expr_sync(class)?.to_display_string();
3822                crate::semantics::dom::remove_class(node, &c);
3823                Ok(ControlFlow::Continue)
3824            }
3825            // ★ `Raise "offline".` — cause a window event, delivered to the PAGE; a dropped file is
3826            // its own act, the file travelling with the drop to the handler it reaches.
3827            crate::ast::stmt::UiStmt::RaiseWindowEvent { event, target, value } => {
3828                let event = self.evaluate_expr_sync(event)?.to_display_string();
3829                let target = self.evaluate_expr_sync(target)?.to_display_string();
3830                let raised = self.evaluate_expr_sync(value)?;
3831                if event == "filedropped" {
3832                    let file = crate::semantics::dom::DroppedFile::from_value(&raised)?;
3833                    return self.drive_page(Drive::DropFile { target, file });
3834                }
3835                self.drive_page(Drive::Raise { event, target, value: raised.to_display_string() })
3836            }
3837            // ★ `Publish M on "t".` — the frame goes to the transport, and THIS page's own
3838            // subscribers hear it too, as the page's own `Publish` delivers it to them. From the
3839            // page's own code the page cannot be driven, and its lowering delivers the message
3840            // after the turn itself.
3841            crate::ast::stmt::UiStmt::Publish { message, topic } => {
3842                let topic = self.evaluate_expr_sync(topic)?.to_display_string();
3843                let message = self.evaluate_expr_sync(message)?.to_display_string();
3844                crate::semantics::dom::publish(&topic, &message);
3845                if !self.page_can_be_driven() {
3846                    return Ok(ControlFlow::Continue);
3847                }
3848                self.drive_page(Drive::Raise {
3849                    event: format!("message:{topic}"),
3850                    target: "body".to_string(),
3851                    value: message,
3852                })
3853            }
3854            // ★ `Go back.` — the visitor's Back button: the location steps back, and the page's
3855            // route listeners hear the popstate as the page settles. At the first entry there is
3856            // nowhere to go, and a browser does nothing there.
3857            crate::ast::stmt::UiStmt::GoBack => {
3858                if crate::semantics::dom::go_back().is_some() {
3859                    self.with_hosted_page(|host, me| host.settle(me));
3860                }
3861                Ok(ControlFlow::Continue)
3862            }
3863            crate::ast::stmt::UiStmt::Navigate { url } => {
3864                let url = self.evaluate_expr_sync(url)?.to_display_string();
3865                self.drive_page(Drive::Navigate { url })
3866            }
3867            crate::ast::stmt::UiStmt::ReplaceUrl { url } => {
3868                let u = self.evaluate_expr_sync(url)?.to_display_string();
3869                crate::semantics::dom::replace_route(&u);
3870                Ok(ControlFlow::Continue)
3871            }
3872            // `Toggle done.` — a Bool flips. Anything else is a mistake worth naming, because a
3873            // toggle only means something for a yes/no.
3874            crate::ast::stmt::UiStmt::Toggle { field } => {
3875                let name = self.ctx.interner.resolve(*field);
3876                let current = self
3877                    .lookup(*field)
3878                    .map_err(|_| format!("`Toggle {name}` needs `{name}` to be a yes/no in scope."))?;
3879                let RuntimeValue::Bool(b) = current else {
3880                    return Err(format!(
3881                        "`Toggle {name}` flips a yes/no, but `{name}` holds {}.",
3882                        current.type_name()
3883                    ));
3884                };
3885                self.assign(*field, RuntimeValue::Bool(!b))?;
3886                Ok(ControlFlow::Continue)
3887            }
3888            crate::ast::stmt::UiStmt::StopTimer { name } => Err(format!(
3889                "`Stop the timer {}` runs inside a component's `Actions:`, against that component's \
3890                 own timers.",
3891                self.ctx.interner.resolve(*name)
3892            )),
3893            crate::ast::stmt::UiStmt::StartTimer { name } => Err(format!(
3894                "`Start the timer {}` runs inside a component's `Actions:`, against that component's \
3895                 own timers.",
3896                self.ctx.interner.resolve(*name)
3897            )),
3898            // `Save`, `Load` and `Forget` read and write the browser's own storage, in the tagged
3899            // text every tier's `Save` writes (`parser/lgx_lower/elements.rs::tagged_value`).
3900            crate::ast::stmt::UiStmt::Save { value, key } => {
3901                let v = self.evaluate_expr_sync(value)?;
3902                let k = self.evaluate_expr_sync(key)?.to_display_string();
3903                let Some(tagged) = Self::tagged_storage_text(&v) else {
3904                    return Err(format!(
3905                        "`Save` keeps text, a number, a yes/no, a list or a record, and this value is \
3906                         {} — storage holds text, and {} has none.",
3907                        v.type_name(),
3908                        v.type_name()
3909                    ));
3910                };
3911                crate::semantics::storage::set(crate::semantics::storage::LOCAL, &k, &tagged)?;
3912                Ok(ControlFlow::Continue)
3913            }
3914            crate::ast::stmt::UiStmt::Load { key, var } => {
3915                let k = self.evaluate_expr_sync(key)?.to_display_string();
3916                let v = match crate::semantics::storage::get(crate::semantics::storage::LOCAL, &k)?
3917                    .and_then(|text| Self::value_from_tagged_storage(&text))
3918                {
3919                    Some(v) => v,
3920                    None => empty_like(self.lookup(*var).ok()),
3921                };
3922                self.assign(*var, v)?;
3923                Ok(ControlFlow::Continue)
3924            }
3925            crate::ast::stmt::UiStmt::Forget { key } => {
3926                let k = self.evaluate_expr_sync(key)?.to_display_string();
3927                crate::semantics::storage::remove(crate::semantics::storage::LOCAL, &k)?;
3928                Ok(ControlFlow::Continue)
3929            }
3930            crate::ast::stmt::UiStmt::Reload => self.drive_page(Drive::Reload),
3931            // `Call Store's action` from a test: the store's action is the function its lowering
3932            // compiled (`__act_<Store>_<action>`), and a test calls it as the page's own code does.
3933            crate::ast::stmt::UiStmt::CallStore { store, action, args } => {
3934                let store_name = self.ctx.interner.resolve(*store).to_string();
3935                let action_name = self.ctx.interner.resolve(*action).to_string();
3936                let lowered = logicaffeine_language::parser::lgx_lower::action_fn_name(&store_name, &action_name);
3937                let function = self
3938                    .ctx
3939                    .interner
3940                    .lookup(&lowered)
3941                    .filter(|f| self.ctx.functions.contains_key(f))
3942                    .ok_or_else(|| {
3943                        format!("`{store_name}` has no action `{action_name}` — declare it under the store's `Actions:`.")
3944                    })?;
3945                let mut values = Vec::with_capacity(args.len());
3946                for arg in args.iter() {
3947                    values.push(self.evaluate_expr_sync(arg)?);
3948                }
3949                self.call_function_with_values_sync(function, values)?;
3950                Ok(ControlFlow::Continue)
3951            }
3952            crate::ast::stmt::UiStmt::Mount { component, selector } => {
3953                let at = match selector {
3954                    Some(e) => Some(self.evaluate_expr_sync(e)?.to_display_string()),
3955                    None => None,
3956                };
3957                self.drive_page(Drive::Mount { component: self.ctx.interner.resolve(*component).to_string(), at })
3958            }
3959        }
3960    }
3961
3962    /// Whether a driving statement can reach the page now: one is seated, and it is not the page's
3963    /// own code that is running.
3964    fn page_can_be_driven(&self) -> bool {
3965        match &self.page {
3966            PageSeat::Unseated => false,
3967            PageSeat::Driven(_) => true,
3968            PageSeat::Here(hosted) => hosted.host.is_some(),
3969        }
3970    }
3971
3972    /// Execute a single statement.
3973    /// Phase 55: Now async for VFS operations.
3974    #[async_recursion(?Send)]
3975    async fn execute_stmt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
3976        self.tick_test_budget()?;
3977        // `--tiers all` replay: test-only statements no-op — EXACTLY the set
3978        // the VM's `compile_tiers` no-ops, so both engines run one program.
3979        if self.tiers_noop
3980            && matches!(
3981                stmt,
3982                Stmt::Expect { .. }
3983                    | Stmt::ExpectFail { .. }
3984                    | Stmt::ExpectOutput { .. }
3985                    | Stmt::AdvanceTime { .. }
3986                    | Stmt::GivenFile { .. }
3987                    | Stmt::ForAll { .. }
3988            )
3989        {
3990            return Ok(ControlFlow::Continue);
3991        }
3992        match stmt {
3993            Stmt::Let { var, value, .. } => {
3994                let val = self.evaluate_expr(value).await?;
3995                self.define(*var, val);
3996                Ok(ControlFlow::Continue)
3997            }
3998
3999            Stmt::Set { target, value } => {
4000                if let Some((before, operands)) = self.text_appends(*target, value) {
4001                    let mut pieces = Vec::with_capacity(operands.len());
4002                    for operand in operands {
4003                        pieces.push(self.evaluate_expr(operand).await?.to_display_string());
4004                    }
4005                    self.append_text(*target, before, pieces)?;
4006                    return Ok(ControlFlow::Continue);
4007                }
4008                let val = self.evaluate_expr(value).await?;
4009                self.assign(*target, val)?;
4010                Ok(ControlFlow::Continue)
4011            }
4012
4013            Stmt::Swap { a, b } => {
4014                // Reversible value exchange — the tree-walker twin of the VM's zero-garbage RevSwap.
4015                let va = self.lookup(*a)?.clone();
4016                let vb = self.lookup(*b)?.clone();
4017                self.assign(*a, vb)?;
4018                self.assign(*b, va)?;
4019                Ok(ControlFlow::Continue)
4020            }
4021
4022            Stmt::Call { function, args } => {
4023                self.call_function(*function, args).await?;
4024                Ok(ControlFlow::Continue)
4025            }
4026
4027            Stmt::If {
4028                cond,
4029                then_block,
4030                else_block,
4031            } => {
4032                let condition = self.evaluate_expr(cond).await?;
4033                if condition.decided_truth()? {
4034                    let flow = self.execute_block(then_block).await?;
4035                    if !matches!(flow, ControlFlow::Continue) {
4036                        return Ok(flow);
4037                    }
4038                } else if let Some(else_stmts) = else_block {
4039                    let flow = self.execute_block(else_stmts).await?;
4040                    if !matches!(flow, ControlFlow::Continue) {
4041                        return Ok(flow);
4042                    }
4043                }
4044                Ok(ControlFlow::Continue)
4045            }
4046
4047            Stmt::While { cond, body, .. } => {
4048                loop {
4049                    let condition = self.evaluate_expr(cond).await?;
4050                    if !condition.decided_truth()? {
4051                        break;
4052                    }
4053                    match self.execute_block(body).await? {
4054                        ControlFlow::Break => break,
4055                        ControlFlow::Return(v) => return Ok(ControlFlow::Return(v)),
4056                        ControlFlow::Continue => {}
4057                    }
4058                }
4059                Ok(ControlFlow::Continue)
4060            }
4061
4062            Stmt::Repeat {
4063                pattern,
4064                iterable,
4065                body,
4066            } => {
4067                use crate::ast::stmt::Pattern;
4068
4069                let iter_val = self.evaluate_expr(iterable).await?;
4070                let items = crate::semantics::collections::iteration_snapshot(&iter_val)?;
4071
4072                self.push_scope();
4073                // Suppress TCO inside a `Repeat` (live iterator) — see SYNC twin.
4074                self.task.repeat_depth_async += 1;
4075                for item in items {
4076                    // Bind variables according to pattern
4077                    match pattern {
4078                        Pattern::Identifier(sym) => {
4079                            self.define(*sym, item);
4080                        }
4081                        Pattern::Tuple(syms) => {
4082                            if let RuntimeValue::Tuple(ref tuple_vals) = item {
4083                                if syms.len() != tuple_vals.len() {
4084                                    self.task.repeat_depth_async -= 1;
4085                                    return Err(format!(
4086                                        "Cannot bind a {}-tuple to {} names",
4087                                        tuple_vals.len(),
4088                                        syms.len()
4089                                    ));
4090                                }
4091                                for (sym, val) in syms.iter().zip(tuple_vals.iter()) {
4092                                    self.define(*sym, val.clone());
4093                                }
4094                            } else {
4095                                self.task.repeat_depth_async -= 1;
4096                                return Err(format!(
4097                                    "Expected tuple for pattern, got {}",
4098                                    item.type_name()
4099                                ));
4100                            }
4101                        }
4102                    }
4103
4104                    match self.execute_block(body).await? {
4105                        ControlFlow::Break => break,
4106                        ControlFlow::Return(v) => {
4107                            self.task.repeat_depth_async -= 1;
4108                            self.pop_scope();
4109                            return Ok(ControlFlow::Return(v));
4110                        }
4111                        ControlFlow::Continue => {}
4112                    }
4113                }
4114                self.task.repeat_depth_async -= 1;
4115                self.pop_scope();
4116                Ok(ControlFlow::Continue)
4117            }
4118
4119            Stmt::Return { value } => {
4120                // Direct self-tail-call → loop-back in `call_function` (see the
4121                // SYNC twin for the full rationale).
4122                if let Some(expr) = value {
4123                    if let Some(call_args) = self.self_tail_call_args_async(*expr) {
4124                        let mut vals = Vec::with_capacity(call_args.len());
4125                        for a in call_args {
4126                            vals.push(self.evaluate_expr(a).await?);
4127                        }
4128                        self.task.pending_tail_call_async = Some(vals);
4129                        return Ok(ControlFlow::Return(RuntimeValue::Nothing));
4130                    }
4131                }
4132                let ret_val = match value {
4133                    Some(expr) => self.evaluate_expr(expr).await?,
4134                    None => RuntimeValue::Nothing,
4135                };
4136                Ok(ControlFlow::Return(ret_val))
4137            }
4138
4139            Stmt::Break => Ok(ControlFlow::Break),
4140
4141            Stmt::FunctionDef {
4142                name,
4143                params,
4144                body,
4145                return_type,
4146                is_native,
4147                native_path,
4148                ..
4149            } => {
4150                let func = FunctionDef {
4151                    params: params.clone(),
4152                    body: *body,
4153                    return_type: *return_type,
4154                    is_native: *is_native,
4155                    native_path: *native_path,
4156                };
4157                self.ctx.functions.insert(*name, func);
4158                Ok(ControlFlow::Continue)
4159            }
4160
4161            Stmt::StructDef { name, fields, .. } => {
4162                self.ctx.struct_defs.insert(*name, fields.clone());
4163                Ok(ControlFlow::Continue)
4164            }
4165
4166            Stmt::SetField {
4167                object,
4168                field,
4169                value,
4170            } => {
4171                let new_val = self.evaluate_expr(value).await?;
4172                let place = self.place(object).await?;
4173                self.set_field_at(place, *field, new_val)?;
4174                Ok(ControlFlow::Continue)
4175            }
4176
4177            // Every write below goes to a place owned by its binding first (`write_target`): a
4178            // bare variable, or any path of fields and items (`Push 5 to item i of grid`,
4179            // `Push 5 to a's b's c`) — never into a collection another binding shares.
4180            Stmt::Push { value, collection } => {
4181                let val = self.evaluate_expr(value).await?;
4182                if let Expr::FieldAccess {
4183                    object: Expr::Identifier(obj_sym),
4184                    field,
4185                } = collection
4186                {
4187                    if let Some(place) = self.place(collection).await? {
4188                        self.place_slot(&place, true);
4189                    }
4190                    let obj_val = self.lookup(*obj_sym)?;
4191                    let field_name = self.ctx.interner.resolve(*field);
4192                    crate::semantics::collections::push_to_struct_field(obj_val, field_name, val)?;
4193                } else {
4194                    let coll_val = self.write_target(collection).await?;
4195                    crate::semantics::collections::list_push(&coll_val, val)?;
4196                }
4197                Ok(ControlFlow::Continue)
4198            }
4199
4200            Stmt::Pop { collection, into } => {
4201                let coll_val = self.write_target(collection).await?;
4202                let popped = crate::semantics::collections::list_pop(&coll_val)?;
4203                if let Some(into_var) = into {
4204                    self.define(*into_var, popped);
4205                }
4206                Ok(ControlFlow::Continue)
4207            }
4208
4209            Stmt::Add { value, collection } => {
4210                let val = self.evaluate_expr(value).await?;
4211                let coll_val = self.write_target(collection).await?;
4212                crate::semantics::collections::set_add(&coll_val, val)?;
4213                Ok(ControlFlow::Continue)
4214            }
4215
4216            Stmt::Remove { value, collection } => {
4217                let val = self.evaluate_expr(value).await?;
4218                let coll_val = self.write_target(collection).await?;
4219                crate::semantics::collections::remove_from(&coll_val, &val)?;
4220                Ok(ControlFlow::Continue)
4221            }
4222
4223            Stmt::SetIndex {
4224                collection,
4225                index,
4226                value,
4227            } => {
4228                let idx_val = self.evaluate_expr(index).await?;
4229                let new_val = self.evaluate_expr(value).await?;
4230                let target = match self.place(collection).await? {
4231                    Some(place) => {
4232                        match self.set_item_in_place(&place, &idx_val, new_val.clone()) {
4233                            Some(done) => {
4234                                done?;
4235                                return Ok(ControlFlow::Continue);
4236                            }
4237                            None => self.read_place(&place)?,
4238                        }
4239                    }
4240                    None => self.evaluate_expr(collection).await?,
4241                };
4242                crate::semantics::collections::index_set(&target, &idx_val, new_val)?;
4243                Ok(ControlFlow::Continue)
4244            }
4245
4246            // A component definition is registered, not executed (`preregister_definitions`).
4247            // An `## Error page STATUS` is part of the SERVER surface: the router renders it when
4248            // a request 404s or 500s, and there is no router yet. Registering it silently — which
4249            // is what every component kind used to get — meant a page declaring a 404 view got one
4250            // quietly ignored, while its three sibling headers (`## Route`, `## Before each
4251            // request`, `## Redirect`) refused by name. A declaration that is accepted and then
4252            // does nothing is the worst outcome for whoever wrote it.
4253            Stmt::ComponentDef(def)
4254                if matches!(
4255                    def.kind,
4256                    crate::ast::component::ComponentKind::ErrorPage { .. }
4257                ) =>
4258            {
4259                {
4260                    // An error page whose template the server-side walk covers is a DECLARATION:
4261                    // the router renders it in place of the bare status. One it cannot render is
4262                    // still refused BY NAME, rather than leaving a declared page silently unused.
4263                    let heading = logicaffeine_language::parser::lgx_lower::construct_heading(
4264                        def,
4265                        self.ctx.interner,
4266                    );
4267                    match def.view.as_ref() {
4268                        Some(v) => match logicaffeine_language::parser::lgx_lower::view_html_lowerable(
4269                            &v.nodes,
4270                            self.ctx.interner,
4271                        ) {
4272                            Ok(()) => Ok(ControlFlow::Continue),
4273                            Err(why) => Err(format!(
4274                                "`{heading}` cannot be rendered on this tier yet: {}.",
4275                                why.message
4276                            )),
4277                        },
4278                        None => Err(format!(
4279                            "`{heading}` cannot be rendered on this tier yet: it has no `View:` to render."
4280                        )),
4281                    }
4282                }
4283            }
4284            Stmt::ComponentDef(_) | Stmt::DirectiveDef { .. } => Ok(ControlFlow::Continue),
4285            Stmt::Ui(ui) => self.execute_ui(ui),
4286            // A `## Route` whose body lowered to a function is a DECLARATION here — the function
4287            // carries it, and `route(method, path)` dispatches. One that could not lower is
4288            // refused BY NAME, saying which part is missing, rather than silently never being
4289            // reachable through the dispatcher (which would read as a 404 for a route the author
4290            // can see in their file).
4291            Stmt::RouteDef {
4292                method,
4293                path,
4294                params,
4295                return_type,
4296                body,
4297                span,
4298            } => {
4299                match logicaffeine_language::parser::lgx_lower::route_lowerable(
4300                    params,
4301                    *return_type,
4302                    body,
4303                    self.ctx.interner,
4304                    &|sym| self.ctx.struct_defs.contains_key(&sym),
4305                    // The components this program declares — without them the server-side walk
4306                    // refuses every template that places one, and the route silently leaves the
4307                    // router.
4308                    &self.ctx.components.values().cloned().collect::<Vec<_>>(),
4309                    *span,
4310                ) {
4311                    Ok(()) => Ok(ControlFlow::Continue),
4312                    Err(why) => Err(format!(
4313                        "`{}` cannot run on this tier yet: {}.",
4314                        logicaffeine_language::parser::lgx_lower::route_heading(
4315                            *method,
4316                            *path,
4317                            self.ctx.interner
4318                        ),
4319                        why.message
4320                    )),
4321                }
4322            }
4323            // A `## Before each request` is a DECLARATION here — it lowered to a function and
4324            // `route(method, path)` calls it before matching. Like a route, nothing runs at the
4325            // point of declaration.
4326            Stmt::MiddlewareDef { .. } => Ok(ControlFlow::Continue),
4327            // A `## Redirect` is a DECLARATION — the router carries it.
4328            Stmt::RedirectDef { .. } => Ok(ControlFlow::Continue),
4329            Stmt::Replay { actions } => {
4330                self.replay_actions(actions)?;
4331                Ok(ControlFlow::Continue)
4332            }
4333            Stmt::ServeFetches => self.serve_fetches_sync(),
4334            Stmt::GivenFetch {
4335                method,
4336                url,
4337                status,
4338                body,
4339            } => self.given_fetch_sync(*method, url, status, body),
4340            Stmt::Fetch { .. } => Err(
4341                "A request that answers into an action (`Get … then loaded`) is sent by a \
4342                 component's own `Actions:`, whose page completes it."
4343                    .to_string(),
4344            ),
4345            Stmt::Splice { body } => {
4346                // Scope-TRANSPARENT by contract (see the AST doc): no block
4347                // scoping — the gensym'd desugar temporaries live in the
4348                // enclosing scope.
4349                for s in body.iter() {
4350                    let flow = self.execute_stmt(s).await?;
4351                    if !matches!(flow, ControlFlow::Continue) {
4352                        return Ok(flow);
4353                    }
4354                }
4355                Ok(ControlFlow::Continue)
4356            }
4357
4358            Stmt::Reversibly { body } => {
4359                // Output-TRANSPARENT: the reversible/uncompute block runs its body in the enclosing
4360                // scope exactly as if the statements were written directly. The block only changes
4361                // the VM's LOWERING (to the zero-garbage reversible ISA); the tree-walker's observable
4362                // behaviour is identical, which is precisely what lets tw ≡ VM hold across it.
4363                for s in body.iter() {
4364                    let flow = self.execute_stmt(s).await?;
4365                    if !matches!(flow, ControlFlow::Continue) {
4366                        return Ok(flow);
4367                    }
4368                }
4369                Ok(ControlFlow::Continue)
4370            }
4371
4372            Stmt::Inspect { target, arms, .. } => {
4373                let target_val = self.evaluate_expr(target).await?;
4374                self.execute_inspect(&target_val, arms).await
4375            }
4376
4377            Stmt::Zone { name, body, .. } => {
4378                self.push_scope();
4379                self.define(*name, RuntimeValue::Nothing);
4380                let result = self.execute_block(body).await;
4381                self.pop_scope();
4382                result?;
4383                Ok(ControlFlow::Continue)
4384            }
4385
4386            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
4387                // In WASM, execute sequentially (no threads)
4388                for task in tasks.iter() {
4389                    self.execute_stmt(task).await?;
4390                }
4391                Ok(ControlFlow::Continue)
4392            }
4393
4394            Stmt::Assert { .. } | Stmt::Trust { .. } => Ok(ControlFlow::Continue),
4395
4396            // A `## Test` block is a declaration: normal execution walks past
4397            // it; the `largo test` runner collects and drives it (Wave 3).
4398            Stmt::TestDef { .. } => Ok(ControlFlow::Continue),
4399
4400            // Test expectations (real semantics under the runner's test mode;
4401            // fail-loud outside it).
4402            Stmt::Expect { condition } => {
4403                if !self.test_mode {
4404                    return Err(TEST_ONLY_STMT_ERR.to_string());
4405                }
4406                self.test_assertions += 1;
4407                let val = self.evaluate_expr(condition).await?;
4408                if !val.decided_truth()? {
4409                    let cond_text =
4410                        logicaffeine_language::printer::render_expr(condition, self.ctx.interner);
4411                    let mut subs = Vec::new();
4412                    logicaffeine_language::printer::subexpressions(condition, &mut subs);
4413                    let mut annotations: Vec<(String, String)> = Vec::new();
4414                    let mut seen = std::collections::HashSet::new();
4415                    for sub in subs {
4416                        let text =
4417                            logicaffeine_language::printer::render_expr(sub, self.ctx.interner);
4418                        if !seen.insert(text.clone()) {
4419                            continue;
4420                        }
4421                        if let Ok(v) = self.evaluate_expr(sub).await {
4422                            annotations.push((text, v.to_display_string()));
4423                        }
4424                    }
4425                    let hint = Self::expect_socratic_hint(condition);
4426                    self.test_failures
4427                        .push(format_expect_failure(&cond_text, &annotations, hint));
4428                }
4429                Ok(ControlFlow::Continue)
4430            }
4431            Stmt::ExpectFail { message, body } => {
4432                if !self.test_mode {
4433                    return Err(TEST_ONLY_STMT_ERR.to_string());
4434                }
4435                self.test_assertions += 1;
4436                let mut failure: Option<String> = None;
4437                for s in body.iter() {
4438                    if let Err(e) = self.execute_stmt(s).await {
4439                        failure = Some(e);
4440                        break;
4441                    }
4442                }
4443                match failure {
4444                    None => self
4445                        .test_failures
4446                        .push("Expected this to fail — but the block succeeded.".to_string()),
4447                    Some(actual) => {
4448                        if let Some(expected) = message {
4449                            let expected = self.ctx.interner.resolve(*expected);
4450                            if actual != expected {
4451                                self.test_failures.push(format!(
4452                                    "Expected this to fail with {expected:?} — but it failed with {actual:?}."
4453                                ));
4454                            }
4455                        }
4456                    }
4457                }
4458                Ok(ControlFlow::Continue)
4459            }
4460            Stmt::ExpectOutput { expected } => {
4461                if !self.test_mode {
4462                    return Err(TEST_ONLY_STMT_ERR.to_string());
4463                }
4464                self.test_assertions += 1;
4465                match expected {
4466                    ExpectedOutput::Inline(sym) => {
4467                        let expected_text = self.ctx.interner.resolve(*sym).to_string();
4468                        let actual = self.output.join("\n");
4469                        if actual != expected_text {
4470                            self.test_failures.push(format!(
4471                                "Expected output {expected_text:?} — but the test printed {actual:?}."
4472                            ));
4473                        }
4474                    }
4475                    ExpectedOutput::File(path) => {
4476                        self.test_failures.push(format!(
4477                            "Expected output as in {:?} — golden files land with the sealed world (Wave 4).",
4478                            self.ctx.interner.resolve(*path)
4479                        ));
4480                    }
4481                }
4482                Ok(ControlFlow::Continue)
4483            }
4484            Stmt::AdvanceTime { millis } => {
4485                if !self.test_mode {
4486                    return Err(TEST_ONLY_STMT_ERR.to_string());
4487                }
4488                let ms = match self.evaluate_expr(millis).await? {
4489                    RuntimeValue::Int(n) => n.max(0) as u64,
4490                    // `3 seconds` lexes as a native Duration literal (ns).
4491                    RuntimeValue::Duration(ns) => (ns.max(0) / 1_000_000) as u64,
4492                    other => {
4493                        return Err(format!(
4494                            "Advance time needs a duration in milliseconds, got {}",
4495                            other.type_name()
4496                        ))
4497                    }
4498                };
4499                self.advance_time_ms(ms)
4500            }
4501            Stmt::GivenFile { path, content } => {
4502                if !self.test_mode {
4503                    return Err(TEST_ONLY_STMT_ERR.to_string());
4504                }
4505                logicaffeine_system::testworld::seed_file(
4506                    self.ctx.interner.resolve(*path).to_string(),
4507                    self.ctx.interner.resolve(*content).to_string(),
4508                );
4509                Ok(ControlFlow::Continue)
4510            }
4511
4512            // Observation statements emit to the SEPARATE observation channel
4513            // (Wave 7) — never to program output. `During` is a
4514            // scope-transparent span: run its body inline.
4515            Stmt::Observe {
4516                category,
4517                message,
4518                payloads,
4519                sample,
4520            } => {
4521                if crate::observe::capturing() {
4522                    let mut vals: Vec<(String, String)> = Vec::with_capacity(payloads.len());
4523                    for (name, expr) in payloads.iter() {
4524                        let v = self.evaluate_expr(expr).await?;
4525                        vals.push((
4526                            self.ctx.interner.resolve(*name).to_string(),
4527                            v.to_display_string(),
4528                        ));
4529                    }
4530                    crate::observe::emit(
4531                        map_obs_category(*category),
4532                        self.ctx.interner.resolve(*message).to_string(),
4533                        vals,
4534                        *sample,
4535                        message.index() as u64,
4536                    );
4537                }
4538                Ok(ControlFlow::Continue)
4539            }
4540            Stmt::During { label, body } => {
4541                // A lexical trace span: bracket the body with balanced
4542                // enter/exit events, emitting exit on EVERY path (normal, early
4543                // control flow, error) so a span can never leak (Wave 8).
4544                let cap = crate::observe::capturing();
4545                let name = if cap {
4546                    self.ctx.interner.resolve(*label).to_string()
4547                } else {
4548                    String::new()
4549                };
4550                if cap {
4551                    crate::observe::enter_span(name.clone());
4552                }
4553                let mut result: Result<ControlFlow, String> = Ok(ControlFlow::Continue);
4554                for s in body.iter() {
4555                    match self.execute_stmt(s).await {
4556                        Ok(ControlFlow::Continue) => {}
4557                        Ok(flow) => {
4558                            result = Ok(flow);
4559                            break;
4560                        }
4561                        Err(e) => {
4562                            result = Err(e);
4563                            break;
4564                        }
4565                    }
4566                }
4567                if cap {
4568                    crate::observe::exit_span(name);
4569                }
4570                result
4571            }
4572            Stmt::ForAll {
4573                vars,
4574                domain,
4575                constraint,
4576                body,
4577            } => {
4578                if !self.test_mode {
4579                    return Err(TEST_ONLY_STMT_ERR.to_string());
4580                }
4581                self.run_property(vars, *domain, *constraint, body)?;
4582                Ok(ControlFlow::Continue)
4583            }
4584
4585            Stmt::RuntimeAssert {
4586                condition, reason, ..
4587            } => {
4588                let val = self.evaluate_expr(condition).await?;
4589                if !val.decided_truth()? {
4590                    return Err(match reason {
4591                        Some(r) => crate::semantics::builtins::contract_reason_text(
4592                            self.evaluate_expr(r).await?,
4593                        )?,
4594                        None => "Assertion failed".to_string(),
4595                    });
4596                }
4597                Ok(ControlFlow::Continue)
4598            }
4599
4600            Stmt::Fail { reason } => Err(self.evaluate_expr(reason).await?.to_display_string()),
4601
4602            Stmt::Give { object, recipient } => {
4603                let obj_val = self.evaluate_expr(object).await?;
4604                if let Expr::Identifier(sym) = recipient {
4605                    self.call_function_with_values(*sym, vec![obj_val]).await?;
4606                }
4607                Ok(ControlFlow::Continue)
4608            }
4609
4610            Stmt::Show { object, recipient } => {
4611                let obj_val = self.evaluate_expr(object).await?;
4612                if let Expr::Identifier(sym) = recipient {
4613                    let name = self.ctx.interner.resolve(*sym);
4614                    if name == "show" {
4615                        self.emit_output(obj_val.to_display_string());
4616                    } else {
4617                        self.call_function_with_values(*sym, vec![obj_val]).await?;
4618                    }
4619                }
4620                Ok(ControlFlow::Continue)
4621            }
4622
4623            // Phase 55: VFS operations now supported
4624            Stmt::ReadFrom { var, source } => {
4625                let content =
4626                    match source {
4627                        ReadSource::Console => {
4628                            // Console read not available in WASM interpreter
4629                            String::new()
4630                        }
4631                        ReadSource::File(path_expr) => {
4632                            let path = self.evaluate_expr(path_expr).await?.to_display_string();
4633                            match &self.ctx.vfs {
4634                                Some(vfs) => vfs.read_to_string(&path).await.map_err(|e| {
4635                                    crate::semantics::builtins::vfs_read_failure(&e)
4636                                })?,
4637                                None => {
4638                                    return Err("VFS not initialized. Use Interpreter::with_vfs()"
4639                                        .to_string())
4640                                }
4641                            }
4642                        }
4643                    };
4644                self.define(*var, RuntimeValue::Text(Rc::new(content)));
4645                Ok(ControlFlow::Continue)
4646            }
4647
4648            Stmt::WriteFile { content, path } => {
4649                let content_val = self.evaluate_expr(content).await?.to_display_string();
4650                let path_val = self.evaluate_expr(path).await?.to_display_string();
4651                match &self.ctx.vfs {
4652                    Some(vfs) => {
4653                        vfs.write(&path_val, content_val.as_bytes())
4654                            .await
4655                            .map_err(|e| crate::semantics::builtins::vfs_write_failure(&e))?;
4656                    }
4657                    None => {
4658                        return Err("VFS not initialized. Use Interpreter::with_vfs()".to_string())
4659                    }
4660                }
4661                Ok(ControlFlow::Continue)
4662            }
4663
4664            Stmt::Spawn { name, .. } => {
4665                self.define(*name, RuntimeValue::Nothing);
4666                Ok(ControlFlow::Continue)
4667            }
4668
4669            // `Send <message> to <peer>` — publish the message on the peer's inbox
4670            // topic over the relay, tagged with our own inbox as the sender so the
4671            // recipient's `Await … from us` can match it.
4672            Stmt::SendMessage {
4673                message,
4674                destination,
4675                compression,
4676                cached,
4677                unchecked,
4678                layout,
4679                shared,
4680                computed,
4681                indexed,
4682                deduped,
4683                unreliable: _,
4684            } => {
4685                use crate::concurrency::marshal::{
4686                    default_integrity, message_to_wire_best, message_to_wire_cached,
4687                    message_to_wire_with, with_compression_codec, with_dedup, with_integrity,
4688                    with_numerics, with_struct_view, with_structure, with_type_registry, WireCodec,
4689                    WireGoal, WireIntegrity, WireNumerics, WireSchemaCache, WireStructure,
4690                };
4691                use logicaffeine_language::ast::SendLayout;
4692                let dest = self.evaluate_expr(destination).await?;
4693                let topic = crate::concurrency::net_inbox::peer_topic(&dest)?;
4694                let msg = self.evaluate_expr(message).await?;
4695                // `Send computed f` — COMPUTE-SHIPPING: lower a pure single-argument function
4696                // into the sandboxed generator so the COMPUTATION crosses the wire (as a
4697                // callable the receiver evaluates in its bounded sandbox), not data. The
4698                // lowering is the safety gate: only a total arithmetic expression over the
4699                // one argument lowers; anything else (I/O, calls, a block, >1 param) is
4700                // refused here, never shipped.
4701                let msg = if *computed {
4702                    match msg {
4703                        RuntimeValue::Function(c) if c.generated.is_some() => {
4704                            RuntimeValue::Function(c)
4705                        }
4706                        RuntimeValue::Function(c) => {
4707                            if c.param_names.len() != 1 {
4708                                return Err(
4709                                    "Send computed requires a single-argument pure function"
4710                                        .to_string(),
4711                                );
4712                            }
4713                            let expr =
4714                                match self.ctx.closure_bodies.get(c.body_index) {
4715                                    Some(ClosureBodyRef::Expression(e)) => *e,
4716                                    _ => return Err(
4717                                        "Send computed requires a pure expression-bodied function"
4718                                            .to_string(),
4719                                    ),
4720                                };
4721                            match crate::concurrency::marshal::lower_expr_to_genexpr(expr, c.param_names[0]) {
4722                                Some(gen) => RuntimeValue::Function(Box::new(ClosureValue {
4723                                    body_index: usize::MAX,
4724                                    captured_env: HashMap::default(),
4725                                    param_names: c.param_names.clone(),
4726                                    generated: Some(std::rc::Rc::new(gen)),
4727                                })),
4728                                None => {
4729                                    return Err(
4730                                        "Send computed: the function is not a pure arithmetic computation over its argument"
4731                                            .to_string(),
4732                                    )
4733                                }
4734                            }
4735                        }
4736                        _ => return Err("Send computed requires a function value".to_string()),
4737                    }
4738                } else {
4739                    msg
4740                };
4741                // Owned so the schema-cache borrow below doesn't alias the inbox topic.
4742                let from = self
4743                    .netbox
4744                    .inbox
4745                    .as_ref()
4746                    .map(|t| t.to_string())
4747                    .unwrap_or_default();
4748                // Advertise our type-registry epoch (set before the first-contact handshake below), so a
4749                // same-program peer with a matching epoch negotiates type-id name elision.
4750                self.netbox.my_profile.registry_epoch = self.build_wire_type_registry().epoch();
4751                // The message is any language value, encoded faithfully for the wire. The
4752                // sender's modifiers are the knobs for their link: `fast|compact|packed`
4753                // is the size↔speed LAYOUT (fixed-memcpy / varint / group-varint);
4754                // `compressed [with <codec>]` shrinks the body (kept only if it helps);
4755                // `cached` references a once-sent struct schema by id; `unchecked` drops
4756                // the integrity checksum (latency↔safety). The wire is self-describing,
4757                // so any peer decodes it regardless of which knobs the sender turned.
4758                let integrity = if *unchecked {
4759                    WireIntegrity::Raw
4760                } else {
4761                    default_integrity()
4762                };
4763                let numerics = match layout {
4764                    Some(SendLayout::Fast) => WireNumerics::Fixed,
4765                    Some(SendLayout::Packed) => WireNumerics::GroupVarint,
4766                    // `smallest`/`best` lets the per-column menu pick each column's own
4767                    // form, so the numeric dial stays the varint baseline it builds on.
4768                    Some(SendLayout::Smallest) => WireNumerics::Varint,
4769                    // `redundant` adds FEC framing OVER the default encoding.
4770                    Some(SendLayout::Redundant) => WireNumerics::Varint,
4771                    Some(SendLayout::Compact) | None => WireNumerics::Varint,
4772                };
4773                // `smallest` turns on the per-column compression menu (delta / DoD /
4774                // frame-of-reference / RLE / dictionary, auto-selected, never worse than
4775                // varint); every other layout leaves structural analysis off.
4776                let structure = match layout {
4777                    Some(SendLayout::Smallest) => WireStructure::Auto,
4778                    _ => WireStructure::Off,
4779                };
4780                // `shared` opts into type-id elision: install the program's type registry
4781                // so structs/enums ship a small id instead of their NAMES. OFF by default
4782                // (an empty registry → byte-identical self-describing encode) because a
4783                // relay or a different-program peer would not share the type ids.
4784                let registry = if *shared {
4785                    self.build_wire_type_registry()
4786                } else {
4787                    crate::concurrency::marshal::WireTypeRegistry::new(Vec::new())
4788                };
4789                // `indexed`/`addressable` opts the record list into the random-access struct-view
4790                // LAYOUT (row + field offset tables) so the receiver reaches any (row, field) in
4791                // O(1). It wraps EVERY path below, so it composes with `compressed`, `cached`,
4792                // `shared`, and `unchecked`. OFF by default (the dense columnar form is smaller).
4793                // A PLAIN send (no explicit codec knob) routes through the SHARED negotiated encoder
4794                // both tiers call, so the tree-walker and the VM net path stay byte-identical (the
4795                // cross-tier lock holds). Any explicit knob — `fast`/`packed`/`smallest`/`cached`/
4796                // `shared`/`indexed`/`compressed`/`computed`/`unchecked`/`redundant` — takes its own
4797                // override path below.
4798                let plain = !*computed
4799                    && !*unchecked
4800                    && !*shared
4801                    && !*indexed
4802                    && !*cached
4803                    && !*deduped
4804                    && compression.is_none()
4805                    && matches!(layout, None | Some(SendLayout::Compact));
4806                let bytes = if plain {
4807                    // Pass the program's registry; type-id fires only when the peer's epoch matched
4808                    // (negotiated), so a raw / different-program peer still gets the plain encoding.
4809                    self.netbox.encode_negotiated(
4810                        &from,
4811                        &msg,
4812                        &topic,
4813                        self.build_wire_type_registry(),
4814                    )?
4815                } else {
4816                    // `deduped` wraps the WHOLE encode: a subtree the same value reaches more than once
4817                    // ships once + backrefs, and the receiver rebuilds the sharing. A no-op when the
4818                    // knob is off, so the path below is byte-identical without it.
4819                    with_dedup(*deduped, || {
4820                        with_struct_view(*indexed, || {
4821                            with_type_registry(registry, || -> Result<Vec<u8>, String> {
4822                                // `smallest`/`best`: the message-level auto-tuner measures every dial
4823                                // combination and ships the PROVABLY smallest encoding (never larger than
4824                                // any single knob). It subsumes the numerics/structure/compression knobs,
4825                                // and composes with `shared` (the registry is active here) and `redundant`
4826                                // (FEC shards the result below). The cross-message schema cache (`cached`)
4827                                // is a separate optimization and keeps its own path. `deduped` is excluded here:
4828                                // the auto-tuner runs MANY encode passes, but the dedup id-table is per-encode, so
4829                                // dedup takes the single-pass general path below instead.
4830                                if matches!(layout, Some(SendLayout::Smallest))
4831                                    && !*cached
4832                                    && !*deduped
4833                                {
4834                                    return with_integrity(integrity, || {
4835                                        message_to_wire_best(&from, &msg, WireGoal::Smallest)
4836                                    });
4837                                }
4838                                if *cached {
4839                                    let cache = self
4840                                        .netbox
4841                                        .send_schema
4842                                        .entry(topic.clone())
4843                                        .or_insert_with(WireSchemaCache::content_addressed);
4844                                    let mut encode = || {
4845                                        message_to_wire_cached(
4846                                            &from,
4847                                            &msg,
4848                                            WireCodec::Native,
4849                                            integrity,
4850                                            cache,
4851                                        )
4852                                    };
4853                                    with_structure(structure, || {
4854                                        with_numerics(numerics, || match compression {
4855                                            Some(codec) => with_compression_codec(
4856                                                wire_compression_of(*codec),
4857                                                &mut encode,
4858                                            ),
4859                                            None => encode(),
4860                                        })
4861                                    })
4862                                } else {
4863                                    let mut encode = || {
4864                                        message_to_wire_with(
4865                                            &from,
4866                                            &msg,
4867                                            WireCodec::Native,
4868                                            integrity,
4869                                        )
4870                                    };
4871                                    with_structure(structure, || {
4872                                        with_numerics(numerics, || match compression {
4873                                            Some(codec) => with_compression_codec(
4874                                                wire_compression_of(*codec),
4875                                                &mut encode,
4876                                            ),
4877                                            None => encode(),
4878                                        })
4879                                    })
4880                                }
4881                            })
4882                        })
4883                    })?
4884                };
4885                // Seal the encoded message under the active crypto session/suite — identity /
4886                // byte-identical when none is engaged — before FEC/publish (compress → encrypt → FEC).
4887                // A keyed session may fail closed (a one-time pad is exhausted): refuse the send rather
4888                // than transmit plaintext.
4889                let bytes =
4890                    crate::concurrency::channel::seal_active_checked(bytes).ok_or_else(|| {
4891                        "one-time pad exhausted — message not sent (PNP fail-closed)".to_string()
4892                    })?;
4893                // Advertise our surface to this peer on FIRST contact — on its HANDSHAKE topic, never
4894                // the data topic — so it can negotiate back. Absorbed by the peer's drain.
4895                if let Some(hs) = self.netbox.first_contact_handshake(&topic) {
4896                    self.netbox.publish(
4897                        &crate::concurrency::net_inbox::handshake_topic_for(&topic),
4898                        hs,
4899                    )?;
4900                }
4901                if matches!(layout, Some(SendLayout::Redundant)) {
4902                    // FEC: split the encoded message into K data + (N−K) parity shards and
4903                    // publish each as its own packet, so a receiver reconstructs the exact
4904                    // message from any K even if some are lost on the link.
4905                    let msg_id = self.netbox.next_msg_id();
4906                    let shards = crate::concurrency::fec::frame_redundant(
4907                        msg_id,
4908                        &bytes,
4909                        REDUNDANT_K,
4910                        REDUNDANT_N,
4911                    )
4912                    .ok_or_else(|| "redundant framing failed".to_string())?;
4913                    for shard in shards {
4914                        self.netbox.publish(&topic, shard)?;
4915                    }
4916                } else {
4917                    self.netbox.publish(&topic, bytes)?;
4918                }
4919                Ok(ControlFlow::Continue)
4920            }
4921
4922            // `Await … from <peer> into x` — block (cooperatively) until a message
4923            // from that peer arrives on our inbox, then bind it to `x`. Messages
4924            // from other peers stay queued for their own `Await`.
4925            Stmt::AwaitMessage {
4926                source,
4927                into,
4928                view,
4929                stream,
4930            } => {
4931                let src = self.evaluate_expr(source).await?;
4932                let want = crate::concurrency::net_inbox::peer_topic(&src)?;
4933                if self.netbox.inbox.is_none() {
4934                    return Err(crate::concurrency::net_inbox::AWAIT_WITHOUT_LISTEN.to_string());
4935                }
4936                // OFFLINE (no relay): the deterministic oracle reads from our own loopback outbox — a
4937                // `Send … to <self>` already delivered the message locally, so `Await` resolves it (no
4938                // real transport needed). A relay-connected node drains the relay instead.
4939                let msg = if *stream {
4940                    self.await_stream_from(&want).await?
4941                } else {
4942                    self.await_message_from(&want, *view).await?
4943                };
4944                self.define(*into, msg);
4945                Ok(ControlFlow::Continue)
4946            }
4947
4948            // `Stream <values> to <peer>` — batch the list into one framed stream message and
4949            // publish it to the peer's inbox; `Await stream from us` deframes it back into a list.
4950            Stmt::StreamMessage {
4951                values,
4952                destination,
4953            } => {
4954                let dest = self.evaluate_expr(destination).await?;
4955                let topic = crate::concurrency::net_inbox::peer_topic(&dest)?;
4956                let list = self.evaluate_expr(values).await?;
4957                let items = match &list {
4958                    RuntimeValue::List(rc) => rc.borrow().to_values(),
4959                    other => vec![other.clone()],
4960                };
4961                let from = self
4962                    .netbox
4963                    .inbox
4964                    .as_ref()
4965                    .map(|t| t.to_string())
4966                    .unwrap_or_default();
4967                let registry = self.build_wire_type_registry();
4968                let blob = crate::concurrency::marshal::with_type_registry(registry, || {
4969                    crate::concurrency::marshal::frame_stream_message(&from, &items)
4970                })?;
4971                // Route through `publish`, which OFFLINE loops the framed stream back into our own inbox
4972                // (a following `Await stream` deframes it) rather than requiring a relay.
4973                self.netbox.publish(&topic, blob)?;
4974                Ok(ControlFlow::Continue)
4975            }
4976
4977            Stmt::MergeCrdt { source, target } => {
4978                let source_val = self.evaluate_expr(source).await?;
4979                let source_fields = match &source_val {
4980                    RuntimeValue::Struct(s) => s.fields.clone(),
4981                    _ => return Err("Merge source must be a struct".to_string()),
4982                };
4983
4984                if let Expr::Identifier(target_sym) = target {
4985                    let mut target_val = self.lookup(*target_sym)?.clone();
4986
4987                    if let RuntimeValue::Struct(ref mut s) = target_val {
4988                        for (field_name, source_field_val) in source_fields {
4989                            let current = s
4990                                .fields
4991                                .get(&field_name)
4992                                .cloned()
4993                                .unwrap_or(RuntimeValue::Int(0));
4994
4995                            let merged = crate::semantics::arith::crdt_merge_field(
4996                                &current,
4997                                source_field_val,
4998                            );
4999                            s.fields.insert(field_name, merged);
5000                        }
5001                        self.assign(*target_sym, target_val)?;
5002                    } else {
5003                        return Err("Merge target must be a struct".to_string());
5004                    }
5005                } else {
5006                    return Err("Merge target must be an identifier".to_string());
5007                }
5008                Ok(ControlFlow::Continue)
5009            }
5010
5011            // The IDEMPOTENT sibling of `MergeCrdt`: a bare-`Int` field takes per-field MAX (not ADD), so a
5012            // redelivered state never double-counts. Counter/other fields defer to `crdt_join_field`'s merge.
5013            Stmt::JoinCrdt { source, target } => {
5014                let source_val = self.evaluate_expr(source).await?;
5015                let source_fields = match &source_val {
5016                    RuntimeValue::Struct(s) => s.fields.clone(),
5017                    _ => return Err("Converge source must be a struct".to_string()),
5018                };
5019
5020                if let Expr::Identifier(target_sym) = target {
5021                    let mut target_val = self.lookup(*target_sym)?.clone();
5022
5023                    if let RuntimeValue::Struct(ref mut s) = target_val {
5024                        for (field_name, source_field_val) in source_fields {
5025                            let current = s
5026                                .fields
5027                                .get(&field_name)
5028                                .cloned()
5029                                .unwrap_or(RuntimeValue::Int(0));
5030
5031                            let joined = crate::semantics::arith::crdt_join_field(
5032                                &current,
5033                                source_field_val,
5034                            );
5035                            s.fields.insert(field_name, joined);
5036                        }
5037                        self.assign(*target_sym, target_val)?;
5038                    } else {
5039                        return Err("Converge target must be a struct".to_string());
5040                    }
5041                } else {
5042                    return Err("Converge target must be an identifier".to_string());
5043                }
5044                Ok(ControlFlow::Continue)
5045            }
5046
5047            Stmt::IncreaseCrdt {
5048                object,
5049                field,
5050                amount,
5051            } => {
5052                let amount_val = self.evaluate_expr(amount).await?;
5053                let amount_int = match amount_val {
5054                    RuntimeValue::Int(n) => n,
5055                    _ => return Err("CRDT increment amount must be an integer".to_string()),
5056                };
5057
5058                if let Expr::Identifier(obj_sym) = object {
5059                    let mut obj_val = self.lookup(*obj_sym)?.clone();
5060
5061                    if let RuntimeValue::Struct(ref mut s) = obj_val {
5062                        let field_name = self.ctx.interner.resolve(*field).to_string();
5063                        let current = s
5064                            .fields
5065                            .get(&field_name)
5066                            .cloned()
5067                            .unwrap_or(RuntimeValue::Int(0));
5068
5069                        let new_val = crate::semantics::arith::crdt_counter_bump(
5070                            current,
5071                            amount_int,
5072                            &field_name,
5073                        )?;
5074                        s.fields.insert(field_name, new_val);
5075                        self.assign(*obj_sym, obj_val)?;
5076                    } else {
5077                        return Err("Cannot increase field on non-struct value".to_string());
5078                    }
5079                } else {
5080                    return Err("IncreaseCrdt target must be an identifier".to_string());
5081                }
5082                Ok(ControlFlow::Continue)
5083            }
5084
5085            Stmt::DecreaseCrdt {
5086                object,
5087                field,
5088                amount,
5089            } => {
5090                let amount_val = self.evaluate_expr(amount).await?;
5091                let amount_int = match amount_val {
5092                    RuntimeValue::Int(n) => n,
5093                    _ => return Err("CRDT decrement amount must be an integer".to_string()),
5094                };
5095
5096                if let Expr::Identifier(obj_sym) = object {
5097                    let mut obj_val = self.lookup(*obj_sym)?.clone();
5098
5099                    if let RuntimeValue::Struct(ref mut s) = obj_val {
5100                        let field_name = self.ctx.interner.resolve(*field).to_string();
5101                        let current = s
5102                            .fields
5103                            .get(&field_name)
5104                            .cloned()
5105                            .unwrap_or(RuntimeValue::Int(0));
5106
5107                        let new_val = crate::semantics::arith::crdt_counter_bump(
5108                            current,
5109                            amount_int.wrapping_neg(),
5110                            &field_name,
5111                        )?;
5112                        s.fields.insert(field_name, new_val);
5113                        self.assign(*obj_sym, obj_val)?;
5114                    } else {
5115                        return Err("Cannot decrease field on non-struct value".to_string());
5116                    }
5117                } else {
5118                    return Err("DecreaseCrdt target must be an identifier".to_string());
5119                }
5120                Ok(ControlFlow::Continue)
5121            }
5122
5123            Stmt::AppendToSequence { sequence, value } => {
5124                let val = self.evaluate_expr(value).await?;
5125                let seq_val = self.evaluate_expr(sequence).await?;
5126                match &seq_val {
5127                    RuntimeValue::Crdt(rc) => rc.borrow_mut().append(&val)?,
5128                    RuntimeValue::List(_) => {
5129                        crate::semantics::collections::list_push(&seq_val, val)?
5130                    }
5131                    _ => return Err(format!("Cannot append to {}", seq_val.type_name())),
5132                }
5133                Ok(ControlFlow::Continue)
5134            }
5135
5136            Stmt::ResolveConflict {
5137                object,
5138                field,
5139                value,
5140            } => {
5141                let val = self.evaluate_expr(value).await?;
5142                let obj_val = self.evaluate_expr(object).await?;
5143                let field_name = self.ctx.interner.resolve(*field);
5144                // A real divergent register resolves in place (its `Rc` is shared with the
5145                // struct field); a plain field falls back to a direct assignment.
5146                if let RuntimeValue::Struct(s) = &obj_val {
5147                    if let Some(RuntimeValue::Crdt(rc)) = s.fields.get(field_name) {
5148                        rc.borrow_mut().resolve(&val)?;
5149                        return Ok(ControlFlow::Continue);
5150                    }
5151                }
5152                if let Expr::Identifier(obj_sym) = object {
5153                    let mut owner = self.lookup(*obj_sym)?.clone();
5154                    if let RuntimeValue::Struct(ref mut s) = owner {
5155                        s.fields.insert(field_name.to_string(), val);
5156                        self.assign(*obj_sym, owner)?;
5157                        return Ok(ControlFlow::Continue);
5158                    }
5159                }
5160                Err("Resolve target must be a struct field".to_string())
5161            }
5162
5163            Stmt::Check { .. } => self.exec_check(stmt),
5164
5165            // `Connect to "<relay>"` — open the transport: dial the relay and hold
5166            // the connection for `Sync` and peer messaging. Accepts the same
5167            // address surface as the compiled path: a libp2p multiaddr
5168            // (`/ip4/H/tcp/P`) normalizes to the relay's `ws://H:P`; a raw `ws://`
5169            // URL passes through.
5170            Stmt::ConnectTo { address, secure } => {
5171                let raw = self.evaluate_expr(address).await?.to_display_string();
5172                let url = crate::concurrency::net_inbox::relay_url(&raw)?;
5173                // Activate the one-time-pad session first, so a bad pad fails the connect (fail-closed).
5174                if let Some(bind) = secure {
5175                    self.activate_pnp_session(bind).await?;
5176                }
5177                // OFFLINE mode (the deterministic tree-walker/VM oracles, no relay transport): `Connect`
5178                // is a local no-op — nothing to dial, so `net` stays None and the following ops run
5179                // locally, exactly as `Listen`/`Send`/`Sync` already do offline. A relay-connected driver
5180                // dials for real. The address is still validated so a malformed one errors on both paths.
5181                if !crate::concurrency::net_inbox::net_is_offline() {
5182                    let net = logicaffeine_system::net::Net::connect(&url)
5183                        .await
5184                        .map_err(|e| format!("Connect to relay '{url}' failed: {e}"))?;
5185                    self.netbox.net = Some(net);
5186                }
5187                Ok(ControlFlow::Continue)
5188            }
5189            // `Listen at "<addr>"` — declare this node's identity: subscribe to its
5190            // inbox topic so peers can reach it with `Send … to`. The relay is the
5191            // transport (a browser cannot bind a socket), so this needs a prior
5192            // `Connect`. The address is canonicalized so `/ip4/H/tcp/P` and the
5193            // `ws://H:P` form name the same inbox.
5194            Stmt::Listen { address, secure } => {
5195                let raw = self.evaluate_expr(address).await?.to_display_string();
5196                let topic = logicaffeine_system::addr::canonical_topic(&raw);
5197                let hs_topic = crate::concurrency::net_inbox::handshake_topic_for(&topic);
5198                if let Some(bind) = secure {
5199                    self.activate_pnp_session(bind).await?;
5200                }
5201                // LOCAL/OFFLINE mode (no relay): declare our inbox identity locally and skip the relay
5202                // subscribe — a single node listening on its own address needs no transport. A relay-
5203                // connected node subscribes so peers can reach it. Either way `Listen` never ERRORS.
5204                if let Some(net) = self.netbox.net.as_mut() {
5205                    net.subscribe(&topic).await?;
5206                    // Also receive peers' capability handshakes on our dedicated handshake topic.
5207                    net.subscribe(&hs_topic).await?;
5208                }
5209                self.netbox.inbox = Some(Rc::new(topic));
5210                Ok(ControlFlow::Continue)
5211            }
5212            // HTTP server: bind a port and, per request, re-enter the LOGOS handler
5213            // (a `Request -> Response` function) with the parsed request and write
5214            // back its response. This is the host→LOGOS callback keystone — the
5215            // accept loop runs inline on this thread (the interpreter is `!Send`),
5216            // never spawning, so `&mut self` is simply borrowed across `.await`.
5217            Stmt::Serve { port, handler } => {
5218                let port_num: u16 = match self.evaluate_expr(port).await? {
5219                    RuntimeValue::Int(n) if (0..=65535).contains(&n) => n as u16,
5220                    RuntimeValue::Int(n) => {
5221                        return Err(format!("Serve: port {n} is out of range (0-65535)"))
5222                    }
5223                    other => {
5224                        return Err(format!(
5225                            "Serve: port must be an Int, got {}",
5226                            other.type_name()
5227                        ))
5228                    }
5229                };
5230                let handler_sym = match handler {
5231                    Expr::Identifier(sym) => *sym,
5232                    _ => return Err("Serve: the handler must be a named function".to_string()),
5233                };
5234                self.serve_http(port_num, handler_sym).await?;
5235                Ok(ControlFlow::Continue)
5236            }
5237            // `Let r be a PeerAgent at "<addr>"` — a handle to a remote peer; its
5238            // value is the peer's canonical inbox topic. Pure (no I/O); `Send`
5239            // and `Await` do the networking.
5240            Stmt::LetPeerAgent { var, address } => {
5241                let raw = self.evaluate_expr(address).await?.to_display_string();
5242                let topic = logicaffeine_system::addr::canonical_topic(&raw);
5243                self.define(*var, RuntimeValue::Peer(Rc::new(topic)));
5244                Ok(ControlFlow::Continue)
5245            }
5246            Stmt::Sleep { milliseconds } => {
5247                let val = self.evaluate_expr(milliseconds).await?;
5248                self.sleep_for(val).await?;
5249                Ok(ControlFlow::Continue)
5250            }
5251            // `Sync x on "topic"` — a CRDT sync POINT over the relay: subscribe,
5252            // publish the local counter, then merge whatever has arrived (the same
5253            // `crdt_merge_field` the in-process merge uses). No background task —
5254            // the merge happens here, keeping the tree-walker's linear model.
5255            Stmt::Sync { var, topic } => {
5256                let topic_str = self.evaluate_expr(topic).await?.to_display_string();
5257                let current = self.lookup(*var)?.clone();
5258                // Rich COLLECTION CRDT (ORSet / RGA / MVRegister) → δ-STATE sync: publish only what
5259                // changed since our last sync on this topic (`delta_since`, per field), and merge
5260                // incoming deltas IN PLACE through the shared `Rc`. The first sync ships the full state
5261                // (delta since nothing); every later sync ships a handful of bytes for the NEW entries,
5262                // never the whole collection. Idempotent + commutative, so redelivery / reordering still
5263                // converges. Covers a bare CrdtValue var (field name "") AND every CrdtValue field of a
5264                // `Shared` struct. A COUNTER CRDT (`ConvergentCount`/`Tally`) is EXCLUDED here: under
5265                // Spec A a counter's readable wire projection is its Int TOTAL (`{"points":3}`), so it
5266                // takes the `crdt_to_wire` JSON path below (`field_to_json` projects it to its scalar),
5267                // not the opaque δ-state bytes — the same wire form a bare-Int counter shipped.
5268                let is_counter = |rc: &std::rc::Rc<
5269                    std::cell::RefCell<crate::semantics::crdt::CrdtValue>,
5270                >| { rc.borrow().counter_value().is_some() };
5271                let crdt_fields: Vec<(
5272                    String,
5273                    std::rc::Rc<std::cell::RefCell<crate::semantics::crdt::CrdtValue>>,
5274                )> = match &current {
5275                    RuntimeValue::Crdt(rc) if !is_counter(rc) => vec![(String::new(), rc.clone())],
5276                    RuntimeValue::Crdt(_) => Vec::new(),
5277                    RuntimeValue::Struct(s) => s
5278                        .fields
5279                        .iter()
5280                        .filter_map(|(k, v)| match v {
5281                            RuntimeValue::Crdt(rc) if !is_counter(rc) => {
5282                                Some((k.clone(), rc.clone()))
5283                            }
5284                            _ => None,
5285                        })
5286                        .collect(),
5287                    _ => Vec::new(),
5288                };
5289                if !crdt_fields.is_empty() {
5290                    let field_key = |name: &str| format!("{topic_str}\u{0}{name}");
5291                    // Each field's delta since the version we last shipped on this topic.
5292                    let mut frame: Vec<(String, Vec<u8>)> = Vec::new();
5293                    for (name, rc) in &crdt_fields {
5294                        let since = self
5295                            .netbox
5296                            .sync_versions
5297                            .get(&field_key(name))
5298                            .cloned()
5299                            .unwrap_or_default();
5300                        if let Some(d) = rc.borrow().delta_since_bytes(&since) {
5301                            frame.push((name.clone(), d));
5302                        }
5303                    }
5304                    let payload = serde_json::to_vec(&frame).unwrap_or_default();
5305                    // LOCAL/OFFLINE mode (no relay): single-node δ-sync is a no-op — nothing arrives,
5306                    // the local state stands; we still advance the per-field versions below. A relay-
5307                    // connected deployment publishes its delta + merges incoming ones.
5308                    if let Some(net) = self.netbox.net.as_mut() {
5309                        net.subscribe(&topic_str).await?;
5310                        if !frame.is_empty() {
5311                            net.publish(&topic_str, payload)?;
5312                        }
5313                        let incoming = net.drain();
5314                        // Merge every incoming field delta into the matching local CRDT field, in place.
5315                        for (_t, data) in incoming {
5316                            let Ok(fields) =
5317                                serde_json::from_slice::<Vec<(String, Vec<u8>)>>(&data)
5318                            else {
5319                                continue;
5320                            };
5321                            for (name, delta) in fields {
5322                                if let Some((_, rc)) = crdt_fields.iter().find(|(n, _)| *n == name)
5323                                {
5324                                    rc.borrow_mut().apply_delta_bytes(&delta);
5325                                }
5326                            }
5327                        }
5328                    }
5329                    // Record the version we now hold per field, so the next sync ships only later changes.
5330                    for (name, rc) in &crdt_fields {
5331                        let v = rc.borrow().version();
5332                        self.netbox.sync_versions.insert(field_key(name), v);
5333                    }
5334                    return Ok(ControlFlow::Continue);
5335                }
5336                // Encode the counter (Int) or counter-struct (named Int fields) as
5337                // the relay wire form; `None` ⇒ nothing to publish yet.
5338                let publish_bytes = crate::semantics::arith::crdt_to_wire(&current);
5339                // LOCAL/OFFLINE mode: with no relay connected (the playground/test path, and any
5340                // program that never `Connect`ed), a `Sync` is a SINGLE-NODE no-op — the local CRDT
5341                // value stands, deterministically. A real deployment that `Connect`ed to a relay takes
5342                // the transport branch (publish our delta, merge everyone else's). Either way `Sync`
5343                // never ERRORS, so a networked program runs identically on tree-walker, VM, and AOT.
5344                let merged = if let Some(net) = self.netbox.net.as_mut() {
5345                    net.subscribe(&topic_str).await?;
5346                    if let Some(bytes) = publish_bytes {
5347                        net.publish(&topic_str, bytes)?;
5348                    }
5349                    // Merge everything that has arrived since the last sync point, field by field —
5350                    // the same CRDT merge the in-process `Merge` uses.
5351                    let incoming = net.drain();
5352                    let mut merged = current;
5353                    for (_t, data) in incoming {
5354                        merged = crate::semantics::arith::crdt_merge_wire(merged, &data);
5355                    }
5356                    merged
5357                } else {
5358                    current
5359                };
5360                self.assign(*var, merged)?;
5361                Ok(ControlFlow::Continue)
5362            }
5363            // Phase 55: Mount now supported via VFS
5364            Stmt::Mount { var, path } => {
5365                let path_val = self.evaluate_expr(path).await?.to_display_string();
5366                match &self.ctx.vfs {
5367                    Some(vfs) => {
5368                        // Read existing content or create empty
5369                        let content = match vfs.read_to_string(&path_val).await {
5370                            Ok(s) => s,
5371                            Err(_) => String::new(),
5372                        };
5373                        self.define(*var, RuntimeValue::Text(Rc::new(content)));
5374                    }
5375                    None => {
5376                        return Err("VFS not initialized. Use Interpreter::with_vfs()".to_string())
5377                    }
5378                }
5379                Ok(ControlFlow::Continue)
5380            }
5381
5382            // Phase 54 / T6-T7: Go-like concurrency, driven by the deterministic
5383            // scheduler via the per-task side-channel (`yield_request`).
5384            Stmt::CreatePipe { var, capacity, .. } => {
5385                let cap = capacity.map(|c| c as usize);
5386                let resume = self.yield_request(BlockingRequest::NewChan(cap)).await;
5387                let ch = resume
5388                    .into_chan()
5389                    .ok_or_else(|| "scheduler did not create a channel".to_string())?;
5390                self.define(*var, RuntimeValue::Chan(ch));
5391                Ok(ControlFlow::Continue)
5392            }
5393            Stmt::SendPipe { value, pipe } => {
5394                let ch = self.eval_chan(pipe).await?;
5395                let val = self.evaluate_expr(value).await?;
5396                let payload = marshal::materialize(&val)
5397                    .map_err(|e| format!("cannot send value through a channel: {:?}", e))?;
5398                self.yield_request(BlockingRequest::Send(ch, payload)).await;
5399                Ok(ControlFlow::Continue)
5400            }
5401            Stmt::ReceivePipe { var, pipe } => {
5402                let ch = self.eval_chan(pipe).await?;
5403                let resume = self.yield_request(BlockingRequest::Recv(ch)).await;
5404                let value = marshal::rebuild(resume.into_payload());
5405                self.define(*var, value);
5406                Ok(ControlFlow::Continue)
5407            }
5408            Stmt::LaunchTask { function, args } => {
5409                let mut arg_vals = Vec::with_capacity(args.len());
5410                for a in args.iter() {
5411                    let val = self.evaluate_expr(a).await?;
5412                    arg_vals.push(crossing_to_a_task(&val)?);
5413                }
5414                let child = self.spawn_child_task(*function, arg_vals);
5415                self.yield_request(BlockingRequest::Spawn(child)).await;
5416                Ok(ControlFlow::Continue)
5417            }
5418            Stmt::LaunchTaskWithHandle {
5419                handle,
5420                function,
5421                args,
5422            } => {
5423                let mut arg_vals = Vec::with_capacity(args.len());
5424                for a in args.iter() {
5425                    let val = self.evaluate_expr(a).await?;
5426                    arg_vals.push(crossing_to_a_task(&val)?);
5427                }
5428                let child = self.spawn_child_task(*function, arg_vals);
5429                let resume = self.yield_request(BlockingRequest::Spawn(child)).await;
5430                let tid = resume
5431                    .into_task()
5432                    .ok_or_else(|| "scheduler did not return a task handle".to_string())?;
5433                self.define(*handle, RuntimeValue::TaskHandle(tid));
5434                Ok(ControlFlow::Continue)
5435            }
5436            Stmt::StopTask { handle } => {
5437                let tid = self.eval_task(handle).await?;
5438                self.yield_request(BlockingRequest::Abort(tid)).await;
5439                Ok(ControlFlow::Continue)
5440            }
5441            Stmt::CloseChannel { channel } => {
5442                let ch = self.eval_chan(channel).await?;
5443                self.yield_request(BlockingRequest::Close(ch)).await;
5444                Ok(ControlFlow::Continue)
5445            }
5446            Stmt::AwaitTask { handle, result } => {
5447                let tid = self.eval_task(handle).await?;
5448                let resume = self.yield_request(BlockingRequest::Await(tid)).await;
5449                let value = marshal::rebuild(resume.into_payload());
5450                if let Some(r) = result {
5451                    self.define(*r, value);
5452                }
5453                Ok(ControlFlow::Continue)
5454            }
5455            Stmt::TrySendPipe {
5456                value,
5457                pipe,
5458                result,
5459            } => {
5460                let ch = self.eval_chan(pipe).await?;
5461                let val = self.evaluate_expr(value).await?;
5462                let payload = marshal::materialize(&val)
5463                    .map_err(|e| format!("cannot send value through a channel: {:?}", e))?;
5464                let resume = self
5465                    .yield_request(BlockingRequest::TrySend(ch, payload))
5466                    .await;
5467                let ok = matches!(resume.into_payload(), RtPayload::Bool(true));
5468                if let Some(res) = result {
5469                    self.define(*res, RuntimeValue::Bool(ok));
5470                }
5471                Ok(ControlFlow::Continue)
5472            }
5473            Stmt::TryReceivePipe { var, pipe } => {
5474                let ch = self.eval_chan(pipe).await?;
5475                let resume = self.yield_request(BlockingRequest::TryRecv(ch)).await;
5476                // ★ A REAL OPTION, like every other producer of one. A try-receive answers
5477                // "a value, or nothing", which IS an Option — but it used to hand back the bare
5478                // value and the `Nothing` sentinel, so `Inspect x: When Some (v):` could only work
5479                // while `Inspect` matched a `Some` arm against anything that was not the sentinel.
5480                // With that catch-all gone it errored with "no arm for the value": honest, but a
5481                // capability the sentence plainly promises.
5482                //
5483                // R1 keeps `Show x` printing the value or `nothing`, and R2 keeps
5484                // `x is equal to nothing` true when empty, so every existing reader is unaffected.
5485                let value = match marshal::rebuild(resume.into_payload()) {
5486                    RuntimeValue::Nothing => option_none(),
5487                    v => option_some(v),
5488                };
5489                self.define(*var, value);
5490                Ok(ControlFlow::Continue)
5491            }
5492            Stmt::Select { branches } => {
5493                use crate::ast::stmt::SelectBranch;
5494                // Resolve each branch to a runtime arm in declaration order, so the
5495                // scheduler's winning index maps straight back to a branch body.
5496                let mut arms = Vec::with_capacity(branches.len());
5497                for branch in branches.iter() {
5498                    match branch {
5499                        SelectBranch::Receive { pipe, .. } => {
5500                            let ch = self.eval_chan(pipe).await?;
5501                            arms.push(SelectArm::Recv(ch));
5502                        }
5503                        SelectBranch::Timeout { milliseconds, .. } => {
5504                            let ticks = self.eval_select_timeout_ticks(milliseconds).await?;
5505                            arms.push(SelectArm::Timeout(ticks));
5506                        }
5507                    }
5508                }
5509                let resume = self.yield_request(BlockingRequest::Select(arms)).await;
5510                let (arm, payload) = resume
5511                    .into_select()
5512                    .ok_or_else(|| "scheduler did not resolve the select".to_string())?;
5513                match &branches[arm] {
5514                    SelectBranch::Receive { var, body, .. } => {
5515                        self.define(*var, marshal::rebuild(payload));
5516                        self.execute_block(*body).await
5517                    }
5518                    SelectBranch::Timeout { body, .. } => self.execute_block(*body).await,
5519                }
5520            }
5521
5522            // Only the Rust backends compile an Escape; every other tier refuses it with the one message.
5523            Stmt::Escape { .. } => Err(crate::semantics::escape::REFUSAL.to_string()),
5524
5525            // Dependencies are compilation metadata. No-op in interpreter.
5526            Stmt::Require { .. } => Ok(ControlFlow::Continue),
5527
5528            // Theorems and definitions are proof-layer declarations verified at
5529            // compile-time, not executed.
5530            Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {
5531                Ok(ControlFlow::Continue)
5532            }
5533
5534            // A failure-site marker (Wave 3): the reference tier's own job with it is exactly
5535            // "current site = id" — see `Stmt::Site`'s and `current_site`'s own doc comments for
5536            // why no call stack is needed. A trap renders with whichever site is current.
5537            Stmt::Site(id) => {
5538                self.current_site = Some(*id);
5539                Ok(ControlFlow::Continue)
5540            }
5541        }
5542    }
5543
5544    /// Execute a block of statements, returning control flow.
5545    /// Phase 55: Now async.
5546    #[async_recursion(?Send)]
5547    async fn execute_block(&mut self, block: Block<'a>) -> Result<ControlFlow, String> {
5548        self.push_scope();
5549        for stmt in block.iter() {
5550            match self.execute_stmt(stmt).await? {
5551                ControlFlow::Continue => {}
5552                flow => {
5553                    self.pop_scope();
5554                    return Ok(flow);
5555                }
5556            }
5557        }
5558        self.pop_scope();
5559        Ok(ControlFlow::Continue)
5560    }
5561
5562    /// The loud message for a non-exhaustive `Inspect` — no arm matched the
5563    /// scrutinee's actual variant and there was no `Otherwise`. Exhaustiveness
5564    /// or a wildcard is required; a silent no-op hid the missing arm. Names the
5565    /// value's own variant and type (gauntlet finding G5) through the ONE shared
5566    /// constructor `semantics::builtins::inspect_unhandled_message` — the VM
5567    /// calls the identical function on the identical `RuntimeValue` shape (its
5568    /// `Value` wraps this crate's own `RuntimeValue` directly), so a mistyped
5569    /// arm fails with the same words on both tiers.
5570    fn inspect_unhandled(&self, target: &RuntimeValue) -> String {
5571        let variant = match target {
5572            RuntimeValue::Inductive(i) => i.constructor.as_str(),
5573            _ => "the value",
5574        };
5575        crate::semantics::builtins::inspect_unhandled_message(target.type_name(), variant)
5576    }
5577
5578    /// Execute Inspect (pattern matching).
5579    /// Phase 55: Now async.
5580    /// Phase 102: Extended to handle kernel inductives.
5581    #[async_recursion(?Send)]
5582    async fn execute_inspect(
5583        &mut self,
5584        target: &RuntimeValue,
5585        arms: &[MatchArm<'a>],
5586    ) -> Result<ControlFlow, String> {
5587        for arm in arms {
5588            // Handle Otherwise (wildcard) case
5589            if arm.variant.is_none() {
5590                let flow = self.execute_block(arm.body).await?;
5591                return Ok(flow);
5592            }
5593
5594            match target {
5595                RuntimeValue::Struct(s) => {
5596                    if let Some(variant) = arm.variant {
5597                        let variant_name = self.ctx.interner.resolve(variant);
5598                        if s.type_name == variant_name {
5599                            self.push_scope();
5600                            for (field_name, binding_name) in &arm.bindings {
5601                                let field_str = self.ctx.interner.resolve(*field_name);
5602                                if let Some(val) = s.fields.get(field_str) {
5603                                    self.define(*binding_name, val.clone());
5604                                }
5605                            }
5606                            let result = self.execute_block(arm.body).await;
5607                            self.pop_scope();
5608                            let flow = result?;
5609                            return Ok(flow);
5610                        }
5611                        // The transparent Option encoding, for a STRUCT payload: `some x` IS x,
5612                        // so `some(a new Response …)` is a Response and a `Some` arm has to match
5613                        // it. Without this the arm above rejects it (its `type_name` is
5614                        // `Response`, not `Some`) and the `other` arm below is never reached,
5615                        // because this branch already claimed the value — so `Option of <any
5616                        // record>` could not be inspected AT ALL, while `Option of Int` worked
5617                        // fine. That asymmetry is invisible until someone writes the first
5618                        // `-> Option of Response`, which is the plan's own middleware signature.
5619                        // ★ A STRUCT NO LONGER ANSWERS A `Some` ARM. This existed because an
5620                        // Option was transparent — `some (a new Response …)` WAS the Response, so
5621                        // without it `Option of <record>` could not be inspected at all while
5622                        // `Option of Int` worked, an asymmetry that stayed invisible until the
5623                        // first `-> Option of Response`. A real Option is an `Inductive` now and
5624                        // is matched by name, so leaving this would let a plain record claim to be
5625                        // a present Option.
5626                    }
5627                }
5628
5629                RuntimeValue::Inductive(ind) => {
5630                    if let Some(variant) = arm.variant {
5631                        let variant_name = self.ctx.interner.resolve(variant);
5632                        if ind.constructor == variant_name {
5633                            self.push_scope();
5634                            for (i, (_, binding_name)) in arm.bindings.iter().enumerate() {
5635                                if i < ind.args.len() {
5636                                    self.define(*binding_name, ind.args[i].clone());
5637                                }
5638                            }
5639                            let result = self.execute_block(arm.body).await;
5640                            self.pop_scope();
5641                            let flow = result?;
5642                            return Ok(flow);
5643                        }
5644                    }
5645                }
5646
5647                // The transparent Option encoding: `some x` IS x and `none` IS
5648                // Nothing, so Some/None arms match presence/absence for
5649                // non-enum values (the boxed `a new Some …` form matches
5650                // through the arms above).
5651                RuntimeValue::Nothing => {
5652                    if let Some(variant) = arm.variant {
5653                        if self.ctx.interner.resolve(variant) == "None" {
5654                            let flow = self.execute_block(arm.body).await?;
5655                            return Ok(flow);
5656                        }
5657                    }
5658                }
5659
5660                // ★ THE TRANSPARENT CATCH-ALL IS GONE. It answered a `Some` arm with ANY value
5661                // that was not the sentinel, which was the encoding's entire presence rule. An
5662                // Option now arrives as an `Inductive("Option", …)` and is matched by name above,
5663                // so this clause would only ever make a bare `7` claim to be a present Option.
5664                _ => {}
5665            }
5666        }
5667        Err(self.inspect_unhandled(target))
5668    }
5669
5670    /// Build the wire type registry from the program's struct definitions. A peer running
5671    /// the SAME program derives the identical (content-addressed) ids, so a `Send shared`
5672    /// struct can ship its id instead of its field names and the receiver resolves it.
5673    /// Skips a compiler-provided struct (`TypeRegistry::is_builtin_struct`, `HttpError`/`File`)
5674    /// — the compiler hands EVERY program those two whether it names them or not, so leaving them
5675    /// in would advertise a non-zero epoch (and inflate the registry) for a program with no
5676    /// struct/enum types of its own, breaking the "same program ⇒ same registry" contract that
5677    /// the sibling `type_registry_for_vm` build in `ui_bridge.rs` already honors.
5678    fn build_wire_type_registry(&self) -> crate::concurrency::marshal::WireTypeRegistry {
5679        let is_builtin = |name_sym: &Symbol| {
5680            self.ctx
5681                .types
5682                .as_ref()
5683                .is_some_and(|t| t.is_builtin_struct(*name_sym))
5684        };
5685        let schemas: Vec<(String, Vec<String>)> = self
5686            .ctx
5687            .struct_defs
5688            .iter()
5689            .filter(|(name_sym, _)| !is_builtin(name_sym))
5690            .map(|(name_sym, fields)| {
5691                let type_name = self.ctx.interner.resolve(*name_sym).to_string();
5692                let field_names = fields
5693                    .iter()
5694                    .map(|(fname, _ty, _public)| self.ctx.interner.resolve(*fname).to_string())
5695                    .collect();
5696                (type_name, field_names)
5697            })
5698            .collect();
5699        let enums: Vec<(String, Vec<String>)> = self
5700            .ctx
5701            .enum_defs
5702            .iter()
5703            .map(|(name_sym, ctors)| {
5704                let type_name = self.ctx.interner.resolve(*name_sym).to_string();
5705                let ctor_names = ctors
5706                    .iter()
5707                    .map(|c| self.ctx.interner.resolve(*c).to_string())
5708                    .collect();
5709                (type_name, ctor_names)
5710            })
5711            .collect();
5712        crate::concurrency::marshal::WireTypeRegistry::new(schemas).with_enums(enums)
5713    }
5714
5715    /// Block (cooperatively) until a message from `want` arrives on our inbox, returning its payload.
5716    /// Drives the shared [`NetInbox`]: try the buffer, else drain the relay and retry, yielding a
5717    /// macrotask between polls so the browser event loop (and the relay's delivery) keeps running.
5718    /// Messages from other senders stay queued for their own `Await`.
5719    async fn await_message_from(&mut self, want: &str, view: bool) -> Result<RuntimeValue, String> {
5720        loop {
5721            if let Some(v) = self.netbox.try_take_message(want, view) {
5722                return Ok(v);
5723            }
5724            let registry = self.build_wire_type_registry();
5725            self.netbox.drain(registry);
5726            if let Some(v) = self.netbox.try_take_message(want, view) {
5727                return Ok(v);
5728            }
5729            Self::poll_tick().await;
5730        }
5731    }
5732
5733    /// Block until a batch STREAM from `want` arrives, then deframe it into a list (mirrors
5734    /// [`await_message_from`] over a `RecvSlot::Stream`).
5735    async fn await_stream_from(&mut self, want: &str) -> Result<RuntimeValue, String> {
5736        loop {
5737            if let Some(v) = self.netbox.try_take_stream(want) {
5738                return Ok(v);
5739            }
5740            let registry = self.build_wire_type_registry();
5741            self.netbox.drain(registry);
5742            if let Some(v) = self.netbox.try_take_stream(want) {
5743                return Ok(v);
5744            }
5745            Self::poll_tick().await;
5746        }
5747    }
5748
5749    /// One cooperative poll interval, cross-target: a short async sleep that lets
5750    /// the relay deliver and (in the browser) the event loop run between polls.
5751    async fn poll_tick() {
5752        #[cfg(not(target_arch = "wasm32"))]
5753        logicaffeine_system::tokio::time::sleep(std::time::Duration::from_millis(2)).await;
5754        #[cfg(target_arch = "wasm32")]
5755        gloo_timers::future::TimeoutFuture::new(2).await;
5756    }
5757
5758    /// Evaluate an expression to a runtime value.
5759    /// Phase 55: Now async.
5760    #[async_recursion(?Send)]
5761    async fn evaluate_expr(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
5762        match expr {
5763            Expr::View(_) => Err(
5764                "A view is drawn by the component it belongs to — place it in that component's `View:`."
5765                    .to_string(),
5766            ),
5767            Expr::Dom(q) => self.evaluate_dom_query(q),
5768            Expr::Literal(lit) => self.evaluate_literal(lit),
5769
5770            Expr::Identifier(sym) => {
5771                let name = self.ctx.interner.resolve(*sym);
5772                // Handle temporal builtins (the NAME wins, even when shadowed)
5773                match name {
5774                    "today" => {
5775                        return Ok(crate::semantics::temporal::today());
5776                    }
5777                    "now" => {
5778                        return Ok(crate::semantics::temporal::now());
5779                    }
5780                    _ => {}
5781                }
5782                self.lookup(*sym).cloned()
5783            }
5784
5785            Expr::BinaryOp { op, left, right } => {
5786                match op {
5787                    BinaryOpKind::And => {
5788                        let left_val = self.evaluate_expr(left).await?;
5789                        if !left_val.decided_truth()? {
5790                            return Ok(RuntimeValue::Bool(false));
5791                        }
5792                        let right_val = self.evaluate_expr(right).await?;
5793                        Ok(RuntimeValue::Bool(right_val.decided_truth()?))
5794                    }
5795                    BinaryOpKind::Or => {
5796                        let left_val = self.evaluate_expr(left).await?;
5797                        if left_val.decided_truth()? {
5798                            return Ok(RuntimeValue::Bool(true));
5799                        }
5800                        let right_val = self.evaluate_expr(right).await?;
5801                        Ok(RuntimeValue::Bool(right_val.decided_truth()?))
5802                    }
5803                    _ => {
5804                        let left_val = self.evaluate_expr(left).await?;
5805                        let right_val = self.evaluate_expr(right).await?;
5806                        self.apply_binary_op(*op, left_val, right_val)
5807                    }
5808                }
5809            }
5810
5811            Expr::Call { function, args } => {
5812                self.call_function(*function, args).await
5813            }
5814
5815            Expr::Index { collection, index } => {
5816                let coll_val = self.evaluate_expr(collection).await?;
5817                let idx_val = self.evaluate_expr(index).await?;
5818                crate::semantics::collections::index_get(&coll_val, &idx_val)
5819            }
5820
5821            Expr::Slice { collection, start, end } => {
5822                let coll_val = self.evaluate_expr(collection).await?;
5823                let start_val = self.evaluate_expr(start).await?;
5824                let end_val = self.evaluate_expr(end).await?;
5825                crate::semantics::collections::slice(&coll_val, &start_val, &end_val)
5826            }
5827
5828            Expr::Copy { expr: inner } => {
5829                let val = self.evaluate_expr(inner).await?;
5830                Ok(val.deep_clone())
5831            }
5832
5833            Expr::Give { value } => {
5834                // In interpreter, Give is just semantic - evaluate the value
5835                self.evaluate_expr(value).await
5836            }
5837
5838            Expr::Length { collection } => {
5839                let coll_val = self.evaluate_expr(collection).await?;
5840                crate::semantics::collections::length_of(&coll_val)
5841            }
5842
5843            Expr::Contains { collection, value } => {
5844                let coll_val = self.evaluate_expr(collection).await?;
5845                let val = self.evaluate_expr(value).await?;
5846                crate::semantics::collections::contains(&coll_val, &val)
5847            }
5848
5849            Expr::Union { left, right } => {
5850                let left_val = self.evaluate_expr(left).await?;
5851                let right_val = self.evaluate_expr(right).await?;
5852                crate::semantics::collections::union(&left_val, &right_val)
5853            }
5854
5855            Expr::Intersection { left, right } => {
5856                let left_val = self.evaluate_expr(left).await?;
5857                let right_val = self.evaluate_expr(right).await?;
5858                crate::semantics::collections::intersection(&left_val, &right_val)
5859            }
5860
5861            Expr::List(items) => {
5862                let mut values = Vec::with_capacity(items.len());
5863                for e in items.iter() {
5864                    values.push(self.evaluate_expr(e).await?);
5865                }
5866                Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::from_values(values)))))
5867            }
5868
5869            Expr::Tuple(items) => {
5870                let mut values = Vec::with_capacity(items.len());
5871                for e in items.iter() {
5872                    values.push(self.evaluate_expr(e).await?);
5873                }
5874                Ok(RuntimeValue::Tuple(Rc::new(values)))
5875            }
5876
5877            Expr::Range { start, end } => {
5878                let start_val = self.evaluate_expr(start).await?;
5879                let end_val = self.evaluate_expr(end).await?;
5880                crate::semantics::collections::range(&start_val, &end_val)
5881            }
5882
5883            Expr::FieldAccess { object, field } => {
5884                let obj_val = self.evaluate_expr(object).await?;
5885                match &obj_val {
5886                    RuntimeValue::Struct(s) => {
5887                        let field_name = self.ctx.interner.resolve(*field);
5888                        s.fields.get(field_name).cloned()
5889                            .ok_or_else(|| format!("Field '{}' not found", field_name))
5890                    }
5891                    _ => Err(format!("Cannot access field on {}", obj_val.type_name())),
5892                }
5893            }
5894
5895            Expr::New { type_name, init_fields, .. } => {
5896                let name = self.ctx.interner.resolve(*type_name).to_string();
5897
5898                if name == "Seq" || name == "List" {
5899                    return Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(Vec::new())))));
5900                }
5901
5902                if name == "Set" || name == "HashSet" {
5903                    return Ok(RuntimeValue::Set(Rc::new(RefCell::new(vec![]))));
5904                }
5905
5906                if name == "Map" || name == "HashMap" {
5907                    return Ok(RuntimeValue::Map(Rc::new(RefCell::new(MapStorage::default()))));
5908                }
5909
5910                let mut fields = HashMap::new();
5911                for (field_sym, field_expr) in init_fields {
5912                    let field_name = self.ctx.interner.resolve(*field_sym).to_string();
5913                    let field_val = self.evaluate_expr(field_expr).await?;
5914                    fields.insert(field_name, field_val);
5915                }
5916
5917                if let Some(def) = self.ctx.struct_defs.get(type_name) {
5918                    for (field_sym, type_sym, _) in def {
5919                        let field_name = self.ctx.interner.resolve(*field_sym).to_string();
5920                        if !fields.contains_key(&field_name) {
5921                            let type_name_str = self.ctx.interner.resolve(*type_sym).to_string();
5922                            let default = default_for_declared_type(type_name_str.as_str());
5923                            fields.insert(field_name, default);
5924                        }
5925                    }
5926                }
5927
5928                Ok(RuntimeValue::Struct(Box::new(StructValue { type_name: name, fields })))
5929            }
5930
5931            // Phase 102: Enum variant constructor
5932            // Now creates RuntimeValue::Inductive for unified kernel types
5933            Expr::NewVariant { enum_name, variant, fields } => {
5934                let inductive_type = self.ctx.interner.resolve(*enum_name).to_string();
5935                let constructor = self.ctx.interner.resolve(*variant).to_string();
5936
5937                // Construction is written field-name-first and is documented ORDER-
5938                // INDEPENDENT (`a new X with b 2 and a 1` is legal) — `Inductive` stores its
5939                // payload POSITIONALLY (`args: Vec<RuntimeValue>`), so each evaluated value is
5940                // re-seated at its DECLARED index (not its WRITTEN index) using the variant's
5941                // own field list (`variant_fields`, from the discovery-pass registry).
5942                // Evaluation itself still runs in WRITTEN order (side effects follow the
5943                // author's own text); only the STORAGE position is corrected. Falls back to
5944                // write order when no declaration is known (a dynamic/built-in variant, or no
5945                // type registry at all). Keyed by `(enum_name, variant)`, not `variant` alone —
5946                // `Expr::NewVariant` already names its own enum, so no ambiguity is possible even
5947                // when another enum declares a same-named variant with a different field shape.
5948                let declared = self.ctx.variant_fields.get(&(*enum_name, *variant)).cloned();
5949                let args = match &declared {
5950                    Some(names) => {
5951                        let mut slots: Vec<Option<RuntimeValue>> = (0..names.len()).map(|_| None).collect();
5952                        for (field_name, field_expr) in fields {
5953                            let field_val = self.evaluate_expr(field_expr).await?;
5954                            if let Some(pos) = names.iter().position(|n| n == field_name) {
5955                                slots[pos] = Some(field_val);
5956                            }
5957                        }
5958                        slots.into_iter().map(|v| v.unwrap_or(RuntimeValue::Nothing)).collect()
5959                    }
5960                    None => {
5961                        let mut args = Vec::with_capacity(fields.len());
5962                        for (_, field_expr) in fields {
5963                            args.push(self.evaluate_expr(field_expr).await?);
5964                        }
5965                        args
5966                    }
5967                };
5968
5969                Ok(RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
5970                    inductive_type,
5971                    constructor,
5972                    args,
5973                })))
5974            }
5975
5976            Expr::ManifestOf { .. } => {
5977                Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(Vec::new())))))
5978            }
5979
5980            Expr::ChunkAt { .. } => {
5981                Ok(RuntimeValue::Nothing)
5982            }
5983
5984            Expr::WithCapacity { value, capacity } => {
5985                let capacity = match self.evaluate_expr(capacity).await? {
5986                    RuntimeValue::Int(capacity) => capacity,
5987                    _ => return Err("Capacity requires an Int".to_string()),
5988                };
5989                let value = self.evaluate_expr(value).await?;
5990                Ok(apply_capacity_hint(value, capacity))
5991            }
5992
5993            // ★ AN OPTION IS A REAL TAGGED VALUE. It used to be TRANSPARENT — `some x` evaluated
5994            // to `x` and `none` to the `Nothing` sentinel — which meant presence was inferred from
5995            // bits rather than carried. That works only while the payload can never BE the
5996            // sentinel, and it cannot survive `some none` (both levels collapse) or a compiled
5997            // tier where `some 0` and `none` are the same machine word.
5998            //
5999            // Display and equality are unchanged: R1 renders the payload (`to_display_string`),
6000            // R2 keeps `none` equal to `nothing` (`semantics::compare`). See `option_tier_lock`.
6001            Expr::OptionSome { value } => {
6002                let inner = self.evaluate_expr(value).await?;
6003                Ok(option_some(inner))
6004            }
6005
6006            Expr::OptionNone => Ok(option_none()),
6007
6008            Expr::Not { operand } => {
6009                let val = self.evaluate_expr(operand).await?;
6010                crate::semantics::arith::not_value(val)
6011            }
6012
6013            Expr::InterpolatedString(parts) => {
6014                let mut result = String::new();
6015                for part in parts {
6016                    match part {
6017                        crate::ast::stmt::StringPart::Literal(sym) => {
6018                            result.push_str(self.ctx.interner.resolve(*sym));
6019                        }
6020                        crate::ast::stmt::StringPart::Expr { value, format_spec, debug } => {
6021                            let val = self.evaluate_expr(value).await?;
6022                            if *debug {
6023                                let prefix = match value {
6024                                    Expr::Identifier(sym) => self.ctx.interner.resolve(*sym).to_string(),
6025                                    _ => "expr".to_string(),
6026                                };
6027                                result.push_str(&prefix);
6028                                result.push('=');
6029                            }
6030                            if let Some(spec_sym) = format_spec {
6031                                let spec = self.ctx.interner.resolve(*spec_sym);
6032                                result.push_str(&apply_format_spec(&val, spec));
6033                            } else {
6034                                result.push_str(&val.to_display_string());
6035                            }
6036                        }
6037                    }
6038                }
6039                Ok(RuntimeValue::Text(Rc::new(result)))
6040            }
6041
6042            Expr::Escape { .. } => {
6043                Err(crate::semantics::escape::REFUSAL.to_string())
6044            }
6045
6046            Expr::Closure { params, body, .. } => {
6047                let free_vars = self.collect_free_vars_in_closure(params, body);
6048                let mut captured_env = HashMap::new();
6049                for sym in &free_vars {
6050                    if let Some(val) = self.task.env.lookup(*sym) {
6051                        captured_env.insert(*sym, val.deep_clone());
6052                    }
6053                }
6054
6055                let body_index = self.ctx.closure_bodies.len();
6056                match body {
6057                    ClosureBody::Expression(expr) => {
6058                        self.ctx.closure_bodies.push(ClosureBodyRef::Expression(expr));
6059                    }
6060                    ClosureBody::Block(block) => {
6061                        self.ctx.closure_bodies.push(ClosureBodyRef::Block(block));
6062                    }
6063                }
6064
6065                let param_names: Vec<Symbol> = params.iter().map(|(name, _)| *name).collect();
6066
6067                Ok(RuntimeValue::Function(Box::new(ClosureValue {
6068                    body_index,
6069                    captured_env,
6070                    param_names,
6071                    generated: None,
6072                })))
6073            }
6074
6075            Expr::CallExpr { callee, args } => {
6076                let callee_val = self.evaluate_expr(callee).await?;
6077                if let RuntimeValue::Function(closure) = callee_val {
6078                    let mut arg_values = Vec::with_capacity(args.len());
6079                    for arg in args.iter() {
6080                        arg_values.push(self.evaluate_expr(arg).await?);
6081                    }
6082                    self.call_closure_value(&closure, arg_values).await
6083                } else {
6084                    Err(format!("Cannot call value of type {}", callee_val.type_name()))
6085                }
6086            }
6087        }
6088    }
6089
6090    /// Evaluate a literal to a runtime value.
6091    fn evaluate_literal(&self, lit: &Literal) -> Result<RuntimeValue, String> {
6092        match lit {
6093            Literal::Number(n) => Ok(RuntimeValue::Int(*n)),
6094            Literal::Float(f) => Ok(RuntimeValue::Float(*f)),
6095            Literal::Text(sym) => Ok(RuntimeValue::Text(Rc::new(
6096                self.ctx.interner.resolve(*sym).to_string(),
6097            ))),
6098            Literal::Boolean(b) => Ok(RuntimeValue::Bool(*b)),
6099            Literal::Nothing => Ok(RuntimeValue::Nothing),
6100            Literal::Char(c) => Ok(RuntimeValue::Char(*c)),
6101            Literal::Duration(nanos) => Ok(RuntimeValue::Duration(*nanos)),
6102            Literal::Date(days) => Ok(RuntimeValue::Date(*days)),
6103            Literal::Moment(nanos) => Ok(RuntimeValue::Moment(*nanos)),
6104            Literal::Span { months, days } => Ok(RuntimeValue::Span {
6105                months: *months,
6106                days: *days,
6107            }),
6108            Literal::Time(nanos) => Ok(RuntimeValue::Time(*nanos)),
6109        }
6110    }
6111
6112    /// Apply a binary operator (delegates to the shared semantics kernel).
6113    fn apply_binary_op(
6114        &self,
6115        op: BinaryOpKind,
6116        left: RuntimeValue,
6117        right: RuntimeValue,
6118    ) -> Result<RuntimeValue, String> {
6119        crate::semantics::arith::binary_op(op, left, right)
6120    }
6121
6122    pub fn values_equal_pub(&self, left: &RuntimeValue, right: &RuntimeValue) -> bool {
6123        self.values_equal(left, right)
6124    }
6125
6126    fn values_equal(&self, left: &RuntimeValue, right: &RuntimeValue) -> bool {
6127        crate::semantics::compare::values_equal(left, right)
6128    }
6129
6130    /// Coerce a function's return value to a NAMED RECORD type: a `-> (quotient: Int, remainder: Int)`
6131    /// function returns a positional tuple `(a, b)`, which becomes a self-describing `StructValue` with the
6132    /// record's field names — so `r's quotient` resolves through the ordinary struct field lookup on every
6133    /// tier. A non-record return, or a non-tuple/arity-mismatch value, passes through unchanged.
6134    fn coerce_record_return(&self, val: RuntimeValue, function: Symbol) -> RuntimeValue {
6135        let rt = match self
6136            .ctx
6137            .functions
6138            .get(&function)
6139            .and_then(|f| f.return_type)
6140        {
6141            Some(rt) => rt,
6142            None => return val,
6143        };
6144        if let crate::ast::stmt::TypeExpr::Record { field_names, .. } = rt {
6145            if let RuntimeValue::Tuple(elems) = &val {
6146                if elems.len() == field_names.len() {
6147                    let mut fields = HashMap::with_capacity(field_names.len());
6148                    for (n, v) in field_names.iter().zip(elems.iter()) {
6149                        fields.insert(self.ctx.interner.resolve(*n).to_string(), v.clone());
6150                    }
6151                    return RuntimeValue::Struct(Box::new(StructValue {
6152                        type_name: "Record".to_string(),
6153                        fields,
6154                    }));
6155                }
6156            }
6157        }
6158        val
6159    }
6160
6161    /// Call a function (built-in or user-defined).
6162    #[async_recursion(?Send)]
6163    async fn call_function(
6164        &mut self,
6165        function: Symbol,
6166        args: &[&'async_recursion Expr<'a>],
6167    ) -> Result<RuntimeValue, String> {
6168        // Built-in functions — Symbol comparison (integer) instead of string matching
6169        let func_sym = Some(function);
6170        if self.declares(function) {
6171            // The program's own function: resolved below, ahead of every builtin and intercept.
6172        } else if func_sym == self.ctx.sym_show {
6173            for arg in args {
6174                let val = self.evaluate_expr(arg).await?;
6175                self.emit_output(val.to_display_string());
6176            }
6177            return Ok(RuntimeValue::Nothing);
6178        } else if func_sym == self.ctx.sym_args {
6179            // `args()` system native: the stored argv as a `Seq of Text`,
6180            // mirroring the compiled binary's `env::args()`. Intercepted BEFORE
6181            // the empty native-decl body would be reached, like `show`.
6182            let items: Vec<RuntimeValue> = self
6183                .ctx
6184                .program_args
6185                .iter()
6186                .map(|s| RuntimeValue::Text(Rc::new(s.clone())))
6187                .collect();
6188            return Ok(RuntimeValue::List(Rc::new(RefCell::new(
6189                ListRepr::from_values(items),
6190            ))));
6191        } else if self.pbkdf2_accel(function, args.len()) {
6192            // crypto.lg's `pbkdf2Sha256` is the FIPS/RFC-locked pure-LOGOS SPEC the
6193            // AOT tiers compile — but SCRAM's Hi() mandates 4096 iterations (~16k
6194            // interpreted SHA-256 compressions ≈ 32s on the tree-walker), untenable
6195            // for a live handshake. Route the interpreted tier through the native
6196            // reference, which is byte-identical (crypto_accel_lock.rs): the whole
6197            // language's `hashlib`-in-C arrangement, no corner cut.
6198            let pw = self.evaluate_expr(&args[0]).await?;
6199            let salt = self.evaluate_expr(&args[1]).await?;
6200            let iters = self.evaluate_expr(&args[2]).await?;
6201            let (pw, salt, iters) = crate::semantics::builtins::pbkdf2_arguments(&pw, &salt, &iters)?;
6202            let dk = crate::crypto_accel::pbkdf2_sha256(&pw, &salt, iters);
6203            return Ok(crate::semantics::builtins::bytes_to_seq(&dk));
6204        } else if let Some(kernel) = self.native_kernel(function, args.len()) {
6205            // A standard-library native kernel (`crypto.lg`'s `## To native` ML-KEM / ML-DSA
6206            // functions): the same Rust kernel the compiled tier links and the VM's
6207            // `CallBuiltin(NativeKernel)` runs.
6208            let mut vals = Vec::with_capacity(args.len());
6209            for arg in args {
6210                vals.push(self.evaluate_expr(arg).await?);
6211            }
6212            return kernel.call(&vals);
6213        } else if let Some(id) = self.system_native_id(function, args.len()) {
6214            // file.lg's `read`/`write`, random.lg's `randomInt`/`randomFloat`, env.lg's `get` and
6215            // time.lg's `now`, EMPTY-bodied on the executing tiers: route through the ONE shared builtin
6216            // implementation (the VM emits the same `CallBuiltin`, so the tiers cannot drift). The
6217            // native guard in `system_native_id` keeps declarer-wins: a user-defined function of
6218            // the same name with a real body is never intercepted.
6219            let mut vals = Vec::with_capacity(args.len());
6220            for arg in args {
6221                vals.push(self.evaluate_expr(arg).await?);
6222            }
6223            return crate::semantics::builtins::call_builtin(id, vals);
6224        } else if self.sleep_native(function, args.len()) {
6225            // time.lg's `sleep(ms)` — the `Sleep` statement's wait, answering nothing.
6226            let val = self.evaluate_expr(&args[0]).await?;
6227            self.sleep_for(val).await?;
6228            return Ok(RuntimeValue::Nothing);
6229        } else if let Some(op) = self.tcp_native_op(function, args.len()) {
6230            // tcp.lg natives — blocking socket IO through the holder's TcpRegistry.
6231            // The ONE value-level exec (`exec_values`) is shared with the VM's io
6232            // driver, so argument decoding, semantics, and Err wording cannot
6233            // drift between tiers. Async twin only: sockets suspend.
6234            let mut vals = Vec::with_capacity(args.len());
6235            for arg in args {
6236                vals.push(self.evaluate_expr(arg).await?);
6237            }
6238            return self.tcpbox.exec_values(op, vals).await;
6239        } else if let Some(id) = self.builtin_id(function) {
6240            // Arity is checked BEFORE evaluating arguments (kernel rule).
6241            crate::semantics::builtins::check_arity(id, args.len())?;
6242            // `format` reads only its first argument; preserve its laziness.
6243            let vals = if id == crate::semantics::builtins::BuiltinId::Format {
6244                match args.first() {
6245                    Some(a) => vec![self.evaluate_expr(a).await?],
6246                    None => Vec::new(),
6247                }
6248            } else {
6249                let mut v = Vec::with_capacity(args.len());
6250                for arg in args {
6251                    v.push(self.evaluate_expr(arg).await?);
6252                }
6253                v
6254            };
6255            if id == crate::semantics::builtins::BuiltinId::DefinedReal {
6256                return self.open_defined_run().define(vals);
6257            }
6258            return crate::semantics::builtins::call_builtin(id, vals);
6259        }
6260
6261        if let Some(refusal) = self.native_refusal(function) {
6262            return Err(refusal);
6263        }
6264
6265        // User-defined function lookup — extract metadata without cloning params
6266        if let Some(func) = self.ctx.functions.get(&function) {
6267            let param_count = func.params.len();
6268            let body = func.body;
6269
6270            if args.len() != param_count {
6271                return Err(format!(
6272                    "Function {} expects {} arguments, got {}",
6273                    self.ctx.interner.resolve(function),
6274                    param_count,
6275                    args.len()
6276                ));
6277            }
6278
6279            // Evaluate arguments before pushing scope
6280            let mut arg_values = Vec::with_capacity(param_count);
6281            let mut lent: Vec<(usize, Place)> = Vec::new();
6282            for (i, arg) in args.iter().enumerate() {
6283                if matches!(
6284                    self.ctx.functions[&function].params[i].1,
6285                    TypeExpr::Mutable { .. }
6286                ) {
6287                    let place = match self.place(arg).await {
6288                        Ok(place) => place,
6289                        Err(e) => {
6290                            let values = self.values_to_give_back(&lent, &mut arg_values);
6291                            self.give_back(lent, values);
6292                            return Err(e);
6293                        }
6294                    };
6295                    if let Some(value) = place.as_ref().and_then(|place| self.lend(place)) {
6296                        arg_values.push(value);
6297                        lent.push((i, place.expect("a lent argument names a place")));
6298                        continue;
6299                    }
6300                }
6301                match self.evaluate_expr(arg).await {
6302                    Ok(v) => arg_values.push(v),
6303                    Err(e) => {
6304                        let values = self.values_to_give_back(&lent, &mut arg_values);
6305                        self.give_back(lent, values);
6306                        return Err(e);
6307                    }
6308                }
6309            }
6310
6311            // Bind parameters in a FRESH frame — the lexical barrier: the body
6312            // sees params, its own bindings, and globals; never caller locals.
6313            if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
6314                let values = self.values_to_give_back(&lent, &mut arg_values);
6315                self.give_back(lent, values);
6316                return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
6317            }
6318            self.task.call_depth += 1;
6319            self.task.env.push_frame();
6320            for i in 0..param_count {
6321                let param_name = self.ctx.functions[&function].params[i].0;
6322                self.task.env.define(
6323                    param_name,
6324                    std::mem::replace(&mut arg_values[i], RuntimeValue::Nothing),
6325                );
6326            }
6327
6328            // Execute function body
6329            // TCO on the async path — mirror of the sync twin in
6330            // `call_function_sync` (constant-stack self-tail-calls).
6331            let prev_tco = self.task.tco_fn_async.replace(function);
6332            let prev_repeat = std::mem::replace(&mut self.task.repeat_depth_async, 0);
6333            let mut return_value = RuntimeValue::Nothing;
6334            let mut body_err = None;
6335            'tco: loop {
6336                self.task.pending_tail_call_async = None;
6337                let mut idx = 0;
6338                while idx < body.len() {
6339                    if idx + 1 < body.len() {
6340                        if let Some(call_args) = crate::tail_call::tail_pair_args(
6341                            &body[idx],
6342                            &body[idx + 1],
6343                            function,
6344                            param_count,
6345                        ) {
6346                            let mut vals = Vec::with_capacity(call_args.len());
6347                            let mut perr = None;
6348                            for a in call_args {
6349                                match self.evaluate_expr(a).await {
6350                                    Ok(v) => vals.push(v),
6351                                    Err(e) => {
6352                                        perr = Some(e);
6353                                        break;
6354                                    }
6355                                }
6356                            }
6357                            match perr {
6358                                Some(e) => body_err = Some(e),
6359                                None => self.task.pending_tail_call_async = Some(vals),
6360                            }
6361                            break;
6362                        }
6363                    }
6364                    match self.execute_stmt(&body[idx]).await {
6365                        Ok(ControlFlow::Return(val)) => {
6366                            return_value = val;
6367                            break;
6368                        }
6369                        Ok(ControlFlow::Break) => break,
6370                        Ok(ControlFlow::Continue) => {}
6371                        Err(e) => {
6372                            body_err = Some(e);
6373                            break;
6374                        }
6375                    }
6376                    idx += 1;
6377                }
6378                if body_err.is_some() {
6379                    break 'tco;
6380                }
6381                match self.task.pending_tail_call_async.take() {
6382                    Some(new_args) => {
6383                        self.task.env.pop_frame();
6384                        self.task.env.push_frame();
6385                        for (i, v) in new_args.into_iter().enumerate() {
6386                            let param_name = self.ctx.functions[&function].params[i].0;
6387                            self.task.env.define(param_name, v);
6388                        }
6389                        continue 'tco;
6390                    }
6391                    None => break 'tco,
6392                }
6393            }
6394            self.task.repeat_depth_async = prev_repeat;
6395            self.task.tco_fn_async = prev_tco;
6396
6397            let returned = self.lent_values(function, &lent);
6398            self.task.env.pop_frame();
6399            self.give_back(lent, returned);
6400            self.task.call_depth -= 1;
6401            match body_err {
6402                Some(e) => Err(e),
6403                None => Ok(self.coerce_record_return(return_value, function)),
6404            }
6405        } else {
6406            // Fallback: check if the function name is a variable holding a closure
6407            let maybe_closure = self.task.env.lookup(function).and_then(|v| {
6408                if let RuntimeValue::Function(c) = v {
6409                    Some((**c).clone())
6410                } else {
6411                    None
6412                }
6413            });
6414
6415            if let Some(closure) = maybe_closure {
6416                let mut arg_values = Vec::with_capacity(args.len());
6417                for arg in args {
6418                    arg_values.push(self.evaluate_expr(arg).await?);
6419                }
6420                self.call_closure_value(&closure, arg_values).await
6421            } else {
6422                Err(format!(
6423                    "Unknown function: {}",
6424                    self.ctx.interner.resolve(function)
6425                ))
6426            }
6427        }
6428    }
6429
6430    /// Call a function with pre-evaluated RuntimeValue arguments.
6431    /// Used by Give and Show statements where the object is already evaluated.
6432    /// Build the suspend-future for a concurrency request. The returned future
6433    /// owns its `Rc` side-channel, so awaiting it does not borrow `self`.
6434    fn yield_request(&self, req: BlockingRequest<'a>) -> YieldFuture<'a> {
6435        let ys = self
6436            .yield_state
6437            .clone()
6438            .expect("concurrency op executed outside a scheduler context");
6439        ys.borrow_mut().request = Some(req);
6440        YieldFuture::new(ys)
6441    }
6442
6443    /// Evaluate an expression to a channel handle.
6444    async fn eval_chan(&mut self, expr: &Expr<'a>) -> Result<ChanId, String> {
6445        match self.evaluate_expr(expr).await? {
6446            RuntimeValue::Chan(id) => Ok(id),
6447            other => Err(format!("expected a channel, found {}", other.type_name())),
6448        }
6449    }
6450
6451    /// Evaluate an expression to a task handle.
6452    async fn eval_task(&mut self, expr: &Expr<'a>) -> Result<TaskId, String> {
6453        match self.evaluate_expr(expr).await? {
6454            RuntimeValue::TaskHandle(id) => Ok(id),
6455            other => Err(format!(
6456                "expected a task handle, found {}",
6457                other.type_name()
6458            )),
6459        }
6460    }
6461
6462    /// Evaluate a `Select` timeout expression to a non-negative logical tick
6463    /// count for the scheduler's timer wheel. A bare integer is read as whole
6464    /// seconds (matching the compiled `Duration::from_secs`), a duration as its
6465    /// own magnitude, and a calendar span as whole seconds.
6466    async fn eval_select_timeout_ticks(&mut self, expr: &Expr<'a>) -> Result<u64, String> {
6467        let ticks = match self.evaluate_expr(expr).await? {
6468            RuntimeValue::Int(n) => n.max(0) as u64,
6469            RuntimeValue::Duration(d) => d.max(0) as u64,
6470            RuntimeValue::Span { months, days } => {
6471                (((months as i64) * 30 + days as i64) * 86_400).max(0) as u64
6472            }
6473            other => {
6474                return Err(format!(
6475                    "select timeout must be a number or duration, found {}",
6476                    other.type_name()
6477                ))
6478            }
6479        };
6480        Ok(ticks)
6481    }
6482
6483    /// Build a child interpreter task that runs `function(args)`, sharing this
6484    /// interpreter's (cloned) context with a fresh per-task state + side-channel.
6485    fn spawn_child_task(
6486        &self,
6487        function: Symbol,
6488        args: Vec<RuntimeValue>,
6489    ) -> Box<dyn logicaffeine_runtime::Task<'a> + 'a> {
6490        let ys: Yield<'a> = Rc::new(RefCell::new(YieldState::new()));
6491        let mut child = Interpreter {
6492            ctx: self.ctx.clone(),
6493            task: TaskState::new(),
6494            output: Vec::new(),
6495            current_site: None,
6496            yield_state: Some(ys.clone()),
6497            err_sink: self.err_sink.clone(),
6498            netbox: crate::concurrency::net_inbox::NetInbox::new(),
6499            tcpbox: crate::concurrency::tcp_registry::TcpRegistry::new(),
6500            // Spawned tasks do NOT inherit test mode: a test-only statement
6501            // inside a task body fails loudly (never silently), and per-task
6502            // budget/failure aggregation is the concurrency-testing wave's
6503            // design (constitution Wave 12).
6504            test_mode: false,
6505            test_failures: Vec::new(),
6506            test_ops: 0,
6507            test_assertions: 0,
6508            request_deadline: None,
6509            deadline_tick: 0,
6510            test_budget: u64::MAX,
6511            gen_rng: 0,
6512            prove_mode: false,
6513            properties_proven: 0,
6514            // General fuel DOES span tasks: one cell for the whole cohort.
6515            fuel: self.fuel.clone(),
6516            tiers_noop: false,
6517            // A spawned task is a background continuation, never the top-level test driver — it
6518            // drives no page and nothing observes its statements.
6519            page: PageSeat::Unseated,
6520            statement_observer: None,
6521            page_main: None,
6522            failed_call_site: None,
6523            defined_run: None,
6524        };
6525        let fut = Box::pin(async move {
6526            child
6527                .call_function_with_values(function, args)
6528                .await
6529                .map(|_| ())
6530        });
6531        Box::new(InterpreterTask::new(fut, ys, self.err_sink.clone()))
6532    }
6533
6534    #[async_recursion(?Send)]
6535    async fn call_function_with_values(
6536        &mut self,
6537        function: Symbol,
6538        mut args: Vec<RuntimeValue>,
6539    ) -> Result<RuntimeValue, String> {
6540        // Handle built-in "show" via Symbol comparison
6541        if Some(function) == self.ctx.sym_show {
6542            for val in args {
6543                self.emit_output(val.to_display_string());
6544            }
6545            return Ok(RuntimeValue::Nothing);
6546        }
6547        if let Some(id) = self.system_native_id(function, args.len()) {
6548            return crate::semantics::builtins::call_builtin(id, args);
6549        }
6550        if let Some(kernel) = self.native_kernel(function, args.len()) {
6551            return kernel.call(&args);
6552        }
6553        if self.sleep_native(function, args.len()) {
6554            self.sleep_for(args.remove(0)).await?;
6555            return Ok(RuntimeValue::Nothing);
6556        }
6557        if let Some(refusal) = self.native_refusal(function) {
6558            return Err(refusal);
6559        }
6560
6561        if let Some(func) = self.ctx.functions.get(&function) {
6562            let param_count = func.params.len();
6563            let body = func.body;
6564
6565            if args.len() != param_count {
6566                return Err(format!(
6567                    "Function {} expects {} arguments, got {}",
6568                    self.ctx.interner.resolve(function),
6569                    param_count,
6570                    args.len()
6571                ));
6572            }
6573
6574            if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
6575                return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
6576            }
6577            self.task.call_depth += 1;
6578            self.task.env.push_frame();
6579            for i in 0..param_count {
6580                let param_name = self.ctx.functions[&function].params[i].0;
6581                self.task.env.define(
6582                    param_name,
6583                    std::mem::replace(&mut args[i], RuntimeValue::Nothing),
6584                );
6585            }
6586
6587            // TCO on the async path — mirror of the sync twin in
6588            // `call_function_sync` (constant-stack self-tail-calls).
6589            let prev_tco = self.task.tco_fn_async.replace(function);
6590            let prev_repeat = std::mem::replace(&mut self.task.repeat_depth_async, 0);
6591            let mut return_value = RuntimeValue::Nothing;
6592            let mut body_err = None;
6593            'tco: loop {
6594                self.task.pending_tail_call_async = None;
6595                let mut idx = 0;
6596                while idx < body.len() {
6597                    if idx + 1 < body.len() {
6598                        if let Some(call_args) = crate::tail_call::tail_pair_args(
6599                            &body[idx],
6600                            &body[idx + 1],
6601                            function,
6602                            param_count,
6603                        ) {
6604                            let mut vals = Vec::with_capacity(call_args.len());
6605                            let mut perr = None;
6606                            for a in call_args {
6607                                match self.evaluate_expr(a).await {
6608                                    Ok(v) => vals.push(v),
6609                                    Err(e) => {
6610                                        perr = Some(e);
6611                                        break;
6612                                    }
6613                                }
6614                            }
6615                            match perr {
6616                                Some(e) => body_err = Some(e),
6617                                None => self.task.pending_tail_call_async = Some(vals),
6618                            }
6619                            break;
6620                        }
6621                    }
6622                    match self.execute_stmt(&body[idx]).await {
6623                        Ok(ControlFlow::Return(val)) => {
6624                            return_value = val;
6625                            break;
6626                        }
6627                        Ok(ControlFlow::Break) => break,
6628                        Ok(ControlFlow::Continue) => {}
6629                        Err(e) => {
6630                            body_err = Some(e);
6631                            break;
6632                        }
6633                    }
6634                    idx += 1;
6635                }
6636                if body_err.is_some() {
6637                    break 'tco;
6638                }
6639                match self.task.pending_tail_call_async.take() {
6640                    Some(new_args) => {
6641                        self.task.env.pop_frame();
6642                        self.task.env.push_frame();
6643                        for (i, v) in new_args.into_iter().enumerate() {
6644                            let param_name = self.ctx.functions[&function].params[i].0;
6645                            self.task.env.define(param_name, v);
6646                        }
6647                        continue 'tco;
6648                    }
6649                    None => break 'tco,
6650                }
6651            }
6652            self.task.repeat_depth_async = prev_repeat;
6653            self.task.tco_fn_async = prev_tco;
6654
6655            self.task.env.pop_frame();
6656            self.task.call_depth -= 1;
6657            match body_err {
6658                Some(e) => Err(e),
6659                None => Ok(self.coerce_record_return(return_value, function)),
6660            }
6661        } else {
6662            let maybe_closure = self.task.env.lookup(function).and_then(|v| {
6663                if let RuntimeValue::Function(c) = v {
6664                    Some((**c).clone())
6665                } else {
6666                    None
6667                }
6668            });
6669
6670            if let Some(closure) = maybe_closure {
6671                self.call_closure_value(&closure, args).await
6672            } else {
6673                Err(format!(
6674                    "Unknown function: {}",
6675                    self.ctx.interner.resolve(function)
6676                ))
6677            }
6678        }
6679    }
6680
6681    /// Map a function symbol to its kernel builtin, via the cached symbols.
6682    /// The system-native seam ([`crate::semantics::builtins::system_native`]): the shared builtin
6683    /// when `f` is a `## To native` declaration of `read`, `write`, `randomInt`, `randomFloat`, `get`
6684    /// or `now` at its arity. A user-defined function with a real body always wins (declarer-wins), so
6685    /// these names are NOT reserved the way [`Self::builtin_id`] names are.
6686    fn system_native_id(
6687        &self,
6688        f: Symbol,
6689        argc: usize,
6690    ) -> Option<crate::semantics::builtins::BuiltinId> {
6691        let id = crate::semantics::builtins::system_native(self.ctx.interner.resolve(f), argc)?;
6692        self.ctx
6693            .functions
6694            .get(&f)
6695            .is_some_and(|fd| fd.is_native)
6696            .then_some(id)
6697    }
6698
6699    /// time.lg's `sleep(ms)` as its `## To native` declaration, which waits as the `Sleep`
6700    /// statement does.
6701    fn sleep_native(&self, f: Symbol, argc: usize) -> bool {
6702        argc == 1
6703            && self.ctx.interner.resolve(f) == "sleep"
6704            && self.ctx.functions.get(&f).is_some_and(|fd| fd.is_native)
6705    }
6706
6707    /// The `Sleep` statement's wait, which `sleep(ms)` shares. Under the deterministic scheduler
6708    /// (any program with tasks or channels) it is a scheduler timer on the logical-tick scale a
6709    /// `Select` `After` arm uses, so it integrates with task scheduling: blocking on a raw host timer
6710    /// would suspend the task with no scheduler request and panic the cooperative driver (and under
6711    /// a non-tokio executor there is no reactor at all). Otherwise it is a real wait, which a tokio
6712    /// reactor drives when one is present (`largo run`, relay hosts) and a plain sync context (the
6713    /// playground harness, tests) blocks for instead of panicking on a missing reactor.
6714    async fn sleep_for(&mut self, val: RuntimeValue) -> Result<(), String> {
6715        if self.yield_state.is_some() {
6716            let ticks = sleep_ticks(&val)?;
6717            if ticks > 0 {
6718                self.yield_request(BlockingRequest::Sleep(ticks)).await;
6719            }
6720            return Ok(());
6721        }
6722        let nanos = sleep_nanos(&val)?;
6723        if nanos > 0 {
6724            #[cfg(not(target_arch = "wasm32"))]
6725            {
6726                let dur = std::time::Duration::from_nanos(nanos as u64);
6727                match logicaffeine_system::tokio::runtime::Handle::try_current() {
6728                    Ok(_) => logicaffeine_system::tokio::time::sleep(dur).await,
6729                    Err(_) => std::thread::sleep(dur),
6730                }
6731            }
6732            #[cfg(target_arch = "wasm32")]
6733            {
6734                let millis = (nanos / 1_000_000) as u32;
6735                if millis > 0 {
6736                    gloo_timers::future::TimeoutFuture::new(millis).await;
6737                }
6738            }
6739        }
6740        Ok(())
6741    }
6742
6743    /// [`Self::sleep_for`] where nothing can be awaited: the sync twin runs no scheduler and no
6744    /// reactor, so this is the blocking wait. A browser cannot block its thread, so there it does
6745    /// not wait at all.
6746    fn sleep_for_sync(&mut self, val: RuntimeValue) -> Result<(), String> {
6747        let nanos = sleep_nanos(&val)?;
6748        #[cfg(not(target_arch = "wasm32"))]
6749        if nanos > 0 {
6750            std::thread::sleep(std::time::Duration::from_nanos(nanos as u64));
6751        }
6752        #[cfg(target_arch = "wasm32")]
6753        let _ = nanos;
6754        Ok(())
6755    }
6756
6757    /// The refusal for a call that reached a `## To native` declaration none of the engine's seams
6758    /// took: there is no body to run, and an empty answer would be a wrong one.
6759    fn native_refusal(&self, f: Symbol) -> Option<String> {
6760        let fd = self.ctx.functions.get(&f)?;
6761        fd.is_native.then(|| {
6762            crate::semantics::builtins::unimplemented_native(
6763                self.ctx.interner.resolve(f),
6764                fd.native_path.map(|p| self.ctx.interner.resolve(p)),
6765            )
6766        })
6767    }
6768
6769    /// crypto.lg's `pbkdf2Sha256` at its 3-arg signature. The interpreted tiers
6770    /// substitute the byte-identical native reference (`crypto_accel`) for the
6771    /// pure Hi() loop, which is far too slow to INTERPRET for a live SCRAM
6772    /// handshake (4096 iterations ≈ 16k SHA-256 compressions). The name denotes
6773    /// exactly PBKDF2-HMAC-SHA256, so the native output is the only correct one;
6774    /// guarded on the function being defined so a bare call to an undefined name
6775    /// still raises the normal "Unknown function" error rather than silently
6776    /// succeeding.
6777    fn pbkdf2_accel(&self, f: Symbol, argc: usize) -> bool {
6778        argc == 3
6779            && self.ctx.interner.resolve(f) == "pbkdf2Sha256"
6780            && crate::loader::is_library_function("pbkdf2Sha256")
6781    }
6782
6783    /// "Declarer wins": does the program define `f` itself, with a body? A native declaration
6784    /// (`## To native …`, empty-bodied here) defers to the engine; the standard library's own
6785    /// accelerated definitions defer to their native implementation (`pbkdf2_accel`).
6786    fn declares(&self, f: Symbol) -> bool {
6787        self.ctx
6788            .functions
6789            .get(&f)
6790            .is_some_and(|d| !d.is_native)
6791            && !self.pbkdf2_accel(f, 3)
6792    }
6793
6794    /// A standard-library native kernel, same declarer-wins rule as [`Self::system_native_id`]: the
6795    /// kernel only when `f` is its `## To native` declaration at the kernel's arity.
6796    fn native_kernel(
6797        &self,
6798        f: Symbol,
6799        argc: usize,
6800    ) -> Option<crate::semantics::native_kernels::NativeKernel> {
6801        let kernel = crate::semantics::native_kernels::NativeKernel::from_name(
6802            self.ctx.interner.resolve(f),
6803        )?;
6804        (kernel.arity() == argc
6805            && self
6806                .ctx
6807                .functions
6808                .get(&f)
6809                .is_some_and(|fd| fd.is_native))
6810        .then_some(kernel)
6811    }
6812
6813    /// tcp.lg's native seam, same declarer-wins rule as [`Self::system_native_id`]:
6814    /// the op only when `f` is the native declaration at the right arity.
6815    fn tcp_native_op(
6816        &self,
6817        f: Symbol,
6818        argc: usize,
6819    ) -> Option<crate::concurrency::tcp_registry::TcpOp> {
6820        let op =
6821            crate::concurrency::tcp_registry::TcpOp::from_name(self.ctx.interner.resolve(f), argc)?;
6822        self.ctx
6823            .functions
6824            .get(&f)
6825            .is_some_and(|fd| fd.is_native)
6826            .then_some(op)
6827    }
6828
6829    fn builtin_id(&self, f: Symbol) -> Option<crate::semantics::builtins::BuiltinId> {
6830        use crate::semantics::builtins::BuiltinId as B;
6831        let s = Some(f);
6832        if s == self.ctx.sym_length {
6833            Some(B::Length)
6834        } else if s == self.ctx.sym_format {
6835            Some(B::Format)
6836        } else if s == self.ctx.sym_parse_int {
6837            Some(B::ParseInt)
6838        } else if s == self.ctx.sym_parse_float {
6839            Some(B::ParseFloat)
6840        } else if s == self.ctx.sym_chr {
6841            Some(B::Chr)
6842        } else if s == self.ctx.sym_abs {
6843            Some(B::Abs)
6844        } else if s == self.ctx.sym_sqrt {
6845            Some(B::Sqrt)
6846        } else if s == self.ctx.sym_min {
6847            Some(B::Min)
6848        } else if s == self.ctx.sym_max {
6849            Some(B::Max)
6850        } else if s == self.ctx.sym_floor {
6851            Some(B::Floor)
6852        } else if s == self.ctx.sym_ceil {
6853            Some(B::Ceil)
6854        } else if s == self.ctx.sym_round {
6855            Some(B::Round)
6856        } else if s == self.ctx.sym_pow {
6857            Some(B::Pow)
6858        } else if s == self.ctx.sym_copy {
6859            Some(B::Copy)
6860        } else if s == self.ctx.sym_count_ones {
6861            Some(B::CountOnes)
6862        } else {
6863            // Fall back to name-based resolution for any builtin NOT pre-interned as a ctx
6864            // symbol (e.g. `run_accepted`). The pre-interned checks above are a fast path;
6865            // this keeps the tree-walker resolving exactly the builtin set the VM does via
6866            // `builtin_from_name` — cross-tier consistent, no silent "Unknown function".
6867            crate::semantics::builtins::builtin_from_name(self.ctx.interner.resolve(f))
6868        }
6869    }
6870
6871    // Scope management
6872
6873    fn push_scope(&mut self) {
6874        self.task.env.push_scope();
6875    }
6876
6877    fn pop_scope(&mut self) {
6878        self.task.env.pop_scope();
6879    }
6880
6881    fn define(&mut self, name: Symbol, value: RuntimeValue) {
6882        self.task.env.define(name, value);
6883    }
6884
6885    fn assign(&mut self, name: Symbol, value: RuntimeValue) -> Result<(), String> {
6886        if self.task.env.assign(name, value) {
6887            Ok(())
6888        } else {
6889            Err(format!(
6890                "Undefined variable: {}",
6891                self.ctx.interner.resolve(name)
6892            ))
6893        }
6894    }
6895
6896    fn lookup(&self, name: Symbol) -> Result<&RuntimeValue, String> {
6897        self.task
6898            .env
6899            .lookup(name)
6900            .ok_or_else(|| format!("Undefined variable: {}", self.ctx.interner.resolve(name)))
6901    }
6902
6903    /// `e` as a place, its item keys evaluated — `None` for an expression that names no place.
6904    fn place_sync(&mut self, e: &Expr<'a>) -> Result<Option<Place>, String> {
6905        let Some((root, shape)) = place_shape(e) else {
6906            return Ok(None);
6907        };
6908        let mut steps = Vec::with_capacity(shape.len());
6909        for step in shape {
6910            steps.push(match step {
6911                PlaceShape::Field(f) => PlaceStep::Field(self.ctx.interner.resolve(f).to_string()),
6912                PlaceShape::Item(k) => PlaceStep::Item(self.evaluate_expr_sync(k)?),
6913            });
6914        }
6915        Ok(Some(Place { root, steps }))
6916    }
6917
6918    /// [`Interpreter::place_sync`] on the async executor.
6919    #[async_recursion(?Send)]
6920    async fn place(&mut self, e: &Expr<'a>) -> Result<Option<Place>, String> {
6921        let Some((root, shape)) = place_shape(e) else {
6922            return Ok(None);
6923        };
6924        let mut steps = Vec::with_capacity(shape.len());
6925        for step in shape {
6926            steps.push(match step {
6927                PlaceShape::Field(f) => PlaceStep::Field(self.ctx.interner.resolve(f).to_string()),
6928                PlaceShape::Item(k) => PlaceStep::Item(self.evaluate_expr(k).await?),
6929            });
6930        }
6931        Ok(Some(Place { root, steps }))
6932    }
6933
6934    /// The value at `place`, to write through — Mutable Value Semantics' ownership rule: every
6935    /// collection on the path from the binding to it (and, when `own_target`, the value itself)
6936    /// is first made the binding's OWN (`own_collection`), so a write through `place` is seen
6937    /// through that binding and no other — not through a `Let` that copied it, not through the
6938    /// caller whose value a plain parameter copied. `None` when the binding or a step does not
6939    /// exist. Under reference semantics (`LOGOS_VALUE_SEMANTICS=0`) nothing is copied.
6940    fn place_slot(&mut self, place: &Place, own_target: bool) -> Option<&mut RuntimeValue> {
6941        let cow = crate::semantics::collections::value_semantics_enabled();
6942        let mut here = self.task.env.lookup_mut(place.root)?;
6943        for step in &place.steps {
6944            if cow {
6945                own_collection(here);
6946            }
6947            here = step_into(here, step)?;
6948        }
6949        if cow && own_target {
6950            own_collection(here);
6951        }
6952        Some(here)
6953    }
6954
6955    /// The value at `place`, read with its already-evaluated item keys — what reading the place's
6956    /// expression answers, in the evaluator's own words when a step has nothing there.
6957    fn read_place(&self, place: &Place) -> Result<RuntimeValue, String> {
6958        let mut here = self.lookup(place.root)?.clone();
6959        for step in &place.steps {
6960            here = match (step, &here) {
6961                (PlaceStep::Field(name), RuntimeValue::Struct(s)) => s
6962                    .fields
6963                    .get(name)
6964                    .cloned()
6965                    .ok_or_else(|| format!("Field '{name}' not found"))?,
6966                (PlaceStep::Field(_), other) => {
6967                    return Err(format!("Cannot access field on {}", other.type_name()))
6968                }
6969                (PlaceStep::Item(key), value) => {
6970                    crate::semantics::collections::index_get(value, key)?
6971                }
6972            };
6973        }
6974        Ok(here)
6975    }
6976
6977    /// The collection a write goes to: the place `target` names, owned by its binding
6978    /// ([`Interpreter::place_slot`]) — or, when no step of the place can be written through, the
6979    /// value the place holds — or the value `target` evaluates to when it names no place. Each
6980    /// item key is evaluated exactly once.
6981    fn write_target_sync(&mut self, target: &Expr<'a>) -> Result<RuntimeValue, String> {
6982        match self.place_sync(target)? {
6983            Some(place) => match self.place_slot(&place, true) {
6984                Some(slot) => Ok(slot.clone()),
6985                None => self.read_place(&place),
6986            },
6987            None => self.evaluate_expr_sync(target),
6988        }
6989    }
6990
6991    /// [`Interpreter::write_target_sync`] on the async executor.
6992    #[async_recursion(?Send)]
6993    async fn write_target(&mut self, target: &Expr<'a>) -> Result<RuntimeValue, String> {
6994        match self.place(target).await? {
6995            Some(place) => match self.place_slot(&place, true) {
6996                Some(slot) => Ok(slot.clone()),
6997                None => self.read_place(&place),
6998            },
6999            None => self.evaluate_expr(target).await,
7000        }
7001    }
7002
7003    /// `Set <object>'s <field> to <value>.` — the field of the record `object` names, written in
7004    /// its binding's own copy of the record.
7005    fn set_field_at(
7006        &mut self,
7007        place: Option<Place>,
7008        field: Symbol,
7009        value: RuntimeValue,
7010    ) -> Result<(), String> {
7011        let Some(place) = place else {
7012            return Err("SetField target must be a variable, a field or an item".to_string());
7013        };
7014        self.lookup(place.root)?;
7015        let name = self.ctx.interner.resolve(field).to_string();
7016        match self.place_slot(&place, true) {
7017            Some(RuntimeValue::Struct(s)) => {
7018                s.fields.insert(name, value);
7019                Ok(())
7020            }
7021            _ => Err("Cannot set field on non-struct value".to_string()),
7022        }
7023    }
7024
7025    /// `Set item <key> of <collection> to <value>.` through the place `place` names — the item of
7026    /// its collection, or the field of a record named by its text (`Set item "n" of box to 5.`,
7027    /// the read side's twin). The slot is reached ONCE: a second ownership pass while a copy of
7028    /// the collection is held would count that copy as a sharer and write into a fresh collection
7029    /// nobody holds. `None` when the place cannot be written, for the caller to write the evaluated
7030    /// value instead.
7031    fn set_item_in_place(
7032        &mut self,
7033        place: &Place,
7034        key: &RuntimeValue,
7035        value: RuntimeValue,
7036    ) -> Option<Result<(), String>> {
7037        let slot = self.place_slot(place, true)?;
7038        Some(match (slot, key) {
7039            (RuntimeValue::Struct(s), RuntimeValue::Text(field)) => {
7040                s.fields.insert(field.to_string(), value);
7041                Ok(())
7042            }
7043            (slot, _) => {
7044                let target = slot.clone();
7045                crate::semantics::collections::index_set(&target, key, value)
7046            }
7047        })
7048    }
7049
7050    /// `Set t to t + a + b …` (`+` or `combined with`, left-nested) where `t` holds Text: the Text
7051    /// `t` holds as the statement starts, and the operands appended to it, in order. Whatever they
7052    /// are, each lands as it shows — exactly what `+` and `combined with` make of a Text on the
7053    /// left. `None` for any other `Set`.
7054    fn text_appends<'e>(
7055        &self,
7056        target: Symbol,
7057        value: &'e Expr<'a>,
7058    ) -> Option<(Rc<String>, Vec<&'e Expr<'a>>)> {
7059        let Some(RuntimeValue::Text(before)) = self.task.env.lookup(target) else {
7060            return None;
7061        };
7062        let mut operands = Vec::new();
7063        let mut here = value;
7064        loop {
7065            match here {
7066                Expr::BinaryOp {
7067                    op: BinaryOpKind::Add | BinaryOpKind::Concat,
7068                    left,
7069                    right,
7070                } => {
7071                    operands.push(*right);
7072                    here = left;
7073                }
7074                Expr::Identifier(sym) if *sym == target && !operands.is_empty() => break,
7075                _ => return None,
7076            }
7077        }
7078        operands.reverse();
7079        Some((before.clone(), operands))
7080    }
7081
7082    /// Append `pieces` — the operands, evaluated after `before` was read — to the Text `target`
7083    /// held as the statement started. When the binding still holds that very string, the pieces go
7084    /// onto its end: in place when nothing else holds it (amortised O(1) per append, a growing
7085    /// buffer), onto a copy of its own when something does, so no other binding sees the append.
7086    /// When an operand rebound `target`, the result is built from `before` and overwrites it, as
7087    /// `Set` does.
7088    fn append_text(
7089        &mut self,
7090        target: Symbol,
7091        before: Rc<String>,
7092        pieces: Vec<String>,
7093    ) -> Result<(), String> {
7094        let slot =
7095            self.task.env.lookup_mut(target).ok_or_else(|| {
7096                format!("Undefined variable: {}", self.ctx.interner.resolve(target))
7097            })?;
7098        if let RuntimeValue::Text(held) = slot {
7099            if Rc::ptr_eq(held, &before) {
7100                drop(before);
7101                let text = Rc::make_mut(held);
7102                for piece in &pieces {
7103                    text.push_str(piece);
7104                }
7105                return Ok(());
7106            }
7107        }
7108        let mut text =
7109            String::with_capacity(before.len() + pieces.iter().map(String::len).sum::<usize>());
7110        text.push_str(&before);
7111        for piece in &pieces {
7112            text.push_str(piece);
7113        }
7114        *slot = RuntimeValue::Text(Rc::new(text));
7115        Ok(())
7116    }
7117
7118    /// A `mutable` parameter is IN-OUT: its argument, when the argument names a place, is LENT to
7119    /// the call — the place's value moves into the parameter and the place is empty until the call
7120    /// returns. The callee then holds the value exactly as the caller did: written in place while
7121    /// nobody else shares it, copied first where somebody does (a plain parameter's copy passed on
7122    /// as `mutable` keeps its caller's value out of reach). `None` when the place cannot be written.
7123    fn lend(&mut self, place: &Place) -> Option<RuntimeValue> {
7124        self.place_slot(place, false)
7125            .map(|slot| std::mem::replace(slot, RuntimeValue::Nothing))
7126    }
7127
7128    /// The final value of every lent parameter, taken out of the callee's frame — which must still
7129    /// be the current one. `lent` pairs each lent parameter's position with its place.
7130    fn lent_values(
7131        &mut self,
7132        function: Symbol,
7133        lent: &[(usize, Place)],
7134    ) -> Vec<Option<RuntimeValue>> {
7135        lent.iter()
7136            .map(|(i, _)| {
7137                let param = self.ctx.functions[&function].params[*i].0;
7138                self.task.env.take_local(param)
7139            })
7140            .collect()
7141    }
7142
7143    /// The lent arguments' values, taken back out of `arg_values` — for a call that stops before
7144    /// its frame exists (a later argument failed, or the depth limit refused it).
7145    fn values_to_give_back(
7146        &self,
7147        lent: &[(usize, Place)],
7148        arg_values: &mut [RuntimeValue],
7149    ) -> Vec<Option<RuntimeValue>> {
7150        lent.iter()
7151            .map(|(i, _)| {
7152                Some(std::mem::replace(
7153                    &mut arg_values[*i],
7154                    RuntimeValue::Nothing,
7155                ))
7156            })
7157            .collect()
7158    }
7159
7160    /// Put each lent value back into the place it was lent from: once the call is over — returned
7161    /// or failed — a `mutable` parameter's writes are the caller's own.
7162    fn give_back(&mut self, lent: Vec<(usize, Place)>, values: Vec<Option<RuntimeValue>>) {
7163        for ((_, place), value) in lent.into_iter().zip(values) {
7164            if let (Some(value), Some(slot)) = (value, self.place_slot(&place, false)) {
7165                *slot = value;
7166            }
7167        }
7168    }
7169
7170    /// Evaluate a policy condition against a subject value.
7171    fn evaluate_policy_condition(
7172        &self,
7173        condition: &PolicyCondition,
7174        subject: &RuntimeValue,
7175        object: Option<&RuntimeValue>,
7176    ) -> bool {
7177        crate::semantics::policy::evaluate_policy_condition(
7178            self.ctx.policy_registry.as_ref(),
7179            self.ctx.interner,
7180            condition,
7181            subject,
7182            object,
7183        )
7184    }
7185
7186    /// The program's global bindings after execution, as sorted
7187    /// `(name, type, value)` rows — the substrate for the REPL's `:vars`
7188    /// inspection (see [`crate::repl::ReplSession::vars`]).
7189    pub fn global_bindings(&self) -> Vec<(String, String, String)> {
7190        let mut rows: Vec<(String, String, String)> = self
7191            .task
7192            .env
7193            .globals
7194            .iter()
7195            .map(|(sym, value)| {
7196                (
7197                    self.ctx.interner.resolve(*sym).to_string(),
7198                    value.type_name().to_string(),
7199                    value.to_display_string(),
7200                )
7201            })
7202            .collect();
7203        rows.sort();
7204        rows
7205    }
7206
7207    // =========================================================================
7208    // Sync execution path — eliminates async/Future overhead for pure programs
7209    // =========================================================================
7210
7211    /// Execute a program synchronously (no async/Future allocation).
7212    /// Use when `needs_async(stmts)` returns false.
7213    pub fn run_sync(&mut self, stmts: &[Stmt<'a>]) -> Result<(), String> {
7214        self.begin_program(stmts);
7215        self.run_top_level_sync(stmts, true)
7216    }
7217
7218    /// Hermetic program start: a fresh process's world ([`crate::semantics::world::begin_run`]),
7219    /// and then the engine's own start ([`Interpreter::begin_engine`]).
7220    fn begin_program(&mut self, stmts: &[Stmt<'a>]) {
7221        crate::semantics::world::begin_run();
7222        self.begin_engine(stmts);
7223    }
7224
7225    /// The engine's own start — no ambient exchange rates carried in (a fresh AOT process's clean
7226    /// slate), a stream of its own ([`crate::semantics::dom::retire_stream`]), and every definition
7227    /// registered before the first statement runs — leaving the world it runs in, the document and
7228    /// the storage profile, to whoever holds them.
7229    fn begin_engine(&mut self, stmts: &[Stmt<'a>]) {
7230        logicaffeine_base::money::clear_ambient_rates();
7231        crate::semantics::dom::retire_stream();
7232        self.preregister_definitions(stmts);
7233        self.seat_page_of(stmts);
7234    }
7235
7236    /// A whole program run ([`Interpreter::run`]/[`Interpreter::run_sync`]) hosts the program's own
7237    /// page LOWERED, on this very interpreter, through the driver every lowered tier shares
7238    /// ([`crate::page_host::LoweredHost`]): its main is the program up to the first statement that
7239    /// acts on the page ([`crate::page_host::page_main_len`]), and the `## Page` it mounts by itself
7240    /// is the one a reload mounts again. A page whose main already ran on this interpreter keeps
7241    /// both; a page another engine executes ([`PageSeat::Driven`]) is left where it is.
7242    fn seat_page_of(&mut self, stmts: &[Stmt<'a>]) {
7243        if self.page_main.is_some() || !matches!(self.page, PageSeat::Here(_)) {
7244            return;
7245        }
7246        let interner = self.ctx.interner;
7247        let main = crate::page_host::page_main_len(stmts, interner);
7248        self.page_main = Some(stmts[..main].to_vec());
7249        self.page = PageSeat::Here(HostedPage::of(
7250            crate::page_host::auto_mounted_page_component(stmts, interner),
7251        ));
7252    }
7253
7254    /// Execute `stmts` as top-level statements, in order, until one returns or breaks; `observed`
7255    /// reports each finished statement's index to the statement observer.
7256    fn run_top_level_sync(&mut self, stmts: &[Stmt<'a>], observed: bool) -> Result<(), String> {
7257        for (i, stmt) in stmts.iter().enumerate() {
7258            let flow = self.execute_stmt_sync(stmt)?;
7259            if observed {
7260                if let Some(f) = self.statement_observer.as_mut() {
7261                    f(i);
7262                }
7263            }
7264            match flow {
7265                ControlFlow::Return(_) => break,
7266                ControlFlow::Break => break,
7267                ControlFlow::Continue => {}
7268            }
7269        }
7270        Ok(())
7271    }
7272
7273    /// Run the page's own program once, as a browser runs a page module's `main`: its definitions
7274    /// are registered and its top-level statements build the globals every later host call reads
7275    /// ([`crate::page_host::LoweredCalls`]). The page arrives in the world its host holds — the
7276    /// document and the storage earlier visits left, which loading a module never clears — so only
7277    /// the engine starts (`Interpreter::begin_engine`). Its statements are not observed — the
7278    /// page's main is the page arriving, not a statement of whatever drives it. A failure is the
7279    /// page's to report and leaves the interpreter callable, as a browser can still call into a
7280    /// module whose `main` trapped.
7281    pub fn run_page_main(&mut self, program: &[Stmt<'a>]) -> Result<(), String> {
7282        if self.page_main.is_some() {
7283            return Err(
7284                "tree-walker: the page's main has already run, and running it again would \
7285                        re-initialize every global the page is using"
7286                    .to_string(),
7287            );
7288        }
7289        self.page_main = Some(program.to_vec());
7290        self.begin_engine(program);
7291        self.run_top_level_sync(program, false)
7292    }
7293
7294    /// Refuse a host call into a page whose main has not run — `what` names the call.
7295    fn require_page_main(&self, what: &str) -> Result<(), String> {
7296        if self.page_main.is_some() {
7297            Ok(())
7298        } else {
7299            Err(format!(
7300                "tree-walker: cannot call {what} before the page's main has run — main registers \
7301                 every function and initializes the globals every function reads"
7302            ))
7303        }
7304    }
7305
7306    /// One call the host makes into the page. A host call is its own entry into the program, so
7307    /// the failure site in force when it was made is the one in force after it returns, whichever
7308    /// sentence the call itself passed through or failed in.
7309    fn host_call<R>(
7310        &mut self,
7311        call: impl FnOnce(&mut Self) -> Result<R, String>,
7312    ) -> Result<R, String> {
7313        let site = self.current_site;
7314        let outcome = call(self);
7315        if outcome.is_err() {
7316            self.failed_call_site = self.current_site;
7317        }
7318        self.current_site = site;
7319        outcome
7320    }
7321
7322    /// Run `f` at the program's top level, whatever the host was in the middle of: no function
7323    /// frame, no open block, no block-scoped binding in view, no self-tail-call in progress — so a
7324    /// page's main binds its globals as globals even when a reload is asked for from inside a
7325    /// test's `If` or a handler's frame. Everything shelved comes back exactly as it was.
7326    fn at_top_level<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
7327        let env = &mut self.task.env;
7328        let frames = std::mem::take(&mut env.frame_stack);
7329        let locals = std::mem::take(&mut env.locals);
7330        let saves = std::mem::take(&mut env.save_stack);
7331        let block = std::mem::take(&mut env.main_block);
7332        let tco = self.task.tco_fn_sync.take();
7333        let repeat = std::mem::replace(&mut self.task.repeat_depth_sync, 0);
7334        let outcome = f(self);
7335        let env = &mut self.task.env;
7336        env.frame_stack = frames;
7337        env.locals = locals;
7338        env.save_stack = saves;
7339        env.main_block = block;
7340        self.task.tco_fn_sync = tco;
7341        self.task.repeat_depth_sync = repeat;
7342        outcome
7343    }
7344
7345    fn execute_stmt_sync(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7346        self.tick_test_budget()?;
7347        // `--tiers all` replay: test-only statements no-op — EXACTLY the set
7348        // the VM's `compile_tiers` no-ops, so both engines run one program.
7349        if self.tiers_noop
7350            && matches!(
7351                stmt,
7352                Stmt::Expect { .. }
7353                    | Stmt::ExpectFail { .. }
7354                    | Stmt::ExpectOutput { .. }
7355                    | Stmt::AdvanceTime { .. }
7356                    | Stmt::GivenFile { .. }
7357                    | Stmt::ForAll { .. }
7358            )
7359        {
7360            return Ok(ControlFlow::Continue);
7361        }
7362        match stmt {
7363            Stmt::Let { var, value, .. } => {
7364                let val = self.evaluate_expr_sync(value)?;
7365                self.define(*var, val);
7366                Ok(ControlFlow::Continue)
7367            }
7368
7369            Stmt::Set { target, value } => {
7370                if let Some((before, operands)) = self.text_appends(*target, value) {
7371                    let mut pieces = Vec::with_capacity(operands.len());
7372                    for operand in operands {
7373                        pieces.push(self.evaluate_expr_sync(operand)?.to_display_string());
7374                    }
7375                    self.append_text(*target, before, pieces)?;
7376                    return Ok(ControlFlow::Continue);
7377                }
7378                let val = self.evaluate_expr_sync(value)?;
7379                self.assign(*target, val)?;
7380                Ok(ControlFlow::Continue)
7381            }
7382
7383            Stmt::Swap { a, b } => {
7384                // Reversible value exchange — the tree-walker twin of the VM's zero-garbage RevSwap.
7385                let va = self.lookup(*a)?.clone();
7386                let vb = self.lookup(*b)?.clone();
7387                self.assign(*a, vb)?;
7388                self.assign(*b, va)?;
7389                Ok(ControlFlow::Continue)
7390            }
7391
7392            Stmt::Call { function, args } => {
7393                self.call_function_sync(*function, args)?;
7394                Ok(ControlFlow::Continue)
7395            }
7396
7397            Stmt::If {
7398                cond,
7399                then_block,
7400                else_block,
7401            } => {
7402                let condition = self.evaluate_expr_sync(cond)?;
7403                if condition.decided_truth()? {
7404                    let flow = self.execute_block_sync(then_block)?;
7405                    if !matches!(flow, ControlFlow::Continue) {
7406                        return Ok(flow);
7407                    }
7408                } else if let Some(else_stmts) = else_block {
7409                    let flow = self.execute_block_sync(else_stmts)?;
7410                    if !matches!(flow, ControlFlow::Continue) {
7411                        return Ok(flow);
7412                    }
7413                }
7414                Ok(ControlFlow::Continue)
7415            }
7416
7417            Stmt::While { cond, body, .. } => {
7418                loop {
7419                    let condition = self.evaluate_expr_sync(cond)?;
7420                    if !condition.decided_truth()? {
7421                        break;
7422                    }
7423                    match self.execute_block_sync(body)? {
7424                        ControlFlow::Break => break,
7425                        ControlFlow::Return(v) => return Ok(ControlFlow::Return(v)),
7426                        ControlFlow::Continue => {}
7427                    }
7428                }
7429                Ok(ControlFlow::Continue)
7430            }
7431
7432            Stmt::Repeat {
7433                pattern,
7434                iterable,
7435                body,
7436            } => self.exec_repeat(stmt),
7437
7438            Stmt::Return { value } => self.exec_return(stmt),
7439
7440            Stmt::Break => Ok(ControlFlow::Break),
7441
7442            Stmt::FunctionDef {
7443                name,
7444                params,
7445                body,
7446                return_type,
7447                is_native,
7448                native_path,
7449                ..
7450            } => {
7451                let func = FunctionDef {
7452                    params: params.clone(),
7453                    body: *body,
7454                    return_type: *return_type,
7455                    is_native: *is_native,
7456                    native_path: *native_path,
7457                };
7458                self.ctx.functions.insert(*name, func);
7459                Ok(ControlFlow::Continue)
7460            }
7461
7462            Stmt::StructDef { name, fields, .. } => {
7463                self.ctx.struct_defs.insert(*name, fields.clone());
7464                Ok(ControlFlow::Continue)
7465            }
7466
7467            Stmt::SetField {
7468                object,
7469                field,
7470                value,
7471            } => {
7472                let new_val = self.evaluate_expr_sync(value)?;
7473                let place = self.place_sync(object)?;
7474                self.set_field_at(place, *field, new_val)?;
7475                Ok(ControlFlow::Continue)
7476            }
7477
7478            Stmt::Push { value, collection } => self.exec_push(stmt),
7479
7480            Stmt::Pop { collection, into } => {
7481                let coll_val = self.write_target_sync(collection)?;
7482                let popped = crate::semantics::collections::list_pop(&coll_val)?;
7483                if let Some(into_var) = into {
7484                    self.define(*into_var, popped);
7485                }
7486                Ok(ControlFlow::Continue)
7487            }
7488
7489            // The collection is any place — a bare variable or a field (`Add "Alice" to p's
7490            // guests`), owned by its binding before the write.
7491            Stmt::Add { value, collection } => {
7492                let val = self.evaluate_expr_sync(value)?;
7493                let coll_val = self.write_target_sync(collection)?;
7494                crate::semantics::collections::set_add(&coll_val, val)?;
7495                Ok(ControlFlow::Continue)
7496            }
7497
7498            Stmt::Remove { value, collection } => {
7499                let val = self.evaluate_expr_sync(value)?;
7500                let coll_val = self.write_target_sync(collection)?;
7501                crate::semantics::collections::remove_from(&coll_val, &val)?;
7502                Ok(ControlFlow::Continue)
7503            }
7504
7505            Stmt::SetIndex {
7506                collection,
7507                index,
7508                value,
7509            } => self.exec_set_index(stmt),
7510
7511            // A component definition is registered, not executed (`preregister_definitions`).
7512            // An `## Error page STATUS` is part of the SERVER surface: the router renders it when
7513            // a request 404s or 500s, and there is no router yet. Registering it silently — which
7514            // is what every component kind used to get — meant a page declaring a 404 view got one
7515            // quietly ignored, while its three sibling headers (`## Route`, `## Before each
7516            // request`, `## Redirect`) refused by name. A declaration that is accepted and then
7517            // does nothing is the worst outcome for whoever wrote it.
7518            Stmt::ComponentDef(def)
7519                if matches!(
7520                    def.kind,
7521                    crate::ast::component::ComponentKind::ErrorPage { .. }
7522                ) =>
7523            {
7524                {
7525                    // An error page whose template the server-side walk covers is a DECLARATION:
7526                    // the router renders it in place of the bare status. One it cannot render is
7527                    // still refused BY NAME, rather than leaving a declared page silently unused.
7528                    let heading = logicaffeine_language::parser::lgx_lower::construct_heading(
7529                        def,
7530                        self.ctx.interner,
7531                    );
7532                    match def.view.as_ref() {
7533                        Some(v) => match logicaffeine_language::parser::lgx_lower::view_html_lowerable(
7534                            &v.nodes,
7535                            self.ctx.interner,
7536                        ) {
7537                            Ok(()) => Ok(ControlFlow::Continue),
7538                            Err(why) => Err(format!(
7539                                "`{heading}` cannot be rendered on this tier yet: {}.",
7540                                why.message
7541                            )),
7542                        },
7543                        None => Err(format!(
7544                            "`{heading}` cannot be rendered on this tier yet: it has no `View:` to render."
7545                        )),
7546                    }
7547                }
7548            }
7549            Stmt::ComponentDef(_) | Stmt::DirectiveDef { .. } => Ok(ControlFlow::Continue),
7550            Stmt::Ui(ui) => self.execute_ui(ui),
7551            // A `## Route` whose body lowered to a function is a DECLARATION here — the function
7552            // carries it, and `route(method, path)` dispatches. One that could not lower is
7553            // refused BY NAME, saying which part is missing, rather than silently never being
7554            // reachable through the dispatcher (which would read as a 404 for a route the author
7555            // can see in their file).
7556            Stmt::RouteDef {
7557                method,
7558                path,
7559                params,
7560                return_type,
7561                body,
7562                span,
7563            } => {
7564                match logicaffeine_language::parser::lgx_lower::route_lowerable(
7565                    params,
7566                    *return_type,
7567                    body,
7568                    self.ctx.interner,
7569                    &|sym| self.ctx.struct_defs.contains_key(&sym),
7570                    // The components this program declares — without them the server-side walk
7571                    // refuses every template that places one, and the route silently leaves the
7572                    // router.
7573                    &self.ctx.components.values().cloned().collect::<Vec<_>>(),
7574                    *span,
7575                ) {
7576                    Ok(()) => Ok(ControlFlow::Continue),
7577                    Err(why) => Err(format!(
7578                        "`{}` cannot run on this tier yet: {}.",
7579                        logicaffeine_language::parser::lgx_lower::route_heading(
7580                            *method,
7581                            *path,
7582                            self.ctx.interner
7583                        ),
7584                        why.message
7585                    )),
7586                }
7587            }
7588            // A `## Before each request` is a DECLARATION here — it lowered to a function and
7589            // `route(method, path)` calls it before matching. Like a route, nothing runs at the
7590            // point of declaration.
7591            Stmt::MiddlewareDef { .. } => Ok(ControlFlow::Continue),
7592            // A `## Redirect` is a DECLARATION — the router carries it.
7593            Stmt::RedirectDef { .. } => Ok(ControlFlow::Continue),
7594            Stmt::Replay { actions } => {
7595                self.replay_actions(actions)?;
7596                Ok(ControlFlow::Continue)
7597            }
7598            Stmt::ServeFetches => self.serve_fetches_sync(),
7599            Stmt::GivenFetch {
7600                method,
7601                url,
7602                status,
7603                body,
7604            } => self.given_fetch_sync(*method, url, status, body),
7605            Stmt::Fetch { .. } => Err(
7606                "A request that answers into an action (`Get … then loaded`) is sent by a \
7607                 component's own `Actions:`, whose page completes it."
7608                    .to_string(),
7609            ),
7610            Stmt::Splice { body } => {
7611                // Scope-transparent; see the async Splice handler.
7612                for s in body.iter() {
7613                    let flow = self.execute_stmt_sync(s)?;
7614                    if !matches!(flow, ControlFlow::Continue) {
7615                        return Ok(flow);
7616                    }
7617                }
7618                Ok(ControlFlow::Continue)
7619            }
7620
7621            Stmt::Reversibly { body } => {
7622                // Output-transparent; see the async Reversibly handler.
7623                for s in body.iter() {
7624                    let flow = self.execute_stmt_sync(s)?;
7625                    if !matches!(flow, ControlFlow::Continue) {
7626                        return Ok(flow);
7627                    }
7628                }
7629                Ok(ControlFlow::Continue)
7630            }
7631
7632            Stmt::Inspect { target, arms, .. } => {
7633                let target_val = self.evaluate_expr_sync(target)?;
7634                self.execute_inspect_sync(&target_val, arms)
7635            }
7636
7637            Stmt::Zone { name, body, .. } => {
7638                self.push_scope();
7639                self.define(*name, RuntimeValue::Nothing);
7640                let result = self.execute_block_sync(body);
7641                self.pop_scope();
7642                result?;
7643                Ok(ControlFlow::Continue)
7644            }
7645
7646            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
7647                for task in tasks.iter() {
7648                    self.execute_stmt_sync(task)?;
7649                }
7650                Ok(ControlFlow::Continue)
7651            }
7652
7653            Stmt::Assert { .. } | Stmt::Trust { .. } => Ok(ControlFlow::Continue),
7654
7655            // A `## Test` block is a declaration: normal execution walks past
7656            // it; the `largo test` runner collects and drives it (Wave 3).
7657            Stmt::TestDef { .. } => Ok(ControlFlow::Continue),
7658
7659            // Test expectations (real semantics under the runner's test mode;
7660            // fail-loud outside it).
7661            Stmt::Expect { condition } => self.exec_expect(stmt),
7662            Stmt::ExpectFail { message, body } => self.exec_expect_fail(stmt),
7663            Stmt::ExpectOutput { expected } => self.exec_expect_output(stmt),
7664            Stmt::AdvanceTime { millis } => {
7665                if !self.test_mode {
7666                    return Err(TEST_ONLY_STMT_ERR.to_string());
7667                }
7668                let ms = match self.evaluate_expr_sync(millis)? {
7669                    RuntimeValue::Int(n) => n.max(0) as u64,
7670                    // `3 seconds` lexes as a native Duration literal (ns).
7671                    RuntimeValue::Duration(ns) => (ns.max(0) / 1_000_000) as u64,
7672                    other => {
7673                        return Err(format!(
7674                            "Advance time needs a duration in milliseconds, got {}",
7675                            other.type_name()
7676                        ))
7677                    }
7678                };
7679                self.advance_time_ms(ms)
7680            }
7681            Stmt::GivenFile { path, content } => {
7682                if !self.test_mode {
7683                    return Err(TEST_ONLY_STMT_ERR.to_string());
7684                }
7685                logicaffeine_system::testworld::seed_file(
7686                    self.ctx.interner.resolve(*path).to_string(),
7687                    self.ctx.interner.resolve(*content).to_string(),
7688                );
7689                Ok(ControlFlow::Continue)
7690            }
7691
7692            // Observation emits to the observation channel (Wave 7); `During`
7693            // runs its body inline (scope-transparent span).
7694            Stmt::Observe {
7695                category,
7696                message,
7697                payloads,
7698                sample,
7699            } => self.exec_observe(stmt),
7700            Stmt::During { label, body } => self.exec_during(stmt),
7701            Stmt::ForAll {
7702                vars,
7703                domain,
7704                constraint,
7705                body,
7706            } => {
7707                if !self.test_mode {
7708                    return Err(TEST_ONLY_STMT_ERR.to_string());
7709                }
7710                self.run_property(vars, *domain, *constraint, body)?;
7711                Ok(ControlFlow::Continue)
7712            }
7713
7714            Stmt::RuntimeAssert {
7715                condition, reason, ..
7716            } => {
7717                let val = self.evaluate_expr_sync(condition)?;
7718                if !val.decided_truth()? {
7719                    return Err(match reason {
7720                        Some(r) => crate::semantics::builtins::contract_reason_text(
7721                            self.evaluate_expr_sync(r)?,
7722                        )?,
7723                        None => "Assertion failed".to_string(),
7724                    });
7725                }
7726                Ok(ControlFlow::Continue)
7727            }
7728
7729            Stmt::Fail { reason } => Err(self.evaluate_expr_sync(reason)?.to_display_string()),
7730
7731            Stmt::Give { object, recipient } => {
7732                let obj_val = self.evaluate_expr_sync(object)?;
7733                if let Expr::Identifier(sym) = recipient {
7734                    self.call_function_with_values_sync(*sym, vec![obj_val])?;
7735                }
7736                Ok(ControlFlow::Continue)
7737            }
7738
7739            Stmt::Show { object, recipient } => {
7740                let obj_val = self.evaluate_expr_sync(object)?;
7741                if let Expr::Identifier(sym) = recipient {
7742                    let name = self.ctx.interner.resolve(*sym);
7743                    if name == "show" {
7744                        self.emit_output(obj_val.to_display_string());
7745                    } else {
7746                        self.call_function_with_values_sync(*sym, vec![obj_val])?;
7747                    }
7748                }
7749                Ok(ControlFlow::Continue)
7750            }
7751
7752            // Async-only operations — unreachable in sync path (checked by needs_async)
7753            Stmt::ReadFrom { var, source } => match source {
7754                ReadSource::Console => {
7755                    self.define(*var, RuntimeValue::Text(Rc::new(String::new())));
7756                    Ok(ControlFlow::Continue)
7757                }
7758                ReadSource::File(_) => Err("File read requires async execution path".to_string()),
7759            },
7760
7761            Stmt::WriteFile { .. } => Err("File write requires async execution path".to_string()),
7762
7763            Stmt::Spawn { name, .. } => {
7764                self.define(*name, RuntimeValue::Nothing);
7765                Ok(ControlFlow::Continue)
7766            }
7767
7768            Stmt::SendMessage { .. } => {
7769                Err("Send (peer messaging) requires the async execution path".to_string())
7770            }
7771            Stmt::StreamMessage { .. } => {
7772                Err("Stream (batch peer messaging) requires the async execution path".to_string())
7773            }
7774
7775            Stmt::AwaitMessage { .. } => {
7776                Err("Await (peer messaging) requires the async execution path".to_string())
7777            }
7778
7779            Stmt::MergeCrdt { source, target } => self.exec_merge_crdt(stmt),
7780
7781            // The IDEMPOTENT sibling of `MergeCrdt`: a bare-`Int` field takes per-field MAX (not ADD), so a
7782            // redelivered state never double-counts. Counter/other fields defer to `crdt_join_field`'s merge.
7783            Stmt::JoinCrdt { source, target } => self.exec_join_crdt(stmt),
7784
7785            Stmt::IncreaseCrdt {
7786                object,
7787                field,
7788                amount,
7789            } => self.exec_increase_crdt(stmt),
7790
7791            Stmt::DecreaseCrdt {
7792                object,
7793                field,
7794                amount,
7795            } => self.exec_decrease_crdt(stmt),
7796
7797            Stmt::AppendToSequence { sequence, value } => {
7798                let val = self.evaluate_expr_sync(value)?;
7799                let seq_val = self.evaluate_expr_sync(sequence)?;
7800                match &seq_val {
7801                    RuntimeValue::Crdt(rc) => rc.borrow_mut().append(&val)?,
7802                    RuntimeValue::List(_) => {
7803                        crate::semantics::collections::list_push(&seq_val, val)?
7804                    }
7805                    _ => return Err(format!("Cannot append to {}", seq_val.type_name())),
7806                }
7807                Ok(ControlFlow::Continue)
7808            }
7809
7810            Stmt::ResolveConflict {
7811                object,
7812                field,
7813                value,
7814            } => self.exec_resolve_conflict(stmt),
7815
7816            Stmt::Check { .. } => self.exec_check(stmt),
7817
7818            Stmt::Listen { .. } | Stmt::ConnectTo { .. } => {
7819                Err("Networking (Connect/Listen) requires the async execution path".to_string())
7820            }
7821            Stmt::Serve { .. } => {
7822                Err("`Serve` (HTTP server) requires the async execution path".to_string())
7823            }
7824            // A PeerAgent handle is pure (just its canonical topic), so it works
7825            // outside the async path; the `Send`/`Await` that use it do not.
7826            Stmt::LetPeerAgent { var, address } => {
7827                let raw = self.evaluate_expr_sync(address)?.to_display_string();
7828                let topic = logicaffeine_system::addr::canonical_topic(&raw);
7829                self.define(*var, RuntimeValue::Peer(Rc::new(topic)));
7830                Ok(ControlFlow::Continue)
7831            }
7832            Stmt::Sleep { .. } => Err("Sleep requires async execution path".to_string()),
7833            Stmt::Sync { .. } => Err("Sync requires the async execution path".to_string()),
7834            Stmt::Mount { .. } => Err("Mount requires async execution path".to_string()),
7835
7836            Stmt::LaunchTask { .. }
7837            | Stmt::LaunchTaskWithHandle { .. }
7838            | Stmt::CreatePipe { .. }
7839            | Stmt::SendPipe { .. }
7840            | Stmt::ReceivePipe { .. }
7841            | Stmt::TrySendPipe { .. }
7842            | Stmt::TryReceivePipe { .. }
7843            | Stmt::StopTask { .. }
7844            | Stmt::CloseChannel { .. }
7845            | Stmt::AwaitTask { .. }
7846            | Stmt::Select { .. } => Err(
7847                "Go-like concurrency (Launch, Pipe, Select) is only supported in compiled mode"
7848                    .to_string(),
7849            ),
7850
7851            Stmt::Escape { .. } => Err(crate::semantics::escape::REFUSAL.to_string()),
7852
7853            Stmt::Require { .. } => Ok(ControlFlow::Continue),
7854
7855            Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {
7856                Ok(ControlFlow::Continue)
7857            }
7858
7859            // A failure-site marker (Wave 3) — see the identical arm in `execute_stmt` (the async
7860            // twin of this function).
7861            Stmt::Site(id) => {
7862                self.current_site = Some(*id);
7863                Ok(ControlFlow::Continue)
7864            }
7865        }
7866    }
7867
7868    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
7869    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
7870    /// recursion level — and one LOGOS call costs several of these frames.
7871    #[inline(never)]
7872    fn exec_check(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7873        let Stmt::Check {
7874            subject,
7875            predicate,
7876            is_capability,
7877            object,
7878            source_text,
7879            ..
7880        } = stmt
7881        else {
7882            unreachable!()
7883        };
7884        let registry = match &self.ctx.policy_registry {
7885            Some(r) => r,
7886            None => return Err(crate::semantics::policy::NO_POLICIES.to_string()),
7887        };
7888
7889        let subj_val = self.lookup(*subject)?.clone();
7890        // The object is only consulted (and only looked up) for
7891        // capability checks.
7892        let obj_val = if *is_capability {
7893            match object {
7894                Some(obj_sym) => Some(self.lookup(*obj_sym)?.clone()),
7895                None => None,
7896            }
7897        } else {
7898            None
7899        };
7900        crate::semantics::policy::check_policy(
7901            registry,
7902            self.ctx.interner,
7903            &subj_val,
7904            *predicate,
7905            *is_capability,
7906            obj_val.as_ref(),
7907            source_text,
7908        )?;
7909        Ok(ControlFlow::Continue)
7910    }
7911
7912    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
7913    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
7914    /// recursion level — and one LOGOS call costs several of these frames.
7915    #[inline(never)]
7916    fn exec_resolve_conflict(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7917        let Stmt::ResolveConflict {
7918            object,
7919            field,
7920            value,
7921        } = stmt
7922        else {
7923            unreachable!()
7924        };
7925        let val = self.evaluate_expr_sync(value)?;
7926        let obj_val = self.evaluate_expr_sync(object)?;
7927        let field_name = self.ctx.interner.resolve(*field);
7928        if let RuntimeValue::Struct(s) = &obj_val {
7929            if let Some(RuntimeValue::Crdt(rc)) = s.fields.get(field_name) {
7930                rc.borrow_mut().resolve(&val)?;
7931                return Ok(ControlFlow::Continue);
7932            }
7933        }
7934        if let Expr::Identifier(obj_sym) = object {
7935            let mut owner = self.lookup(*obj_sym)?.clone();
7936            if let RuntimeValue::Struct(ref mut s) = owner {
7937                s.fields.insert(field_name.to_string(), val);
7938                self.assign(*obj_sym, owner)?;
7939                return Ok(ControlFlow::Continue);
7940            }
7941        }
7942        Err("Resolve target must be a struct field".to_string())
7943    }
7944
7945    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
7946    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
7947    /// recursion level — and one LOGOS call costs several of these frames.
7948    #[inline(never)]
7949    fn exec_decrease_crdt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7950        let Stmt::DecreaseCrdt {
7951            object,
7952            field,
7953            amount,
7954        } = stmt
7955        else {
7956            unreachable!()
7957        };
7958        let amount_val = self.evaluate_expr_sync(amount)?;
7959        let amount_int = match amount_val {
7960            RuntimeValue::Int(n) => n,
7961            _ => return Err("CRDT decrement amount must be an integer".to_string()),
7962        };
7963
7964        if let Expr::Identifier(obj_sym) = object {
7965            let mut obj_val = self.lookup(*obj_sym)?.clone();
7966
7967            if let RuntimeValue::Struct(ref mut s) = obj_val {
7968                let field_name = self.ctx.interner.resolve(*field).to_string();
7969                let current = s
7970                    .fields
7971                    .get(&field_name)
7972                    .cloned()
7973                    .unwrap_or(RuntimeValue::Int(0));
7974
7975                let new_val = crate::semantics::arith::crdt_counter_bump(
7976                    current,
7977                    amount_int.wrapping_neg(),
7978                    &field_name,
7979                )?;
7980                s.fields.insert(field_name, new_val);
7981                self.assign(*obj_sym, obj_val)?;
7982            } else {
7983                return Err("Cannot decrease field on non-struct value".to_string());
7984            }
7985        } else {
7986            return Err("DecreaseCrdt target must be an identifier".to_string());
7987        }
7988        Ok(ControlFlow::Continue)
7989    }
7990
7991    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
7992    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
7993    /// recursion level — and one LOGOS call costs several of these frames.
7994    #[inline(never)]
7995    fn exec_increase_crdt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7996        let Stmt::IncreaseCrdt {
7997            object,
7998            field,
7999            amount,
8000        } = stmt
8001        else {
8002            unreachable!()
8003        };
8004        let amount_val = self.evaluate_expr_sync(amount)?;
8005        let amount_int = match amount_val {
8006            RuntimeValue::Int(n) => n,
8007            _ => return Err("CRDT increment amount must be an integer".to_string()),
8008        };
8009
8010        if let Expr::Identifier(obj_sym) = object {
8011            let mut obj_val = self.lookup(*obj_sym)?.clone();
8012
8013            if let RuntimeValue::Struct(ref mut s) = obj_val {
8014                let field_name = self.ctx.interner.resolve(*field).to_string();
8015                let current = s
8016                    .fields
8017                    .get(&field_name)
8018                    .cloned()
8019                    .unwrap_or(RuntimeValue::Int(0));
8020
8021                let new_val =
8022                    crate::semantics::arith::crdt_counter_bump(current, amount_int, &field_name)?;
8023                s.fields.insert(field_name, new_val);
8024                self.assign(*obj_sym, obj_val)?;
8025            } else {
8026                return Err("Cannot increase field on non-struct value".to_string());
8027            }
8028        } else {
8029            return Err("IncreaseCrdt target must be an identifier".to_string());
8030        }
8031        Ok(ControlFlow::Continue)
8032    }
8033
8034    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8035    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8036    /// recursion level — and one LOGOS call costs several of these frames.
8037    #[inline(never)]
8038    fn exec_join_crdt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8039        let Stmt::JoinCrdt { source, target } = stmt else {
8040            unreachable!()
8041        };
8042        let source_val = self.evaluate_expr_sync(source)?;
8043        let source_fields = match &source_val {
8044            RuntimeValue::Struct(s) => s.fields.clone(),
8045            _ => return Err("Converge source must be a struct".to_string()),
8046        };
8047
8048        if let Expr::Identifier(target_sym) = target {
8049            let mut target_val = self.lookup(*target_sym)?.clone();
8050
8051            if let RuntimeValue::Struct(ref mut s) = target_val {
8052                for (field_name, source_field_val) in source_fields {
8053                    let current = s
8054                        .fields
8055                        .get(&field_name)
8056                        .cloned()
8057                        .unwrap_or(RuntimeValue::Int(0));
8058
8059                    let joined =
8060                        crate::semantics::arith::crdt_join_field(&current, source_field_val);
8061                    s.fields.insert(field_name, joined);
8062                }
8063                self.assign(*target_sym, target_val)?;
8064            } else {
8065                return Err("Converge target must be a struct".to_string());
8066            }
8067        } else {
8068            return Err("Converge target must be an identifier".to_string());
8069        }
8070        Ok(ControlFlow::Continue)
8071    }
8072
8073    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8074    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8075    /// recursion level — and one LOGOS call costs several of these frames.
8076    #[inline(never)]
8077    fn exec_merge_crdt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8078        let Stmt::MergeCrdt { source, target } = stmt else {
8079            unreachable!()
8080        };
8081        let source_val = self.evaluate_expr_sync(source)?;
8082        let source_fields = match &source_val {
8083            RuntimeValue::Struct(s) => s.fields.clone(),
8084            _ => return Err("Merge source must be a struct".to_string()),
8085        };
8086
8087        if let Expr::Identifier(target_sym) = target {
8088            let mut target_val = self.lookup(*target_sym)?.clone();
8089
8090            if let RuntimeValue::Struct(ref mut s) = target_val {
8091                for (field_name, source_field_val) in source_fields {
8092                    let current = s
8093                        .fields
8094                        .get(&field_name)
8095                        .cloned()
8096                        .unwrap_or(RuntimeValue::Int(0));
8097
8098                    let merged =
8099                        crate::semantics::arith::crdt_merge_field(&current, source_field_val);
8100                    s.fields.insert(field_name, merged);
8101                }
8102                self.assign(*target_sym, target_val)?;
8103            } else {
8104                return Err("Merge target must be a struct".to_string());
8105            }
8106        } else {
8107            return Err("Merge target must be an identifier".to_string());
8108        }
8109        Ok(ControlFlow::Continue)
8110    }
8111
8112    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8113    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8114    /// recursion level — and one LOGOS call costs several of these frames.
8115    #[inline(never)]
8116    fn exec_during(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8117        let Stmt::During { label, body } = stmt else {
8118            unreachable!()
8119        };
8120        // Balanced span bracketing on every exit path (Wave 8).
8121        let cap = crate::observe::capturing();
8122        let name = if cap {
8123            self.ctx.interner.resolve(*label).to_string()
8124        } else {
8125            String::new()
8126        };
8127        if cap {
8128            crate::observe::enter_span(name.clone());
8129        }
8130        let mut result: Result<ControlFlow, String> = Ok(ControlFlow::Continue);
8131        for s in body.iter() {
8132            match self.execute_stmt_sync(s) {
8133                Ok(ControlFlow::Continue) => {}
8134                Ok(flow) => {
8135                    result = Ok(flow);
8136                    break;
8137                }
8138                Err(e) => {
8139                    result = Err(e);
8140                    break;
8141                }
8142            }
8143        }
8144        if cap {
8145            crate::observe::exit_span(name);
8146        }
8147        result
8148    }
8149
8150    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8151    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8152    /// recursion level — and one LOGOS call costs several of these frames.
8153    #[inline(never)]
8154    fn exec_observe(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8155        let Stmt::Observe {
8156            category,
8157            message,
8158            payloads,
8159            sample,
8160        } = stmt
8161        else {
8162            unreachable!()
8163        };
8164        if crate::observe::capturing() {
8165            let mut vals: Vec<(String, String)> = Vec::with_capacity(payloads.len());
8166            for (name, expr) in payloads.iter() {
8167                let v = self.evaluate_expr_sync(expr)?;
8168                vals.push((
8169                    self.ctx.interner.resolve(*name).to_string(),
8170                    v.to_display_string(),
8171                ));
8172            }
8173            crate::observe::emit(
8174                map_obs_category(*category),
8175                self.ctx.interner.resolve(*message).to_string(),
8176                vals,
8177                *sample,
8178                message.index() as u64,
8179            );
8180        }
8181        Ok(ControlFlow::Continue)
8182    }
8183
8184    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8185    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8186    /// recursion level — and one LOGOS call costs several of these frames.
8187    #[inline(never)]
8188    fn exec_expect_output(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8189        let Stmt::ExpectOutput { expected } = stmt else {
8190            unreachable!()
8191        };
8192        if !self.test_mode {
8193            return Err(TEST_ONLY_STMT_ERR.to_string());
8194        }
8195        self.test_assertions += 1;
8196        match expected {
8197            ExpectedOutput::Inline(sym) => {
8198                let expected_text = self.ctx.interner.resolve(*sym).to_string();
8199                let actual = self.output.join("\n");
8200                if actual != expected_text {
8201                    self.test_failures.push(format!(
8202                        "Expected output {expected_text:?} — but the test printed {actual:?}."
8203                    ));
8204                }
8205            }
8206            ExpectedOutput::File(path) => {
8207                self.test_failures.push(format!(
8208                        "Expected output as in {:?} — golden files land with the sealed world (Wave 4).",
8209                        self.ctx.interner.resolve(*path)
8210                    ));
8211            }
8212        }
8213        Ok(ControlFlow::Continue)
8214    }
8215
8216    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8217    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8218    /// recursion level — and one LOGOS call costs several of these frames.
8219    #[inline(never)]
8220    fn exec_expect_fail(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8221        let Stmt::ExpectFail { message, body } = stmt else {
8222            unreachable!()
8223        };
8224        if !self.test_mode {
8225            return Err(TEST_ONLY_STMT_ERR.to_string());
8226        }
8227        self.test_assertions += 1;
8228        let mut failure: Option<String> = None;
8229        for s in body.iter() {
8230            if let Err(e) = self.execute_stmt_sync(s) {
8231                failure = Some(e);
8232                break;
8233            }
8234        }
8235        match failure {
8236            None => self
8237                .test_failures
8238                .push("Expected this to fail — but the block succeeded.".to_string()),
8239            Some(actual) => {
8240                if let Some(expected) = message {
8241                    let expected = self.ctx.interner.resolve(*expected);
8242                    if actual != expected {
8243                        self.test_failures.push(format!(
8244                                "Expected this to fail with {expected:?} — but it failed with {actual:?}."
8245                            ));
8246                    }
8247                }
8248            }
8249        }
8250        Ok(ControlFlow::Continue)
8251    }
8252
8253    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8254    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8255    /// recursion level — and one LOGOS call costs several of these frames.
8256    #[inline(never)]
8257    fn exec_expect(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8258        let Stmt::Expect { condition } = stmt else {
8259            unreachable!()
8260        };
8261        if !self.test_mode {
8262            return Err(TEST_ONLY_STMT_ERR.to_string());
8263        }
8264        self.test_assertions += 1;
8265        let val = self.evaluate_expr_sync(condition)?;
8266        if !val.decided_truth()? {
8267            let cond_text =
8268                logicaffeine_language::printer::render_expr(condition, self.ctx.interner);
8269            let mut subs = Vec::new();
8270            logicaffeine_language::printer::subexpressions(condition, &mut subs);
8271            let mut annotations: Vec<(String, String)> = Vec::new();
8272            let mut seen = std::collections::HashSet::new();
8273            for sub in subs {
8274                let text = logicaffeine_language::printer::render_expr(sub, self.ctx.interner);
8275                if !seen.insert(text.clone()) {
8276                    continue;
8277                }
8278                if let Ok(v) = self.evaluate_expr_sync(sub) {
8279                    annotations.push((text, v.to_display_string()));
8280                }
8281            }
8282            let hint = Self::expect_socratic_hint(condition);
8283            self.test_failures
8284                .push(format_expect_failure(&cond_text, &annotations, hint));
8285        }
8286        Ok(ControlFlow::Continue)
8287    }
8288
8289    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8290    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8291    /// recursion level — and one LOGOS call costs several of these frames.
8292    #[inline(never)]
8293    fn exec_set_index(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8294        let Stmt::SetIndex {
8295            collection,
8296            index,
8297            value,
8298        } = stmt
8299        else {
8300            unreachable!()
8301        };
8302        let idx_val = self.evaluate_expr_sync(index)?;
8303        let new_val = self.evaluate_expr_sync(value)?;
8304        let target = match self.place_sync(collection)? {
8305            Some(place) => match self.set_item_in_place(&place, &idx_val, new_val.clone()) {
8306                Some(done) => {
8307                    done?;
8308                    return Ok(ControlFlow::Continue);
8309                }
8310                None => self.read_place(&place)?,
8311            },
8312            None => self.evaluate_expr_sync(collection)?,
8313        };
8314        crate::semantics::collections::index_set(&target, &idx_val, new_val)?;
8315        Ok(ControlFlow::Continue)
8316    }
8317
8318    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8319    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8320    /// recursion level — and one LOGOS call costs several of these frames.
8321    #[inline(never)]
8322    fn exec_push(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8323        let Stmt::Push { value, collection } = stmt else {
8324            unreachable!()
8325        };
8326        let val = self.evaluate_expr_sync(value)?;
8327        if let Expr::FieldAccess {
8328            object: Expr::Identifier(obj_sym),
8329            field,
8330        } = collection
8331        {
8332            if let Some(place) = self.place_sync(collection)? {
8333                self.place_slot(&place, true);
8334            }
8335            let obj_val = self.lookup(*obj_sym)?;
8336            let field_name = self.ctx.interner.resolve(*field);
8337            crate::semantics::collections::push_to_struct_field(obj_val, field_name, val)?;
8338        } else {
8339            let coll_val = self.write_target_sync(collection)?;
8340            crate::semantics::collections::list_push(&coll_val, val)?;
8341        }
8342        Ok(ControlFlow::Continue)
8343    }
8344
8345    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8346    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8347    /// recursion level — and one LOGOS call costs several of these frames.
8348    #[inline(never)]
8349    fn exec_return(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8350        let Stmt::Return { value } = stmt else {
8351            unreachable!()
8352        };
8353        // A direct self-tail-call `Return self(args)` becomes a loop-back
8354        // in `call_function_sync`: signal it via `pending_tail_call` and
8355        // return control to the body driver (which sees the sentinel and
8356        // restarts instead of using the value). Args are evaluated here —
8357        // a nested self-call in an argument stays ordinary recursion.
8358        if let Some(expr) = value {
8359            if let Some(call_args) = self.self_tail_call_args_sync(*expr) {
8360                let mut vals = Vec::with_capacity(call_args.len());
8361                for a in call_args {
8362                    vals.push(self.evaluate_expr_sync(a)?);
8363                }
8364                self.task.pending_tail_call = Some(vals);
8365                return Ok(ControlFlow::Return(RuntimeValue::Nothing));
8366            }
8367        }
8368        let ret_val = match value {
8369            Some(expr) => self.evaluate_expr_sync(expr)?,
8370            None => RuntimeValue::Nothing,
8371        };
8372        Ok(ControlFlow::Return(ret_val))
8373    }
8374
8375    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8376    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8377    /// recursion level — and one LOGOS call costs several of these frames.
8378    #[inline(never)]
8379    fn exec_repeat(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8380        let Stmt::Repeat {
8381            pattern,
8382            iterable,
8383            body,
8384        } = stmt
8385        else {
8386            unreachable!()
8387        };
8388        use crate::ast::stmt::Pattern;
8389
8390        let iter_val = self.evaluate_expr_sync(iterable)?;
8391        let items = crate::semantics::collections::iteration_snapshot(&iter_val)?;
8392
8393        self.push_scope();
8394        // A `Repeat` owns a live iterator: suppress TCO of any self-call
8395        // detected inside it (jumping to the body start would abandon the
8396        // iterator), matching the VM's `is_repeat` guard exactly.
8397        self.task.repeat_depth_sync += 1;
8398        for item in items {
8399            match pattern {
8400                Pattern::Identifier(sym) => {
8401                    self.define(*sym, item);
8402                }
8403                Pattern::Tuple(syms) => {
8404                    if let RuntimeValue::Tuple(ref tuple_vals) = item {
8405                        if syms.len() != tuple_vals.len() {
8406                            self.task.repeat_depth_sync -= 1;
8407                            return Err(format!(
8408                                "Cannot bind a {}-tuple to {} names",
8409                                tuple_vals.len(),
8410                                syms.len()
8411                            ));
8412                        }
8413                        for (sym, val) in syms.iter().zip(tuple_vals.iter()) {
8414                            self.define(*sym, val.clone());
8415                        }
8416                    } else {
8417                        self.task.repeat_depth_sync -= 1;
8418                        return Err(format!(
8419                            "Expected tuple for pattern, got {}",
8420                            item.type_name()
8421                        ));
8422                    }
8423                }
8424            }
8425
8426            match self.execute_block_sync(body)? {
8427                ControlFlow::Break => break,
8428                ControlFlow::Return(v) => {
8429                    self.task.repeat_depth_sync -= 1;
8430                    self.pop_scope();
8431                    return Ok(ControlFlow::Return(v));
8432                }
8433                ControlFlow::Continue => {}
8434            }
8435        }
8436        self.task.repeat_depth_sync -= 1;
8437        self.pop_scope();
8438        Ok(ControlFlow::Continue)
8439    }
8440
8441    fn execute_block_sync(&mut self, block: Block<'a>) -> Result<ControlFlow, String> {
8442        self.push_scope();
8443        for stmt in block.iter() {
8444            match self.execute_stmt_sync(stmt)? {
8445                ControlFlow::Continue => {}
8446                flow => {
8447                    self.pop_scope();
8448                    return Ok(flow);
8449                }
8450            }
8451        }
8452        self.pop_scope();
8453        Ok(ControlFlow::Continue)
8454    }
8455
8456    fn execute_inspect_sync(
8457        &mut self,
8458        target: &RuntimeValue,
8459        arms: &[MatchArm<'a>],
8460    ) -> Result<ControlFlow, String> {
8461        for arm in arms {
8462            if arm.variant.is_none() {
8463                let flow = self.execute_block_sync(arm.body)?;
8464                return Ok(flow);
8465            }
8466
8467            match target {
8468                RuntimeValue::Struct(s) => {
8469                    if let Some(variant) = arm.variant {
8470                        let variant_name = self.ctx.interner.resolve(variant);
8471                        if s.type_name == variant_name {
8472                            self.push_scope();
8473                            for (field_name, binding_name) in &arm.bindings {
8474                                let field_str = self.ctx.interner.resolve(*field_name);
8475                                if let Some(val) = s.fields.get(field_str) {
8476                                    self.define(*binding_name, val.clone());
8477                                }
8478                            }
8479                            let result = self.execute_block_sync(arm.body);
8480                            self.pop_scope();
8481                            let flow = result?;
8482                            return Ok(flow);
8483                        }
8484                        // The transparent Option encoding, for a STRUCT payload: `some x` IS x,
8485                        // so `some(a new Response …)` is a Response and a `Some` arm has to match
8486                        // it. Without this the arm above rejects it (its `type_name` is
8487                        // `Response`, not `Some`) and the `other` arm below is never reached,
8488                        // because this branch already claimed the value — so `Option of <any
8489                        // record>` could not be inspected AT ALL, while `Option of Int` worked
8490                        // fine. That asymmetry is invisible until someone writes the first
8491                        // `-> Option of Response`, which is the plan's own middleware signature.
8492                        // ★ A STRUCT NO LONGER ANSWERS A `Some` ARM. This existed because an
8493                        // Option was transparent — `some (a new Response …)` WAS the Response, so
8494                        // without it `Option of <record>` could not be inspected at all while
8495                        // `Option of Int` worked, an asymmetry that stayed invisible until the
8496                        // first `-> Option of Response`. A real Option is an `Inductive` now and
8497                        // is matched by name, so leaving this would let a plain record claim to be
8498                        // a present Option.
8499                    }
8500                }
8501
8502                RuntimeValue::Inductive(ind) => {
8503                    if let Some(variant) = arm.variant {
8504                        let variant_name = self.ctx.interner.resolve(variant);
8505                        if ind.constructor == variant_name {
8506                            self.push_scope();
8507                            for (i, (_, binding_name)) in arm.bindings.iter().enumerate() {
8508                                if i < ind.args.len() {
8509                                    self.define(*binding_name, ind.args[i].clone());
8510                                }
8511                            }
8512                            let result = self.execute_block_sync(arm.body);
8513                            self.pop_scope();
8514                            let flow = result?;
8515                            return Ok(flow);
8516                        }
8517                    }
8518                }
8519
8520                // The transparent Option encoding: `some x` IS x and `none` IS
8521                // Nothing, so Some/None arms match presence/absence for
8522                // non-enum values (the boxed `a new Some …` form matches
8523                // through the arms above).
8524                RuntimeValue::Nothing => {
8525                    if let Some(variant) = arm.variant {
8526                        if self.ctx.interner.resolve(variant) == "None" {
8527                            let flow = self.execute_block_sync(arm.body)?;
8528                            return Ok(flow);
8529                        }
8530                    }
8531                }
8532
8533                // The sync twin of the removed transparent catch-all — see the async copy.
8534                _ => {}
8535            }
8536        }
8537        Err(self.inspect_unhandled(target))
8538    }
8539
8540    fn evaluate_expr_sync(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8541        match expr {
8542            Expr::View(_) => Err(
8543                "A view is drawn by the component it belongs to — place it in that component's `View:`."
8544                    .to_string(),
8545            ),
8546            Expr::Dom(q) => self.evaluate_dom_query(q),
8547            Expr::Literal(lit) => self.evaluate_literal(lit),
8548
8549            Expr::Identifier(sym) => {
8550                let name = self.ctx.interner.resolve(*sym);
8551                // Handle temporal builtins (the NAME wins, even when shadowed)
8552                match name {
8553                    "today" => {
8554                        return Ok(crate::semantics::temporal::today());
8555                    }
8556                    "now" => {
8557                        return Ok(crate::semantics::temporal::now());
8558                    }
8559                    _ => {}
8560                }
8561                self.lookup(*sym).cloned()
8562            }
8563
8564            Expr::BinaryOp { op, left, right } => self.eval_binary_op(expr),
8565
8566            Expr::Call { function, args } => {
8567                self.call_function_sync(*function, args)
8568            }
8569
8570            Expr::Index { collection, index } => {
8571                let coll_val = self.evaluate_expr_sync(collection)?;
8572                let idx_val = self.evaluate_expr_sync(index)?;
8573                crate::semantics::collections::index_get(&coll_val, &idx_val)
8574            }
8575
8576            Expr::Slice { collection, start, end } => {
8577                let coll_val = self.evaluate_expr_sync(collection)?;
8578                let start_val = self.evaluate_expr_sync(start)?;
8579                let end_val = self.evaluate_expr_sync(end)?;
8580                crate::semantics::collections::slice(&coll_val, &start_val, &end_val)
8581            }
8582
8583            Expr::Copy { expr: inner } => {
8584                let val = self.evaluate_expr_sync(inner)?;
8585                Ok(val.deep_clone())
8586            }
8587
8588            Expr::Give { value } => {
8589                self.evaluate_expr_sync(value)
8590            }
8591
8592            Expr::Length { collection } => {
8593                let coll_val = self.evaluate_expr_sync(collection)?;
8594                crate::semantics::collections::length_of(&coll_val)
8595            }
8596
8597            Expr::Contains { collection, value } => {
8598                let coll_val = self.evaluate_expr_sync(collection)?;
8599                let val = self.evaluate_expr_sync(value)?;
8600                crate::semantics::collections::contains(&coll_val, &val)
8601            }
8602
8603            Expr::Union { left, right } => {
8604                let left_val = self.evaluate_expr_sync(left)?;
8605                let right_val = self.evaluate_expr_sync(right)?;
8606                crate::semantics::collections::union(&left_val, &right_val)
8607            }
8608
8609            Expr::Intersection { left, right } => {
8610                let left_val = self.evaluate_expr_sync(left)?;
8611                let right_val = self.evaluate_expr_sync(right)?;
8612                crate::semantics::collections::intersection(&left_val, &right_val)
8613            }
8614
8615            Expr::List(items) => {
8616                let mut values = Vec::with_capacity(items.len());
8617                for e in items.iter() {
8618                    values.push(self.evaluate_expr_sync(e)?);
8619                }
8620                Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::from_values(values)))))
8621            }
8622
8623            Expr::Tuple(items) => {
8624                let mut values = Vec::with_capacity(items.len());
8625                for e in items.iter() {
8626                    values.push(self.evaluate_expr_sync(e)?);
8627                }
8628                Ok(RuntimeValue::Tuple(Rc::new(values)))
8629            }
8630
8631            Expr::Range { start, end } => {
8632                let start_val = self.evaluate_expr_sync(start)?;
8633                let end_val = self.evaluate_expr_sync(end)?;
8634                crate::semantics::collections::range(&start_val, &end_val)
8635            }
8636
8637            Expr::FieldAccess { object, field } => {
8638                let obj_val = self.evaluate_expr_sync(object)?;
8639                match &obj_val {
8640                    RuntimeValue::Struct(s) => {
8641                        let field_name = self.ctx.interner.resolve(*field);
8642                        s.fields.get(field_name).cloned()
8643                            .ok_or_else(|| format!("Field '{}' not found", field_name))
8644                    }
8645                    _ => Err(format!("Cannot access field on {}", obj_val.type_name())),
8646                }
8647            }
8648
8649            Expr::New { type_name, init_fields, .. } => self.eval_new(expr),
8650
8651            Expr::NewVariant { enum_name, variant, fields } => self.eval_new_variant(expr),
8652
8653            Expr::ManifestOf { .. } => {
8654                Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(Vec::new())))))
8655            }
8656
8657            Expr::ChunkAt { .. } => {
8658                Ok(RuntimeValue::Nothing)
8659            }
8660
8661            Expr::WithCapacity { value, capacity } => {
8662                let capacity = match self.evaluate_expr_sync(capacity)? {
8663                    RuntimeValue::Int(capacity) => capacity,
8664                    _ => return Err("Capacity requires an Int".to_string()),
8665                };
8666                let value = self.evaluate_expr_sync(value)?;
8667                Ok(apply_capacity_hint(value, capacity))
8668            }
8669
8670            // The sync twin of the boxed Option above — same rule, same reasons.
8671            Expr::OptionSome { value } => {
8672                let inner = self.evaluate_expr_sync(value)?;
8673                Ok(option_some(inner))
8674            }
8675
8676            Expr::OptionNone => Ok(option_none()),
8677
8678            Expr::Not { operand } => {
8679                let val = self.evaluate_expr_sync(operand)?;
8680                crate::semantics::arith::not_value(val)
8681            }
8682
8683            Expr::InterpolatedString(parts) => self.eval_interpolated_string(expr),
8684
8685            Expr::Escape { .. } => {
8686                Err(crate::semantics::escape::REFUSAL.to_string())
8687            }
8688
8689            Expr::Closure { params, body, .. } => self.eval_closure(expr),
8690
8691            Expr::CallExpr { callee, args } => {
8692                let callee_val = self.evaluate_expr_sync(callee)?;
8693                if let RuntimeValue::Function(closure) = callee_val {
8694                    let mut arg_values = Vec::with_capacity(args.len());
8695                    for arg in args.iter() {
8696                        arg_values.push(self.evaluate_expr_sync(arg)?);
8697                    }
8698                    self.call_closure_value_sync(&closure, arg_values)
8699                } else {
8700                    Err(format!("Cannot call value of type {}", callee_val.type_name()))
8701                }
8702            }
8703        }
8704    }
8705
8706    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8707    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8708    /// recursion level — and one LOGOS call costs several of these frames.
8709    #[inline(never)]
8710    fn eval_closure(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8711        let Expr::Closure { params, body, .. } = expr else {
8712            unreachable!()
8713        };
8714        let free_vars = self.collect_free_vars_in_closure(params, body);
8715        let mut captured_env = HashMap::new();
8716        for sym in &free_vars {
8717            if let Some(val) = self.task.env.lookup(*sym) {
8718                captured_env.insert(*sym, val.deep_clone());
8719            }
8720        }
8721
8722        let body_index = self.ctx.closure_bodies.len();
8723        match body {
8724            ClosureBody::Expression(expr) => {
8725                self.ctx
8726                    .closure_bodies
8727                    .push(ClosureBodyRef::Expression(expr));
8728            }
8729            ClosureBody::Block(block) => {
8730                self.ctx.closure_bodies.push(ClosureBodyRef::Block(block));
8731            }
8732        }
8733
8734        let param_names: Vec<Symbol> = params.iter().map(|(name, _)| *name).collect();
8735
8736        Ok(RuntimeValue::Function(Box::new(ClosureValue {
8737            body_index,
8738            captured_env,
8739            param_names,
8740            generated: None,
8741        })))
8742    }
8743
8744    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8745    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8746    /// recursion level — and one LOGOS call costs several of these frames.
8747    #[inline(never)]
8748    fn eval_interpolated_string(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8749        let Expr::InterpolatedString(parts) = expr else {
8750            unreachable!()
8751        };
8752        let mut result = String::new();
8753        for part in parts {
8754            match part {
8755                crate::ast::stmt::StringPart::Literal(sym) => {
8756                    result.push_str(self.ctx.interner.resolve(*sym));
8757                }
8758                crate::ast::stmt::StringPart::Expr {
8759                    value,
8760                    format_spec,
8761                    debug,
8762                } => {
8763                    let val = self.evaluate_expr_sync(value)?;
8764                    if *debug {
8765                        let prefix = match value {
8766                            Expr::Identifier(sym) => self.ctx.interner.resolve(*sym).to_string(),
8767                            _ => "expr".to_string(),
8768                        };
8769                        result.push_str(&prefix);
8770                        result.push('=');
8771                    }
8772                    if let Some(spec_sym) = format_spec {
8773                        let spec = self.ctx.interner.resolve(*spec_sym);
8774                        result.push_str(&apply_format_spec(&val, spec));
8775                    } else {
8776                        result.push_str(&val.to_display_string());
8777                    }
8778                }
8779            }
8780        }
8781        Ok(RuntimeValue::Text(Rc::new(result)))
8782    }
8783
8784    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8785    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8786    /// recursion level — and one LOGOS call costs several of these frames.
8787    #[inline(never)]
8788    fn eval_new_variant(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8789        let Expr::NewVariant {
8790            enum_name,
8791            variant,
8792            fields,
8793        } = expr
8794        else {
8795            unreachable!()
8796        };
8797        let inductive_type = self.ctx.interner.resolve(*enum_name).to_string();
8798        let constructor = self.ctx.interner.resolve(*variant).to_string();
8799
8800        // See the async `Expr::NewVariant` arm's own comment: construction is written
8801        // field-name-first and order-independent, but `Inductive` stores its payload
8802        // positionally — re-seat each evaluated value at its DECLARED index, not its
8803        // WRITTEN one. Keyed by `(enum_name, variant)` — see `variant_fields`'s own doc
8804        // comment for why the variant name alone is not a safe key.
8805        let declared = self
8806            .ctx
8807            .variant_fields
8808            .get(&(*enum_name, *variant))
8809            .cloned();
8810        let args = match &declared {
8811            Some(names) => {
8812                let mut slots: Vec<Option<RuntimeValue>> = (0..names.len()).map(|_| None).collect();
8813                for (field_name, field_expr) in fields {
8814                    let field_val = self.evaluate_expr_sync(field_expr)?;
8815                    if let Some(pos) = names.iter().position(|n| n == field_name) {
8816                        slots[pos] = Some(field_val);
8817                    }
8818                }
8819                slots
8820                    .into_iter()
8821                    .map(|v| v.unwrap_or(RuntimeValue::Nothing))
8822                    .collect()
8823            }
8824            None => {
8825                let mut args = Vec::with_capacity(fields.len());
8826                for (_, field_expr) in fields {
8827                    args.push(self.evaluate_expr_sync(field_expr)?);
8828                }
8829                args
8830            }
8831        };
8832
8833        Ok(RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
8834            inductive_type,
8835            constructor,
8836            args,
8837        })))
8838    }
8839
8840    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8841    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8842    /// recursion level — and one LOGOS call costs several of these frames.
8843    #[inline(never)]
8844    fn eval_new(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8845        let Expr::New {
8846            type_name,
8847            init_fields,
8848            ..
8849        } = expr
8850        else {
8851            unreachable!()
8852        };
8853        let name = self.ctx.interner.resolve(*type_name).to_string();
8854
8855        if name == "Seq" || name == "List" {
8856            return Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(
8857                Vec::new(),
8858            )))));
8859        }
8860
8861        if name == "Set" || name == "HashSet" {
8862            return Ok(RuntimeValue::Set(Rc::new(RefCell::new(vec![]))));
8863        }
8864
8865        if name == "Map" || name == "HashMap" {
8866            return Ok(RuntimeValue::Map(Rc::new(RefCell::new(
8867                MapStorage::default(),
8868            ))));
8869        }
8870
8871        let mut fields = HashMap::new();
8872        for (field_sym, field_expr) in init_fields {
8873            let field_name = self.ctx.interner.resolve(*field_sym).to_string();
8874            let field_val = self.evaluate_expr_sync(field_expr)?;
8875            fields.insert(field_name, field_val);
8876        }
8877
8878        if let Some(def) = self.ctx.struct_defs.get(type_name) {
8879            for (field_sym, type_sym, _) in def {
8880                let field_name = self.ctx.interner.resolve(*field_sym).to_string();
8881                if !fields.contains_key(&field_name) {
8882                    let type_name_str = self.ctx.interner.resolve(*type_sym).to_string();
8883                    let default = default_for_declared_type(type_name_str.as_str());
8884                    fields.insert(field_name, default);
8885                }
8886            }
8887        }
8888
8889        Ok(RuntimeValue::Struct(Box::new(StructValue {
8890            type_name: name,
8891            fields,
8892        })))
8893    }
8894
8895    /// One arm of the walker above, in a frame of its own: in a debug build every arm's
8896    /// locals share the enclosing frame, so the widest arms set the stack cost of EVERY
8897    /// recursion level — and one LOGOS call costs several of these frames.
8898    #[inline(never)]
8899    fn eval_binary_op(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8900        let Expr::BinaryOp { op, left, right } = expr else {
8901            unreachable!()
8902        };
8903        match op {
8904            BinaryOpKind::And => {
8905                let left_val = self.evaluate_expr_sync(left)?;
8906                if !left_val.decided_truth()? {
8907                    return Ok(RuntimeValue::Bool(false));
8908                }
8909                let right_val = self.evaluate_expr_sync(right)?;
8910                Ok(RuntimeValue::Bool(right_val.decided_truth()?))
8911            }
8912            BinaryOpKind::Or => {
8913                let left_val = self.evaluate_expr_sync(left)?;
8914                if left_val.decided_truth()? {
8915                    return Ok(RuntimeValue::Bool(true));
8916                }
8917                let right_val = self.evaluate_expr_sync(right)?;
8918                Ok(RuntimeValue::Bool(right_val.decided_truth()?))
8919            }
8920            _ => {
8921                let left_val = self.evaluate_expr_sync(left)?;
8922                let right_val = self.evaluate_expr_sync(right)?;
8923                self.apply_binary_op(*op, left_val, right_val)
8924            }
8925        }
8926    }
8927
8928    /// If `expr` is a direct self-tail-call — `self(args)` of the function the
8929    /// SYNC path is currently executing, with matching arity and not inside a
8930    /// `Repeat` — return its argument expressions for `call_function_sync` to
8931    /// evaluate and loop on. `None` leaves the `Return` an ordinary one.
8932    fn self_tail_call_args_sync(&self, expr: &'a Expr<'a>) -> Option<&'a [&'a Expr<'a>]> {
8933        if self.task.repeat_depth_sync != 0 {
8934            return None;
8935        }
8936        let cur = self.task.tco_fn_sync?;
8937        let param_count = self.ctx.functions.get(&cur)?.params.len();
8938        crate::tail_call::direct_self_tail_args(expr, cur, param_count)
8939    }
8940
8941    /// ASYNC twin of [`Self::self_tail_call_args_sync`].
8942    fn self_tail_call_args_async(&self, expr: &'a Expr<'a>) -> Option<&'a [&'a Expr<'a>]> {
8943        if self.task.repeat_depth_async != 0 {
8944            return None;
8945        }
8946        let cur = self.task.tco_fn_async?;
8947        let param_count = self.ctx.functions.get(&cur)?.params.len();
8948        crate::tail_call::direct_self_tail_args(expr, cur, param_count)
8949    }
8950
8951    fn call_function_sync(
8952        &mut self,
8953        function: Symbol,
8954        args: &[&Expr<'a>],
8955    ) -> Result<RuntimeValue, String> {
8956        // Built-in functions — Symbol comparison (integer) instead of string matching
8957        let func_sym = Some(function);
8958        if self.declares(function) {
8959            // The program's own function: resolved below, ahead of every builtin and intercept.
8960        } else if func_sym == self.ctx.sym_show {
8961            for arg in args {
8962                let val = self.evaluate_expr_sync(arg)?;
8963                self.emit_output(val.to_display_string());
8964            }
8965            return Ok(RuntimeValue::Nothing);
8966        } else if func_sym == self.ctx.sym_args {
8967            // `args()` system native: the stored argv as a `Seq of Text`,
8968            // mirroring the compiled binary's `env::args()`. Must match the
8969            // async path AND the VM (the shadow oracle asserts VM ≡ tree-walker).
8970            let items: Vec<RuntimeValue> = self
8971                .ctx
8972                .program_args
8973                .iter()
8974                .map(|s| RuntimeValue::Text(Rc::new(s.clone())))
8975                .collect();
8976            return Ok(RuntimeValue::List(Rc::new(RefCell::new(
8977                ListRepr::from_values(items),
8978            ))));
8979        } else if self.pbkdf2_accel(function, args.len()) {
8980            // Byte-identical native PBKDF2-HMAC-SHA256 — same rationale as the
8981            // async twin (crypto_accel is the FIPS/RFC-locked reference; the pure
8982            // Hi() loop is too slow to interpret).
8983            let pw = self.evaluate_expr_sync(&args[0])?;
8984            let salt = self.evaluate_expr_sync(&args[1])?;
8985            let iters = self.evaluate_expr_sync(&args[2])?;
8986            let (pw, salt, iters) = crate::semantics::builtins::pbkdf2_arguments(&pw, &salt, &iters)?;
8987            let dk = crate::crypto_accel::pbkdf2_sha256(&pw, &salt, iters);
8988            return Ok(crate::semantics::builtins::bytes_to_seq(&dk));
8989        } else if let Some(kernel) = self.native_kernel(function, args.len()) {
8990            // A standard-library native kernel — the same seam as the async twin.
8991            let mut vals = Vec::with_capacity(args.len());
8992            for arg in args {
8993                vals.push(self.evaluate_expr_sync(arg)?);
8994            }
8995            return kernel.call(&vals);
8996        } else if let Some(id) = self.system_native_id(function, args.len()) {
8997            // The system natives — the same shared builtin seam as the async twin and the VM's
8998            // `CallBuiltin` (must match exactly).
8999            let mut vals = Vec::with_capacity(args.len());
9000            for arg in args {
9001                vals.push(self.evaluate_expr_sync(arg)?);
9002            }
9003            return crate::semantics::builtins::call_builtin(id, vals);
9004        } else if self.sleep_native(function, args.len()) {
9005            let val = self.evaluate_expr_sync(&args[0])?;
9006            self.sleep_for_sync(val)?;
9007            return Ok(RuntimeValue::Nothing);
9008        } else if self.tcp_native_op(function, args.len()).is_some() {
9009            // Sockets suspend — a tcp program routes to the async twin via
9010            // `needs_async`; reaching here is a routing bug, surfaced loudly.
9011            return Err(format!(
9012                "{} (tcp) requires the async interpreter path",
9013                self.ctx.interner.resolve(function)
9014            ));
9015        } else if let Some(id) = self.builtin_id(function) {
9016            // Arity is checked BEFORE evaluating arguments (kernel rule).
9017            crate::semantics::builtins::check_arity(id, args.len())?;
9018            // `format` reads only its first argument; preserve its laziness.
9019            let vals = if id == crate::semantics::builtins::BuiltinId::Format {
9020                match args.first() {
9021                    Some(a) => vec![self.evaluate_expr_sync(a)?],
9022                    None => Vec::new(),
9023                }
9024            } else {
9025                let mut v = Vec::with_capacity(args.len());
9026                for arg in args {
9027                    v.push(self.evaluate_expr_sync(arg)?);
9028                }
9029                v
9030            };
9031            if id == crate::semantics::builtins::BuiltinId::DefinedReal {
9032                return self.open_defined_run().define(vals);
9033            }
9034            return crate::semantics::builtins::call_builtin(id, vals);
9035        }
9036
9037        if let Some(refusal) = self.native_refusal(function) {
9038            return Err(refusal);
9039        }
9040
9041        // User-defined function lookup — extract metadata without cloning params
9042        if let Some(func) = self.ctx.functions.get(&function) {
9043            let param_count = func.params.len();
9044            let body = func.body;
9045
9046            if args.len() != param_count {
9047                return Err(format!(
9048                    "Function {} expects {} arguments, got {}",
9049                    self.ctx.interner.resolve(function),
9050                    param_count,
9051                    args.len()
9052                ));
9053            }
9054
9055            let mut arg_values = Vec::with_capacity(param_count);
9056            let mut lent: Vec<(usize, Place)> = Vec::new();
9057            for (i, arg) in args.iter().enumerate() {
9058                if matches!(
9059                    self.ctx.functions[&function].params[i].1,
9060                    TypeExpr::Mutable { .. }
9061                ) {
9062                    let place = match self.place_sync(arg) {
9063                        Ok(place) => place,
9064                        Err(e) => {
9065                            let values = self.values_to_give_back(&lent, &mut arg_values);
9066                            self.give_back(lent, values);
9067                            return Err(e);
9068                        }
9069                    };
9070                    if let Some(value) = place.as_ref().and_then(|place| self.lend(place)) {
9071                        arg_values.push(value);
9072                        lent.push((i, place.expect("a lent argument names a place")));
9073                        continue;
9074                    }
9075                }
9076                match self.evaluate_expr_sync(arg) {
9077                    Ok(v) => arg_values.push(v),
9078                    Err(e) => {
9079                        let values = self.values_to_give_back(&lent, &mut arg_values);
9080                        self.give_back(lent, values);
9081                        return Err(e);
9082                    }
9083                }
9084            }
9085
9086            if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
9087                let values = self.values_to_give_back(&lent, &mut arg_values);
9088                self.give_back(lent, values);
9089                return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
9090            }
9091            self.task.call_depth += 1;
9092            self.task.env.push_frame();
9093            for i in 0..param_count {
9094                let param_name = self.ctx.functions[&function].params[i].0;
9095                self.task.env.define(
9096                    param_name,
9097                    std::mem::replace(&mut arg_values[i], RuntimeValue::Nothing),
9098                );
9099            }
9100
9101            // TCO: while executing THIS function's body, a self-tail-call is a
9102            // loop-back (reassign params + restart the body) rather than a real
9103            // recursive call. `tco_fn_sync`/`repeat_depth_sync` are per-activation,
9104            // so save the caller's and reset for this body.
9105            let prev_tco = self.task.tco_fn_sync.replace(function);
9106            let prev_repeat = std::mem::replace(&mut self.task.repeat_depth_sync, 0);
9107            let mut return_value = RuntimeValue::Nothing;
9108            let mut body_err = None;
9109            'tco: loop {
9110                self.task.pending_tail_call = None;
9111                let mut idx = 0;
9112                while idx < body.len() {
9113                    // Top-level `Set/Let x to self(args); Return x` pair — a tail
9114                    // call. (A direct `Return self(args)` at any depth is caught
9115                    // in execute_stmt_sync's Return arm.)
9116                    if idx + 1 < body.len() {
9117                        if let Some(call_args) = crate::tail_call::tail_pair_args(
9118                            &body[idx],
9119                            &body[idx + 1],
9120                            function,
9121                            param_count,
9122                        ) {
9123                            let mut vals = Vec::with_capacity(call_args.len());
9124                            let mut perr = None;
9125                            for a in call_args {
9126                                match self.evaluate_expr_sync(a) {
9127                                    Ok(v) => vals.push(v),
9128                                    Err(e) => {
9129                                        perr = Some(e);
9130                                        break;
9131                                    }
9132                                }
9133                            }
9134                            match perr {
9135                                Some(e) => body_err = Some(e),
9136                                None => self.task.pending_tail_call = Some(vals),
9137                            }
9138                            break;
9139                        }
9140                    }
9141                    match self.execute_stmt_sync(&body[idx]) {
9142                        Ok(ControlFlow::Return(val)) => {
9143                            return_value = val;
9144                            break;
9145                        }
9146                        Ok(ControlFlow::Break) => break,
9147                        Ok(ControlFlow::Continue) => {}
9148                        Err(e) => {
9149                            body_err = Some(e);
9150                            break;
9151                        }
9152                    }
9153                    idx += 1;
9154                }
9155                if body_err.is_some() {
9156                    break 'tco;
9157                }
9158                match self.task.pending_tail_call.take() {
9159                    Some(new_args) => {
9160                        // Loop-back: a fresh frame (no stale locals) with the
9161                        // reassigned parameters — constant stack, no depth bump.
9162                        self.task.env.pop_frame();
9163                        self.task.env.push_frame();
9164                        for (i, v) in new_args.into_iter().enumerate() {
9165                            let param_name = self.ctx.functions[&function].params[i].0;
9166                            self.task.env.define(param_name, v);
9167                        }
9168                        continue 'tco;
9169                    }
9170                    None => break 'tco,
9171                }
9172            }
9173            self.task.repeat_depth_sync = prev_repeat;
9174            self.task.tco_fn_sync = prev_tco;
9175
9176            let returned = self.lent_values(function, &lent);
9177            self.task.env.pop_frame();
9178            self.give_back(lent, returned);
9179            self.task.call_depth -= 1;
9180            match body_err {
9181                Some(e) => Err(e),
9182                None => Ok(self.coerce_record_return(return_value, function)),
9183            }
9184        } else {
9185            // Fallback: check if the function name is a variable holding a closure
9186            let maybe_closure = self.task.env.lookup(function).and_then(|v| {
9187                if let RuntimeValue::Function(c) = v {
9188                    Some((**c).clone())
9189                } else {
9190                    None
9191                }
9192            });
9193
9194            if let Some(closure) = maybe_closure {
9195                let mut arg_values = Vec::with_capacity(args.len());
9196                for arg in args {
9197                    arg_values.push(self.evaluate_expr_sync(arg)?);
9198                }
9199                self.call_closure_value_sync(&closure, arg_values)
9200            } else {
9201                Err(format!(
9202                    "Unknown function: {}",
9203                    self.ctx.interner.resolve(function)
9204                ))
9205            }
9206        }
9207    }
9208
9209    fn call_function_with_values_sync(
9210        &mut self,
9211        function: Symbol,
9212        mut args: Vec<RuntimeValue>,
9213    ) -> Result<RuntimeValue, String> {
9214        // Handle built-in "show" via Symbol comparison
9215        if Some(function) == self.ctx.sym_show {
9216            for val in args {
9217                self.emit_output(val.to_display_string());
9218            }
9219            return Ok(RuntimeValue::Nothing);
9220        }
9221        if let Some(id) = self.system_native_id(function, args.len()) {
9222            return crate::semantics::builtins::call_builtin(id, args);
9223        }
9224        if let Some(kernel) = self.native_kernel(function, args.len()) {
9225            return kernel.call(&args);
9226        }
9227        if self.sleep_native(function, args.len()) {
9228            self.sleep_for_sync(args.remove(0))?;
9229            return Ok(RuntimeValue::Nothing);
9230        }
9231        if let Some(refusal) = self.native_refusal(function) {
9232            return Err(refusal);
9233        }
9234
9235        if let Some(func) = self.ctx.functions.get(&function) {
9236            let param_count = func.params.len();
9237            let body = func.body;
9238
9239            if args.len() != param_count {
9240                return Err(format!(
9241                    "Function {} expects {} arguments, got {}",
9242                    self.ctx.interner.resolve(function),
9243                    param_count,
9244                    args.len()
9245                ));
9246            }
9247
9248            if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
9249                return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
9250            }
9251            self.task.call_depth += 1;
9252            self.task.env.push_frame();
9253            for i in 0..param_count {
9254                let param_name = self.ctx.functions[&function].params[i].0;
9255                self.task.env.define(
9256                    param_name,
9257                    std::mem::replace(&mut args[i], RuntimeValue::Nothing),
9258                );
9259            }
9260
9261            // TCO: while executing THIS function's body, a self-tail-call is a
9262            // loop-back (reassign params + restart the body) rather than a real
9263            // recursive call. `tco_fn_sync`/`repeat_depth_sync` are per-activation,
9264            // so save the caller's and reset for this body.
9265            let prev_tco = self.task.tco_fn_sync.replace(function);
9266            let prev_repeat = std::mem::replace(&mut self.task.repeat_depth_sync, 0);
9267            let mut return_value = RuntimeValue::Nothing;
9268            let mut body_err = None;
9269            'tco: loop {
9270                self.task.pending_tail_call = None;
9271                let mut idx = 0;
9272                while idx < body.len() {
9273                    // Top-level `Set/Let x to self(args); Return x` pair — a tail
9274                    // call. (A direct `Return self(args)` at any depth is caught
9275                    // in execute_stmt_sync's Return arm.)
9276                    if idx + 1 < body.len() {
9277                        if let Some(call_args) = crate::tail_call::tail_pair_args(
9278                            &body[idx],
9279                            &body[idx + 1],
9280                            function,
9281                            param_count,
9282                        ) {
9283                            let mut vals = Vec::with_capacity(call_args.len());
9284                            let mut perr = None;
9285                            for a in call_args {
9286                                match self.evaluate_expr_sync(a) {
9287                                    Ok(v) => vals.push(v),
9288                                    Err(e) => {
9289                                        perr = Some(e);
9290                                        break;
9291                                    }
9292                                }
9293                            }
9294                            match perr {
9295                                Some(e) => body_err = Some(e),
9296                                None => self.task.pending_tail_call = Some(vals),
9297                            }
9298                            break;
9299                        }
9300                    }
9301                    match self.execute_stmt_sync(&body[idx]) {
9302                        Ok(ControlFlow::Return(val)) => {
9303                            return_value = val;
9304                            break;
9305                        }
9306                        Ok(ControlFlow::Break) => break,
9307                        Ok(ControlFlow::Continue) => {}
9308                        Err(e) => {
9309                            body_err = Some(e);
9310                            break;
9311                        }
9312                    }
9313                    idx += 1;
9314                }
9315                if body_err.is_some() {
9316                    break 'tco;
9317                }
9318                match self.task.pending_tail_call.take() {
9319                    Some(new_args) => {
9320                        // Loop-back: a fresh frame (no stale locals) with the
9321                        // reassigned parameters — constant stack, no depth bump.
9322                        self.task.env.pop_frame();
9323                        self.task.env.push_frame();
9324                        for (i, v) in new_args.into_iter().enumerate() {
9325                            let param_name = self.ctx.functions[&function].params[i].0;
9326                            self.task.env.define(param_name, v);
9327                        }
9328                        continue 'tco;
9329                    }
9330                    None => break 'tco,
9331                }
9332            }
9333            self.task.repeat_depth_sync = prev_repeat;
9334            self.task.tco_fn_sync = prev_tco;
9335
9336            self.task.env.pop_frame();
9337            self.task.call_depth -= 1;
9338            match body_err {
9339                Some(e) => Err(e),
9340                None => Ok(self.coerce_record_return(return_value, function)),
9341            }
9342        } else {
9343            let maybe_closure = self.task.env.lookup(function).and_then(|v| {
9344                if let RuntimeValue::Function(c) = v {
9345                    Some((**c).clone())
9346                } else {
9347                    None
9348                }
9349            });
9350
9351            if let Some(closure) = maybe_closure {
9352                self.call_closure_value_sync(&closure, args)
9353            } else {
9354                Err(format!(
9355                    "Unknown function: {}",
9356                    self.ctx.interner.resolve(function)
9357                ))
9358            }
9359        }
9360    }
9361
9362    // =========================================================================
9363    // Closure support: free variable collection and closure invocation
9364    // =========================================================================
9365
9366    /// Collect free variable symbols from a closure body.
9367    /// Returns all Identifier symbols referenced in the body that are not parameter names.
9368    /// Shared with the bytecode VM's compiler — both engines MUST agree on the
9369    /// capture set, so there is exactly one implementation.
9370    pub(crate) fn collect_free_vars_in_closure(
9371        &self,
9372        params: &[(Symbol, &TypeExpr<'a>)],
9373        body: &ClosureBody<'a>,
9374    ) -> Vec<Symbol> {
9375        Self::free_vars_in_closure(params, body)
9376    }
9377
9378    /// Static form of [`Self::collect_free_vars_in_closure`] (the VM compiler
9379    /// has no interpreter instance).
9380    pub(crate) fn free_vars_in_closure(
9381        params: &[(Symbol, &TypeExpr<'a>)],
9382        body: &ClosureBody<'a>,
9383    ) -> Vec<Symbol> {
9384        let param_set: std::collections::HashSet<Symbol> = params.iter().map(|(s, _)| *s).collect();
9385        let mut out = Vec::new();
9386        let mut seen = std::collections::HashSet::new();
9387
9388        match body {
9389            ClosureBody::Expression(expr) => {
9390                Self::collect_symbols_from_expr(expr, &param_set, &mut out, &mut seen);
9391            }
9392            ClosureBody::Block(block) => {
9393                Self::collect_symbols_from_block(block, &param_set, &mut out, &mut seen);
9394            }
9395        }
9396
9397        out
9398    }
9399
9400    fn collect_symbols_from_expr(
9401        expr: &Expr<'a>,
9402        exclude: &std::collections::HashSet<Symbol>,
9403        out: &mut Vec<Symbol>,
9404        seen: &mut std::collections::HashSet<Symbol>,
9405    ) {
9406        match expr {
9407            Expr::Dom(q) => {
9408                if let Some(sel) = q.selector() {
9409                    Self::collect_symbols_from_expr(sel, exclude, out, seen);
9410                }
9411            }
9412            Expr::View(v) => {
9413                let (view_exprs, view_blocks) = v.exprs_and_blocks();
9414                for e in view_exprs {
9415                    Self::collect_symbols_from_expr(e, exclude, out, seen);
9416                }
9417                let _ = &view_blocks;
9418            }
9419            Expr::Identifier(sym) => {
9420                if !exclude.contains(sym) && seen.insert(*sym) {
9421                    out.push(*sym);
9422                }
9423            }
9424            Expr::Literal(_) | Expr::OptionNone | Expr::Escape { .. } => {}
9425            Expr::BinaryOp { left, right, .. } => {
9426                Self::collect_symbols_from_expr(left, exclude, out, seen);
9427                Self::collect_symbols_from_expr(right, exclude, out, seen);
9428            }
9429            Expr::Call { function, args } => {
9430                if !exclude.contains(function) && seen.insert(*function) {
9431                    out.push(*function);
9432                }
9433                for arg in args {
9434                    Self::collect_symbols_from_expr(arg, exclude, out, seen);
9435                }
9436            }
9437            Expr::FieldAccess { object, .. } => {
9438                Self::collect_symbols_from_expr(object, exclude, out, seen);
9439            }
9440            Expr::Index { collection, index } => {
9441                Self::collect_symbols_from_expr(collection, exclude, out, seen);
9442                Self::collect_symbols_from_expr(index, exclude, out, seen);
9443            }
9444            Expr::Slice {
9445                collection,
9446                start,
9447                end,
9448            } => {
9449                Self::collect_symbols_from_expr(collection, exclude, out, seen);
9450                Self::collect_symbols_from_expr(start, exclude, out, seen);
9451                Self::collect_symbols_from_expr(end, exclude, out, seen);
9452            }
9453            Expr::Copy { expr: e }
9454            | Expr::Give { value: e }
9455            | Expr::Length { collection: e }
9456            | Expr::Not { operand: e } => {
9457                Self::collect_symbols_from_expr(e, exclude, out, seen);
9458            }
9459            Expr::List(items) | Expr::Tuple(items) => {
9460                for item in items {
9461                    Self::collect_symbols_from_expr(item, exclude, out, seen);
9462                }
9463            }
9464            Expr::Range { start, end } => {
9465                Self::collect_symbols_from_expr(start, exclude, out, seen);
9466                Self::collect_symbols_from_expr(end, exclude, out, seen);
9467            }
9468            Expr::New { init_fields, .. } => {
9469                for (_, e) in init_fields {
9470                    Self::collect_symbols_from_expr(e, exclude, out, seen);
9471                }
9472            }
9473            Expr::NewVariant { fields, .. } => {
9474                for (_, e) in fields {
9475                    Self::collect_symbols_from_expr(e, exclude, out, seen);
9476                }
9477            }
9478            Expr::Contains { collection, value }
9479            | Expr::Union {
9480                left: collection,
9481                right: value,
9482            }
9483            | Expr::Intersection {
9484                left: collection,
9485                right: value,
9486            } => {
9487                Self::collect_symbols_from_expr(collection, exclude, out, seen);
9488                Self::collect_symbols_from_expr(value, exclude, out, seen);
9489            }
9490            Expr::ManifestOf { zone } | Expr::OptionSome { value: zone } => {
9491                Self::collect_symbols_from_expr(zone, exclude, out, seen);
9492            }
9493            Expr::ChunkAt { index, zone }
9494            | Expr::WithCapacity {
9495                value: index,
9496                capacity: zone,
9497            } => {
9498                Self::collect_symbols_from_expr(index, exclude, out, seen);
9499                Self::collect_symbols_from_expr(zone, exclude, out, seen);
9500            }
9501            Expr::Closure {
9502                params: inner_params,
9503                body: inner_body,
9504                ..
9505            } => {
9506                // Nested closure: exclude inner params too
9507                let mut inner_exclude = exclude.clone();
9508                for (s, _) in inner_params {
9509                    inner_exclude.insert(*s);
9510                }
9511                match inner_body {
9512                    ClosureBody::Expression(e) => {
9513                        Self::collect_symbols_from_expr(e, &inner_exclude, out, seen);
9514                    }
9515                    ClosureBody::Block(b) => {
9516                        Self::collect_symbols_from_block(b, &inner_exclude, out, seen);
9517                    }
9518                }
9519            }
9520            Expr::CallExpr { callee, args } => {
9521                Self::collect_symbols_from_expr(callee, exclude, out, seen);
9522                for arg in args {
9523                    Self::collect_symbols_from_expr(arg, exclude, out, seen);
9524                }
9525            }
9526            Expr::InterpolatedString(parts) => {
9527                for part in parts {
9528                    if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
9529                        Self::collect_symbols_from_expr(value, exclude, out, seen);
9530                    }
9531                }
9532            }
9533        }
9534    }
9535
9536    fn collect_symbols_from_block(
9537        stmts: &[Stmt<'a>],
9538        exclude: &std::collections::HashSet<Symbol>,
9539        out: &mut Vec<Symbol>,
9540        seen: &mut std::collections::HashSet<Symbol>,
9541    ) {
9542        use crate::ast::stmt::Pattern;
9543        // `bound` = params + the locals introduced so far in THIS block's scope.
9544        // A `Let` (or `Repeat`/`Inspect` pattern) binding excludes later uses of
9545        // that name from the FREE-variable set — without this a function's own
9546        // local that happens to share a name with a Main top-level variable would
9547        // leak as "free", over-promoting that Main var to a global and blocking
9548        // the JIT from tiering Main's hot loops. Nested blocks clone `bound`, so a
9549        // binding never leaks to a sibling block or past its scope.
9550        let mut bound = exclude.clone();
9551        for stmt in stmts {
9552            match stmt {
9553                Stmt::Let { var, value, .. } => {
9554                    Self::collect_symbols_from_expr(value, &bound, out, seen);
9555                    bound.insert(*var);
9556                }
9557                Stmt::Set { target, value } => {
9558                    Self::collect_symbols_from_expr(value, &bound, out, seen);
9559                    // The TARGET is a reference too. Everything else here reaches a name
9560                    // through an expression, and a `Set`'s target is the one name that arrives
9561                    // as a bare symbol — so leaving it out made a body whose ONLY use of an
9562                    // outer name was a write look like a body that never mentioned it. The VM
9563                    // promotes a Main binding to a global slot exactly when this walk names it,
9564                    // so the write then had nowhere to land ("Undefined variable" at the store).
9565                    if !bound.contains(target) && seen.insert(*target) {
9566                        out.push(*target);
9567                    }
9568                }
9569                Stmt::Call { function, args } => {
9570                    if !bound.contains(function) && seen.insert(*function) {
9571                        out.push(*function);
9572                    }
9573                    for arg in args {
9574                        Self::collect_symbols_from_expr(arg, &bound, out, seen);
9575                    }
9576                }
9577                Stmt::Return { value: Some(e) } => {
9578                    Self::collect_symbols_from_expr(e, &bound, out, seen);
9579                }
9580                Stmt::If {
9581                    cond,
9582                    then_block,
9583                    else_block,
9584                } => {
9585                    Self::collect_symbols_from_expr(cond, &bound, out, seen);
9586                    Self::collect_symbols_from_block(then_block, &bound, out, seen);
9587                    if let Some(eb) = else_block {
9588                        Self::collect_symbols_from_block(eb, &bound, out, seen);
9589                    }
9590                }
9591                Stmt::While { cond, body, .. } => {
9592                    Self::collect_symbols_from_expr(cond, &bound, out, seen);
9593                    Self::collect_symbols_from_block(body, &bound, out, seen);
9594                }
9595                Stmt::Repeat {
9596                    pattern,
9597                    iterable,
9598                    body,
9599                } => {
9600                    Self::collect_symbols_from_expr(iterable, &bound, out, seen);
9601                    let mut body_bound = bound.clone();
9602                    match pattern {
9603                        Pattern::Identifier(s) => {
9604                            body_bound.insert(*s);
9605                        }
9606                        Pattern::Tuple(syms) => {
9607                            for s in syms {
9608                                body_bound.insert(*s);
9609                            }
9610                        }
9611                    }
9612                    Self::collect_symbols_from_block(body, &body_bound, out, seen);
9613                }
9614                Stmt::Show { object, .. } | Stmt::Give { object, .. } => {
9615                    Self::collect_symbols_from_expr(object, &bound, out, seen);
9616                }
9617                Stmt::Push { value, collection }
9618                | Stmt::Add { value, collection }
9619                | Stmt::Remove { value, collection } => {
9620                    Self::collect_symbols_from_expr(value, &bound, out, seen);
9621                    Self::collect_symbols_from_expr(collection, &bound, out, seen);
9622                }
9623                Stmt::SetIndex {
9624                    collection,
9625                    index,
9626                    value,
9627                } => {
9628                    Self::collect_symbols_from_expr(collection, &bound, out, seen);
9629                    Self::collect_symbols_from_expr(index, &bound, out, seen);
9630                    Self::collect_symbols_from_expr(value, &bound, out, seen);
9631                }
9632                Stmt::SetField { object, value, .. } => {
9633                    Self::collect_symbols_from_expr(object, &bound, out, seen);
9634                    Self::collect_symbols_from_expr(value, &bound, out, seen);
9635                }
9636                Stmt::RuntimeAssert {
9637                    condition, reason, ..
9638                } => {
9639                    Self::collect_symbols_from_expr(condition, &bound, out, seen);
9640                    if let Some(r) = reason {
9641                        Self::collect_symbols_from_expr(r, &bound, out, seen);
9642                    }
9643                }
9644                Stmt::Fail { reason } => {
9645                    Self::collect_symbols_from_expr(reason, &bound, out, seen);
9646                }
9647                Stmt::Zone { body, .. } => {
9648                    Self::collect_symbols_from_block(body, &bound, out, seen);
9649                }
9650                Stmt::Inspect { target, arms, .. } => {
9651                    Self::collect_symbols_from_expr(target, &bound, out, seen);
9652                    for arm in arms {
9653                        Self::collect_symbols_from_block(arm.body, &bound, out, seen);
9654                    }
9655                }
9656                Stmt::Pop { collection, .. } => {
9657                    Self::collect_symbols_from_expr(collection, &bound, out, seen);
9658                }
9659                _ => {}
9660            }
9661        }
9662    }
9663
9664    /// Run the HTTP server for a `Serve` statement: bind `port`, then serve
9665    /// connections CONCURRENTLY, re-entering the LOGOS handler function with a
9666    /// `Request` value per request and writing back its `Response`.
9667    ///
9668    /// Hosting: the interpreter is normally driven by `futures::executor` (no
9669    /// tokio reactor — the `largo serve`/`largo run` path), so with no runtime
9670    /// current this stands up a current-thread tokio runtime and blocks on the
9671    /// loop; when a runtime IS already current (an async host awaiting
9672    /// `interpret_for_ui`), it serves on that ambient runtime directly.
9673    #[cfg(not(target_arch = "wasm32"))]
9674    async fn serve_http(&mut self, port: u16, handler: Symbol) -> Result<(), String> {
9675        // The ONE deployment/dev-proxy seam: `LOGOS_PORT` (then `PORT`)
9676        // overrides the program's port expression — shared with the AOT tier
9677        // through `env_port_override` so the tiers cannot drift.
9678        let port = logicaffeine_system::http::server::env_port_override(port);
9679        if logicaffeine_system::tokio::runtime::Handle::try_current().is_ok() {
9680            return self.serve_http_concurrent(port, handler).await;
9681        }
9682        let rt = logicaffeine_system::tokio::runtime::Builder::new_current_thread()
9683            .enable_all()
9684            .build()
9685            .map_err(|e| format!("Serve: cannot start async runtime: {e}"))?;
9686        rt.block_on(self.serve_http_concurrent(port, handler))
9687    }
9688
9689    /// The concurrent serve loop. The interpreter is `!Send`, so nothing is
9690    /// spawned: every connection is an OWNED future (socket + buffer inside) in
9691    /// one `FuturesUnordered` driven inline on this thread, overlapped with the
9692    /// accept future by `select!` — a stalled or held-open connection can never
9693    /// head-of-line-block the rest. Handler calls are the only points that
9694    /// touch `&mut self`, so they serialize naturally (one at a time, exactly
9695    /// the single-threaded language model); reads and writes overlap freely.
9696    ///
9697    /// Crash-proofing: a handler failure (runtime error, or a non-`Response`
9698    /// return) answers the shared `internal_error` 500 for THAT request — the
9699    /// detail goes to stderr, never the wire — and the loop keeps serving
9700    /// (`call_function_with_values` unwinds its frame on error, so no state
9701    /// poisons later requests). Keep-alive follows the shared
9702    /// `request_wants_keep_alive` law; a parse error answers 400 and closes;
9703    /// at most `MAX_INFLIGHT` connections are held at once.
9704    #[cfg(not(target_arch = "wasm32"))]
9705    async fn serve_http_concurrent(&mut self, port: u16, handler: Symbol) -> Result<(), String> {
9706        use futures::stream::{FuturesUnordered, StreamExt};
9707        use logicaffeine_system::http::server::{
9708            internal_error, read_error_response, try_upgrade, Conn, Listener, ReadError,
9709            UpgradeHandler,
9710        };
9711        use logicaffeine_system::http::wire::{
9712            request_wants_keep_alive, HttpRequest, HttpResponse,
9713        };
9714        use logicaffeine_system::http::{
9715            service_unavailable, shutdown_requested, Admission, Lifecycle, LifecycleConfig,
9716        };
9717        use std::time::Duration;
9718
9719        /// One connection's next lifecycle event, with the connection handed
9720        /// back so the loop can continue it.
9721        enum Step {
9722            /// The next read attempt finished: a request, or the read error
9723            /// that ends the connection.
9724            Request(Conn, Result<HttpRequest, ReadError>),
9725            /// The connection is done (response written with `close`, write
9726            /// failed, or the peer went away).
9727            Closed,
9728        }
9729        type StepFut = std::pin::Pin<Box<dyn std::future::Future<Output = Step>>>;
9730
9731        /// Read one request under the configured body cap and read deadline.
9732        ///
9733        /// The deadline is the slowloris defense: a peer that connects and then
9734        /// dribbles bytes is dropped rather than holding a connection forever. The
9735        /// cap is what turns an announced-but-enormous body into a defined `413`
9736        /// instead of an allocation.
9737        async fn read_bounded(
9738            conn: &mut Conn,
9739            max_body: usize,
9740            deadline: Duration,
9741        ) -> Option<Result<HttpRequest, ReadError>> {
9742            match logicaffeine_system::tokio::time::timeout(
9743                deadline,
9744                conn.read_request_capped(max_body),
9745            )
9746            .await
9747            {
9748                Ok(read) => Some(read),
9749                Err(_) => None,
9750            }
9751        }
9752
9753        /// A fresh or idle connection: read its next request.
9754        fn read_step(mut conn: Conn, max_body: usize, deadline: Duration) -> StepFut {
9755            Box::pin(async move {
9756                match read_bounded(&mut conn, max_body, deadline).await {
9757                    Some(read) => Step::Request(conn, read),
9758                    None => Step::Closed,
9759                }
9760            })
9761        }
9762
9763        /// Write `resp` with the decided disposition, then (keep-alive) read
9764        /// the connection's next request or (close / write error) finish.
9765        fn write_step(
9766            mut conn: Conn,
9767            resp: HttpResponse,
9768            keep_alive: bool,
9769            max_body: usize,
9770            deadline: Duration,
9771        ) -> StepFut {
9772            Box::pin(async move {
9773                if conn.write_response_conn(&resp, keep_alive).await.is_err() || !keep_alive {
9774                    return Step::Closed;
9775                }
9776                match read_bounded(&mut conn, max_body, deadline).await {
9777                    Some(read) => Step::Request(conn, read),
9778                    None => Step::Closed,
9779                }
9780            })
9781        }
9782
9783        // The SAME lifecycle the compiled tier gets, read from the SAME place, so
9784        // the three tiers cannot drift: readiness, bounded backpressure, the body
9785        // cap, the read deadline, the drain timeout and the optional probe paths.
9786        let lifecycle = Lifecycle::new(LifecycleConfig::from_env());
9787        lifecycle.set_ready(true);
9788        let cfg = lifecycle.config();
9789        let (max_body, read_deadline, max_inflight) =
9790            (cfg.max_body, cfg.read_deadline, cfg.max_inflight);
9791        let (drain_timeout, request_timeout) = (cfg.drain_timeout, cfg.request_timeout);
9792
9793        // The address, not just the port: `LOGOS_HOST` names the interface
9794        // (default loopback) and `env_bind_address` composes it with the port,
9795        // so a deployed binary can be reached from outside its own machine and
9796        // every tier binds the same address from the same environment.
9797        let addr = logicaffeine_system::http::server::env_bind_address(port);
9798        let listener = Listener::bind(&addr)
9799            .await
9800            .map_err(|e| format!("Serve: cannot bind {addr}: {e}"))?;
9801        let bound = listener.local_addr().map_err(|e| format!("Serve: {e}"))?;
9802        // Announced at once on stdout (`announce_serving`, the one announcement every tier
9803        // makes), not pushed into the program's output: the streaming host echoes
9804        // `self.output` as it grows, so pushing it as well would announce the port twice.
9805        logicaffeine_system::http::server::announce_serving(bound);
9806
9807        // A program whose pages talk to the relay answers `/_relay` itself (`analysis::relay`) — the
9808        // same table, and the same `try_upgrade` decision, a compiled backend serves.
9809        let upgrades: std::collections::BTreeMap<String, UpgradeHandler> = if self
9810            .ctx
9811            .components
9812            .values()
9813            .any(crate::analysis::relay::component_uses_the_relay)
9814        {
9815            logicaffeine_system::relay::RelayHub::new()
9816                .upgrades()
9817                .into_iter()
9818                .map(|(path, handler)| (path.to_string(), handler))
9819                .collect()
9820        } else {
9821            std::collections::BTreeMap::new()
9822        };
9823
9824        let shutdown = shutdown_requested();
9825        futures::pin_mut!(shutdown);
9826        let mut draining = false;
9827        let mut inflight: FuturesUnordered<StepFut> = FuturesUnordered::new();
9828        loop {
9829            // A drain ends the loop once the work that was already accepted is
9830            // finished — that is the whole difference between a graceful stop and
9831            // dropping requests on the floor.
9832            if draining && inflight.is_empty() {
9833                return Ok(());
9834            }
9835            logicaffeine_system::tokio::select! {
9836                accepted = listener.accept(), if !draining && inflight.len() < max_inflight => {
9837                    if let Ok(conn) = accepted {
9838                        inflight.push(read_step(conn, max_body, read_deadline));
9839                    }
9840                }
9841                // A stop request: stop advertising readiness so traffic moves away,
9842                // stop accepting, and give the in-flight work its deadline to finish.
9843                _ = &mut shutdown, if !draining => {
9844                    lifecycle.set_ready(false);
9845                    draining = true;
9846                    let _ = logicaffeine_system::tokio::time::timeout(
9847                        drain_timeout,
9848                        std::future::pending::<()>(),
9849                    );
9850                }
9851                Some(step) = inflight.next() => {
9852                    match step {
9853                        Step::Request(conn, Ok(req)) => {
9854                            // An upgrade ends this connection's HTTP life: answered and handed over,
9855                            // or — when its handshake cannot complete — dropped with no response.
9856                            match try_upgrade(&req, &upgrades) {
9857                                Some(Ok((response, handler))) => {
9858                                    inflight.push(Box::pin(async move {
9859                                        conn.upgrade(response, handler).await;
9860                                        Step::Closed
9861                                    }));
9862                                    continue;
9863                                }
9864                                Some(Err(())) => continue,
9865                                None => {}
9866                            }
9867                            let keep_alive = request_wants_keep_alive(&req);
9868                            // A configured probe answers before admission, so a
9869                            // monitor gets a reply during an overload or a drain.
9870                            if let Some(resp) = lifecycle.probe_response(&req.path) {
9871                                inflight.push(write_step(conn, resp, keep_alive, max_body, read_deadline));
9872                                continue;
9873                            }
9874                            // Admission: once draining, or once the slots are full,
9875                            // a request is shed immediately rather than queued into
9876                            // an unbounded wait.
9877                            let guard = match lifecycle.admit() {
9878                                Admission::Admit(g) => g,
9879                                Admission::NotReady | Admission::Overloaded => {
9880                                    inflight.push(write_step(conn, service_unavailable(), false, max_body, read_deadline));
9881                                    continue;
9882                                }
9883                            };
9884                            let request_value = Self::http_request_to_value(&req);
9885                            // Arm this request's wall-clock budget. The handler runs
9886                            // inline on this thread, so the budget is enforced from
9887                            // inside the tree-walker rather than by racing a timer.
9888                            self.request_deadline = Some(std::time::Instant::now() + request_timeout);
9889                            let outcome =
9890                                self.call_function_with_values(handler, vec![request_value]).await;
9891                            self.request_deadline = None;
9892                            let resp = match outcome {
9893                                Ok(value) => match Self::value_to_http_response(&value) {
9894                                    Ok(resp) => resp,
9895                                    Err(e) => {
9896                                        eprintln!("Serve: handler error: {e}");
9897                                        internal_error()
9898                                    }
9899                                },
9900                                // A request that outran its budget is a 503: the work
9901                                // was abandoned, and the peer may retry. Any other
9902                                // failure is the handler's own, and a 500.
9903                                Err(e) if e == crate::interpreter::REQUEST_TIMED_OUT => {
9904                                    eprintln!("Serve: {e}");
9905                                    service_unavailable()
9906                                }
9907                                Err(e) => {
9908                                    eprintln!("Serve: handler error: {e}");
9909                                    internal_error()
9910                                }
9911                            };
9912                            drop(guard);
9913                            lifecycle.notify_slot_freed();
9914                            inflight.push(write_step(conn, resp, keep_alive, max_body, read_deadline));
9915                        }
9916                        Step::Request(conn, Err(ReadError::Parse(ref e))) => {
9917                            // Match the native tier's status law exactly: an oversized
9918                            // body is 413, every other malformed request is 400.
9919                            inflight.push(write_step(conn, read_error_response(e), false, max_body, read_deadline));
9920                        }
9921                        // A clean close or socket error between requests: the
9922                        // connection just ends.
9923                        Step::Request(_, Err(_)) | Step::Closed => {}
9924                    }
9925                }
9926            }
9927        }
9928    }
9929
9930    #[cfg(target_arch = "wasm32")]
9931    async fn serve_http(&mut self, _port: u16, _handler: Symbol) -> Result<(), String> {
9932        Err("`Serve` (HTTP server) is not available in the browser".to_string())
9933    }
9934
9935    /// Build a LOGOS `Request` struct value from a parsed HTTP request. The
9936    /// `headers` map carries the wire parser's lowercased names; `query`
9937    /// carries the percent-decoded parameters. Both are inserted in the wire
9938    /// map's (sorted) order, matching the AOT bridge byte for byte.
9939    #[cfg(not(target_arch = "wasm32"))]
9940    pub(crate) fn http_request_to_value(
9941        req: &logicaffeine_system::http::wire::HttpRequest,
9942    ) -> RuntimeValue {
9943        let text_map = |src: &std::collections::BTreeMap<String, String>| {
9944            let mut m = MapStorage::default();
9945            for (k, v) in src {
9946                m.insert(
9947                    RuntimeValue::Text(Rc::new(k.clone())),
9948                    RuntimeValue::Text(Rc::new(v.clone())),
9949                );
9950            }
9951            RuntimeValue::Map(Rc::new(RefCell::new(m)))
9952        };
9953        let mut fields = HashMap::new();
9954        fields.insert(
9955            "method".to_string(),
9956            RuntimeValue::Text(Rc::new(req.method.clone())),
9957        );
9958        fields.insert(
9959            "path".to_string(),
9960            RuntimeValue::Text(Rc::new(req.path.clone())),
9961        );
9962        fields.insert(
9963            "body".to_string(),
9964            RuntimeValue::Text(Rc::new(String::from_utf8_lossy(&req.body).into_owned())),
9965        );
9966        fields.insert("headers".to_string(), text_map(&req.headers));
9967        fields.insert("query".to_string(), text_map(&req.query));
9968        RuntimeValue::Struct(Box::new(StructValue {
9969            type_name: "Request".to_string(),
9970            fields,
9971        }))
9972    }
9973
9974    /// Read a LOGOS `Response` struct value into an HTTP response to serialize.
9975    #[cfg(not(target_arch = "wasm32"))]
9976    pub(crate) fn value_to_http_response(
9977        value: &RuntimeValue,
9978    ) -> Result<logicaffeine_system::http::wire::HttpResponse, String> {
9979        use logicaffeine_system::http::wire::HttpResponse;
9980        use std::collections::BTreeMap;
9981
9982        let s = match value {
9983            RuntimeValue::Struct(s) => s,
9984            other => {
9985                return Err(format!(
9986                    "Serve: handler must return a Response, got {}",
9987                    other.type_name()
9988                ))
9989            }
9990        };
9991        let status = match s.fields.get("status") {
9992            Some(RuntimeValue::Int(n)) if (100..=599).contains(n) => *n as u16,
9993            Some(RuntimeValue::Int(n)) => {
9994                return Err(format!(
9995                    "Serve: response status {n} is out of range (100-599)"
9996                ))
9997            }
9998            _ => 200,
9999        };
10000        // The `contentType` field is authoritative but must be wire-safe: a
10001        // CR/LF smuggled into it must never split the response (`safe_content_type`
10002        // is the shared law both tiers apply).
10003        let content_type = match s.fields.get("contentType") {
10004            Some(RuntimeValue::Text(t)) => {
10005                logicaffeine_system::http::wire::safe_content_type(t).to_string()
10006            }
10007            _ => "text/plain".to_string(),
10008        };
10009        // A non-empty `bytes` field is a raw binary body (a `.wasm`, an image …) and
10010        // wins over the text `body`; each Int is one byte.
10011        let bytes_body = match s.fields.get("bytes") {
10012            Some(RuntimeValue::List(list)) => {
10013                let l = list.borrow();
10014                (l.len() > 0).then(|| {
10015                    (0..l.len())
10016                        .filter_map(|i| l.get(i))
10017                        .map(|v| match v {
10018                            RuntimeValue::Int(n) => n as u8,
10019                            _ => 0,
10020                        })
10021                        .collect::<Vec<u8>>()
10022                })
10023            }
10024            _ => None,
10025        };
10026        let body = bytes_body.unwrap_or_else(|| match s.fields.get("body") {
10027            Some(RuntimeValue::Text(t)) => t.as_bytes().to_vec(),
10028            Some(other) => other.to_display_string().into_bytes(),
10029            None => Vec::new(),
10030        });
10031        // Merge the Response's `headers` map through the shared denylist +
10032        // response-splitting filter (`response_header_allowed` — one law for
10033        // both tiers), then set the authoritative Content-Type last.
10034        let mut headers = BTreeMap::new();
10035        if let Some(RuntimeValue::Map(m)) = s.fields.get("headers") {
10036            for (k, v) in m.borrow().iter() {
10037                if let (RuntimeValue::Text(name), RuntimeValue::Text(value)) = (k, v) {
10038                    if logicaffeine_system::http::wire::response_header_allowed(name, value) {
10039                        headers.insert(name.to_string(), value.to_string());
10040                    }
10041                }
10042            }
10043        }
10044        headers.insert("Content-Type".to_string(), content_type);
10045        Ok(HttpResponse {
10046            status,
10047            headers,
10048            body,
10049        })
10050    }
10051
10052    /// Execute a closure with pre-evaluated argument values (async).
10053    #[async_recursion(?Send)]
10054    async fn call_closure_value(
10055        &mut self,
10056        closure: &ClosureValue,
10057        mut arg_values: Vec<RuntimeValue>,
10058    ) -> Result<RuntimeValue, String> {
10059        if arg_values.len() != closure.param_names.len() {
10060            return Err(format!(
10061                "Closure expects {} arguments, got {}",
10062                closure.param_names.len(),
10063                arg_values.len()
10064            ));
10065        }
10066
10067        // A SHIPPED generator function carries its body as a sandboxed `GenExpr` (it crossed
10068        // the wire — there is no arena AST to run). Evaluate it directly: total, bounded, no
10069        // frame, no escape. Single-argument arithmetic (the lowerable subset) → an `Int`.
10070        if let Some(expr) = &closure.generated {
10071            let i = match arg_values.first() {
10072                Some(RuntimeValue::Int(n)) => *n,
10073                _ => 0,
10074            };
10075            return Ok(RuntimeValue::Int(crate::concurrency::marshal::gen_eval(
10076                expr, i,
10077            )));
10078        }
10079
10080        // Extract body reference from side-table (breaks borrow on self)
10081        let body_index = closure.body_index;
10082        let is_block = matches!(
10083            self.ctx.closure_bodies.get(body_index),
10084            Some(ClosureBodyRef::Block(_))
10085        );
10086
10087        // A closure body is a fresh frame (lexical barrier): it sees its
10088        // captures, its parameters, and globals — never the caller's locals.
10089        if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
10090            return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
10091        }
10092        self.task.call_depth += 1;
10093        self.task.env.push_frame();
10094
10095        // Bind captured environment
10096        for (sym, val) in &closure.captured_env {
10097            self.task.env.define(*sym, val.deep_clone());
10098        }
10099
10100        // Bind parameters
10101        for (i, param_sym) in closure.param_names.iter().enumerate() {
10102            self.task.env.define(
10103                *param_sym,
10104                std::mem::replace(&mut arg_values[i], RuntimeValue::Nothing),
10105            );
10106        }
10107
10108        let result = if is_block {
10109            let block = match &self.ctx.closure_bodies[body_index] {
10110                ClosureBodyRef::Block(b) => *b,
10111                _ => unreachable!(),
10112            };
10113            let mut outcome = Ok(RuntimeValue::Nothing);
10114            for stmt in block.iter() {
10115                match self.execute_stmt(stmt).await {
10116                    Ok(ControlFlow::Return(val)) => {
10117                        outcome = Ok(val);
10118                        break;
10119                    }
10120                    Ok(ControlFlow::Break) => break,
10121                    Ok(ControlFlow::Continue) => {}
10122                    Err(e) => {
10123                        outcome = Err(e);
10124                        break;
10125                    }
10126                }
10127            }
10128            outcome
10129        } else {
10130            let expr = match &self.ctx.closure_bodies[body_index] {
10131                ClosureBodyRef::Expression(e) => *e,
10132                _ => unreachable!(),
10133            };
10134            self.evaluate_expr(expr).await
10135        };
10136
10137        self.task.env.pop_frame();
10138        self.task.call_depth -= 1;
10139        result
10140    }
10141
10142    /// Open the run real numbers the program defines by a function read their functions in, or hand
10143    /// it an evaluator over the program as it stands now: the closure a real is defined by was built
10144    /// just before, and a child sees the closures its context held when it was made. The evaluator
10145    /// calls a closure in a child interpreter over the same program, which shares nothing with this
10146    /// one but the program and the fuel, so a digit read in the middle of an operation leaves this
10147    /// interpreter's state as it was.
10148    fn open_defined_run(&mut self) -> &crate::semantics::defined::RunScope<'a> {
10149        let child = RefCell::new(Interpreter::evaluation_child(self.ctx.clone(), self.fuel.clone()));
10150        let (ctx, fuel) = (self.ctx.clone(), self.fuel.clone());
10151        let evaluator: crate::semantics::defined::Evaluator<'a> = Rc::new(move |closure, n| {
10152            let RuntimeValue::Function(c) = closure else {
10153                return Err(format!("a real number is defined by a function, got {}", closure.type_name()));
10154            };
10155            let args = vec![RuntimeValue::Int(n)];
10156            match child.try_borrow_mut() {
10157                Ok(mut child) => child.call_closure_value_sync(c, args),
10158                Err(_) => Interpreter::evaluation_child(ctx.clone(), fuel.clone()).call_closure_value_sync(c, args),
10159            }
10160        });
10161        match &self.defined_run {
10162            Some(run) => run.renew(evaluator),
10163            None => self.defined_run = Some(crate::semantics::defined::open_run(evaluator)),
10164        }
10165        self.defined_run.as_ref().expect("the run is open")
10166    }
10167
10168    /// An interpreter over `ctx` that runs one function value and nothing else: no page, no task of
10169    /// the scheduler's, no output anyone reads.
10170    fn evaluation_child(ctx: SharedCtx<'a>, fuel: Option<FuelHandles>) -> Interpreter<'a> {
10171        Interpreter {
10172            ctx,
10173            task: TaskState::new(),
10174            output: Vec::new(),
10175            current_site: None,
10176            yield_state: None,
10177            err_sink: None,
10178            netbox: crate::concurrency::net_inbox::NetInbox::new(),
10179            tcpbox: crate::concurrency::tcp_registry::TcpRegistry::new(),
10180            test_mode: false,
10181            test_failures: Vec::new(),
10182            test_ops: 0,
10183            test_assertions: 0,
10184            test_budget: u64::MAX,
10185            gen_rng: 0,
10186            prove_mode: false,
10187            properties_proven: 0,
10188            fuel,
10189            request_deadline: None,
10190            deadline_tick: 0,
10191            tiers_noop: false,
10192            page: PageSeat::Unseated,
10193            statement_observer: None,
10194            page_main: None,
10195            failed_call_site: None,
10196            defined_run: None,
10197        }
10198    }
10199
10200    /// Execute a closure with pre-evaluated argument values (sync).
10201    fn call_closure_value_sync(
10202        &mut self,
10203        closure: &ClosureValue,
10204        mut arg_values: Vec<RuntimeValue>,
10205    ) -> Result<RuntimeValue, String> {
10206        if arg_values.len() != closure.param_names.len() {
10207            return Err(format!(
10208                "Closure expects {} arguments, got {}",
10209                closure.param_names.len(),
10210                arg_values.len()
10211            ));
10212        }
10213
10214        // A SHIPPED generator function evaluates its sandboxed body directly (see async twin).
10215        if let Some(expr) = &closure.generated {
10216            let i = match arg_values.first() {
10217                Some(RuntimeValue::Int(n)) => *n,
10218                _ => 0,
10219            };
10220            return Ok(RuntimeValue::Int(crate::concurrency::marshal::gen_eval(
10221                expr, i,
10222            )));
10223        }
10224
10225        let body_index = closure.body_index;
10226        let is_block = matches!(
10227            self.ctx.closure_bodies.get(body_index),
10228            Some(ClosureBodyRef::Block(_))
10229        );
10230
10231        // A closure body is a fresh frame (lexical barrier); see the async twin.
10232        if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
10233            return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
10234        }
10235        self.task.call_depth += 1;
10236        self.task.env.push_frame();
10237
10238        for (sym, val) in &closure.captured_env {
10239            self.task.env.define(*sym, val.deep_clone());
10240        }
10241
10242        for (i, param_sym) in closure.param_names.iter().enumerate() {
10243            self.task.env.define(
10244                *param_sym,
10245                std::mem::replace(&mut arg_values[i], RuntimeValue::Nothing),
10246            );
10247        }
10248
10249        let result = if is_block {
10250            let block = match &self.ctx.closure_bodies[body_index] {
10251                ClosureBodyRef::Block(b) => *b,
10252                _ => unreachable!(),
10253            };
10254            let mut outcome = Ok(RuntimeValue::Nothing);
10255            for stmt in block.iter() {
10256                match self.execute_stmt_sync(stmt) {
10257                    Ok(ControlFlow::Return(val)) => {
10258                        outcome = Ok(val);
10259                        break;
10260                    }
10261                    Ok(ControlFlow::Break) => break,
10262                    Ok(ControlFlow::Continue) => {}
10263                    Err(e) => {
10264                        outcome = Err(e);
10265                        break;
10266                    }
10267                }
10268            }
10269            outcome
10270        } else {
10271            let expr = match &self.ctx.closure_bodies[body_index] {
10272                ClosureBodyRef::Expression(e) => *e,
10273                _ => unreachable!(),
10274            };
10275            self.evaluate_expr_sync(expr)
10276        };
10277
10278        self.task.env.pop_frame();
10279        self.task.call_depth -= 1;
10280        result
10281    }
10282}
10283
10284/// The tree-walker as the engine a lowered page runs on ([`crate::page_host::LoweredPage`]'s
10285/// host calls): the page's main has run through [`Interpreter::run_page_main`], and every call
10286/// lands on the globals it built — the same model, the same failure contract and the same refusals
10287/// as the bytecode VM's [`crate::vm::session::Session`]. A call that fails unwinds every frame,
10288/// scope and loop it opened and leaves the page callable.
10289impl<'a> crate::page_host::LoweredCalls for Interpreter<'a> {
10290    fn call(&mut self, name: &str, args: Vec<RuntimeValue>) -> Result<RuntimeValue, String> {
10291        self.require_page_main(&format!("`{name}`"))?;
10292        let function = self
10293            .ctx
10294            .interner
10295            .lookup(name)
10296            .filter(|f| self.ctx.functions.contains_key(f))
10297            .ok_or_else(|| format!("tree-walker: this program has no function `{name}`"))?;
10298        let expected = self.ctx.functions[&function].params.len();
10299        if args.len() != expected {
10300            return Err(format!(
10301                "`{name}` expects {expected} arguments, got {}",
10302                args.len()
10303            ));
10304        }
10305        self.host_call(|me| me.call_function_with_values_sync(function, args))
10306    }
10307
10308    fn call_value(
10309        &mut self,
10310        callee: &RuntimeValue,
10311        args: Vec<RuntimeValue>,
10312    ) -> Result<RuntimeValue, String> {
10313        self.require_page_main("a closure")?;
10314        match callee {
10315            RuntimeValue::Function(closure) => {
10316                self.host_call(|me| me.call_closure_value_sync(closure, args))
10317            }
10318            other => Err(format!("Cannot call value of type {}", other.type_name())),
10319        }
10320    }
10321
10322    fn has(&self, name: &str) -> bool {
10323        self.ctx
10324            .interner
10325            .lookup(name)
10326            .is_some_and(|f| self.ctx.functions.contains_key(&f))
10327    }
10328
10329    /// The page's main run again at the top level, over the globals it builds: every one of them
10330    /// starts over, and a binding the page's main does not make — whatever drives the page bound
10331    /// for itself — is left exactly as it was.
10332    fn reload(&mut self) -> Result<(), String> {
10333        self.require_page_main("a reload")?;
10334        let program = self.page_main.clone().unwrap_or_default();
10335        self.at_top_level(|me| me.host_call(|me| me.run_top_level_sync(&program, false)))
10336    }
10337
10338    fn lines(&self) -> &[String] {
10339        &self.output
10340    }
10341
10342    fn failure_site(&self) -> Option<u32> {
10343        self.failed_call_site
10344    }
10345}
10346
10347/// The stack a tree-walker session runs on.
10348///
10349/// A LOGOS call costs the tree-walker a chain of Rust frames — statement, expression, call, and
10350/// the statement inside it — so the depth every engine promises ([`crate::semantics::
10351/// MAX_CALL_DEPTH`], which the bytecode VM reaches on any thread because its frames live on the
10352/// heap) needs far more stack than the 2 MiB an ordinary thread gets. The reservation is virtual:
10353/// pages are committed only as deep recursion touches them.
10354pub const SESSION_STACK_BYTES: usize = 256 * 1024 * 1024;
10355
10356thread_local! {
10357    /// Whether this thread is a session thread [`on_session_stack`] started.
10358    static ON_SESSION_STACK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
10359}
10360
10361/// A [`PageWorld`] handed between a session's caller and the session's thread.
10362#[cfg(not(target_arch = "wasm32"))]
10363struct WorldHandoff(PageWorld);
10364
10365#[cfg(not(target_arch = "wasm32"))]
10366impl WorldHandoff {
10367    /// The world, arrived — installed as the receiving thread's.
10368    fn arrive(self) {
10369        self.0.restore();
10370    }
10371}
10372
10373// SAFETY: a world holds `Rc`s (a listener's closure, a request's completion), which may share their
10374// counts with values the caller still holds. It crosses threads only in `on_session_stack`, and only
10375// by value — no reference into it crosses: into the session thread as that thread starts, back out
10376// as it finishes, while the caller is parked in the scope's join the whole time. So exactly one
10377// thread ever touches those counts at once, and the spawn and the join order every access on one
10378// side before every access on the other. Nothing inside the session can carry one of those `Rc`s
10379// anywhere else: every other thread takes only `Send` data, which an `Rc` is not, and this is the
10380// one `unsafe` crossing that carries page state (census: `session_world_lock`); whatever the
10381// session still holds when it ends is dropped on its thread before the join returns.
10382#[cfg(not(target_arch = "wasm32"))]
10383unsafe impl Send for WorldHandoff {}
10384
10385/// Run one tree-walker session on a thread whose stack holds the full call depth
10386/// ([`SESSION_STACK_BYTES`]), and hand its result back.
10387///
10388/// ★ THE SESSION RUNS IN ITS CALLER'S WORLD. The page world
10389/// ([`crate::semantics::world::PageWorld`]) moves to the session's thread as the session starts
10390/// and back as it ends, so the session reads what its caller set up
10391/// and its caller reads what the session left — a session on its own stack is the session run in
10392/// place, and nothing reads the world from the wrong thread. A session started inside a session
10393/// runs where it is. A panic inside reaches the caller unchanged, after the world it left.
10394pub fn on_session_stack<R: Send>(session: impl FnOnce() -> R + Send) -> R {
10395    #[cfg(not(target_arch = "wasm32"))]
10396    {
10397        if ON_SESSION_STACK.with(|on| on.get()) {
10398            return session();
10399        }
10400        let world = WorldHandoff(PageWorld::take());
10401        let (ran, world) = std::thread::scope(|scope| {
10402            let worker = std::thread::Builder::new()
10403                .name("logos-session".to_string())
10404                .stack_size(SESSION_STACK_BYTES)
10405                .spawn_scoped(scope, move || {
10406                    ON_SESSION_STACK.with(|on| on.set(true));
10407                    world.arrive();
10408                    let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(session));
10409                    (ran, WorldHandoff(PageWorld::take()))
10410                })
10411                .expect("spawn the tree-walker session thread");
10412            worker
10413                .join()
10414                .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
10415        });
10416        world.arrive();
10417        ran.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
10418    }
10419    #[cfg(target_arch = "wasm32")]
10420    {
10421        session()
10422    }
10423}
10424
10425/// Check whether a program requires async execution.
10426///
10427/// Only 4 statement types need async: ReadFrom (file), WriteFile, Sleep, Mount.
10428/// If none are present, the sync execution path can be used for better performance.
10429fn apply_format_spec(val: &RuntimeValue, spec: &str) -> String {
10430    crate::semantics::format::apply_format_spec(val, spec)
10431}
10432
10433/// A value as a launched task receives it: materialized as it crosses to the task, which may run on a
10434/// worker thread of its own, and rebuilt there — a value that cannot cross refused in the words a
10435/// channel refuses it with, as the VM's spawn does.
10436fn crossing_to_a_task(val: &RuntimeValue) -> Result<RuntimeValue, String> {
10437    let payload =
10438        marshal::materialize(val).map_err(|e| format!("cannot send value through a channel: {:?}", e))?;
10439    Ok(marshal::rebuild(payload))
10440}
10441
10442/// A `Sleep`'s length on the scheduler's logical-tick scale: an Int or a Duration, as written.
10443fn sleep_ticks(val: &RuntimeValue) -> Result<u64, String> {
10444    match val {
10445        RuntimeValue::Int(n) => Ok((*n).max(0) as u64),
10446        RuntimeValue::Duration(d) => Ok((*d).max(0) as u64),
10447        _ => Err(format!(
10448            "Sleep requires Duration or Int, got {}",
10449            val.type_name()
10450        )),
10451    }
10452}
10453
10454/// A `Sleep`'s length in nanoseconds: a Duration as it is, an Int as milliseconds.
10455fn sleep_nanos(val: &RuntimeValue) -> Result<i64, String> {
10456    match val {
10457        RuntimeValue::Duration(nanos) => Ok(*nanos),
10458        RuntimeValue::Int(ms) => Ok(ms.wrapping_mul(1_000_000)),
10459        _ => Err(format!(
10460            "Sleep requires Duration or Int, got {}",
10461            val.type_name()
10462        )),
10463    }
10464}
10465
10466pub fn needs_async(stmts: &[Stmt], interner: &Interner) -> bool {
10467    stmts.iter().any(|s| stmt_needs_async(s, interner))
10468}
10469
10470fn stmt_needs_async(stmt: &Stmt, interner: &Interner) -> bool {
10471    match stmt {
10472        Stmt::ReadFrom { source, .. } => {
10473            matches!(source, ReadSource::File(_))
10474        }
10475        Stmt::WriteFile { .. } | Stmt::Sleep { .. } | Stmt::Mount { .. } => true,
10476        // Networking over the relay is async (dial + subscribe await).
10477        Stmt::Sync { .. } | Stmt::Listen { .. } | Stmt::ConnectTo { .. } => true,
10478        // The HTTP server binds a tokio listener and awaits per-request handling.
10479        Stmt::Serve { .. } => true,
10480        // Peer messaging rides the relay (subscribe/publish/poll) — async only.
10481        Stmt::SendMessage { .. } | Stmt::AwaitMessage { .. } | Stmt::StreamMessage { .. } => true,
10482        // tcp.lg natives block on sockets — async only. The prelude splices tcp.lg
10483        // ONLY when the program references one of its names (declarer-wins fixpoint),
10484        // so the spliced EMPTY-bodied native declaration IS the reference detector.
10485        Stmt::FunctionDef {
10486            name,
10487            is_native: true,
10488            ..
10489        } if matches!(
10490            interner.resolve(*name),
10491            "tcpConnect"
10492                | "tcpSend"
10493                | "tcpRecv"
10494                | "tcpRecvExact"
10495                | "tcpClose"
10496                | "tcpSetTimeout"
10497                | "tcpListen"
10498                | "tcpAccept"
10499                | "tcpListenerPort"
10500                | "tcpShutdownWrite"
10501                | "tcpConnectTls"
10502                | "tcpUpgradeTls"
10503        ) =>
10504        {
10505            true
10506        }
10507        Stmt::If {
10508            then_block,
10509            else_block,
10510            ..
10511        } => {
10512            needs_async(then_block, interner)
10513                || else_block
10514                    .as_ref()
10515                    .map_or(false, |b| needs_async(b, interner))
10516        }
10517        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => needs_async(body, interner),
10518        Stmt::FunctionDef { body, .. } => needs_async(body, interner),
10519        Stmt::Zone { body, .. } => needs_async(body, interner),
10520        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => needs_async(tasks, interner),
10521        Stmt::Inspect { arms, .. } => arms.iter().any(|arm| needs_async(arm.body, interner)),
10522        _ => false,
10523    }
10524}
10525
10526/// Phase 102: Count the number of Pi (function) arguments in a kernel Term.
10527///
10528/// Used to determine constructor arity for inductive types.
10529fn count_pi_args(term: &crate::kernel::Term) -> usize {
10530    use crate::kernel::Term;
10531    match term {
10532        Term::Pi { body_type, .. } => 1 + count_pi_args(body_type),
10533        _ => 0,
10534    }
10535}
10536
10537/// RUN-ONLY tree-walking-interpreter timing — the interpreter analog of [`crate::vm::run_nanos`].
10538/// Executes the SAME statements the register-bytecode VM and the FPGA soft-core run, returning the MIN
10539/// wall-time in nanoseconds over `iters` runs (a fresh `Interpreter` each run, symmetric with `run_nanos`
10540/// building a fresh `Vm`). `Interpreter::new` is light (interned-symbol lookups only, no stdlib-prelude
10541/// load), so this is a clean run-only number — the slowest tier of the cross-tier speed table
10542/// (`benchmarks/silicon/benchmark_timing.json`): tree-walk (this) → bytecode VM (`run_nanos`) → native
10543/// silicon (the on-chip cycle counter).
10544pub fn interp_nanos<'a>(stmts: &[Stmt<'a>], interner: &'a Interner, iters: usize) -> Option<u128> {
10545    {
10546        let mut it = Interpreter::new(interner);
10547        let _ = it.run_sync(stmts); // warm up
10548    }
10549    let mut best = u128::MAX;
10550    for _ in 0..iters {
10551        let mut it = Interpreter::new(interner);
10552        let t = std::time::Instant::now();
10553        let _ = it.run_sync(stmts);
10554        best = best.min(t.elapsed().as_nanos());
10555    }
10556    Some(best)
10557}
10558
10559/// Result from program interpretation.
10560///
10561/// Contains both the output produced by `show()` calls and any error
10562/// that occurred during execution. Used by the UI bridge to display
10563/// program output to users.
10564#[derive(Debug, Clone)]
10565pub struct InterpreterResult {
10566    /// Output lines from `show()` calls during execution.
10567    pub lines: Vec<String>,
10568    /// Error message if execution failed, or `None` on success.
10569    pub error: Option<String>,
10570}
10571
10572#[cfg(test)]
10573#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/ints_i32_repr_tests.rs"]
10574mod ints_i32_repr_tests;
10575
10576#[cfg(test)]
10577#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/structs_repr_tests.rs"]
10578mod structs_repr_tests;
10579
10580#[cfg(test)]
10581#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/enums_repr_tests.rs"]
10582mod enums_repr_tests;
10583
10584#[cfg(test)]
10585#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/float_comparison_tests.rs"]
10586mod float_comparison_tests;
10587
10588#[cfg(test)]
10589#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/page_seam_tests.rs"]
10590mod page_seam_tests;
10591
10592#[cfg(test)]
10593#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/lowered_calls_tests.rs"]
10594mod lowered_calls_tests;