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::{Diagnostic, 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_diag;
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) -> Diagnostic {
65 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 // Diagnostic-native completion: `try_wait` already
696 // returns the keyed payload, so no anyhow echo is
697 // needed. `exit_code_of_diag` walks the `Diagnostic`
698 // source chain for the code, and `flatten_chain`
699 // renders exactly what `{err:#}` printed for the
700 // single-wrap chain, keeping the stored text
701 // byte-identical.
702 let completion = TaskCompletion {
703 ok: false,
704 exit_code: exit_code_of_diag(&err).unwrap_or(1),
705 result: None,
706 error: state_diag::flatten_chain(&err),
707 };
708 guard.completion = Some(TaskCompletion {
709 ok: completion.ok,
710 exit_code: completion.exit_code,
711 result: completion.result.clone(),
712 error: completion.error.clone(),
713 });
714 TaskObservation {
715 running: false,
716 ok: completion.ok,
717 exit_code: completion.exit_code,
718 result: completion.result,
719 error: completion.error,
720 }
721 }
722 },
723 }
724 }
725
726 /// Block until the teardown owner has consumed the handle and joined
727 /// the task thread. Lock-free for callers except the wait itself.
728 pub(super) fn wait_reaped(&self) {
729 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
730 while !guard.reaped {
731 guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
732 }
733 }
734
735 /// Mark teardown complete and wake every rendezvous waiter.
736 pub(super) fn finish_teardown(&self) {
737 {
738 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
739 guard.handle = None;
740 guard.reaped = true;
741 }
742 self.done.notify_all();
743 }
744}
745
746/// Step-indexed keeper expiry for one `ASYNC` worker thread. Guards are
747/// keyed by the top-level body index of the final producer step for each
748/// pipe: dropping the guards for step `k` once it completes keeps the
749/// pipe open across every transient gap between producers, then releases
750/// it so later consumer steps in the same task observe EOF.
751///
752/// Slice identity (`body_addr`/`body_len`) gates discharge: nested bodies
753/// (`FOR`/`IF`/`TIMEOUT`/inner `ASYNC`) execute through the same stepping
754/// code with different slices and must never consume the worker's
755/// top-level map.
756pub(super) struct KeeperExpiry {
757 body_addr: usize,
758 body_len: usize,
759 map: HashMap<usize, Vec<KeeperGuard>>,
760}
761
762impl KeeperExpiry {
763 pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
764 Self {
765 body_addr: steps.as_ptr() as usize,
766 body_len: steps.len(),
767 map,
768 }
769 }
770
771 pub(super) fn matches(&self, steps: &[Step]) -> bool {
772 self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
773 }
774
775 /// Drop the guards expiring at top-level step `idx`. Returns true when
776 /// the map is drained and the expiry itself can be cleared.
777 pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
778 if self.matches(steps) {
779 drop(self.map.remove(&idx));
780 }
781 self.map.is_empty()
782 }
783}
784
785/// Defining-file call context (#322): (envs, inherit names,
786/// selection, cwd). One alias shared by the resolver and every call
787/// site, never a restated tuple.
788pub(super) type FileCallCtx = (
789 HashMap<String, String>,
790 Vec<String>,
791 WorkspaceSelection,
792 GuardedPath,
793);
794
795impl<P: ProcessManager> ExecState<P> {
796 /// Script-map environment lookup for DSL evaluation (`is_exec_name`,
797 /// `Expr::Env`, expansions): exact hit first, case-insensitive
798 /// fallback on Windows so `{{ env:Path }}` resolves the seeded
799 /// `PATH`. The map is seeded at init, so no fallback layer exists.
800 pub(super) fn get_env(&self, key: &str) -> Option<&str> {
801 if let Some(v) = self.envs.get(key) {
802 return Some(v.as_str());
803 }
804 #[allow(clippy::disallowed_macros)]
805 if cfg!(windows) {
806 return self
807 .envs
808 .iter()
809 .find(|(k, _)| oxdock_process::names_eq(k, key))
810 .map(|(_, v)| v.as_str());
811 }
812 None
813 }
814
815 pub(super) fn command_ctx(&self) -> DiagnosticResult<CommandContext> {
816 // Resolve the working directory through the snapshot choke point: a
817 // snapshot-rooted cwd materializes here (so `RUN` executes against a
818 // real directory) while a local cwd resolves purely lexically with
819 // zero I/O. The seeded scratch materializes alongside: `HOME` and
820 // `TMPDIR` point at it, so children writing temp or profile data
821 // must observe real directories, never lexical candidates.
822 let cwd = self
823 .fs
824 .resolve_write(&self.cwd, ".")
825 .map_err(|err| state_diag::eval_workdir_resolve_failed(&err))?;
826 self.cargo_scratch
827 .ensure_materialized()
828 .map_err(|err| state_diag::eval_scratch_materialize_failed(&err))?;
829 Ok(CommandContext::new(
830 &cwd.into(),
831 Arc::clone(&self.envs),
832 &self.cargo_scratch,
833 self.fs.root(),
834 self.fs.build_context(),
835 ))
836 }
837
838 /// Draw the next task id, enforcing the global live-task cap and
839 /// sweeping retained finished entries. Every ASYNC allocation path
840 /// calls this, so named and anonymous tasks share one choke point.
841 /// The live count is atomic and shared across all forked workers,
842 /// so nested spawns cannot bypass the cap that a per-state scan
843 /// would miss. Refusal is backpressure: a full host fails the spawn
844 /// loudly instead of wedging.
845 pub(super) fn alloc_task_id(&mut self) -> DiagnosticResult<u64> {
846 // Purge cleanly-finished anonymous children first: their threads
847 // are gone and a zero exit has no reporter, so retaining them
848 // only grows the vec. Failed handles stay for the end-pipeline
849 // reaper, which owns their error reporting.
850 self.bg_children
851 .retain_mut(|child| match child.handle.try_wait() {
852 Ok(None) => true,
853 Ok(Some(status)) => !status.success(),
854 Err(_) => true,
855 });
856 self.live_tasks
857 .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
858 (n < MAX_RUNNING_TASKS as u64).then_some(n + 1)
859 })
860 .map_err(|_| state_diag::eval_task_cap_exceeded(MAX_RUNNING_TASKS as u64))?;
861 let id = self.next_task_id.fetch_add(1, Ordering::SeqCst);
862 self.sweep_finished_tasks();
863 Ok(id)
864 }
865
866 /// Drop finished entries past `MAX_RETAINED_FINISHED`, oldest
867 /// first. Finished means a terminal phase or a completed join;
868 /// `Awaiting` entries always survive (a waiter is rendezvousing)
869 /// and running entries are never touched. Evicted ids read as
870 /// unknown/already-awaited afterwards, like an awaited task.
871 fn sweep_finished_tasks(&self) {
872 let mut finished: Vec<u64> = Vec::new();
873 {
874 let named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
875 for (id, entry) in named.iter() {
876 // `is_live` already exempts awaiting entries: a waiter
877 // is rendezvousing on them.
878 if !entry.is_live() {
879 finished.push(*id);
880 }
881 }
882 }
883 if finished.len() <= MAX_RETAINED_FINISHED {
884 return;
885 }
886 finished.sort_unstable();
887 let mut named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
888 for id in finished.iter().take(finished.len() - MAX_RETAINED_FINISHED) {
889 named.remove(id);
890 }
891 }
892
893 /// Fork the execution state for a child thread. The child gets:
894 /// - A cloned filesystem handle (shared snapshot backing, independent root selection)
895 /// - Cloned envs, cwd, cargo scratch name, var_scopes, const_scopes
896 /// - Fresh bg_children, scope_stack (empty -- child manages its own)
897 /// - Block imports flattened into the cloned unit-top map (the live
898 /// frames stay with the parent's scopes, so the child observes
899 /// what the parent saw at spawn without inheriting unwindable frames)
900 /// - Shared assert_windows, assert_windows_stderr, exact_stdout (Arc clones)
901 /// - Cloned io configuration
902 /// - Independent cancel_token, active_process (child manages its own)
903 /// - Shared named_tasks and next_task_id (via Arc clone)
904 #[allow(dead_code)]
905 pub(super) fn fork(&self) -> Self {
906 let mut executed_alias_targets = self.executed_alias_targets.clone();
907 for frame in &self.scope_alias_frames {
908 for (alias, targets) in &frame.targets {
909 executed_alias_targets
910 .entry(frame.unit.clone())
911 .or_default()
912 .entry(alias.clone())
913 .or_default()
914 .extend(targets.iter().cloned());
915 }
916 }
917 Self {
918 fs: self.fs.clone_box(),
919 cargo_scratch: self.cargo_scratch.clone(),
920 seed: Arc::clone(&self.seed),
921 cwd: self.cwd.clone(),
922 envs: Arc::clone(&self.envs),
923 bg_children: Vec::new(),
924 scope_stack: Vec::new(),
925 isolated_stack: self.isolated_stack.clone(),
926 io: self.io.clone(),
927 assert_windows: Arc::clone(&self.assert_windows),
928 assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
929 exact_stdout: Arc::clone(&self.exact_stdout),
930 var_scopes: self.var_scopes.clone(),
931 const_scopes: self.const_scopes.clone(),
932 cancel_token: Arc::new(AtomicBool::new(false)),
933 // Fresh cancellation, inherited telemetry: the fork's
934 // workers still attribute to the originating run.
935 cancel_hub: Arc::new(CancelHub::with_counter(self.cancel_hub.worker_counter())),
936 active_process: Arc::new(Mutex::new(None)),
937 named_tasks: Arc::clone(&self.named_tasks),
938 next_task_id: Arc::clone(&self.next_task_id),
939 // Shared live count, never reset: nested workers report into
940 // the same cap their spawner was admitted under.
941 live_tasks: Arc::clone(&self.live_tasks),
942 inside_async: true,
943 keeper_expiry: None,
944 cancellable: self.cancellable,
945 reap_floor: self.reap_floor,
946 functions: self.functions.clone(),
947 entry_file: self.entry_file.clone(),
948 import_stack: self.import_stack.clone(),
949 modules: self.modules.clone(),
950 validated_modules: self.validated_modules.clone(),
951 module_stack: self.module_stack.clone(),
952 executed_alias_targets,
953 call_alias_frames: self.call_alias_frames.clone(),
954 scope_alias_frames: Vec::new(),
955 init_scope_depths: Vec::new(),
956 func_floors: self.func_floors.clone(),
957 harvest_map: self.harvest_map.clone(),
958 module_table: self.module_table.clone(),
959 types: self.types.clone(),
960 record_schemas: self.record_schemas.clone(),
961 module_states: self.module_states.clone(),
962 type_aliases: self.type_aliases.clone(),
963 type_env_digest: self.type_env_digest,
964 call_depth: self.call_depth,
965 init_inherit_stack: self.init_inherit_stack.clone(),
966 task_id: self.task_id,
967 // Forks start with an empty manifest: async children record
968 // their own executions; the guest packs the root manifest.
969 push_manifest: Vec::new(),
970 _marker: PhantomData,
971 }
972 }
973
974 /// Whether `pipe` may promote to an OS kernel pair on behalf of
975 /// `task_id`: only when it was declared by that same task and no
976 /// spawned child can observe it. Anything else stays script-backed, so
977 /// concurrent tasks can never disagree about EOF propagation.
978 /// Spawning tasks pass their worker id (not the spawner's): promotion
979 /// is judged from the worker's perspective, since it is the worker's
980 /// bindings that will hold raw descriptors.
981 pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
982 pipe.declaring_task() == task_id && !pipe.has_escaped()
983 }
984
985 /// Whether `pipe` may promote on the current thread (main flow and
986 /// inline resolves).
987 pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
988 Self::can_promote_in_task(pipe, self.task_id)
989 }
990
991 /// Mark every pipe visible in scope as shared-with-a-child. Called
992 /// synchronously on the spawner before a worker thread starts: forking
993 /// copies the whole environment, so every visible pipe is capturable
994 /// whether or not the child body names it. Over-marking only costs
995 /// zero-copy opportunities, never correctness.
996 pub(super) fn mark_captured_pipes_escaped(&self) {
997 for scope in self.var_scopes.iter() {
998 for (_, value) in scope.values() {
999 mark_value_pipes_escaped(value);
1000 }
1001 }
1002 for record in self.modules.values() {
1003 if let Some(init) = record.init.as_ref() {
1004 for entry in init.vars.values() {
1005 mark_value_pipes_escaped(&entry.1);
1006 }
1007 }
1008 }
1009 }
1010
1011 pub(super) fn push_var_scope(&mut self) {
1012 self.var_scopes.push(HashMap::new());
1013 self.const_scopes.push(HashSet::new());
1014 }
1015
1016 pub(super) fn pop_var_scope(&mut self) {
1017 self.var_scopes.pop();
1018 self.const_scopes.pop();
1019 }
1020
1021 /// Reset module-owned env (#115, #322): env to the module init
1022 /// stored map. Workspace and cwd are reset separately by the
1023 /// caller to the snapshot jail, so a module never observes the
1024 /// importer workspace. The surrounding `push_scope` restores the
1025 /// caller afterwards.
1026 pub(super) fn reset_module_env(&mut self, envs: HashMap<String, String>) {
1027 self.envs = Arc::new(envs);
1028 }
1029
1030 /// Entry top-level tracking (#322 follow-up): true only for the
1031 /// entry prelude itself, never inside any call, module, or
1032 /// lexical block. Blocks (`ISOLATED`, `IF`, `FOR`, `WHILE`,
1033 /// `SWITCH`, `WITH_IO`) push `scope_stack` so their env unwinds
1034 /// on exit; capturing those writes would leak block-scoped and
1035 /// isolated secrets into every later entry call. Guard-gated
1036 /// top-level statements execute without pushing a scope, so
1037 /// conditional configuration still seeds the prelude. Caller
1038 /// env must never flow into the entry prelude store: `INHERIT_ENV`
1039 /// inherits from the engine, never another script, ever.
1040 pub(super) fn is_entry_top_level(&self) -> bool {
1041 self.call_depth == 0 && self.module_stack.is_empty() && self.scope_stack.is_empty()
1042 }
1043
1044 /// Defining-file call context (#322): the single owner resolving
1045 /// what a `FUNC` body restores. The definition-site jail wins
1046 /// when the definition sealed one; otherwise the defining file
1047 /// fallback applies (module init jail, entry snapshot default).
1048 /// Env always resolves file-level (module init delta, entry
1049 /// prelude) with `INHERIT_ENV` re-read from the engine, never
1050 /// caller ambient. One lookup for every file, entry included:
1051 /// the entry record lives under the sentinel, so callers never
1052 /// restate a `Some`/`None` branch. Spelled once as [`FileCallCtx`].
1053 pub(super) fn callee_file_ctx(
1054 &self,
1055 module_key: Option<&str>,
1056 def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1057 ) -> Option<FileCallCtx> {
1058 let unit = super::import::unit_key(module_key);
1059 if let Some((selection, cwd)) = def_jail {
1060 let (envs, inherit_names) = self.modules.get(unit).and_then(|record| {
1061 record
1062 .init
1063 .as_ref()
1064 .map(|init| (init.envs.clone(), init.inherit_names.clone()))
1065 })?;
1066 return Some((envs, inherit_names, selection, cwd));
1067 }
1068 self.modules.get(unit).and_then(|record| {
1069 record.init.as_ref().map(|init| {
1070 (
1071 init.envs.clone(),
1072 init.inherit_names.clone(),
1073 init.selection,
1074 init.cwd.clone(),
1075 )
1076 })
1077 })
1078 }
1079
1080 /// Enter a lexical scope: snapshot cwd/root/envs and open a fresh
1081 /// variable scope. Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE);
1082 /// only pipes (ExecIo) and filesystem effects cross scope boundaries.
1083 /// Function definitions scope through the registry's own frames.
1084 pub(super) fn push_scope(&mut self) {
1085 self.scope_stack.push(ScopeSnapshot {
1086 cwd: self.cwd.clone(),
1087 selection: self.fs.selection(),
1088 envs: Arc::clone(&self.envs),
1089 });
1090 self.functions.push_scope();
1091 self.push_var_scope();
1092 }
1093
1094 /// Exit a lexical scope, restoring everything `push_scope` saved
1095 /// plus dropping block import frames deeper than the surviving
1096 /// stack, so block imports unwind with their block.
1097 pub(super) fn pop_scope(&mut self) -> DiagnosticResult<()> {
1098 let snapshot = self
1099 .scope_stack
1100 .pop()
1101 .ok_or_else(state_diag::eval_scope_underflow)?;
1102 self.fs.restore_selection(snapshot.selection);
1103 self.cwd = snapshot.cwd;
1104 self.envs = snapshot.envs;
1105 self.functions.pop_scope();
1106 self.pop_var_scope();
1107 let depth = self.scope_stack.len();
1108 self.scope_alias_frames.retain(|frame| frame.depth <= depth);
1109 Ok(())
1110 }
1111 pub(super) fn declare_var(
1112 &mut self,
1113 key: String,
1114 kind: TypeTag,
1115 value: Value,
1116 ) -> DiagnosticResult<()> {
1117 if self
1118 .var_scopes
1119 .last()
1120 .map(|s| s.contains_key(&key))
1121 .unwrap_or(false)
1122 {
1123 return Err(state_diag::eval_redeclare_var(&key));
1124 }
1125 let coerced = super::args::coerce_value(value, &kind)?;
1126 let scope = self
1127 .var_scopes
1128 .last_mut()
1129 .ok_or_else(state_diag::eval_no_var_scope)?;
1130 scope.insert(key, (kind, coerced));
1131 Ok(())
1132 }
1133
1134 /// Declare a `CONST` binding: same namespace as
1135 /// [`declare_var`](Self::declare_var)
1136 /// (a `LET` and a `CONST` cannot share a name in one frame), then
1137 /// mark the frame const and deep-freeze the value, so nested
1138 /// containers freeze with the binding instead of aliasing a
1139 /// mutable buffer.
1140 pub(super) fn declare_const(
1141 &mut self,
1142 key: String,
1143 kind: TypeTag,
1144 value: Value,
1145 ) -> DiagnosticResult<()> {
1146 let at_entry_top = self.is_entry_top_level();
1147 if self
1148 .var_scopes
1149 .last()
1150 .map(|s| s.contains_key(&key))
1151 .unwrap_or(false)
1152 {
1153 return Err(state_diag::eval_redeclare_const(&key));
1154 }
1155 let coerced = super::args::coerce_value(value, &kind)?;
1156 let frozen = Value::deep_freeze(&coerced);
1157 let scope = self
1158 .var_scopes
1159 .last_mut()
1160 .ok_or_else(state_diag::eval_no_var_scope)?;
1161 scope.insert(key.clone(), (kind.clone(), frozen.clone()));
1162 if let Some(frame) = self.const_scopes.last_mut() {
1163 frame.insert(key.clone());
1164 }
1165 if at_entry_top {
1166 // Entry prelude capture: the entry record's init store
1167 // holds the top-level `CONST`s seeded into every entry
1168 // call, mirroring how module inits drain theirs.
1169 if let Some(init) = self
1170 .modules
1171 .get_mut(super::import::ENTRY_UNIT)
1172 .and_then(|record| record.init.as_mut())
1173 {
1174 init.vars.insert(key.clone(), (kind, frozen));
1175 init.const_vars.insert(key);
1176 }
1177 }
1178 Ok(())
1179 }
1180
1181 /// Whether the entry-`CONST` fallback applies here: entry context
1182 /// (no owning module) whose caller is also entry (or top level).
1183 /// Entry callees called from module code stay params-only, so a
1184 /// module caller never observes entry file state. Single owner
1185 /// for the caller check every entry fallback reads.
1186 fn entry_fallback_allowed(&self) -> bool {
1187 if self.current_module().is_some() {
1188 return false;
1189 }
1190 match self.module_stack.len() {
1191 0 => true,
1192 1 => true,
1193 _ => matches!(
1194 self.module_stack.get(self.module_stack.len() - 2),
1195 None | Some(None)
1196 ),
1197 }
1198 }
1199
1200 /// Entry-`CONST` fallback init: the entry record's init when the
1201 /// fallback is allowed (entry context whose caller is also entry).
1202 /// Single owner for the caller check plus the init borrow, so
1203 /// every entry fallback reads hashes `ENTRY_UNIT` and checks the
1204 /// caller once. Call sites filter to `const_vars`, so `LET`s never
1205 /// cross.
1206 fn entry_const_init(&self) -> Option<&ModuleInit> {
1207 if !self.entry_fallback_allowed() {
1208 return None;
1209 }
1210 self.modules.get(super::import::ENTRY_UNIT)?.init.as_ref()
1211 }
1212
1213 /// Whether `key` names a `CONST` binding visible here: the
1214 /// innermost lexical frame holding the name decides (a local
1215 /// `LET` shadowing a module-level `CONST` stays mutable), exactly
1216 /// mirroring [`mutate_var`](Self::mutate_var)'s resolution; only
1217 /// when no lexical frame declares the name does the owning
1218 /// module's shared store answer. Single owner for the const check
1219 /// behind `$var = <expr>` reassignment and `LIST_APPEND`.
1220 pub(super) fn is_const_var(&self, key: &str) -> bool {
1221 for idx in (0..self.var_scopes.len()).rev() {
1222 if self.var_scopes[idx].contains_key(key) {
1223 return self
1224 .const_scopes
1225 .get(idx)
1226 .is_some_and(|frame| frame.contains(key));
1227 }
1228 }
1229 if let Some(module) = self.current_module()
1230 && let Some(record) = self.modules.get(&module)
1231 && let Some(init) = record.init.as_ref()
1232 && init.vars.contains_key(key)
1233 {
1234 return init.const_vars.contains(key);
1235 }
1236 // Entry `CONST`s are visible by fallback (#318): no synthetic
1237 // seed frame, just the init store filtered to consts.
1238 self.entry_const_init()
1239 .is_some_and(|init| init.vars.contains_key(key) && init.const_vars.contains(key))
1240 }
1241
1242 /// Shared declaration switch behind `LET` and `CONST` capture,
1243 /// async, and await paths: one call site per declare, so a new
1244 /// binding form cannot forget the const branch.
1245 pub(super) fn declare_binding(
1246 &mut self,
1247 key: String,
1248 kind: TypeTag,
1249 value: Value,
1250 is_const: bool,
1251 ) -> DiagnosticResult<()> {
1252 if is_const {
1253 self.declare_const(key, kind, value)
1254 } else {
1255 self.declare_var(key, kind, value)
1256 }
1257 }
1258
1259 pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> DiagnosticResult<()> {
1260 if self.is_const_var(key) {
1261 return Err(state_diag::eval_const_mutation(key));
1262 }
1263 let kind = self
1264 .var_scopes
1265 .iter()
1266 .rev()
1267 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
1268 .or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
1269 .ok_or_else(|| state_diag::eval_undeclared_declare(key, KEYWORD_TYPE))?;
1270 let coerced = super::args::coerce_value(value, &kind)?;
1271 for scope in self.var_scopes.iter_mut().rev() {
1272 if let Some(slot) = scope.get_mut(key) {
1273 slot.1 = coerced;
1274 return Ok(());
1275 }
1276 }
1277 // Not a lexical binding: update the owning module's shared
1278 // store in place, so every alias observes the mutation.
1279 if let Some((_, stored)) = self.module_var_mut(key) {
1280 *stored = coerced;
1281 return Ok(());
1282 }
1283 Err(state_diag::eval_undeclared(key))
1284 }
1285
1286 /// Append `item` to the LIST binding `key` in place. Copy-on-write:
1287 /// the buffer detaches only when shared, so aliases keep their
1288 /// contents; the sole owner mutates with no copy. Bails for
1289 /// undeclared names and non-list bindings. Shaped lists validate
1290 /// the item against the element tag, so a push can never silently
1291 /// corrupt the shape the declaration promises.
1292 pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> DiagnosticResult<()> {
1293 if self.is_const_var(key) {
1294 return Err(state_diag::eval_const_mutation(key));
1295 }
1296 let kind = self
1297 .var_scopes
1298 .iter()
1299 .rev()
1300 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
1301 .or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
1302 .ok_or_else(|| {
1303 state_diag::eval_undeclared_declare(key, &format!("{LIST_TYPE_NAME}<...>"))
1304 })?;
1305 let element = match kind {
1306 TypeTag::List => None,
1307 TypeTag::ListOf(element) => Some(element.as_ref().clone()),
1308 _ => {
1309 return Err(state_diag::eval_list_not_list(key, kind.name()));
1310 }
1311 };
1312 for scope in self.var_scopes.iter_mut().rev() {
1313 if let Some(slot) = scope.get_mut(key) {
1314 if slot.1.is_frozen() {
1315 return Err(state_diag::eval_const_mutation(key));
1316 }
1317 let list = slot
1318 .1
1319 .as_list_mut()
1320 .ok_or_else(|| state_diag::eval_list_value_not_list(key))?;
1321 if let Some(expected) = element {
1322 oxdock_parser::check_value_at(
1323 &expected,
1324 &item,
1325 &format!("{}[{}]", sigil_var(key), list.len()),
1326 )
1327 .map_err(|err| state_diag::eval_list_element_failed(&err))?;
1328 }
1329 list.push(item);
1330 return Ok(());
1331 }
1332 }
1333 // Not a lexical binding: append to the owning module's shared
1334 // store in place, so module-global lists stay appendable from
1335 // module-owned functions with no importer visibility.
1336 if let Some((_, value)) = self.module_var_mut(key) {
1337 if value.is_frozen() {
1338 return Err(state_diag::eval_const_mutation(key));
1339 }
1340 let list = value
1341 .as_list_mut()
1342 .ok_or_else(|| state_diag::eval_list_value_not_list(key))?;
1343 if let Some(expected) = element {
1344 oxdock_parser::check_value_at(
1345 &expected,
1346 &item,
1347 &format!("{}[{}]", sigil_var(key), list.len()),
1348 )
1349 .map_err(|err| state_diag::eval_list_element_failed(&err))?;
1350 }
1351 list.push(item);
1352 return Ok(());
1353 }
1354 Err(state_diag::eval_undeclared(key))
1355 }
1356
1357 pub(super) fn get_var(&self, key: &str) -> Option<Value> {
1358 // Walk scopes from innermost to outermost
1359 for scope in self.var_scopes.iter().rev() {
1360 if let Some((_, value)) = scope.get(key) {
1361 return Some(value.clone());
1362 }
1363 }
1364 // Module-owned code falls back to the owning module's shared
1365 // store (#115): one file's functions share one global state.
1366 if let Some((_, value)) = self.module_var(key) {
1367 return Some(value.clone());
1368 }
1369 // Entry `CONST` fallback (#318): same init-store read the seed
1370 // frame copied, filtered to consts so `LET`s never cross.
1371 if let Some(init) = self.entry_const_init()
1372 && let Some((_, value)) = init.vars.get(key)
1373 && init.const_vars.contains(key)
1374 {
1375 return Some(value.clone());
1376 }
1377 None
1378 }
1379
1380 pub(super) fn get_var_typed(&self, key: &str) -> Option<(TypeTag, Value)> {
1381 for scope in self.var_scopes.iter().rev() {
1382 if let Some(entry) = scope.get(key) {
1383 return Some(entry.clone());
1384 }
1385 }
1386 if let Some(entry) = self.module_var(key) {
1387 return Some(entry.clone());
1388 }
1389 if let Some(init) = self.entry_const_init()
1390 && let Some(entry) = init.vars.get(key)
1391 && init.const_vars.contains(key)
1392 {
1393 return Some(entry.clone());
1394 }
1395 None
1396 }
1397
1398 /// Owning module of the executing code (#115): the top of the
1399 /// module stack when it names a module, `None` past an entry
1400 /// boundary or outside any module. Lookups stop at the first
1401 /// entry from the top, so entry functions called from module
1402 /// code stay params-only.
1403 pub(super) fn current_module(&self) -> Option<String> {
1404 match self.module_stack.last() {
1405 Some(Some(key)) => Some(key.clone()),
1406 _ => None,
1407 }
1408 }
1409
1410 /// Frame-1 file scope for one unit: entry and modules share this
1411 /// one lookup, so the runtime walk reads the same shape for both.
1412 /// `None` only when the unit record is absent (never after
1413 /// validation, which registers the entry record).
1414 pub(super) fn unit_top_funcs(&self, unit: &str) -> Option<&HashMap<String, Vec<RawFuncDef>>> {
1415 self.modules.get(unit).map(|record| &record.top_funcs)
1416 }
1417
1418 /// One lookup for the owning module's shared store (#115): the
1419 /// single fallback every variable accessor uses after its lexical
1420 /// walk misses, so module-global visibility lives in exactly one
1421 /// place. Entry code never reaches here (its boundary pushes
1422 /// `None`, and `current_module` yields nothing then).
1423 fn module_var(&self, key: &str) -> Option<&(TypeTag, Value)> {
1424 self.module_store()?.get(key)
1425 }
1426
1427 /// Mutable twin of [`ExecState::module_var`], for the two
1428 /// accessors that write through to the store in place.
1429 fn module_var_mut(&mut self, key: &str) -> Option<&mut (TypeTag, Value)> {
1430 self.module_store_mut()?.get_mut(key)
1431 }
1432
1433 /// Get a flattened view of all variables across all scopes.
1434 /// Inner scopes take precedence over outer scopes. Module-owned
1435 /// code additionally sees the owning module's shared store beneath
1436 /// every lexical frame; entry code sees the entry `CONST` fallback
1437 /// (filtered to consts) instead of a seed frame.
1438 pub(super) fn all_vars(&self) -> HashMap<String, Value> {
1439 let mut result = HashMap::new();
1440 for scope in self.var_scopes.iter().rev() {
1441 for (k, (_, v)) in scope {
1442 result.entry(k.clone()).or_insert_with(|| v.clone());
1443 }
1444 }
1445 if let Some(store) = self.module_store() {
1446 for (k, (_, v)) in store {
1447 result.entry(k.clone()).or_insert_with(|| v.clone());
1448 }
1449 }
1450 if let Some(init) = self.entry_const_init() {
1451 for (k, (_, v)) in &init.vars {
1452 if init.const_vars.contains(k) {
1453 result.entry(k.clone()).or_insert_with(|| v.clone());
1454 }
1455 }
1456 }
1457 result
1458 }
1459
1460 /// Borrow the owning module's shared store, if any. The single
1461 /// map behind [`ExecState::module_var`], exposed whole for the
1462 /// one accessor that flattens every binding.
1463 fn module_store(&self) -> Option<&HashMap<String, (TypeTag, Value)>> {
1464 let module = self.current_module()?;
1465 self.modules
1466 .get(&module)?
1467 .init
1468 .as_ref()
1469 .map(|init| &init.vars)
1470 }
1471
1472 /// Mutable twin of [`ExecState::module_store`], for the accessors
1473 /// that write through to the store in place.
1474 fn module_store_mut(&mut self) -> Option<&mut HashMap<String, (TypeTag, Value)>> {
1475 let module = self.current_module()?;
1476 self.modules
1477 .get_mut(&module)?
1478 .init
1479 .as_mut()
1480 .map(|init| &mut init.vars)
1481 }
1482}
1483
1484/// Mark every pipe handle reachable from `value` as shared-with-a-child.
1485/// Pipes travel inside lists and maps (`LET $bag: LIST = [$p]`), so a
1486/// shallow top-level check would miss them and let a later promotion
1487/// corrupt the shared EOF contract. Values form a tree, so recursion
1488/// terminates; host-opaque payloads cannot carry handles.
1489fn mark_value_pipes_escaped(value: &Value) {
1490 if let Some(handle) = value.as_pipe_handle() {
1491 handle.mark_escaped();
1492 return;
1493 }
1494 if let Some(items) = value.as_list() {
1495 for item in items {
1496 mark_value_pipes_escaped(item);
1497 }
1498 }
1499 if let Some(entries) = value.as_map() {
1500 for item in entries.values() {
1501 mark_value_pipes_escaped(item);
1502 }
1503 }
1504}