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