Skip to main content

oxdock_core/exec/
state.rs

1use std::collections::{HashMap, HashSet};
2use std::marker::PhantomData;
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, Condvar, Mutex};
5
6use super::diagnostics as state_diag;
7use oxdock_diagnostics::DiagnosticResult;
8use oxdock_fs::{CargoScratch, GuardedPath, WorkspaceFs, WorkspaceSelection};
9use oxdock_parser::{
10    Field, GuardExpr, KEYWORD_TYPE, LIST_TYPE_NAME, Step, TypeDescriptor, TypeTag, Value, sigil_var,
11};
12use oxdock_process::{BackgroundHandle, CancelHub, CommandContext, ProcessManager};
13
14use super::exit::exit_code_of;
15use super::io::{ExactCapture, ExecIo, SlidingWindow, TeeStream};
16use super::native::FunctionRegistry;
17use oxdock_pipe::KeeperGuard;
18
19/// Maximum nested function-call depth. Guards the host thread stack against
20/// runaway recursion; the error names the function that overflowed.
21pub(super) const MAX_CALL_DEPTH: usize = 64;
22
23/// Retained finished-task cap. Bounds `named_tasks` tombstones plus
24/// their tail buffers in long-lived sessions: spawning past the cap
25/// evicts the oldest finished entry. Running entries are never evicted.
26pub(super) const MAX_RETAINED_FINISHED: usize = 128;
27
28/// Live-task concurrency cap. Enforced globally through the shared
29/// counter below: any ASYNC spawn, in any nested worker, sees the
30/// same count. Refusal is backpressure, not silent kills and not an
31/// unbounded queue.
32pub const MAX_RUNNING_TASKS: usize = 64;
33
34/// RAII slot for the global live-task count. Created first inside
35/// every ASYNC worker thread; dropping on return or unwind releases
36/// the slot. The count therefore tracks threads actually alive, never
37/// table entries, so un-awaited finished tasks cannot squat slots and
38/// nested workers cannot bypass the cap.
39pub(super) struct TaskSlotGuard {
40    counter: Arc<AtomicU64>,
41}
42
43impl TaskSlotGuard {
44    pub(super) fn new(counter: Arc<AtomicU64>) -> Self {
45        Self { counter }
46    }
47}
48
49impl Drop for TaskSlotGuard {
50    fn drop(&mut self) {
51        self.counter.fetch_sub(1, Ordering::SeqCst);
52    }
53}
54
55/// Per-stream live tail cap for background tasks. Matches the
56/// foreground capture scale: the same never-grows guarantee.
57const TASK_TAIL_CAP: usize = 64 * 1024;
58
59/// Single message shape for every refused `CONST` write: `$var = <expr>`
60/// reassignment, `LIST_APPEND`, `MAP_SET`/`MERGE_MAPS`, and frozen-buffer
61/// render this prefix, so tests and diagnostics match one string.
62/// Free function (not a method) so host-function extractors and
63/// macro-generated wrappers share it without a state handle.
64pub fn const_mutation_error(what: &str) -> anyhow::Error {
65    anyhow::Error::new(state_diag::eval_const_mutation(what))
66}
67
68/// Execution state for one script run. Public so hosts can register
69/// functions and introspect listings; all fields stay crate-private so the
70/// scope, recursion-budget, and task invariants cannot be broken from outside.
71pub struct ExecState<P: ProcessManager> {
72    pub(super) fs: Box<dyn WorkspaceFs>,
73    /// Pre-reserved guarded scratch dir (session temp for child
74    /// writes). Opaque [`CargoScratch`]: renderable for the child
75    /// environment but not nameable as a `&GuardedPath`, so host code
76    /// cannot `ensure()` or `create_dir_all` it. The child `cargo` creates it on demand.
77    pub(super) cargo_scratch: CargoScratch,
78    /// Pure session seed from [`oxdock_process::seed_defaults`], stored at
79    /// init alongside the layered `envs`. `ISOLATED` resets clone this
80    /// (not the layered map), and transport sanitize diffs against it.
81    /// Built once: re-seeding would re-read host fallbacks and break
82    /// state stability.
83    pub(super) seed: Arc<HashMap<String, String>>,
84    pub(super) cwd: GuardedPath,
85    pub(super) envs: Arc<HashMap<String, String>>,
86    /// Each entry is the script env as it stood at that block's entry, so
87    /// the block allowlist resolves against the enclosing scope even as
88    /// the live envs are scrubbed underneath. Nesting snapshots the
89    /// already-scrubbed parent, so narrowing is monotonic by
90    /// construction. Cloned (not reset) by `fork()` so tasks spawned
91    /// inside a block inherit its scrub.
92    pub(super) isolated_stack: Vec<Arc<HashMap<String, String>>>,
93    pub(super) bg_children: Vec<BgChild>,
94    pub(super) scope_stack: Vec<ScopeSnapshot>,
95    pub(super) io: ExecIo,
96    /// Pre-registered SlidingWindow observers for stream assertion steps.
97    /// Keyed by (generation, step index). TeeWriter pushes every chunk to all windows.
98    pub(super) assert_windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
99    /// Same observer map fed by the stderr tee for `ASSERT_CONTAINS stderr`.
100    pub(super) assert_windows_stderr: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
101    /// Exact-match stdout accumulators for `ASSERT_EQ`/`ASSERT_NE stdout`, keyed by
102    /// generation and fed by the same tee. Entries allocated during
103    /// pre-registration observe bytes from scope entry; the common
104    /// top-level case therefore sees trial-cumulative output.
105    pub(super) exact_stdout: Arc<Mutex<HashMap<usize, ExactCapture>>>,
106    /// Variable scopes for $variable bindings (FOR loops, LET assignments).
107    /// Innermost scope is last. Variables are looked up from innermost to outermost.
108    /// Each entry carries its declared type name alongside the value.
109    pub(super) var_scopes: Vec<HashMap<String, (TypeTag, Value)>>,
110    /// `CONST` names per variable scope frame, pushed and popped in
111    /// lockstep with `var_scopes`. A name present here refuses `$var = <expr>`
112    /// reassignment, `LIST_APPEND`, and rebinding; the value-level frozen flag
113    /// additionally refuses writes through `LET`-bound aliases.
114    pub(super) const_scopes: Vec<HashSet<String>>,
115    /// Name directory for type resolution: startup descriptors plus the
116    /// run's host descriptors. Words carry their own vtables, so this map
117    /// serves only name queries (declarations, `TYPES()`, `TYPE_DESCRIBE`).
118    pub(super) types: HashMap<String, &'static TypeDescriptor>,
119    /// Named record schemas for shaped MAP bindings: schema name to its
120    /// field table. Populated from host modules alongside descriptors, so
121    /// `LET $s: SSH_SESSION_INFO` resolves exactly when the owning module
122    /// is registered. Impossible to reference an unregistered schema.
123    pub(super) record_schemas: HashMap<String, Arc<[Field]>>,
124    /// Module-shared state stashed at registration, keyed by owning
125    /// module name plus value type. Bodies fetch it through
126    /// `StepCtx::module_state` instead of hand-built closures, so
127    /// every entry can stay `#[oxdock_func]`.
128    pub(super) module_states:
129        HashMap<(String, std::any::TypeId), Arc<dyn std::any::Any + Send + Sync>>,
130    /// Script-level type aliases for this run: alias name to canonical
131    /// target spelling (`PERSON` to `MAP<name:STRING>`). Populated once
132    /// from top-level `TYPE` steps before the static pass, so forward
133    /// references resolve run-wide at first coercion.
134    pub(super) type_aliases: HashMap<String, String>,
135    /// Digest of the type environment above (aliases, schemas, custom
136    /// types), folded per mutation: interned rendered tags key on
137    /// spelling plus this digest, so one run's alias-dependent
138    /// shapes never share entries with another run's.
139    pub(super) type_env_digest: u64,
140    /// Cancellation token for background thread teardown.
141    #[allow(dead_code)]
142    pub(super) cancel_token: Arc<AtomicBool>,
143    /// Event hub fanning the same cancellation to pump supervisors.
144    /// Marked everywhere the token is stored, so blocking pumps wake
145    /// without polling. Forks get a fresh hub with their fresh token.
146    #[allow(dead_code)]
147    pub(super) cancel_hub: Arc<CancelHub>,
148    /// Handle to the currently executing foreground OS process, so
149    /// ThreadJoinHandle::kill() can interrupt a blocking wait().
150    #[allow(dead_code)]
151    pub(super) active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
152    /// Named task registry for AWAIT/CANCEL support. Shared across subscopes
153    /// via Arc. Each entry is a synchronized state machine (`TaskEntry`):
154    /// the handle lives inside the entry so `CANCEL` can synchronously tear
155    /// down a task even while a concurrent `AWAIT` is waiting on it.
156    /// Entries are retained as `Cancelled`/`Completed` tombstones so later
157    /// `AWAIT`/`CANCEL` report precise errors instead of `TaskNotFound`.
158    #[allow(dead_code)]
159    pub(super) named_tasks: Arc<Mutex<HashMap<u64, Arc<TaskEntry>>>>,
160    /// Counter for generating unique task IDs. Shared across subscopes via Arc.
161    #[allow(dead_code)]
162    pub(super) next_task_id: Arc<AtomicU64>,
163    /// Shared live-task count across every forked worker. Forks clone
164    /// the `Arc`, so nested spawns see the same total: the cap is
165    /// global, not per scope. Incremented atomically at allocation,
166    /// released by the worker thread's slot guard on exit.
167    pub(super) live_tasks: Arc<AtomicU64>,
168    /// Whether we're inside an ASYNC block thread. When true, `handlers::run()`
169    /// spawns in background mode so the handle can be registered for cancellation.
170    pub(super) inside_async: bool,
171    /// Step-indexed keeper expiry for one `ASYNC` worker. Each guard pins a
172    /// pipe the worker produces to, bridging the spawn-to-first-attach
173    /// window and every transient gap between producer steps. Guards keyed
174    /// to step `k` drop when the worker completes its top-level step `k`
175    /// (matched by slice identity, so nested bodies never discharge them);
176    /// leftovers drop with the worker thread. Always `None` outside
177    /// workers; `fork` never inherits it.
178    pub(super) keeper_expiry: Option<KeeperExpiry>,
179    /// Whether `handlers::run()` must spawn in background mode so the handle
180    /// registers in `active_process` for cancellation. Set while a `TIMEOUT`
181    /// body executes on the current thread so the deadline watcher can kill
182    /// a blocking foreground process. Unlike `inside_async`, this does not
183    /// affect end-of-pipeline named-task reaping.
184    pub(super) cancellable: bool,
185    /// Scope floor for the end-of-body reaper: task ids at or above this
186    /// joined at scope end, older ones ignored. Set only by `TIMEOUT`
187    /// (snapshot of the task-id counter at scope entry), so a worker the
188    /// body leaves running gets up to the deadline while pre-existing
189    /// tasks keep running past the scope. `None` joins everything: the
190    /// pipeline top and every other scope.
191    pub(super) reap_floor: Option<u64>,
192    /// The single function registry: DSL `FUNC` definitions, builtins, and
193    /// host extensions. Script entries scope lexically through the
194    /// registry's own frames (managed by `push_scope`/`pop_scope`);
195    /// native entries persist. Shared across `fork()` via clone.
196    pub(super) functions: FunctionRegistry<P>,
197    /// Entry script file (#115), when the run started from a file: base
198    /// for top-level relative `IMPORT` paths. `None` for stdin and inline
199    /// runs (imports resolve against the workspace root).
200    pub(super) entry_file: Option<GuardedPath>,
201    /// Active file-import chain (#115), innermost last: cycle detection
202    /// names the full chain, and the importer dir is the top's parent.
203    pub(super) import_stack: Vec<GuardedPath>,
204    /// One file module per resolved import path (#115): parse once,
205    /// validate once, initialize once. Every alias is a view onto the
206    /// same record and the same shared state.
207    pub(super) modules: HashMap<String, ModuleRecord>,
208    pub(super) validated_modules: HashSet<String>,
209    /// Files the static closure pass already proved (#115): entry plus
210    /// every transitively imported file, checked with full nested
211    /// knowledge. Runtime re-validation of the same registry-cached
212    /// body would only false-positive on nested calls, so imports skip
213    /// the single-file re-proof when their key is present. Unseen
214    /// files (direct API use, no static pass) still validate here.
215    /// Active module context (#115), innermost last: `Some(key)` while
216    /// module-owned code runs (init body or module-owned `FUNC`),
217    /// `None` past an entry-function boundary (entry `FUNC`s stay
218    /// params-only and never see module state). Reads and mutations
219    /// consult the topmost `Some` store after lexical frames miss.
220    pub(super) module_stack: Vec<Option<String>>,
221    /// Executed file-import alias targets per unit (#115): alias to
222    /// defining file keys for imports that actually ran, keyed by the
223    /// importing unit (`"entry"` for entry steps, the file key for
224    /// module bodies). Unit-top layer only: unit-top-level imports
225    /// land here (anything executed without a live lexical scope);
226    /// function-local imports land on the innermost
227    /// [`ExecState::call_alias_frames`] entry instead, and block
228    /// imports on the innermost [`ExecState::scope_alias_frames`]
229    /// entry, so neither leaks past its boundary. Mirrors the static
230    /// per-unit `outbound_alias_targets` for the runtime placeholder
231    /// gate, so file-backed `EXPAND` templates (invisible to static
232    /// checking) classify known aliases identically: host harvests
233    /// record an explicit host branch, and module bodies resolve
234    /// against their own file's imports, never the importer's.
235    pub(super) executed_alias_targets: HashMap<String, super::native::AliasTargets>,
236    /// Block-scoped import frames, innermost last: one entry per
237    /// live lexical scope that executed an `IMPORT`, tagged with the
238    /// scope-stack depth at creation and the importing unit. Reads
239    /// merge every live frame for their unit (outer-to-inner) over
240    /// the unit-top map, so an `IMPORT` inside `IF`/`FOR`/`WHILE`/
241    /// `SWITCH`/`ISOLATED` resolves within its block and unwinds on
242    /// exit. `pop_scope` drops frames deeper than the surviving
243    /// stack; `fork` flattens live frames into the child's unit-top
244    /// map (the child manages its own scopes). Function bodies keep
245    /// using [`ExecState::call_alias_frames`], checked first.
246    pub(super) scope_alias_frames: Vec<ScopeAliasFrame>,
247    /// Active function-call import frames: one entry per live
248    /// [`call_func_value`](super::handlers::call_func_value) invocation,
249    /// holding that invocation's own local imports. The innermost frame
250    /// for the active unit shadows the unit-top map exactly like the
251    /// static per-function overlays shadow the unit imports; popping on
252    /// return (via an RAII guard) restores the caller's view. Each
253    /// frame records the scope-stack depth at call entry: imports
254    /// execute into the call frame only at that depth (the body's own
255    /// top level), while deeper block scopes record into
256    /// [`ExecState::scope_alias_frames`] so they unwind on block exit;
257    /// reads merge only scope frames deeper than the innermost live
258    /// call frame, so a caller block's imports never leak into a
259    /// same-unit callee.
260    pub(super) call_alias_frames: Vec<CallAliasFrame>,
261    /// Frame-2..N floor (#322): `functions.scopes` index at which the
262    /// current module call (or init) body starts. Nested-frame lookup
263    /// walks down to this floor and no further, so caller frames from
264    /// other units are unreachable by construction. Pushed alongside
265    /// `call_alias_frames` (and init scopes) on every path. Entry
266    /// calls walk all live frames: with inits popped, every live
267    /// frame is entry-owned by construction.
268    pub(super) func_floors: Vec<usize>,
269    /// Bare-harvest visibility per importing unit (#322): (unit, base)
270    /// to defining file key. Harvests persist through this map past
271    /// init pops, never through scope frames.
272    pub(super) harvest_map: HashMap<(String, String), String>,
273    /// Parse-time module table (#115): imported files parse with the same
274    /// table as the entry script.
275    pub(super) module_table: oxdock_parser::ModuleTable,
276    /// Current nested function-call depth on this thread. Enforced against
277    /// `MAX_CALL_DEPTH`; cloned (not reset) by `fork()` so async children
278    /// inherit the caller's depth budget.
279    pub(super) call_depth: usize,
280    /// Executed `INHERIT_ENV` keys per live module init, innermost last.
281    /// Pushed empty before the init body runs and popped after, so
282    /// `inherit_env` records keys as they actually execute under their
283    /// guards instead of re-scanning steps against final envs.
284    pub(super) init_inherit_stack: Vec<Vec<String>>,
285    /// Scope-stack depths that are module-init top levels, innermost
286    /// last: `ensure_module_init` (`super::import`) pushes its isolation
287    /// scope here so `record_executed_alias` can tell a module's own
288    /// top level (unit-top, like the entry's) from a lexical block
289    /// (scope frame, unwinds on exit). Nested inits nest strictly,
290    /// so depths never repeat while live; `fork` clears it (the
291    /// child's scopes restart empty).
292    pub(super) init_scope_depths: Vec<usize>,
293    /// Identity of the task this state executes (`0` = root flow).
294    /// Stamped onto pipe handles minted here and compared by the promotion
295    /// check: only the declaring task may promote its own pipes.
296    pub(super) task_id: u64,
297    /// Declared `--to-host` transfers recorded strictly at execution time:
298    /// each executed flagged `COPY` appends its evaluated
299    /// `(guest_src, host_dst)` pair. The guest serve loop packs exactly
300    /// these entries, so dead branches contribute nothing and dynamic
301    /// paths (`$var`, `{{ ... }}`) resolve normally. Shared with the sink
302    /// in [`ExecIo`] when staged.
303    pub(super) push_manifest: Vec<(String, String)>,
304    pub(super) _marker: PhantomData<P>,
305}
306
307pub(super) struct ScopeSnapshot {
308    pub(super) cwd: GuardedPath,
309    pub(super) selection: WorkspaceSelection,
310    pub(super) envs: Arc<HashMap<String, String>>,
311}
312
313/// One live block's imports: the scope-stack depth at creation plus
314/// the importing unit's alias targets. Single owner for the
315/// scope-frame shape; `record_executed_alias` writes it,
316/// `unit_alias_targets` merges it, `pop_scope` reaps it.
317#[derive(Clone, Default)]
318pub(super) struct ScopeAliasFrame {
319    pub(super) depth: usize,
320    pub(super) unit: String,
321    pub(super) targets: super::native::AliasTargets,
322}
323
324/// One live function call's imports: the importing unit, the
325/// scope-stack depth at call entry (right after the call scope
326/// pushes), and the call's own local imports. The depth tells
327/// `record_executed_alias` apart the body's own top level (records
328/// here) from nested blocks (record into [`ScopeAliasFrame`]), and
329/// tells `unit_alias_targets` which scope frames belong to this
330/// invocation (deeper ones) versus caller context. A forked child
331/// restarts its scope stack at zero, so a cloned frame whose depth
332/// exceeds the child's stack is stale: the child still merges its
333/// targets (inherited visibility) but applies no depth floor from
334/// it. Single owner for the call-frame shape.
335#[derive(Clone, Default)]
336pub(super) struct CallAliasFrame {
337    pub(super) unit: String,
338    pub(super) depth: usize,
339    pub(super) targets: super::native::AliasTargets,
340}
341
342/// One parsed file module (#115), keyed by resolved display path: parse
343/// once, validate once, initialize once. `init` is `None` until the
344/// first import executes the body; every alias is a view onto the
345/// same record and the same shared state.
346#[derive(Clone, Default)]
347pub(super) struct ModuleRecord {
348    pub(super) steps: Vec<Step>,
349    /// Single-file `EXPORT` metadata: `EXPORT` func names, `EXPORT TYPE`
350    /// names, and `EXPORT CONST` names, each in source order. One struct
351    /// (never three parallel lists) so the MCP server never confuses a
352    /// type for a tool, and only `CONST` names are readable through
353    /// `$ALIAS::NAME`.
354    pub(super) exports: oxdock_parser::Exports,
355    pub(super) init: Option<ModuleInit>,
356    /// Frame-1 file scope (#322): every top-level `FUNC` of the file
357    /// (exported, harvested, and private alike), indexed once at load
358    /// so calls resolve without scanning steps on every invocation.
359    /// Single owner for the defining-file view; the runtime walk and
360    /// the static home index read the same shape.
361    pub(super) top_funcs: HashMap<String, Vec<RawFuncDef>>,
362}
363
364impl ModuleInit {
365    /// Fresh entry-unit init store (#4): the session seed plus the
366    /// entry top-level's own `ENV` contributions, tracked as they
367    /// execute. Entry `FUNC` calls reset to this map (never caller
368    /// env), mirroring how module calls reset to `ModuleInit::envs`.
369    /// `vars`/`const_vars` hold the entry prelude `CONST`s seeded
370    /// into every entry call; `inherit_names` re-reads from the
371    /// engine per call. Single owner for the entry record shape, so
372    /// `new_state` and the test constructors can never drift.
373    pub(super) fn entry_seed(envs: HashMap<String, String>, cwd: GuardedPath) -> Self {
374        Self {
375            vars: HashMap::new(),
376            const_vars: HashSet::new(),
377            return_value: Value::string(String::new()),
378            envs,
379            inherit_names: Vec::new(),
380            selection: WorkspaceSelection::Snapshot,
381            cwd,
382        }
383    }
384}
385
386impl ModuleRecord {
387    /// Fresh entry-unit record (#4): empty steps/top-funcs plus the
388    /// seeded init store above. Single owner for the entry shape, so
389    /// every constructor seeds the same fields.
390    pub(super) fn entry_record(envs: HashMap<String, String>, cwd: GuardedPath) -> Self {
391        Self {
392            steps: Vec::new(),
393            exports: oxdock_parser::Exports::default(),
394            init: Some(ModuleInit::entry_seed(envs, cwd)),
395            top_funcs: HashMap::new(),
396        }
397    }
398}
399
400/// One top-level `FUNC` definition as parsed: the file frame of the
401/// unit scope stack (#322). Params and return stay in source spelling
402/// until a call resolves tags. Guards ride along and are evaluated
403/// with the live env at use time, mirroring the previous per-call
404/// step scan exactly (init-gated defs behave as before). `jail` is
405/// sealed at execution: the first top-level execution of this
406/// definition pins the live workspace selection and cwd, so later
407/// calls restore the definition site, never caller ambient. `None`
408/// for never-executed defs (forward refs, skipped harvests), which
409/// fall back to the defining file default at call time.
410#[derive(Clone, Debug, Default)]
411pub(super) struct RawFuncDef {
412    pub(super) params: Vec<(String, String, bool)>,
413    pub(super) return_spelling: String,
414    pub(super) is_async: bool,
415    pub(super) body: Vec<Step>,
416    pub(super) guard: Option<GuardExpr>,
417    pub(super) jail: Option<(WorkspaceSelection, GuardedPath)>,
418}
419
420/// Initialized module state (#115): the shared globals every alias of
421/// one file observes. `vars` holds the module body's top-level `LET`
422/// bindings, drained from the init frame when the first import runs;
423/// module-owned `FUNC`s resolve names against `vars` after lexical
424/// frames miss, so one file's functions share one global state instead
425/// of each alias getting a private copy. `return_value` caches the
426/// init body's `RETURN`, so repeated imports bind the same value.
427#[derive(Clone)]
428pub(super) struct ModuleInit {
429    pub(super) vars: HashMap<String, (TypeTag, Value)>,
430    /// Top-level `CONST` names drained with `vars`: rebinding,
431    /// `$var = <expr>` reassignment, and `LIST_APPEND` against these fail;
432    /// rebuilds fail on the value-level frozen flag.
433    pub(super) const_vars: HashSet<String>,
434    pub(super) return_value: Value,
435    /// Script env the module's functions execute with (#115): the
436    /// session seed plus the init body's own `ENV` contributions
437    /// (captured as a delta against the pre-init map, so
438    /// caller-established values stay out). `INHERIT_ENV` names are
439    /// re-read from the host at each call (see `inherit_names`),
440    /// since a re-inherit of an already-present value leaves no delta
441    /// yet must still admit the name.
442    pub(super) envs: HashMap<String, String>,
443    /// Top-level `INHERIT_ENV` names of the module file, re-established
444    /// from the host on every module-owned call. A module never
445    /// inherits its caller's environment; each file declares what it
446    /// reads, and the values flow from the host (or literals) at
447    /// init/call time.
448    pub(super) inherit_names: Vec<String>,
449    /// The module top-level jail (#322): the workspace selection and
450    /// cwd as the init body left them. Module-owned `FUNC`s restore
451    /// this on entry (unless the body overrides it), so a callee
452    /// executes in its defining file context no matter which
453    /// workspace the caller sits in. Captured before the init scope
454    /// pops; the pop restores the importer afterwards.
455    pub(super) selection: WorkspaceSelection,
456    pub(super) cwd: GuardedPath,
457}
458
459/// One anonymous background worker: the thread-join handle plus the
460/// task id drawn for the worker at spawn. Only `ThreadJoinHandle`s are
461/// ever pushed (a worker's own `RUN` steps wait inline); the id lets a
462/// `TIMEOUT` scope-end reaper join only the workers its own body
463/// spawned, leaving pre-existing ones alone.
464pub(super) struct BgChild {
465    pub(super) handle: Box<dyn BackgroundHandle>,
466    pub(super) task_id: u64,
467}
468
469/// Task completion record, written once by the first observer of a
470/// finished task and read by later polls. Never consumed: polls and a
471/// subsequent `AWAIT` all read the same record.
472#[derive(Clone)]
473pub(super) struct TaskCompletion {
474    pub(super) ok: bool,
475    pub(super) exit_code: i64,
476    pub(super) result: Option<Value>,
477    pub(super) error: String,
478}
479
480/// Point-in-time task view for `TASK_POLL`. Owned strings, bounded by
481/// the tail caps.
482pub(super) struct TaskObservation {
483    pub(super) running: bool,
484    pub(super) ok: bool,
485    pub(super) exit_code: i64,
486    pub(super) result: Option<Value>,
487    pub(super) error: String,
488}
489
490/// Bounded per-stream accumulator for one background task. Same
491/// drop-the-head discipline as the foreground tail rings.
492pub(super) struct TaskTails {
493    out: Vec<u8>,
494    err: Vec<u8>,
495    total_out: u64,
496    total_err: u64,
497}
498
499impl TaskTails {
500    pub(super) fn new() -> Self {
501        Self {
502            out: Vec::new(),
503            err: Vec::new(),
504            total_out: 0,
505            total_err: 0,
506        }
507    }
508
509    pub(super) fn push(&mut self, stream: TeeStream, bytes: &[u8]) {
510        let (buf, total) = match stream {
511            TeeStream::Stdout => (&mut self.out, &mut self.total_out),
512            TeeStream::Stderr => (&mut self.err, &mut self.total_err),
513        };
514        *total += bytes.len() as u64;
515        buf.extend_from_slice(bytes);
516        let excess = buf.len().saturating_sub(TASK_TAIL_CAP);
517        if excess > 0 {
518            buf.drain(..excess);
519        }
520    }
521
522    pub(super) fn snapshot(&self) -> (String, String, u64) {
523        let dropped = self.total_out.saturating_sub(self.out.len() as u64)
524            + self.total_err.saturating_sub(self.err.len() as u64);
525        (
526            String::from_utf8_lossy(&self.out).into_owned(),
527            String::from_utf8_lossy(&self.err).into_owned(),
528            dropped,
529        )
530    }
531}
532
533/// Lifecycle phase of a named background task (`LET $var: HANDLE<T> = ASYNC ...`).
534/// `Running` and `Awaiting` both hold the live handle inside the entry;
535/// `Cancelled` and `Completed` are terminal tombstones with no handle.
536pub(super) enum TaskPhase {
537    Running,
538    Awaiting,
539    Cancelled,
540    Completed,
541}
542
543pub(super) struct TaskEntryState {
544    pub(super) phase: TaskPhase,
545    pub(super) handle: Option<Box<dyn BackgroundHandle>>,
546    /// True once the handle has been consumed and its thread joined
547    /// (`kill()` for cancellations, `try_wait`-reap for natural completion).
548    /// Threads observing `Cancelled` must wait on `done` until `reaped`
549    /// before resuming, so no caller outruns OS process teardown.
550    pub(super) reaped: bool,
551    /// Explicit result of a background task, published by `RETURN` (block
552    /// bodies) or the function call itself (single-`CALL` bodies). Set
553    /// under the entry lock before `done.notify_all()`; read by
554    /// `LET $o: TYPE = AWAIT $t`. `None` for tasks that have not finished
555    /// or have fallen off the end. Task stdout is never captured: it
556    /// streams live to the shared parent writer.
557    pub(super) return_value: Option<Value>,
558    /// Completion record written once by the first observer of a
559    /// finished task (`TASK_POLL` or the teardown path). Read by later
560    /// polls and post-mortem rendering; never consumed.
561    pub(super) completion: Option<TaskCompletion>,
562    /// Whether this task's body can publish a value: single-`CALL` bodies
563    /// always can; block bodies can iff they contain a `RETURN` in their
564    /// own scope. A task that can return but falls off the end fails its
565    /// capture loudly; a task that cannot return yields `INT` 0.
566    pub(super) returns_value: bool,
567}
568
569/// Synchronized named-task entry shared by every scope that can observe the
570/// task (`AWAIT`, `CANCEL`, `TASK_POLL`, end-poll reaping). Exactly one
571/// thread ever takes the handle and performs teardown; all other
572/// observers rendezvous on `done`/`reaped`.
573pub(super) struct TaskEntry {
574    pub(super) state: Mutex<TaskEntryState>,
575    pub(super) done: Condvar,
576    /// Bounded live output. Fed by the worker tee, drained by
577    /// `TASK_POLL` without consuming, dropped with the entry.
578    pub(super) tails: Arc<Mutex<TaskTails>>,
579}
580
581impl TaskEntry {
582    /// Whether this entry occupies a live slot: awaiting a join, or
583    /// running with an unfinished thread. Terminal phases and reaped
584    /// joins are done. Un-awaited finished tasks report done via
585    /// `try_wait`, so ghosts never hold a slot. Never blocks: a
586    /// still-running thread reports `Ok(None)` without joining.
587    pub(super) fn is_live(&self) -> bool {
588        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
589        match guard.phase {
590            TaskPhase::Running => match guard.handle.as_mut() {
591                Some(handle) => matches!(handle.try_wait(), Ok(None)),
592                None => false,
593            },
594            TaskPhase::Awaiting => true,
595            TaskPhase::Completed | TaskPhase::Cancelled => false,
596        }
597    }
598
599    pub(super) fn new(
600        handle: Box<dyn BackgroundHandle>,
601        returns_value: bool,
602        tails: Arc<Mutex<TaskTails>>,
603    ) -> Self {
604        Self {
605            state: Mutex::new(TaskEntryState {
606                phase: TaskPhase::Running,
607                handle: Some(handle),
608                reaped: false,
609                return_value: None,
610                completion: None,
611                returns_value,
612            }),
613            done: Condvar::new(),
614            tails,
615        }
616    }
617
618    /// Non-destructive snapshot of live tails plus dropped head count.
619    /// Never blocks execution: a poisoned lock reads through.
620    pub(super) fn snapshot_tails(&self) -> (String, String, u64) {
621        self.tails
622            .lock()
623            .map(|tails| tails.snapshot())
624            .unwrap_or_else(|e| e.into_inner().snapshot())
625    }
626
627    /// Observe completion without consuming the task. Never transitions
628    /// phase, never takes the handle, never notifies: a later `AWAIT`
629    /// still joins normally. First observation of a finished task
630    /// records the completion for later polls; the `try_wait` reap it
631    /// performs is the same one `AWAIT` would do, and the cached status
632    /// keeps that path consistent.
633    pub(super) fn observe_completion(&self) -> TaskObservation {
634        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
635        if let Some(done) = guard.completion.clone() {
636            return TaskObservation {
637                running: false,
638                ok: done.ok,
639                exit_code: done.exit_code,
640                result: done.result,
641                error: done.error,
642            };
643        }
644        if !matches!(guard.phase, TaskPhase::Running) {
645            return TaskObservation {
646                running: false,
647                ok: false,
648                exit_code: -1,
649                result: None,
650                error: "task handle was not found or has already been awaited".to_string(),
651            };
652        }
653        match guard.handle.as_mut() {
654            None => TaskObservation {
655                running: true,
656                ok: true,
657                exit_code: -1,
658                result: None,
659                error: String::new(),
660            },
661            Some(handle) => match handle.try_wait() {
662                Ok(Some(status)) => {
663                    let completion = TaskCompletion {
664                        ok: status.success(),
665                        exit_code: status.code().map(i64::from).unwrap_or(-1),
666                        result: guard.return_value.clone(),
667                        error: if status.success() {
668                            String::new()
669                        } else {
670                            format!("task exited with status {status}")
671                        },
672                    };
673                    guard.completion = Some(TaskCompletion {
674                        ok: completion.ok,
675                        exit_code: completion.exit_code,
676                        result: completion.result.clone(),
677                        error: completion.error.clone(),
678                    });
679                    TaskObservation {
680                        running: false,
681                        ok: completion.ok,
682                        exit_code: completion.exit_code,
683                        result: completion.result,
684                        error: completion.error,
685                    }
686                }
687                Ok(None) => TaskObservation {
688                    running: true,
689                    ok: true,
690                    exit_code: -1,
691                    result: None,
692                    error: String::new(),
693                },
694                Err(err) => {
695                    let completion = TaskCompletion {
696                        ok: false,
697                        exit_code: exit_code_of(&err).unwrap_or(1),
698                        result: None,
699                        error: format!("{err:#}"),
700                    };
701                    guard.completion = Some(TaskCompletion {
702                        ok: completion.ok,
703                        exit_code: completion.exit_code,
704                        result: completion.result.clone(),
705                        error: completion.error.clone(),
706                    });
707                    TaskObservation {
708                        running: false,
709                        ok: completion.ok,
710                        exit_code: completion.exit_code,
711                        result: completion.result,
712                        error: completion.error,
713                    }
714                }
715            },
716        }
717    }
718
719    /// Block until the teardown owner has consumed the handle and joined
720    /// the task thread. Lock-free for callers except the wait itself.
721    pub(super) fn wait_reaped(&self) {
722        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
723        while !guard.reaped {
724            guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
725        }
726    }
727
728    /// Mark teardown complete and wake every rendezvous waiter.
729    pub(super) fn finish_teardown(&self) {
730        {
731            let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
732            guard.handle = None;
733            guard.reaped = true;
734        }
735        self.done.notify_all();
736    }
737}
738
739/// Step-indexed keeper expiry for one `ASYNC` worker thread. Guards are
740/// keyed by the top-level body index of the final producer step for each
741/// pipe: dropping the guards for step `k` once it completes keeps the
742/// pipe open across every transient gap between producers, then releases
743/// it so later consumer steps in the same task observe EOF.
744///
745/// Slice identity (`body_addr`/`body_len`) gates discharge: nested bodies
746/// (`FOR`/`IF`/`TIMEOUT`/inner `ASYNC`) execute through the same stepping
747/// code with different slices and must never consume the worker's
748/// top-level map.
749pub(super) struct KeeperExpiry {
750    body_addr: usize,
751    body_len: usize,
752    map: HashMap<usize, Vec<KeeperGuard>>,
753}
754
755impl KeeperExpiry {
756    pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
757        Self {
758            body_addr: steps.as_ptr() as usize,
759            body_len: steps.len(),
760            map,
761        }
762    }
763
764    pub(super) fn matches(&self, steps: &[Step]) -> bool {
765        self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
766    }
767
768    /// Drop the guards expiring at top-level step `idx`. Returns true when
769    /// the map is drained and the expiry itself can be cleared.
770    pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
771        if self.matches(steps) {
772            drop(self.map.remove(&idx));
773        }
774        self.map.is_empty()
775    }
776}
777
778/// Defining-file call context (#322): (envs, inherit names,
779/// selection, cwd). One alias shared by the resolver and every call
780/// site, never a restated tuple.
781pub(super) type FileCallCtx = (
782    HashMap<String, String>,
783    Vec<String>,
784    WorkspaceSelection,
785    GuardedPath,
786);
787
788impl<P: ProcessManager> ExecState<P> {
789    /// Script-map environment lookup for DSL evaluation (`is_exec_name`,
790    /// `Expr::Env`, expansions): exact hit first, case-insensitive
791    /// fallback on Windows so `{{ env:Path }}` resolves the seeded
792    /// `PATH`. The map is seeded at init, so no fallback layer exists.
793    pub(super) fn get_env(&self, key: &str) -> Option<&str> {
794        if let Some(v) = self.envs.get(key) {
795            return Some(v.as_str());
796        }
797        #[allow(clippy::disallowed_macros)]
798        if cfg!(windows) {
799            return self
800                .envs
801                .iter()
802                .find(|(k, _)| oxdock_process::names_eq(k, key))
803                .map(|(_, v)| v.as_str());
804        }
805        None
806    }
807
808    pub(super) fn command_ctx(&self) -> DiagnosticResult<CommandContext> {
809        // Resolve the working directory through the snapshot choke point: a
810        // snapshot-rooted cwd materializes here (so `RUN` executes against a
811        // real directory) while a local cwd resolves purely lexically with
812        // zero I/O. The seeded scratch materializes alongside: `HOME` and
813        // `TMPDIR` point at it, so children writing temp or profile data
814        // must observe real directories, never lexical candidates.
815        let cwd = self
816            .fs
817            .resolve_write(&self.cwd, ".")
818            .map_err(|err| state_diag::eval_workdir_resolve_failed(&err))?;
819        self.cargo_scratch
820            .ensure_materialized()
821            .map_err(|err| state_diag::eval_scratch_materialize_failed(&err))?;
822        Ok(CommandContext::new(
823            &cwd.into(),
824            Arc::clone(&self.envs),
825            &self.cargo_scratch,
826            self.fs.root(),
827            self.fs.build_context(),
828        ))
829    }
830
831    /// Draw the next task id, enforcing the global live-task cap and
832    /// sweeping retained finished entries. Every ASYNC allocation path
833    /// calls this, so named and anonymous tasks share one choke point.
834    /// The live count is atomic and shared across all forked workers,
835    /// so nested spawns cannot bypass the cap that a per-state scan
836    /// would miss. Refusal is backpressure: a full host fails the spawn
837    /// loudly instead of wedging.
838    pub(super) fn alloc_task_id(&mut self) -> DiagnosticResult<u64> {
839        // Purge cleanly-finished anonymous children first: their threads
840        // are gone and a zero exit has no reporter, so retaining them
841        // only grows the vec. Failed handles stay for the end-pipeline
842        // reaper, which owns their error reporting.
843        self.bg_children
844            .retain_mut(|child| match child.handle.try_wait() {
845                Ok(None) => true,
846                Ok(Some(status)) => !status.success(),
847                Err(_) => true,
848            });
849        self.live_tasks
850            .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
851                (n < MAX_RUNNING_TASKS as u64).then_some(n + 1)
852            })
853            .map_err(|_| state_diag::eval_task_cap_exceeded(MAX_RUNNING_TASKS as u64))?;
854        let id = self.next_task_id.fetch_add(1, Ordering::SeqCst);
855        self.sweep_finished_tasks();
856        Ok(id)
857    }
858
859    /// Drop finished entries past `MAX_RETAINED_FINISHED`, oldest
860    /// first. Finished means a terminal phase or a completed join;
861    /// `Awaiting` entries always survive (a waiter is rendezvousing)
862    /// and running entries are never touched. Evicted ids read as
863    /// unknown/already-awaited afterwards, like an awaited task.
864    fn sweep_finished_tasks(&self) {
865        let mut finished: Vec<u64> = Vec::new();
866        {
867            let named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
868            for (id, entry) in named.iter() {
869                // `is_live` already exempts awaiting entries: a waiter
870                // is rendezvousing on them.
871                if !entry.is_live() {
872                    finished.push(*id);
873                }
874            }
875        }
876        if finished.len() <= MAX_RETAINED_FINISHED {
877            return;
878        }
879        finished.sort_unstable();
880        let mut named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
881        for id in finished.iter().take(finished.len() - MAX_RETAINED_FINISHED) {
882            named.remove(id);
883        }
884    }
885
886    /// Fork the execution state for a child thread. The child gets:
887    /// - A cloned filesystem handle (shared snapshot backing, independent root selection)
888    /// - Cloned envs, cwd, cargo scratch name, var_scopes, const_scopes
889    /// - Fresh bg_children, scope_stack (empty -- child manages its own)
890    /// - Block imports flattened into the cloned unit-top map (the live
891    ///   frames stay with the parent's scopes, so the child observes
892    ///   what the parent saw at spawn without inheriting unwindable frames)
893    /// - Shared assert_windows, assert_windows_stderr, exact_stdout (Arc clones)
894    /// - Cloned io configuration
895    /// - Independent cancel_token, active_process (child manages its own)
896    /// - Shared named_tasks and next_task_id (via Arc clone)
897    #[allow(dead_code)]
898    pub(super) fn fork(&self) -> Self {
899        let mut executed_alias_targets = self.executed_alias_targets.clone();
900        for frame in &self.scope_alias_frames {
901            for (alias, targets) in &frame.targets {
902                executed_alias_targets
903                    .entry(frame.unit.clone())
904                    .or_default()
905                    .entry(alias.clone())
906                    .or_default()
907                    .extend(targets.iter().cloned());
908            }
909        }
910        Self {
911            fs: self.fs.clone_box(),
912            cargo_scratch: self.cargo_scratch.clone(),
913            seed: Arc::clone(&self.seed),
914            cwd: self.cwd.clone(),
915            envs: Arc::clone(&self.envs),
916            bg_children: Vec::new(),
917            scope_stack: Vec::new(),
918            isolated_stack: self.isolated_stack.clone(),
919            io: self.io.clone(),
920            assert_windows: Arc::clone(&self.assert_windows),
921            assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
922            exact_stdout: Arc::clone(&self.exact_stdout),
923            var_scopes: self.var_scopes.clone(),
924            const_scopes: self.const_scopes.clone(),
925            cancel_token: Arc::new(AtomicBool::new(false)),
926            // Fresh cancellation, inherited telemetry: the fork's
927            // workers still attribute to the originating run.
928            cancel_hub: Arc::new(CancelHub::with_counter(self.cancel_hub.worker_counter())),
929            active_process: Arc::new(Mutex::new(None)),
930            named_tasks: Arc::clone(&self.named_tasks),
931            next_task_id: Arc::clone(&self.next_task_id),
932            // Shared live count, never reset: nested workers report into
933            // the same cap their spawner was admitted under.
934            live_tasks: Arc::clone(&self.live_tasks),
935            inside_async: true,
936            keeper_expiry: None,
937            cancellable: self.cancellable,
938            reap_floor: self.reap_floor,
939            functions: self.functions.clone(),
940            entry_file: self.entry_file.clone(),
941            import_stack: self.import_stack.clone(),
942            modules: self.modules.clone(),
943            validated_modules: self.validated_modules.clone(),
944            module_stack: self.module_stack.clone(),
945            executed_alias_targets,
946            call_alias_frames: self.call_alias_frames.clone(),
947            scope_alias_frames: Vec::new(),
948            init_scope_depths: Vec::new(),
949            func_floors: self.func_floors.clone(),
950            harvest_map: self.harvest_map.clone(),
951            module_table: self.module_table.clone(),
952            types: self.types.clone(),
953            record_schemas: self.record_schemas.clone(),
954            module_states: self.module_states.clone(),
955            type_aliases: self.type_aliases.clone(),
956            type_env_digest: self.type_env_digest,
957            call_depth: self.call_depth,
958            init_inherit_stack: self.init_inherit_stack.clone(),
959            task_id: self.task_id,
960            // Forks start with an empty manifest: async children record
961            // their own executions; the guest packs the root manifest.
962            push_manifest: Vec::new(),
963            _marker: PhantomData,
964        }
965    }
966
967    /// Whether `pipe` may promote to an OS kernel pair on behalf of
968    /// `task_id`: only when it was declared by that same task and no
969    /// spawned child can observe it. Anything else stays script-backed, so
970    /// concurrent tasks can never disagree about EOF propagation.
971    /// Spawning tasks pass their worker id (not the spawner's): promotion
972    /// is judged from the worker's perspective, since it is the worker's
973    /// bindings that will hold raw descriptors.
974    pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
975        pipe.declaring_task() == task_id && !pipe.has_escaped()
976    }
977
978    /// Whether `pipe` may promote on the current thread (main flow and
979    /// inline resolves).
980    pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
981        Self::can_promote_in_task(pipe, self.task_id)
982    }
983
984    /// Mark every pipe visible in scope as shared-with-a-child. Called
985    /// synchronously on the spawner before a worker thread starts: forking
986    /// copies the whole environment, so every visible pipe is capturable
987    /// whether or not the child body names it. Over-marking only costs
988    /// zero-copy opportunities, never correctness.
989    pub(super) fn mark_captured_pipes_escaped(&self) {
990        for scope in self.var_scopes.iter() {
991            for (_, value) in scope.values() {
992                mark_value_pipes_escaped(value);
993            }
994        }
995        for record in self.modules.values() {
996            if let Some(init) = record.init.as_ref() {
997                for entry in init.vars.values() {
998                    mark_value_pipes_escaped(&entry.1);
999                }
1000            }
1001        }
1002    }
1003
1004    pub(super) fn push_var_scope(&mut self) {
1005        self.var_scopes.push(HashMap::new());
1006        self.const_scopes.push(HashSet::new());
1007    }
1008
1009    pub(super) fn pop_var_scope(&mut self) {
1010        self.var_scopes.pop();
1011        self.const_scopes.pop();
1012    }
1013
1014    /// Reset module-owned env (#115, #322): env to the module init
1015    /// stored map. Workspace and cwd are reset separately by the
1016    /// caller to the snapshot jail, so a module never observes the
1017    /// importer workspace. The surrounding `push_scope` restores the
1018    /// caller afterwards.
1019    pub(super) fn reset_module_env(&mut self, envs: HashMap<String, String>) {
1020        self.envs = Arc::new(envs);
1021    }
1022
1023    /// Entry top-level tracking (#322 follow-up): true only for the
1024    /// entry prelude itself, never inside any call, module, or
1025    /// lexical block. Blocks (`ISOLATED`, `IF`, `FOR`, `WHILE`,
1026    /// `SWITCH`, `WITH_IO`) push `scope_stack` so their env unwinds
1027    /// on exit; capturing those writes would leak block-scoped and
1028    /// isolated secrets into every later entry call. Guard-gated
1029    /// top-level statements execute without pushing a scope, so
1030    /// conditional configuration still seeds the prelude. Caller
1031    /// env must never flow into the entry prelude store: `INHERIT_ENV`
1032    /// inherits from the engine, never another script, ever.
1033    pub(super) fn is_entry_top_level(&self) -> bool {
1034        self.call_depth == 0 && self.module_stack.is_empty() && self.scope_stack.is_empty()
1035    }
1036
1037    /// Defining-file call context (#322): the single owner resolving
1038    /// what a `FUNC` body restores. The definition-site jail wins
1039    /// when the definition sealed one; otherwise the defining file
1040    /// fallback applies (module init jail, entry snapshot default).
1041    /// Env always resolves file-level (module init delta, entry
1042    /// prelude) with `INHERIT_ENV` re-read from the engine, never
1043    /// caller ambient. One lookup for every file, entry included:
1044    /// the entry record lives under the sentinel, so callers never
1045    /// restate a `Some`/`None` branch. Spelled once as [`FileCallCtx`].
1046    pub(super) fn callee_file_ctx(
1047        &self,
1048        module_key: Option<&str>,
1049        def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1050    ) -> Option<FileCallCtx> {
1051        let unit = super::import::unit_key(module_key);
1052        if let Some((selection, cwd)) = def_jail {
1053            let (envs, inherit_names) = self.modules.get(unit).and_then(|record| {
1054                record
1055                    .init
1056                    .as_ref()
1057                    .map(|init| (init.envs.clone(), init.inherit_names.clone()))
1058            })?;
1059            return Some((envs, inherit_names, selection, cwd));
1060        }
1061        self.modules.get(unit).and_then(|record| {
1062            record.init.as_ref().map(|init| {
1063                (
1064                    init.envs.clone(),
1065                    init.inherit_names.clone(),
1066                    init.selection,
1067                    init.cwd.clone(),
1068                )
1069            })
1070        })
1071    }
1072
1073    /// Enter a lexical scope: snapshot cwd/root/envs and open a fresh
1074    /// variable scope. Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE);
1075    /// only pipes (ExecIo) and filesystem effects cross scope boundaries.
1076    /// Function definitions scope through the registry's own frames.
1077    pub(super) fn push_scope(&mut self) {
1078        self.scope_stack.push(ScopeSnapshot {
1079            cwd: self.cwd.clone(),
1080            selection: self.fs.selection(),
1081            envs: Arc::clone(&self.envs),
1082        });
1083        self.functions.push_scope();
1084        self.push_var_scope();
1085    }
1086
1087    /// Exit a lexical scope, restoring everything `push_scope` saved
1088    /// plus dropping block import frames deeper than the surviving
1089    /// stack, so block imports unwind with their block.
1090    pub(super) fn pop_scope(&mut self) -> DiagnosticResult<()> {
1091        let snapshot = self
1092            .scope_stack
1093            .pop()
1094            .ok_or_else(state_diag::eval_scope_underflow)?;
1095        self.fs.restore_selection(snapshot.selection);
1096        self.cwd = snapshot.cwd;
1097        self.envs = snapshot.envs;
1098        self.functions.pop_scope();
1099        self.pop_var_scope();
1100        let depth = self.scope_stack.len();
1101        self.scope_alias_frames.retain(|frame| frame.depth <= depth);
1102        Ok(())
1103    }
1104    pub(super) fn declare_var(
1105        &mut self,
1106        key: String,
1107        kind: TypeTag,
1108        value: Value,
1109    ) -> DiagnosticResult<()> {
1110        if self
1111            .var_scopes
1112            .last()
1113            .map(|s| s.contains_key(&key))
1114            .unwrap_or(false)
1115        {
1116            return Err(state_diag::eval_redeclare_var(&key));
1117        }
1118        let coerced = super::args::coerce_value(value, &kind)?;
1119        let scope = self
1120            .var_scopes
1121            .last_mut()
1122            .ok_or_else(state_diag::eval_no_var_scope)?;
1123        scope.insert(key, (kind, coerced));
1124        Ok(())
1125    }
1126
1127    /// Declare a `CONST` binding: same namespace as
1128    /// [`declare_var`](Self::declare_var)
1129    /// (a `LET` and a `CONST` cannot share a name in one frame), then
1130    /// mark the frame const and deep-freeze the value, so nested
1131    /// containers freeze with the binding instead of aliasing a
1132    /// mutable buffer.
1133    pub(super) fn declare_const(
1134        &mut self,
1135        key: String,
1136        kind: TypeTag,
1137        value: Value,
1138    ) -> DiagnosticResult<()> {
1139        let at_entry_top = self.is_entry_top_level();
1140        if self
1141            .var_scopes
1142            .last()
1143            .map(|s| s.contains_key(&key))
1144            .unwrap_or(false)
1145        {
1146            return Err(state_diag::eval_redeclare_const(&key));
1147        }
1148        let coerced = super::args::coerce_value(value, &kind)?;
1149        let frozen = Value::deep_freeze(&coerced);
1150        let scope = self
1151            .var_scopes
1152            .last_mut()
1153            .ok_or_else(state_diag::eval_no_var_scope)?;
1154        scope.insert(key.clone(), (kind.clone(), frozen.clone()));
1155        if let Some(frame) = self.const_scopes.last_mut() {
1156            frame.insert(key.clone());
1157        }
1158        if at_entry_top {
1159            // Entry prelude capture: the entry record's init store
1160            // holds the top-level `CONST`s seeded into every entry
1161            // call, mirroring how module inits drain theirs.
1162            if let Some(init) = self
1163                .modules
1164                .get_mut(super::import::ENTRY_UNIT)
1165                .and_then(|record| record.init.as_mut())
1166            {
1167                init.vars.insert(key.clone(), (kind, frozen));
1168                init.const_vars.insert(key);
1169            }
1170        }
1171        Ok(())
1172    }
1173
1174    /// Whether the entry-`CONST` fallback applies here: entry context
1175    /// (no owning module) whose caller is also entry (or top level).
1176    /// Entry callees called from module code stay params-only, so a
1177    /// module caller never observes entry file state. Single owner
1178    /// for the caller check every entry fallback reads.
1179    fn entry_fallback_allowed(&self) -> bool {
1180        if self.current_module().is_some() {
1181            return false;
1182        }
1183        match self.module_stack.len() {
1184            0 => true,
1185            1 => true,
1186            _ => matches!(
1187                self.module_stack.get(self.module_stack.len() - 2),
1188                None | Some(None)
1189            ),
1190        }
1191    }
1192
1193    /// Entry-`CONST` fallback init: the entry record's init when the
1194    /// fallback is allowed (entry context whose caller is also entry).
1195    /// Single owner for the caller check plus the init borrow, so
1196    /// every entry fallback reads hashes `ENTRY_UNIT` and checks the
1197    /// caller once. Call sites filter to `const_vars`, so `LET`s never
1198    /// cross.
1199    fn entry_const_init(&self) -> Option<&ModuleInit> {
1200        if !self.entry_fallback_allowed() {
1201            return None;
1202        }
1203        self.modules.get(super::import::ENTRY_UNIT)?.init.as_ref()
1204    }
1205
1206    /// Whether `key` names a `CONST` binding visible here: the
1207    /// innermost lexical frame holding the name decides (a local
1208    /// `LET` shadowing a module-level `CONST` stays mutable), exactly
1209    /// mirroring [`mutate_var`](Self::mutate_var)'s resolution; only
1210    /// when no lexical frame declares the name does the owning
1211    /// module's shared store answer. Single owner for the const check
1212    /// behind `$var = <expr>` reassignment and `LIST_APPEND`.
1213    pub(super) fn is_const_var(&self, key: &str) -> bool {
1214        for idx in (0..self.var_scopes.len()).rev() {
1215            if self.var_scopes[idx].contains_key(key) {
1216                return self
1217                    .const_scopes
1218                    .get(idx)
1219                    .is_some_and(|frame| frame.contains(key));
1220            }
1221        }
1222        if let Some(module) = self.current_module()
1223            && let Some(record) = self.modules.get(&module)
1224            && let Some(init) = record.init.as_ref()
1225            && init.vars.contains_key(key)
1226        {
1227            return init.const_vars.contains(key);
1228        }
1229        // Entry `CONST`s are visible by fallback (#318): no synthetic
1230        // seed frame, just the init store filtered to consts.
1231        self.entry_const_init()
1232            .is_some_and(|init| init.vars.contains_key(key) && init.const_vars.contains(key))
1233    }
1234
1235    /// Shared declaration switch behind `LET` and `CONST` capture,
1236    /// async, and await paths: one call site per declare, so a new
1237    /// binding form cannot forget the const branch.
1238    pub(super) fn declare_binding(
1239        &mut self,
1240        key: String,
1241        kind: TypeTag,
1242        value: Value,
1243        is_const: bool,
1244    ) -> DiagnosticResult<()> {
1245        if is_const {
1246            self.declare_const(key, kind, value)
1247        } else {
1248            self.declare_var(key, kind, value)
1249        }
1250    }
1251
1252    pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> DiagnosticResult<()> {
1253        if self.is_const_var(key) {
1254            return Err(state_diag::eval_const_mutation(key));
1255        }
1256        let kind = self
1257            .var_scopes
1258            .iter()
1259            .rev()
1260            .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
1261            .or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
1262            .ok_or_else(|| state_diag::eval_undeclared_declare(key, KEYWORD_TYPE))?;
1263        let coerced = super::args::coerce_value(value, &kind)?;
1264        for scope in self.var_scopes.iter_mut().rev() {
1265            if let Some(slot) = scope.get_mut(key) {
1266                slot.1 = coerced;
1267                return Ok(());
1268            }
1269        }
1270        // Not a lexical binding: update the owning module's shared
1271        // store in place, so every alias observes the mutation.
1272        if let Some((_, stored)) = self.module_var_mut(key) {
1273            *stored = coerced;
1274            return Ok(());
1275        }
1276        Err(state_diag::eval_undeclared(key))
1277    }
1278
1279    /// Append `item` to the LIST binding `key` in place. Copy-on-write:
1280    /// the buffer detaches only when shared, so aliases keep their
1281    /// contents; the sole owner mutates with no copy. Bails for
1282    /// undeclared names and non-list bindings. Shaped lists validate
1283    /// the item against the element tag, so a push can never silently
1284    /// corrupt the shape the declaration promises.
1285    pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> DiagnosticResult<()> {
1286        if self.is_const_var(key) {
1287            return Err(state_diag::eval_const_mutation(key));
1288        }
1289        let kind = self
1290            .var_scopes
1291            .iter()
1292            .rev()
1293            .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
1294            .or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
1295            .ok_or_else(|| {
1296                state_diag::eval_undeclared_declare(key, &format!("{LIST_TYPE_NAME}<...>"))
1297            })?;
1298        let element = match kind {
1299            TypeTag::List => None,
1300            TypeTag::ListOf(element) => Some(element.as_ref().clone()),
1301            _ => {
1302                return Err(state_diag::eval_list_not_list(key, kind.name()));
1303            }
1304        };
1305        for scope in self.var_scopes.iter_mut().rev() {
1306            if let Some(slot) = scope.get_mut(key) {
1307                if slot.1.is_frozen() {
1308                    return Err(state_diag::eval_const_mutation(key));
1309                }
1310                let list = slot
1311                    .1
1312                    .as_list_mut()
1313                    .ok_or_else(|| state_diag::eval_list_value_not_list(key))?;
1314                if let Some(expected) = element {
1315                    oxdock_parser::check_value_at(
1316                        &expected,
1317                        &item,
1318                        &format!("{}[{}]", sigil_var(key), list.len()),
1319                    )
1320                    .map_err(|err| state_diag::eval_list_element_failed(&err))?;
1321                }
1322                list.push(item);
1323                return Ok(());
1324            }
1325        }
1326        // Not a lexical binding: append to the owning module's shared
1327        // store in place, so module-global lists stay appendable from
1328        // module-owned functions with no importer visibility.
1329        if let Some((_, value)) = self.module_var_mut(key) {
1330            if value.is_frozen() {
1331                return Err(state_diag::eval_const_mutation(key));
1332            }
1333            let list = value
1334                .as_list_mut()
1335                .ok_or_else(|| state_diag::eval_list_value_not_list(key))?;
1336            if let Some(expected) = element {
1337                oxdock_parser::check_value_at(
1338                    &expected,
1339                    &item,
1340                    &format!("{}[{}]", sigil_var(key), list.len()),
1341                )
1342                .map_err(|err| state_diag::eval_list_element_failed(&err))?;
1343            }
1344            list.push(item);
1345            return Ok(());
1346        }
1347        Err(state_diag::eval_undeclared(key))
1348    }
1349
1350    pub(super) fn get_var(&self, key: &str) -> Option<Value> {
1351        // Walk scopes from innermost to outermost
1352        for scope in self.var_scopes.iter().rev() {
1353            if let Some((_, value)) = scope.get(key) {
1354                return Some(value.clone());
1355            }
1356        }
1357        // Module-owned code falls back to the owning module's shared
1358        // store (#115): one file's functions share one global state.
1359        if let Some((_, value)) = self.module_var(key) {
1360            return Some(value.clone());
1361        }
1362        // Entry `CONST` fallback (#318): same init-store read the seed
1363        // frame copied, filtered to consts so `LET`s never cross.
1364        if let Some(init) = self.entry_const_init()
1365            && let Some((_, value)) = init.vars.get(key)
1366            && init.const_vars.contains(key)
1367        {
1368            return Some(value.clone());
1369        }
1370        None
1371    }
1372
1373    pub(super) fn get_var_typed(&self, key: &str) -> Option<(TypeTag, Value)> {
1374        for scope in self.var_scopes.iter().rev() {
1375            if let Some(entry) = scope.get(key) {
1376                return Some(entry.clone());
1377            }
1378        }
1379        if let Some(entry) = self.module_var(key) {
1380            return Some(entry.clone());
1381        }
1382        if let Some(init) = self.entry_const_init()
1383            && let Some(entry) = init.vars.get(key)
1384            && init.const_vars.contains(key)
1385        {
1386            return Some(entry.clone());
1387        }
1388        None
1389    }
1390
1391    /// Owning module of the executing code (#115): the top of the
1392    /// module stack when it names a module, `None` past an entry
1393    /// boundary or outside any module. Lookups stop at the first
1394    /// entry from the top, so entry functions called from module
1395    /// code stay params-only.
1396    pub(super) fn current_module(&self) -> Option<String> {
1397        match self.module_stack.last() {
1398            Some(Some(key)) => Some(key.clone()),
1399            _ => None,
1400        }
1401    }
1402
1403    /// Frame-1 file scope for one unit: entry and modules share this
1404    /// one lookup, so the runtime walk reads the same shape for both.
1405    /// `None` only when the unit record is absent (never after
1406    /// validation, which registers the entry record).
1407    pub(super) fn unit_top_funcs(&self, unit: &str) -> Option<&HashMap<String, Vec<RawFuncDef>>> {
1408        self.modules.get(unit).map(|record| &record.top_funcs)
1409    }
1410
1411    /// One lookup for the owning module's shared store (#115): the
1412    /// single fallback every variable accessor uses after its lexical
1413    /// walk misses, so module-global visibility lives in exactly one
1414    /// place. Entry code never reaches here (its boundary pushes
1415    /// `None`, and `current_module` yields nothing then).
1416    fn module_var(&self, key: &str) -> Option<&(TypeTag, Value)> {
1417        self.module_store()?.get(key)
1418    }
1419
1420    /// Mutable twin of [`ExecState::module_var`], for the two
1421    /// accessors that write through to the store in place.
1422    fn module_var_mut(&mut self, key: &str) -> Option<&mut (TypeTag, Value)> {
1423        self.module_store_mut()?.get_mut(key)
1424    }
1425
1426    /// Get a flattened view of all variables across all scopes.
1427    /// Inner scopes take precedence over outer scopes. Module-owned
1428    /// code additionally sees the owning module's shared store beneath
1429    /// every lexical frame; entry code sees the entry `CONST` fallback
1430    /// (filtered to consts) instead of a seed frame.
1431    pub(super) fn all_vars(&self) -> HashMap<String, Value> {
1432        let mut result = HashMap::new();
1433        for scope in self.var_scopes.iter().rev() {
1434            for (k, (_, v)) in scope {
1435                result.entry(k.clone()).or_insert_with(|| v.clone());
1436            }
1437        }
1438        if let Some(store) = self.module_store() {
1439            for (k, (_, v)) in store {
1440                result.entry(k.clone()).or_insert_with(|| v.clone());
1441            }
1442        }
1443        if let Some(init) = self.entry_const_init() {
1444            for (k, (_, v)) in &init.vars {
1445                if init.const_vars.contains(k) {
1446                    result.entry(k.clone()).or_insert_with(|| v.clone());
1447                }
1448            }
1449        }
1450        result
1451    }
1452
1453    /// Borrow the owning module's shared store, if any. The single
1454    /// map behind [`ExecState::module_var`], exposed whole for the
1455    /// one accessor that flattens every binding.
1456    fn module_store(&self) -> Option<&HashMap<String, (TypeTag, Value)>> {
1457        let module = self.current_module()?;
1458        self.modules
1459            .get(&module)?
1460            .init
1461            .as_ref()
1462            .map(|init| &init.vars)
1463    }
1464
1465    /// Mutable twin of [`ExecState::module_store`], for the accessors
1466    /// that write through to the store in place.
1467    fn module_store_mut(&mut self) -> Option<&mut HashMap<String, (TypeTag, Value)>> {
1468        let module = self.current_module()?;
1469        self.modules
1470            .get_mut(&module)?
1471            .init
1472            .as_mut()
1473            .map(|init| &mut init.vars)
1474    }
1475}
1476
1477/// Mark every pipe handle reachable from `value` as shared-with-a-child.
1478/// Pipes travel inside lists and maps (`LET $bag: LIST = [$p]`), so a
1479/// shallow top-level check would miss them and let a later promotion
1480/// corrupt the shared EOF contract. Values form a tree, so recursion
1481/// terminates; host-opaque payloads cannot carry handles.
1482fn mark_value_pipes_escaped(value: &Value) {
1483    if let Some(handle) = value.as_pipe_handle() {
1484        handle.mark_escaped();
1485        return;
1486    }
1487    if let Some(items) = value.as_list() {
1488        for item in items {
1489            mark_value_pipes_escaped(item);
1490        }
1491    }
1492    if let Some(entries) = value.as_map() {
1493        for item in entries.values() {
1494            mark_value_pipes_escaped(item);
1495        }
1496    }
1497}