Skip to main content

oxdock_core/exec/
state.rs

1use std::collections::HashMap;
2use std::marker::PhantomData;
3use std::sync::atomic::{AtomicBool, AtomicU64};
4use std::sync::{Arc, Condvar, Mutex};
5
6use anyhow::Result;
7use oxdock_fs::{CargoScratch, GuardedPath, WorkspaceFs};
8use oxdock_parser::{Field, Step, TypeDescriptor, TypeTag, Value};
9use oxdock_process::{BackgroundHandle, CancelHub, CommandContext, ProcessManager};
10
11use super::io::{ExactCapture, ExecIo, SlidingWindow};
12use super::native::FunctionRegistry;
13use oxdock_pipe::KeeperGuard;
14
15/// Maximum nested function-call depth. Guards the host thread stack against
16/// runaway recursion; the error names the function that overflowed.
17pub(super) const MAX_CALL_DEPTH: usize = 64;
18
19/// Execution state for one script run. Public so hosts can register
20/// functions and introspect listings; all fields stay crate-private so the
21/// scope, recursion-budget, and task invariants cannot be broken from outside.
22pub struct ExecState<P: ProcessManager> {
23    pub(super) fs: Box<dyn WorkspaceFs>,
24    /// Pre-reserved guarded scratch name for `CARGO_TARGET_DIR` (issue #131).
25    /// Opaque [`CargoScratch`]: renderable for the child environment but not
26    /// nameable as a `&GuardedPath`, so host code cannot `ensure()` or
27    /// `create_dir_all` it. The child `cargo` creates it on demand.
28    pub(super) cargo_scratch: CargoScratch,
29    /// Pure session seed from [`oxdock_process::seed_defaults`], stored at
30    /// init alongside the layered `envs`. `ISOLATED` resets clone this
31    /// (not the layered map), and transport sanitize diffs against it.
32    /// Built once: re-seeding would re-read host fallbacks and break
33    /// state stability.
34    pub(super) seed: Arc<HashMap<String, String>>,
35    pub(super) cwd: GuardedPath,
36    pub(super) envs: Arc<HashMap<String, String>>,
37    /// Outer-scope env snapshots for `ISOLATED` blocks, innermost last.
38    /// Each entry is the script env as it stood at that block's entry, so
39    /// the block allowlist resolves against the enclosing scope even as
40    /// the live envs are scrubbed underneath. Nesting snapshots the
41    /// already-scrubbed parent, so narrowing is monotonic by
42    /// construction. Cloned (not reset) by `fork()` so tasks spawned
43    /// inside a block inherit its scrub.
44    pub(super) isolated_stack: Vec<Arc<HashMap<String, String>>>,
45    pub(super) bg_children: Vec<Box<dyn BackgroundHandle>>,
46    pub(super) scope_stack: Vec<ScopeSnapshot>,
47    pub(super) io: ExecIo,
48    /// Pre-registered SlidingWindow observers for stream assertion steps.
49    /// Keyed by (generation, step index). TeeWriter pushes every chunk to all windows.
50    pub(super) assert_windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
51    /// Same observer map fed by the stderr tee for `ASSERT_CONTAINS stderr`.
52    pub(super) assert_windows_stderr: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
53    /// Exact-match stdout accumulators for `ASSERT_EQ stdout`, keyed by
54    /// generation and fed by the same tee. Entries allocated during
55    /// pre-registration observe bytes from scope entry; the common
56    /// top-level case therefore sees trial-cumulative output.
57    pub(super) exact_stdout: Arc<Mutex<HashMap<usize, ExactCapture>>>,
58    /// Variable scopes for $variable bindings (FOR loops, LET assignments).
59    /// Innermost scope is last. Variables are looked up from innermost to outermost.
60    /// Each entry carries its declared type name alongside the value.
61    pub(super) var_scopes: Vec<HashMap<String, (TypeTag, Value)>>,
62    /// Name directory for type resolution: startup descriptors plus the
63    /// run's host descriptors. Words carry their own vtables, so this map
64    /// serves only name queries (declarations, `TYPES()`, `TYPE_DESCRIBE`).
65    pub(super) types: HashMap<String, &'static TypeDescriptor>,
66    /// Named record schemas for shaped MAP bindings: schema name to its
67    /// field table. Populated from host modules alongside descriptors, so
68    /// `LET $s: SSH_SESSION_INFO` resolves exactly when the owning module
69    /// is registered. Impossible to reference an unregistered schema.
70    pub(super) record_schemas: HashMap<String, Arc<[Field]>>,
71    /// Module-shared state stashed at registration, keyed by owning
72    /// module name plus value type. Bodies fetch it through
73    /// `StepCtx::module_state` instead of hand-built closures, so
74    /// every entry can stay `#[oxdock_func]`.
75    pub(super) module_states:
76        HashMap<(String, std::any::TypeId), Arc<dyn std::any::Any + Send + Sync>>,
77    /// Script-level type aliases for this run: alias name to canonical
78    /// target spelling (`PERSON` to `MAP<name:STRING>`). Populated once
79    /// from top-level `TYPE` steps before the static pass, so forward
80    /// references resolve run-wide at first coercion.
81    pub(super) type_aliases: HashMap<String, String>,
82    /// Cancellation token for background thread teardown.
83    #[allow(dead_code)]
84    pub(super) cancel_token: Arc<AtomicBool>,
85    /// Event hub fanning the same cancellation to pump supervisors.
86    /// Marked everywhere the token is stored, so blocking pumps wake
87    /// without polling. Forks get a fresh hub with their fresh token.
88    #[allow(dead_code)]
89    pub(super) cancel_hub: Arc<CancelHub>,
90    /// Handle to the currently executing foreground OS process, so
91    /// ThreadJoinHandle::kill() can interrupt a blocking wait().
92    #[allow(dead_code)]
93    pub(super) active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
94    /// Named task registry for AWAIT/CANCEL support. Shared across subscopes
95    /// via Arc. Each entry is a synchronized state machine (`TaskEntry`):
96    /// the handle lives inside the entry so `CANCEL` can synchronously tear
97    /// down a task even while a concurrent `AWAIT` is waiting on it.
98    /// Entries are retained as `Cancelled`/`Completed` tombstones so later
99    /// `AWAIT`/`CANCEL` report precise errors instead of `TaskNotFound`.
100    #[allow(dead_code)]
101    pub(super) named_tasks: Arc<Mutex<HashMap<u64, Arc<TaskEntry>>>>,
102    /// Counter for generating unique task IDs. Shared across subscopes via Arc.
103    #[allow(dead_code)]
104    pub(super) next_task_id: Arc<AtomicU64>,
105    /// Whether we're inside an ASYNC block thread. When true, `handlers::run()`
106    /// spawns in background mode so the handle can be registered for cancellation.
107    pub(super) inside_async: bool,
108    /// Step-indexed keeper expiry for one `ASYNC` worker. Each guard pins a
109    /// pipe the worker produces to, bridging the spawn-to-first-attach
110    /// window and every transient gap between producer steps. Guards keyed
111    /// to step `k` drop when the worker completes its top-level step `k`
112    /// (matched by slice identity, so nested bodies never discharge them);
113    /// leftovers drop with the worker thread. Always `None` outside
114    /// workers; `fork` never inherits it.
115    pub(super) keeper_expiry: Option<KeeperExpiry>,
116    /// Whether `handlers::run()` must spawn in background mode so the handle
117    /// registers in `active_process` for cancellation. Set while a `TIMEOUT`
118    /// body executes on the current thread so the deadline watcher can kill
119    /// a blocking foreground process. Unlike `inside_async`, this does not
120    /// affect end-of-pipeline named-task reaping.
121    pub(super) cancellable: bool,
122    /// The single function registry: DSL `FUNC` definitions, builtins, and
123    /// host extensions. Script entries scope lexically through the
124    /// registry's own frames (managed by `push_scope`/`pop_scope`);
125    /// native entries persist. Shared across `fork()` via clone.
126    pub(super) functions: FunctionRegistry<P>,
127    /// Current nested function-call depth on this thread. Enforced against
128    /// `MAX_CALL_DEPTH`; cloned (not reset) by `fork()` so async children
129    /// inherit the caller's depth budget.
130    pub(super) call_depth: usize,
131    /// Identity of the task this state executes (`0` = root flow).
132    /// Stamped onto pipe handles minted here and compared by the promotion
133    /// check: only the declaring task may promote its own pipes.
134    pub(super) task_id: u64,
135    /// Declared `--to-host` transfers recorded strictly at execution time:
136    /// each executed flagged `COPY` appends its evaluated
137    /// `(guest_src, host_dst)` pair. The guest serve loop packs exactly
138    /// these entries, so dead branches contribute nothing and dynamic
139    /// paths (`$var`, `{{ ... }}`) resolve normally. Shared with the sink
140    /// in [`ExecIo`] when staged.
141    pub(super) push_manifest: Vec<(String, String)>,
142    pub(super) _marker: PhantomData<P>,
143}
144
145pub(super) struct ScopeSnapshot {
146    pub(super) cwd: GuardedPath,
147    pub(super) root: GuardedPath,
148    pub(super) envs: Arc<HashMap<String, String>>,
149}
150
151/// Lifecycle phase of a named background task (`LET $var: HANDLE = ASYNC ...`).
152/// `Running` and `Awaiting` both hold the live handle inside the entry;
153/// `Cancelled` and `Completed` are terminal tombstones with no handle.
154pub(super) enum TaskPhase {
155    Running,
156    Awaiting,
157    Cancelled,
158    Completed,
159}
160
161pub(super) struct TaskEntryState {
162    pub(super) phase: TaskPhase,
163    pub(super) handle: Option<Box<dyn BackgroundHandle>>,
164    /// True once the handle has been consumed and its thread joined
165    /// (`kill()` for cancellations, `try_wait`-reap for natural completion).
166    /// Threads observing `Cancelled` must wait on `done` until `reaped`
167    /// before resuming, so no caller outruns OS process teardown.
168    pub(super) reaped: bool,
169    /// Explicit result of a background task, published by `RETURN` (block
170    /// bodies) or the function call itself (single-`CALL` bodies). Set
171    /// under the entry lock before `done.notify_all()`; read by
172    /// `LET $o: TYPE = AWAIT $t`. `None` for tasks that returned nothing
173    /// or have not finished. Task stdout is never captured: it streams
174    /// live to the shared parent writer.
175    pub(super) return_value: Option<Value>,
176    /// Whether this task's body can publish a value: single-`CALL` bodies
177    /// always can; block bodies can iff they contain a `RETURN` in their
178    /// own scope. A task that can return but falls off the end fails its
179    /// capture loudly; a task that cannot return yields `INT` 0.
180    pub(super) returns_value: bool,
181}
182
183/// Synchronized named-task entry shared by every scope that can observe the
184/// task (`AWAIT`, `CANCEL`, end-poll reaping). Exactly one thread ever takes
185/// the handle and performs teardown; all other observers rendezvous on
186/// `done`/`reaped`.
187pub(super) struct TaskEntry {
188    pub(super) state: Mutex<TaskEntryState>,
189    pub(super) done: Condvar,
190}
191
192impl TaskEntry {
193    pub(super) fn new(handle: Box<dyn BackgroundHandle>, returns_value: bool) -> Self {
194        Self {
195            state: Mutex::new(TaskEntryState {
196                phase: TaskPhase::Running,
197                handle: Some(handle),
198                reaped: false,
199                return_value: None,
200                returns_value,
201            }),
202            done: Condvar::new(),
203        }
204    }
205
206    /// Block until the teardown owner has consumed the handle and joined
207    /// the task thread. Lock-free for callers except the wait itself.
208    pub(super) fn wait_reaped(&self) {
209        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
210        while !guard.reaped {
211            guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
212        }
213    }
214
215    /// Mark teardown complete and wake every rendezvous waiter.
216    pub(super) fn finish_teardown(&self) {
217        {
218            let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
219            guard.handle = None;
220            guard.reaped = true;
221        }
222        self.done.notify_all();
223    }
224}
225
226/// Step-indexed keeper expiry for one `ASYNC` worker thread. Guards are
227/// keyed by the top-level body index of the final producer step for each
228/// pipe: dropping the guards for step `k` once it completes keeps the
229/// pipe open across every transient gap between producers, then releases
230/// it so later consumer steps in the same task observe EOF.
231///
232/// Slice identity (`body_addr`/`body_len`) gates discharge: nested bodies
233/// (`FOR`/`IF`/`TIMEOUT`/inner `ASYNC`) execute through the same stepping
234/// code with different slices and must never consume the worker's
235/// top-level map.
236pub(super) struct KeeperExpiry {
237    body_addr: usize,
238    body_len: usize,
239    map: HashMap<usize, Vec<KeeperGuard>>,
240}
241
242impl KeeperExpiry {
243    pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
244        Self {
245            body_addr: steps.as_ptr() as usize,
246            body_len: steps.len(),
247            map,
248        }
249    }
250
251    pub(super) fn matches(&self, steps: &[Step]) -> bool {
252        self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
253    }
254
255    /// Drop the guards expiring at top-level step `idx`. Returns true when
256    /// the map is drained and the expiry itself can be cleared.
257    pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
258        if self.matches(steps) {
259            drop(self.map.remove(&idx));
260        }
261        self.map.is_empty()
262    }
263}
264
265impl<P: ProcessManager> ExecState<P> {
266    /// Script-map environment lookup for DSL evaluation (`is_exec_name`,
267    /// `Expr::Env`, expansions): exact hit first, case-insensitive
268    /// fallback on Windows so `{{ env:Path }}` resolves the seeded
269    /// `PATH`. The map is seeded at init, so no fallback layer exists.
270    pub(super) fn get_env(&self, key: &str) -> Option<&str> {
271        if let Some(v) = self.envs.get(key) {
272            return Some(v.as_str());
273        }
274        #[allow(clippy::disallowed_macros)]
275        if cfg!(windows) {
276            return self
277                .envs
278                .iter()
279                .find(|(k, _)| oxdock_process::names_eq(k, key))
280                .map(|(_, v)| v.as_str());
281        }
282        None
283    }
284
285    pub(super) fn command_ctx(&self) -> Result<CommandContext> {
286        // Resolve the working directory through the snapshot choke point: a
287        // snapshot-rooted cwd materializes here (so `RUN` executes against a
288        // real directory) while a local cwd resolves purely lexically with
289        // zero I/O. The seeded scratch materializes alongside: `HOME` and
290        // `TMPDIR` point at it, so children writing temp or profile data
291        // must observe real directories, never lexical candidates.
292        let cwd = self.fs.resolve_write(&self.cwd, ".")?;
293        self.cargo_scratch.ensure_materialized()?;
294        Ok(CommandContext::new(
295            &cwd.into(),
296            Arc::clone(&self.envs),
297            &self.cargo_scratch,
298            self.fs.root(),
299            self.fs.build_context(),
300        ))
301    }
302
303    /// Fork the execution state for a child thread. The child gets:
304    /// - A cloned filesystem handle (shared snapshot backing, independent root selection)
305    /// - Cloned envs, cwd, cargo scratch name, var_scopes
306    /// - Fresh bg_children, scope_stack (empty -- child manages its own)
307    /// - Shared assert_windows, assert_windows_stderr, exact_stdout (Arc clones)
308    /// - Cloned io configuration
309    /// - Independent cancel_token, active_process (child manages its own)
310    /// - Shared named_tasks and next_task_id (via Arc clone)
311    #[allow(dead_code)]
312    pub(super) fn fork(&self) -> Self {
313        Self {
314            fs: self.fs.clone_box(),
315            cargo_scratch: self.cargo_scratch.clone(),
316            seed: Arc::clone(&self.seed),
317            cwd: self.cwd.clone(),
318            envs: Arc::clone(&self.envs),
319            bg_children: Vec::new(),
320            scope_stack: Vec::new(),
321            isolated_stack: self.isolated_stack.clone(),
322            io: self.io.clone(),
323            assert_windows: Arc::clone(&self.assert_windows),
324            assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
325            exact_stdout: Arc::clone(&self.exact_stdout),
326            var_scopes: self.var_scopes.clone(),
327            cancel_token: Arc::new(AtomicBool::new(false)),
328            // Fresh cancellation, inherited telemetry: the fork's
329            // workers still attribute to the originating run.
330            cancel_hub: Arc::new(CancelHub::with_counter(self.cancel_hub.worker_counter())),
331            active_process: Arc::new(Mutex::new(None)),
332            named_tasks: Arc::clone(&self.named_tasks),
333            next_task_id: Arc::clone(&self.next_task_id),
334            inside_async: true,
335            keeper_expiry: None,
336            cancellable: self.cancellable,
337            functions: self.functions.clone(),
338            types: self.types.clone(),
339            record_schemas: self.record_schemas.clone(),
340            module_states: self.module_states.clone(),
341            type_aliases: self.type_aliases.clone(),
342            call_depth: self.call_depth,
343            task_id: self.task_id,
344            // Forks start with an empty manifest: async children record
345            // their own executions; the guest packs the root manifest.
346            push_manifest: Vec::new(),
347            _marker: PhantomData,
348        }
349    }
350
351    /// Whether `pipe` may promote to an OS kernel pair on behalf of
352    /// `task_id`: only when it was declared by that same task and no
353    /// spawned child can observe it. Anything else stays script-backed, so
354    /// concurrent tasks can never disagree about EOF propagation.
355    /// Spawning tasks pass their worker id (not the spawner's): promotion
356    /// is judged from the worker's perspective, since it is the worker's
357    /// bindings that will hold raw descriptors.
358    pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
359        pipe.declaring_task() == task_id && !pipe.has_escaped()
360    }
361
362    /// Whether `pipe` may promote on the current thread (main flow and
363    /// inline resolves).
364    pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
365        Self::can_promote_in_task(pipe, self.task_id)
366    }
367
368    /// Mark every pipe visible in scope as shared-with-a-child. Called
369    /// synchronously on the spawner before a worker thread starts: forking
370    /// copies the whole environment, so every visible pipe is capturable
371    /// whether or not the child body names it. Over-marking only costs
372    /// zero-copy opportunities, never correctness.
373    pub(super) fn mark_captured_pipes_escaped(&self) {
374        for scope in self.var_scopes.iter() {
375            for (_, value) in scope.values() {
376                mark_value_pipes_escaped(value);
377            }
378        }
379    }
380
381    pub(super) fn push_var_scope(&mut self) {
382        self.var_scopes.push(HashMap::new());
383    }
384
385    pub(super) fn pop_var_scope(&mut self) {
386        self.var_scopes.pop();
387    }
388
389    /// Enter a lexical scope: snapshot cwd/root/envs and open a fresh
390    /// variable scope. Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE);
391    /// only pipes (ExecIo) and filesystem effects cross scope boundaries.
392    /// Function definitions scope through the registry's own frames.
393    pub(super) fn push_scope(&mut self) {
394        self.scope_stack.push(ScopeSnapshot {
395            cwd: self.cwd.clone(),
396            root: self.fs.root().clone(),
397            envs: Arc::clone(&self.envs),
398        });
399        self.functions.push_scope();
400        self.push_var_scope();
401    }
402
403    /// Exit a lexical scope, restoring everything `push_scope` saved.
404    pub(super) fn pop_scope(&mut self) -> Result<()> {
405        let snapshot = self
406            .scope_stack
407            .pop()
408            .ok_or_else(|| anyhow::anyhow!("scope stack underflow during pop"))?;
409        self.fs.set_root(&snapshot.root);
410        self.cwd = snapshot.cwd;
411        self.envs = snapshot.envs;
412        self.functions.pop_scope();
413        self.pop_var_scope();
414        Ok(())
415    }
416    pub(super) fn declare_var(&mut self, key: String, kind: TypeTag, value: Value) -> Result<()> {
417        if self
418            .var_scopes
419            .last()
420            .map(|s| s.contains_key(&key))
421            .unwrap_or(false)
422        {
423            anyhow::bail!(
424                "redeclaration error: ${} already declared in this scope; use ${} = ... to mutate",
425                key,
426                key
427            );
428        }
429        let coerced = super::args::coerce_value(value, &kind)?;
430        let scope = self
431            .var_scopes
432            .last_mut()
433            .ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
434        scope.insert(key, (kind, coerced));
435        Ok(())
436    }
437
438    pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> Result<()> {
439        let kind = self
440            .var_scopes
441            .iter()
442            .rev()
443            .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
444            .ok_or_else(|| {
445                anyhow::anyhow!(
446                    "undeclared variable ${key}: declare it first with LET ${key}: TYPE = ..."
447                )
448            })?;
449        let coerced = super::args::coerce_value(value, &kind)?;
450        for scope in self.var_scopes.iter_mut().rev() {
451            if let Some(slot) = scope.get_mut(key) {
452                slot.1 = coerced;
453                return Ok(());
454            }
455        }
456        anyhow::bail!("undeclared variable ${key}");
457    }
458
459    /// Append `item` to the LIST binding `key` in place. Copy-on-write:
460    /// the buffer detaches only when shared, so aliases keep their
461    /// contents; the sole owner mutates with no copy. Bails for
462    /// undeclared names and non-list bindings. Shaped lists validate
463    /// the item against the element tag, so a push can never silently
464    /// corrupt the shape the declaration promises.
465    pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> Result<()> {
466        let kind = self
467            .var_scopes
468            .iter()
469            .rev()
470            .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
471            .ok_or_else(|| {
472                anyhow::anyhow!(
473                    "undeclared variable ${key}: declare it first with LET ${key}: LIST<...> = ..."
474                )
475            })?;
476        let element = match kind {
477            TypeTag::List => None,
478            TypeTag::ListOf(element) => Some(element.as_ref().clone()),
479            _ => {
480                anyhow::bail!("LIST_APPEND ${key}: variable is {}, not LIST", kind.name());
481            }
482        };
483        for scope in self.var_scopes.iter_mut().rev() {
484            if let Some(slot) = scope.get_mut(key) {
485                let list = slot.1.as_list_mut().ok_or_else(|| {
486                    anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
487                })?;
488                if let Some(expected) = element {
489                    oxdock_parser::check_value_at(
490                        &expected,
491                        &item,
492                        &format!("${key}[{}]", list.len()),
493                    )?;
494                }
495                list.push(item);
496                return Ok(());
497            }
498        }
499        anyhow::bail!("undeclared variable ${key}");
500    }
501
502    pub(super) fn get_var(&self, key: &str) -> Option<Value> {
503        // Walk scopes from innermost to outermost
504        for scope in self.var_scopes.iter().rev() {
505            if let Some((_, value)) = scope.get(key) {
506                return Some(value.clone());
507            }
508        }
509        None
510    }
511
512    pub(super) fn get_var_typed(&self, key: &str) -> Option<(TypeTag, Value)> {
513        for scope in self.var_scopes.iter().rev() {
514            if let Some(entry) = scope.get(key) {
515                return Some(entry.clone());
516            }
517        }
518        None
519    }
520
521    /// Get a flattened view of all variables across all scopes.
522    /// Inner scopes take precedence over outer scopes.
523    pub(super) fn all_vars(&self) -> HashMap<String, Value> {
524        let mut result = HashMap::new();
525        for scope in self.var_scopes.iter().rev() {
526            for (k, (_, v)) in scope {
527                result.entry(k.clone()).or_insert_with(|| v.clone());
528            }
529        }
530        result
531    }
532}
533
534/// Mark every pipe handle reachable from `value` as shared-with-a-child.
535/// Pipes travel inside lists and maps (`LET $bag: LIST = [$p]`), so a
536/// shallow top-level check would miss them and let a later promotion
537/// corrupt the shared EOF contract. Values form a tree, so recursion
538/// terminates; host-opaque payloads cannot carry handles.
539fn mark_value_pipes_escaped(value: &Value) {
540    if let Some(handle) = value.as_pipe_handle() {
541        handle.mark_escaped();
542        return;
543    }
544    if let Some(items) = value.as_list() {
545        for item in items {
546            mark_value_pipes_escaped(item);
547        }
548    }
549    if let Some(entries) = value.as_map() {
550        for item in entries.values() {
551            mark_value_pipes_escaped(item);
552        }
553    }
554}