Skip to main content

oxdock_core/exec/
steps.rs

1use std::collections::HashMap;
2use std::process::ExitStatus;
3use std::sync::Arc;
4use std::sync::Mutex;
5use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6
7use anyhow::{Result, bail};
8use oxdock_fs::GuardedPath;
9use oxdock_parser::{Arg, AssertTarget, Step, StepKind, Value, guard_option_allows};
10use oxdock_process::{BackgroundHandle, CommandStdin, ProcessManager, SharedInput, SharedOutput};
11
12/// Create an ExitStatus from a raw exit code. Cross-platform.
13fn exit_status_from_code(code: i32) -> ExitStatus {
14    #[cfg(unix)]
15    {
16        use std::os::unix::process::ExitStatusExt;
17        ExitStatus::from_raw(code << 8)
18    }
19    #[cfg(windows)]
20    {
21        use std::os::windows::process::ExitStatusExt;
22        ExitStatus::from_raw(code as u32)
23    }
24}
25
26use super::handlers;
27use super::io::{ExactCapture, SlidingWindow, StreamHandle};
28use super::native::PureTable;
29use super::state::{ExecState, TaskEntry, TaskPhase};
30use oxdock_pipe::PipeInner;
31
32/// A background handle wrapping a `std::thread::JoinHandle` for ASYNC blocks
33/// that execute commands in a background thread.
34pub(super) struct ThreadJoinHandle {
35    join: Option<std::thread::JoinHandle<Result<()>>>,
36    cancel_token: Arc<AtomicBool>,
37    cancel_hub: Arc<oxdock_process::CancelHub>,
38    active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
39    /// Identity of the worker thread, published by the child on entry.
40    /// Forked worker state shares the parent task registry via `Arc`, so a
41    /// parent that errors out can drop its registry reference while the
42    /// worker is still alive. The worker then becomes the last registry
43    /// owner and would drop (and join) its own handle on thread exit, which
44    /// is undefined behavior (`pthread_join` on self). Detect that case and
45    /// detach instead of joining.
46    worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
47    /// Preserved error from the child thread, if any.
48    thread_error: Option<anyhow::Error>,
49    /// `EXIT` code from the child thread, if it exited. anyhow errors do
50    /// not cross the join boundary by value, and the re-emit below would
51    /// otherwise flatten the typed request into a plain string.
52    thread_exit_code: Option<i64>,
53}
54
55impl ThreadJoinHandle {
56    pub(super) fn new(
57        join: std::thread::JoinHandle<Result<()>>,
58        cancel_token: Arc<AtomicBool>,
59        cancel_hub: Arc<oxdock_process::CancelHub>,
60        active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
61        worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
62    ) -> Self {
63        Self {
64            join: Some(join),
65            cancel_token,
66            cancel_hub,
67            active_process,
68            worker,
69            thread_error: None,
70            thread_exit_code: None,
71        }
72    }
73
74    /// Re-emit the preserved thread error. `anyhow` errors do not cross
75    /// the join boundary by value, so an EXIT code rides alongside in
76    /// `thread_exit_code` and is re-attached here as a typed request
77    /// under the flattened message: the text stays identical, and the
78    /// code stays machine readable.
79    fn reemit_error(&self) -> anyhow::Error {
80        let msg = self
81            .thread_error
82            .as_ref()
83            .map(|err| format!("{err:#}"))
84            .unwrap_or_else(|| "background thread failed without an error".to_string());
85        match self.thread_exit_code {
86            Some(code) => anyhow::Error::new(super::exit::ExitRequest(code)).context(msg),
87            None => anyhow::anyhow!("{msg}"),
88        }
89    }
90
91    /// Whether the caller is the worker thread owned by this handle.
92    fn is_self(&self) -> bool {
93        let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
94        guard.is_some_and(|id| id == std::thread::current().id())
95    }
96
97    /// Reap the thread if finished, preserving any error.
98    fn reap(&mut self) {
99        if self.join.is_none() {
100            return;
101        }
102        if self.is_self() {
103            // The worker is dropping the last registry reference on its own
104            // exit path (parent already tore down or errored out). Detach
105            // instead of joining self, which is undefined behavior.
106            let _ = self.join.take();
107            return;
108        }
109        let handle = self.join.take().unwrap();
110        match handle.join() {
111            Ok(Ok(())) => {}
112            Ok(Err(e)) => {
113                self.thread_exit_code = super::exit::exit_code_of(&e);
114                self.thread_error = Some(e);
115            }
116            Err(panic) => {
117                let msg = if let Some(s) = panic.downcast_ref::<&str>() {
118                    s.to_string()
119                } else if let Some(s) = panic.downcast_ref::<String>() {
120                    s.clone()
121                } else {
122                    "thread panicked".to_string()
123                };
124                self.thread_error = Some(anyhow::anyhow!("{msg}"));
125            }
126        }
127    }
128}
129
130impl BackgroundHandle for ThreadJoinHandle {
131    fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
132        if let Some(join) = &self.join {
133            if join.is_finished() {
134                self.reap();
135            } else {
136                return Ok(None);
137            }
138        }
139        // anyhow::Error is not Clone and this method may run repeatedly,
140        // so the preserved error is re-emitted rather than moved. The
141        // alternate display (`{err:#}`) flattens the full causal chain
142        // into the new message: `{err}` alone would drop every
143        // `Caused by` layer at the ASYNC task boundary.
144        if self.thread_error.is_some() {
145            Err(self.reemit_error())
146        } else {
147            Ok(Some(exit_status_from_code(0)))
148        }
149    }
150
151    fn kill(&mut self) -> Result<()> {
152        // Signal cancellation
153        self.cancel_token.store(true, Ordering::SeqCst);
154        // Fan out to pump supervisors waiting on the hub (blocking
155        // reads and channel waits cannot poll the token).
156        self.cancel_hub.mark_cancelled();
157        // Kill any active OS process to interrupt blocking wait
158        if let Ok(mut guard) = self.active_process.lock()
159            && let Some(ref mut proc) = *guard
160        {
161            let _ = proc.kill();
162        }
163        // Join the thread to ensure it completes before returning
164        self.reap();
165        Ok(())
166    }
167
168    fn wait(&mut self) -> Result<ExitStatus> {
169        self.reap();
170        // Same chain-preserving re-emit as `try_wait` above.
171        if self.thread_error.is_some() {
172            Err(self.reemit_error())
173        } else {
174            Ok(exit_status_from_code(0))
175        }
176    }
177}
178
179impl Drop for ThreadJoinHandle {
180    fn drop(&mut self) {
181        let _ = self.kill();
182    }
183}
184
185/// Monotonically increasing generation counter for assert_windows key scoping.
186/// Each execute_steps invocation gets a unique generation, preventing key
187/// collisions between nested scopes (for_loop bodies, WithIo blocks).
188static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
189
190/// Intra-thread control-flow signal (`BREAK`/`CONTINUE`/`RETURN`).
191/// Produced by steps, consumed by the nearest loop (`Break`/`Continue`) or
192/// `call_func` (`Return`). Anything reaching a thread boundary (`ASYNC`
193/// spawn, `await` reaping) or the pipeline top becomes a step-numbered
194/// error. `idx` is the 0-based index of the originating step in its own
195/// body, so boundary errors can name it.
196#[derive(Debug)]
197pub(super) enum Flow {
198    Done,
199    Break { idx: usize },
200    Continue { idx: usize },
201    Return { idx: usize, value: Value },
202}
203
204pub(super) fn allocate_assert_generation() -> usize {
205    ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
206}
207
208/// Which stream a stream-targeted assertion observes.
209#[derive(Clone, Copy, PartialEq, Eq)]
210pub(super) enum AssertStream {
211    Stdout,
212    Stderr,
213}
214
215/// Extract the substring needle from a step asserting over a stream:
216/// `ASSERT_CONTAINS stdout|stderr`, handling both top-level and
217/// WITH_IO-wrapped variants. Returns the observed stream and the needle.
218fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
219    let step = match kind {
220        StepKind::WithIo { cmd, .. } => cmd.as_ref(),
221        other => other,
222    };
223    match step {
224        StepKind::AssertContains { haystack, needle } => match haystack {
225            AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
226            AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
227            _ => None,
228        },
229        _ => None,
230    }
231}
232
233/// Whether the step needs the exact-match stdout accumulator:
234/// `ASSERT_EQ stdout`, top-level or WITH_IO-wrapped.
235fn needs_exact_stdout(kind: &StepKind) -> bool {
236    let step = match kind {
237        StepKind::WithIo { cmd, .. } => cmd.as_ref(),
238        other => other,
239    };
240    matches!(
241        step,
242        StepKind::AssertEq {
243            actual: AssertTarget::Stdout,
244            ..
245        }
246    )
247}
248
249/// An assertion first argument evaluated far enough to check:
250/// values stay typed, streams stay references to live buffers.
251pub(super) enum ResolvedAssertTarget {
252    Value(Value),
253    Stdout,
254    Stderr,
255    Pipe(Vec<u8>),
256}
257
258/// Evaluate an assertion target. `Arg::Expr` evaluates typed;
259/// strings, templates, and parts render to `String`; stream markers
260/// resolve to live buffers (peeked, never consumed). A `$var` holding a
261/// `PIPE` likewise peeks its backend bytes: lowering cannot know variable
262/// types, so the pipe dispatch lives here where the value exists.
263pub(super) fn resolve_assert_target<P: ProcessManager>(
264    target: &AssertTarget,
265    cx: &mut StepCtx<'_, P>,
266) -> Result<ResolvedAssertTarget> {
267    match target {
268        AssertTarget::Value(arg) => {
269            let value = super::args::evaluate_assert_operand(arg, cx)?;
270            if let Some(handle) = value.as_pipe_handle() {
271                let bytes =
272                    cx.state.io.peek_pipe_content(&handle).map_err(|e| {
273                        anyhow::anyhow!("step pipe assertion cannot read pipe: {e}")
274                    })?;
275                return Ok(ResolvedAssertTarget::Pipe(bytes));
276            }
277            Ok(ResolvedAssertTarget::Value(value))
278        }
279        AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
280        AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
281    }
282}
283
284/// Pre-register stream assertion observers so tees feed them data before
285/// the steps execute. Substring needles (`ASSERT_CONTAINS stdout|stderr`)
286/// get per-step `SlidingWindow`s; `ASSERT_EQ stdout` allocates the
287/// generation's exact accumulator. Uses `args::resolve_arg_state` for
288/// actual template expansion. Handles both top-level and WITH_IO-wrapped
289/// assertions via `extract_stream_needle` / `needs_exact_stdout`.
290pub(super) fn pre_register_assertions<P: ProcessManager>(
291    state: &mut ExecState<P>,
292    steps: &[Step],
293    generation: usize,
294) -> Result<()> {
295    let mut windows = match state.assert_windows.lock() {
296        Ok(guard) => guard,
297        Err(_) => bail!("assert_windows poisoned"),
298    };
299    let mut stderr_windows = match state.assert_windows_stderr.lock() {
300        Ok(guard) => guard,
301        Err(_) => bail!("assert_windows_stderr poisoned"),
302    };
303    let mut exact = match state.exact_stdout.lock() {
304        Ok(guard) => guard,
305        Err(_) => bail!("exact_stdout poisoned"),
306    };
307    for (idx, step) in steps.iter().enumerate() {
308        if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
309            let resolved = super::args::resolve_arg_state(arg, state)?;
310            let map = match stream {
311                AssertStream::Stdout => &mut windows,
312                AssertStream::Stderr => &mut stderr_windows,
313            };
314            map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
315        }
316        if needs_exact_stdout(&step.kind) {
317            exact.entry(generation).or_insert_with(ExactCapture::new);
318        }
319    }
320    Ok(())
321}
322
323/// After an environment mutation (ENV or INHERIT_ENV), re-expand all
324/// substring assertion needles for the current generation to reflect new
325/// env values. Preserves ring buffer history via `update_needle`. Handles
326/// both top-level and WITH_IO-wrapped assertions. Exact accumulators hold
327/// no needle and need no sync.
328#[allow(clippy::collapsible_if)]
329pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
330    state: &ExecState<P>,
331    steps: &[Step],
332    generation: usize,
333) -> Result<()> {
334    let mut windows = match state.assert_windows.lock() {
335        Ok(guard) => guard,
336        Err(_) => bail!("assert_windows poisoned"),
337    };
338    let mut stderr_windows = match state.assert_windows_stderr.lock() {
339        Ok(guard) => guard,
340        Err(_) => bail!("assert_windows_stderr poisoned"),
341    };
342    for (idx, step) in steps.iter().enumerate() {
343        if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
344            let map = match stream {
345                AssertStream::Stdout => &mut windows,
346                AssertStream::Stderr => &mut stderr_windows,
347            };
348            if let Some(w) = map.get_mut(&(generation, idx)) {
349                let resolved = super::args::resolve_arg_state(arg, state)?;
350                w.update_needle(resolved.into_bytes());
351            }
352        }
353    }
354    Ok(())
355}
356
357/// Pseudo-terminal request carried from `WITH_IO [tty]` bindings to
358/// the `RUN` handlers: terminal geometry for the pty master. `None`
359/// (the common case) keeps hermetic pipes. Only `with_io` populates
360/// this from the step bindings; every other context constructs `None`.
361/// Dimensions stay optional until spawn: unnamed sides read the host
362/// terminal when one sits behind our own stdio, falling back to the
363/// shared default otherwise.
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub struct TtyRequest {
366    /// Terminal rows (`rows = <int>`), or `None` to read the host.
367    pub rows: Option<u16>,
368    /// Terminal columns (`cols = <int>`), or `None` to read the host.
369    pub cols: Option<u16>,
370}
371
372/// Per-step execution context handed to every command handler.
373///
374/// Host-registered functions receive this context: read script state through
375/// the public accessors (`get_var`, `get_env`, `cwd`) and return a `Value`.
376/// The fields stay crate-private so execution invariants hold for hosts.
377///
378/// Output contract (load-bearing for `LET`-capture, pipes, and stream assertions):
379/// handlers must emit stdout/stderr ONLY through `out`/`err` : via
380/// `write_stdout` or `StreamHandle::to_stdout`/`to_stderr` : and never write
381/// to host stdout directly. The step runner swaps these handles per context:
382/// `LET $x: STRING = <command>` installs a spillable capture sink, `WITH_IO`
383/// installs named-pipe endpoints, and the root installs the assertion tee. A handler that bypasses its context handles silently breaks all three.
384pub struct StepCtx<'a, P: ProcessManager> {
385    pub(super) state: &'a mut ExecState<P>,
386    pub(super) process: &'a mut P,
387    pub(super) stdin: CommandStdin,
388    pub(super) expose_stdin: bool,
389    pub(super) out: Option<StreamHandle>,
390    pub(super) err: Option<StreamHandle>,
391    /// Pipe backend backing `out`, when a `WITH_IO` stdout binding resolved
392    /// to a script pipe. Uniform context enrichment (populated for every
393    /// command, read only by consumers that need the backend, like the
394    /// network bridge). `None` for inherited, captured, and tee outputs,
395    /// and for OS pairs (kernel bytes are invisible).
396    pub(super) out_pipe: Option<Arc<PipeInner>>,
397    /// Pipe backend backing `stdin`, when a `WITH_IO` stdin binding
398    /// resolved to a script pipe. Lets bridge workers run timeout-bounded
399    /// reads without touching shared pipe semantics (`None` for OS pairs,
400    /// which fall back to blocking reads).
401    pub(super) stdin_pipe: Option<Arc<PipeInner>>,
402    /// Pseudo-terminal request from an enclosing `WITH_IO [tty]`
403    /// binding. `RUN` handlers spawn through the shared pty pump when
404    /// this is `Some`; every other command ignores it (lowering rejects
405    /// `tty` outside `RUN` before execution reaches them).
406    pub(super) tty: Option<TtyRequest>,
407}
408
409impl<'a, P: ProcessManager> StepCtx<'a, P> {
410    /// Minimal context for headless MCP tool dispatch: no stdin, caller
411    /// supplied output handles, no pipe backends. Stdin is always Null
412    /// so tools can never block on host input.
413    pub(super) fn for_mcp(
414        state: &'a mut ExecState<P>,
415        process: &'a mut P,
416        stdin: CommandStdin,
417        out: Option<StreamHandle>,
418        err: Option<StreamHandle>,
419    ) -> Self {
420        Self {
421            state,
422            process,
423            stdin,
424            expose_stdin: false,
425            out,
426            err,
427            out_pipe: None,
428            stdin_pipe: None,
429            tty: None,
430        }
431    }
432
433    /// Shared writer behind the step error stream, when one exists (never
434    /// for OS kernel pairs). Lets streaming hosts pump guest stderr live
435    /// instead of buffering it to the end of the block.
436    pub(super) fn err_shared(&self) -> Option<SharedOutput> {
437        match self.err.clone() {
438            Some(StreamHandle::Stream(writer)) => Some(writer),
439            _ => None,
440        }
441    }
442
443    /// Look up a script variable by name (innermost scope first).
444    pub fn get_var(&self, key: &str) -> Option<Value> {
445        self.state.get_var(key)
446    }
447
448    /// Look up an environment variable visible to the script: the
449    /// script map, seeded at session start. Exact hit first,
450    /// case-insensitive fallback on Windows.
451    pub fn get_env(&self, key: &str) -> Option<String> {
452        self.state.get_env(key).map(str::to_string)
453    }
454
455    /// Snapshot of the script-visible environment: `ENV` assignments
456    /// layered over inherited entries, as currently scoped. Hosts staging
457    /// child processes layer this over the host environment (the same
458    /// contract `RUN` honors through `CommandContext`), so block-scoped
459    /// `ENV` reaches the child and reverts at scope exit with no extra
460    /// machinery.
461    pub fn env_snapshot(&self) -> HashMap<String, String> {
462        self.state.envs.as_ref().clone()
463    }
464
465    /// Materialize the session scratch hierarchy (root + `tmp`) for
466    /// spawn sites that stage children without a `CommandContext`
467    /// (PTY): the seeded `HOME`/`TMPDIR` paths must exist when the
468    /// guest writes them, even when no `RUN` step ran first.
469    pub fn ensure_scratch_materialized(&self) -> Result<()> {
470        self.state.cargo_scratch.ensure_materialized()
471    }
472
473    /// Current working directory (guarded; stays inside the workspace).
474    pub fn cwd(&self) -> &GuardedPath {
475        &self.state.cwd
476    }
477
478    /// Shared snapshot of every registered pure function, keyed by
479    /// qualified name. Lets host-driven expansion resolve
480    /// `{{ MODULE::FUNC(args) }}` through the live registry instead of
481    /// hardcoding module or function names. Stateful, script, and pipe
482    /// backed entries never appear here: placeholder evaluation has no
483    /// step context and must stay side effect free. Dual entries
484    /// contribute their template arm.
485    pub fn pure_functions(&self) -> std::sync::Arc<PureTable> {
486        self.state.pure_function_table()
487    }
488
489    /// Mint a fresh unbound pipe handle, like bare `LET $p: PIPE`. The
490    /// backend materializes lazily on first binding; return it from a
491    /// host function to hand the DSL a pipe it can bind. Tagged with the
492    /// current task so promotion checks see the declaration origin.
493    pub fn new_pipe(&self) -> Value {
494        Value::pipe_fresh_in_task(self.state.task_id)
495    }
496
497    /// Borrow the read half of a `PIPE` value for byte streaming (see
498    /// [`PipeStream`](super::PipeStream)). Unbound handles materialize as script pipes :
499    /// hosts cannot spawn `RUN`, so script is the only sensible kind,
500    /// and a later `RUN` binding adapts through the shared path. DSL,
501    /// bridge, and host bindings on an OS-materialized handle resolve
502    /// through the single-take bridge: the first call takes, repeats bail
503    /// loudly (same contract as DSL consumers; use script-backed pipes
504    /// for repeat or multi access).
505    pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
506        use oxdock_pipe::{Materialized, materialize};
507        let Some(handle) = value.as_pipe_handle() else {
508            anyhow::bail!(
509                "host pipe_reader needs a PIPE value, got {}",
510                value.type_name()
511            );
512        };
513        match materialize(&handle, false)? {
514            Materialized::Script(backend) => Ok(backend.reader_handle()),
515            #[cfg(not(miri))]
516            Materialized::Os(entry) => {
517                let owned = entry.reader.take().map_err(|_| {
518                    anyhow::anyhow!(
519                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
520                    )
521                })?;
522                Ok(Arc::new(Mutex::new(owned)))
523            }
524        }
525    }
526
527    /// Borrow the write half of a `PIPE` value for byte streaming (see
528    /// [`PipeStream`](super::PipeStream)). Same materialization and take-once contract as
529    /// [`StepCtx::pipe_reader`].
530    pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
531        use oxdock_pipe::{Materialized, materialize};
532        let Some(handle) = value.as_pipe_handle() else {
533            anyhow::bail!(
534                "host pipe_writer needs a PIPE value, got {}",
535                value.type_name()
536            );
537        };
538        match materialize(&handle, false)? {
539            Materialized::Script(backend) => Ok(backend.writer_handle()),
540            #[cfg(not(miri))]
541            Materialized::Os(entry) => {
542                let owned = entry.writer.take().map_err(|_| {
543                    anyhow::anyhow!(
544                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
545                    )
546                })?;
547                Ok(Arc::new(Mutex::new(owned)))
548            }
549        }
550    }
551
552    /// Explicitly close a script pipe: readers drain buffered bytes, then
553    /// observe EOF regardless of live writers or keeper pins. Unbound
554    /// handles bail (closing a never-bound pipe is a caller bug), and
555    /// OS-materialized handles bail (kernel pairs close by dropping their
556    /// taken halves : drop the value instead).
557    pub fn close_pipe(&self, value: &Value) -> Result<()> {
558        let Some(handle) = value.as_pipe_handle() else {
559            anyhow::bail!(
560                "host close_pipe needs a PIPE value, got {}",
561                value.type_name()
562            );
563        };
564        let Some(backend) = oxdock_pipe::script_backend(&handle) else {
565            anyhow::bail!(
566                "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
567            );
568        };
569        backend.force_close();
570        Ok(())
571    }
572
573    /// Whether the current task was cancelled (`CANCEL`/`TIMEOUT`). For
574    /// external host modules running blocking pumps: poll each tick so
575    /// silent-but-open pipes cannot strand the task thread.
576    pub fn is_cancelled(&self) -> bool {
577        self.state
578            .cancel_token
579            .load(std::sync::atomic::Ordering::SeqCst)
580    }
581
582    /// Shared cancellation flag for pump threads spawned by host
583    /// functions: clone into the worker and poll each tick, same as
584    /// `is_cancelled`, so `CANCEL`/`TIMEOUT` ends the pump and its
585    /// writer drop closes the output pipe for downstream readers.
586    pub fn cancel_token(&self) -> Arc<AtomicBool> {
587        Arc::clone(&self.state.cancel_token)
588    }
589
590    /// Event hub for the same cancellation: supervisors of blocking
591    /// pumps wait on this instead of polling the token, and every
592    /// `kill`/`TIMEOUT` path marks it alongside the token store.
593    pub fn cancel_hub(&self) -> Arc<oxdock_process::CancelHub> {
594        Arc::clone(&self.state.cancel_hub)
595    }
596
597    /// Whether this step runs on an `ASYNC` task thread. Blocking pumps
598    /// must refuse the main sequential flow.
599    pub fn is_async_task(&self) -> bool {
600        self.state.inside_async
601    }
602
603    /// Module-shared state stashed at registration (`HostModule::with_state`).
604    /// Lets `#[oxdock_func]` bodies reach state that cannot ride in a
605    /// value (endpoint registries) without hand-built closures. `None`
606    /// when the module registered no such state: a programmer error at
607    /// module-build time, never a script failure.
608    pub fn module_state<T: Send + Sync + 'static>(
609        &self,
610        module: &str,
611    ) -> Option<std::sync::Arc<T>> {
612        self.state
613            .module_states
614            .get(&(module.to_string(), std::any::TypeId::of::<T>()))?
615            .clone()
616            .downcast::<T>()
617            .ok()
618    }
619
620    /// Resolve an explicitly passed `PIPE` value to its script backend for
621    /// backend-aware pump operations (explicit close, cancel). This is value-based on
622    /// purpose: the ambient `out_pipe`/`stdin_pipe` fields only populate via
623    /// engine-level `WITH_IO` resolution, which never runs for host function
624    /// calls. Returns `None` for unbound and OS-materialized handles, which
625    /// fall back to plain blocking I/O.
626    pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
627        let handle = value.as_pipe_handle()?;
628        oxdock_pipe::script_backend(&handle)
629    }
630}
631
632#[allow(clippy::too_many_arguments)]
633pub(super) fn execute_steps<P: ProcessManager>(
634    state: &mut ExecState<P>,
635    process: &mut P,
636    steps: &[Step],
637    stdin: CommandStdin,
638    expose_stdin: bool,
639    out: Option<StreamHandle>,
640    err: Option<StreamHandle>,
641    out_pipe: Option<Arc<PipeInner>>,
642    stdin_pipe: Option<Arc<PipeInner>>,
643    wait_at_end: bool,
644) -> Result<Flow> {
645    let generation = allocate_assert_generation();
646    let flow = match execute_steps_inner(InnerArgs {
647        state,
648        process,
649        generation,
650        steps,
651        stdin,
652        expose_stdin,
653        out,
654        err,
655        out_pipe,
656        stdin_pipe,
657        wait_at_end,
658    }) {
659        Ok(flow) => flow,
660        Err(e) => {
661            // A step failed before end-of-pipeline reaping ran. Join
662            // background work now so the parent owns teardown: otherwise the
663            // parent drops its task-registry reference while a worker still
664            // lives, leaving the worker as the last registry owner to drop
665            // (and join) its own handle on thread exit.
666            teardown_tasks_on_error(state);
667            cleanup_assertion_generation(state, generation)?;
668            return Err(e);
669        }
670    };
671    // Cleanup: remove all assertion state for this generation
672    cleanup_assertion_generation(state, generation)?;
673    Ok(flow)
674}
675
676/// Remove per-generation assertion observers. Runs on success and on step
677/// failure so a failed pipeline never leaks windows into later runs.
678fn cleanup_assertion_generation<P: ProcessManager>(
679    state: &mut ExecState<P>,
680    generation: usize,
681) -> Result<()> {
682    let mut windows = match state.assert_windows.lock() {
683        Ok(guard) => guard,
684        Err(_) => bail!("assert_windows poisoned"),
685    };
686    windows.retain(|(g, _), _| *g != generation);
687    let mut stderr_windows = match state.assert_windows_stderr.lock() {
688        Ok(guard) => guard,
689        Err(_) => bail!("assert_windows_stderr poisoned"),
690    };
691    stderr_windows.retain(|(g, _), _| *g != generation);
692    let mut exact = match state.exact_stdout.lock() {
693        Ok(guard) => guard,
694        Err(_) => bail!("exact_stdout poisoned"),
695    };
696    exact.retain(|g, _| *g != generation);
697    Ok(())
698}
699
700/// Join background work after a step failure, mirroring the end-of-pipeline
701/// fail-fast teardown. Anonymous handles always belong to the current
702/// thread. Named entries are root-owned: worker threads must never block on
703/// sibling tasks, which may depend on the worker via AWAIT.
704fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
705    for survivor in state.bg_children.iter_mut() {
706        let _ = survivor.handle.kill();
707    }
708    state.bg_children.clear();
709    if state.inside_async {
710        return;
711    }
712    let entries: Vec<Arc<TaskEntry>> = {
713        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
714        named.values().cloned().collect()
715    };
716    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
717    for entry in &entries {
718        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
719        match guard.phase {
720            TaskPhase::Running | TaskPhase::Awaiting => {
721                guard.phase = TaskPhase::Cancelled;
722                if let Some(handle) = guard.handle.take() {
723                    to_kill.push((Arc::clone(entry), handle));
724                }
725            }
726            TaskPhase::Cancelled | TaskPhase::Completed => {}
727        }
728    }
729    for (entry, mut handle) in to_kill {
730        let _ = handle.kill();
731        entry.finish_teardown();
732    }
733}
734
735/// Execute a single step with an explicit generation and index.
736/// Used by `with_io` to preserve the parent step's index for assertion window keys.
737#[allow(clippy::too_many_arguments)]
738pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
739    state: &mut ExecState<P>,
740    process: &mut P,
741    cmd: &StepKind,
742    generation: usize,
743    idx: usize,
744    stdin: CommandStdin,
745    expose_stdin: bool,
746    out: Option<StreamHandle>,
747    err: Option<StreamHandle>,
748    out_pipe: Option<Arc<PipeInner>>,
749    stdin_pipe: Option<Arc<PipeInner>>,
750    tty: Option<TtyRequest>,
751) -> Result<Flow> {
752    let mut cx = StepCtx {
753        state,
754        process,
755        stdin,
756        expose_stdin,
757        out,
758        err,
759        out_pipe,
760        stdin_pipe,
761        tty,
762    };
763    // Compound steps (loops, functions, scoped wrappers) participate in
764    // Flow and dispatch through the Flow path; every other variant runs
765    // the leaf pipeline below and yields Done.
766    match cmd {
767        StepKind::FuncDef { .. }
768        | StepKind::Call { .. }
769        | StepKind::Return { .. }
770        | StepKind::ImportFile { .. }
771        | StepKind::ImportFuncs { .. }
772        | StepKind::While { .. }
773        | StepKind::Break
774        | StepKind::Continue
775        | StepKind::For { .. }
776        | StepKind::If { .. }
777        | StepKind::Timeout { .. }
778        | StepKind::Isolated { .. }
779        | StepKind::WithIo { .. }
780        | StepKind::AssignCapture { .. } => {
781            return dispatch_flow_step(cmd, &mut cx, generation, idx);
782        }
783        _ => {}
784    }
785    match cmd {
786        StepKind::Run(arg) => {
787            let cmd = super::args::resolve_arg(arg, &mut cx)?;
788            let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
789            handlers::run(&mut cx, &cmd)
790        }
791        StepKind::RunExec { argv } => {
792            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
793            handlers::run_argv(&mut cx, &resolved)
794        }
795        StepKind::Echo(arg) => {
796            let msg = super::args::resolve_arg(arg, &mut cx)?;
797            handlers::echo(&mut cx, &msg)
798        }
799        StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
800        StepKind::Workdir(arg) => {
801            let path = super::args::resolve_arg(arg, &mut cx)?;
802            handlers::workdir(&mut cx, &path)
803        }
804        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
805        StepKind::RemoteBlock {
806            target,
807            vars,
808            env,
809            body,
810        } => super::remote::run_remote_block(&mut cx, target, vars, env, body),
811        StepKind::Env { key, value } => {
812            let resolved = super::args::resolve_arg(value, &mut cx)?;
813            handlers::env(&mut cx, key, &resolved)
814        }
815        StepKind::InheritEnv { keys } => {
816            handlers::inherit_env(&mut cx, keys)?;
817            sync_iteration_assert_needles(
818                cx.state,
819                &[Step {
820                    guard: None,
821                    kind: cmd.clone(),
822                    scope_enter: 0,
823                    scope_exit: 0,
824                    line: 0,
825                    col: 0,
826                }],
827                generation,
828            )?;
829            Ok(())
830        }
831        StepKind::IsolatedInheritEnv { keys } => {
832            handlers::isolated_inherit_env(&mut cx, keys)?;
833            Ok(())
834        }
835        StepKind::Copy {
836            from_workspace,
837            from_host,
838            to_host,
839            from,
840            to,
841        } => {
842            if *from_host || *to_host {
843                super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
844            } else {
845                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
846                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
847                handlers::copy(
848                    &mut cx,
849                    from_workspace.clone(),
850                    &from_resolved,
851                    &to_resolved,
852                )
853            }
854        }
855        StepKind::CopyGit {
856            rev,
857            from,
858            to,
859            include_dirty,
860        } => {
861            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
862            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
863            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
864            handlers::copy_git(
865                &mut cx,
866                &rev_resolved,
867                &from_resolved,
868                &to_resolved,
869                *include_dirty,
870            )
871        }
872        StepKind::Archive { src, dst, raw } => {
873            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
874            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
875            handlers::archive(&mut cx, &src_resolved, &dst_resolved, *raw)
876        }
877        StepKind::Unarchive {
878            src,
879            dst,
880            max_bytes,
881        } => {
882            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
883            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
884            let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
885            handlers::unarchive(
886                &mut cx,
887                &src_resolved,
888                &dst_resolved,
889                cap_resolved.as_deref(),
890            )
891        }
892        StepKind::Symlink {
893            from_workspace,
894            from,
895            to,
896        } => {
897            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
898            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
899            handlers::symlink(
900                &mut cx,
901                from_workspace.clone(),
902                &from_resolved,
903                &to_resolved,
904            )
905        }
906        StepKind::Mkdir(arg) => {
907            let path = super::args::resolve_arg(arg, &mut cx)?;
908            handlers::mkdir(&mut cx, &path)
909        }
910        StepKind::Install { from, to } => {
911            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
912            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
913            handlers::install(&mut cx, &from_resolved, &to_resolved)
914        }
915        StepKind::Ls(arg) => {
916            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
917            handlers::ls(&mut cx, &resolved)
918        }
919        StepKind::Read(arg) => {
920            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
921            handlers::read(&mut cx, &resolved)
922        }
923        StepKind::ReadLine { var } => handlers::read_line(&mut cx, var),
924        StepKind::Prompt {
925            var,
926            message,
927            default,
928        } => {
929            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
930            let default_resolved = match default {
931                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
932                None => None,
933            };
934            handlers::prompt(&mut cx, var, &message_resolved, default_resolved.as_deref())
935        }
936        StepKind::ListAppend { list, item } => {
937            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
938            handlers::push_into(&mut cx, list, value)
939        }
940        StepKind::Write { path, contents } => {
941            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
942            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
943            handlers::write(&mut cx, &path_resolved, contents_resolved.as_deref())
944        }
945        StepKind::Append { path, contents } => {
946            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
947            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
948            handlers::append(&mut cx, &path_resolved, contents_resolved.as_deref())
949        }
950        StepKind::Remove { path, recursive } => {
951            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
952            handlers::remove(&mut cx, &path_resolved, *recursive)
953        }
954        StepKind::Expand { path, overrides } => {
955            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
956            let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
957            handlers::replace(&mut cx, &path_resolved, &overrides_resolved)
958        }
959        StepKind::AssertEq {
960            hash,
961            actual,
962            expected,
963        } => {
964            let target = resolve_assert_target(actual, &mut cx)?;
965            let expected_resolved = match expected {
966                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
967                None => None,
968            };
969            handlers::assert_eq(
970                &mut cx,
971                generation,
972                hash,
973                &target,
974                expected_resolved.as_ref(),
975            )
976        }
977        StepKind::AssertContains { haystack, needle } => {
978            let target = resolve_assert_target(haystack, &mut cx)?;
979            handlers::assert_contains(&mut cx, generation, idx, &target, needle)
980        }
981        StepKind::WithIoBlock { .. } => {
982            bail!("WITH_IO block should have been expanded during parsing")
983        }
984        StepKind::Exit(code) => {
985            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
986            handlers::exit(&mut cx, code)
987        }
988        StepKind::Assign {
989            var,
990            decl_type,
991            expr,
992        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
993        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
994        StepKind::AssignAsync {
995            var,
996            decl_type,
997            body,
998        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
999        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1000        StepKind::AwaitCapture {
1001            out_var,
1002            out_type,
1003            task_var,
1004        } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
1005        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1006        StepKind::Sleep { duration } => {
1007            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1008            handlers::sleep(&mut cx, &duration)
1009        }
1010        StepKind::TypeAlias { .. } => {
1011            // Static declaration: collected before the run and
1012            // resolved at first coercion. Nothing to execute.
1013            Ok(())
1014        }
1015        StepKind::FuncDef { .. }
1016        | StepKind::Call { .. }
1017        | StepKind::Return { .. }
1018        | StepKind::ImportFile { .. }
1019        | StepKind::ImportFuncs { .. }
1020        | StepKind::While { .. }
1021        | StepKind::Break
1022        | StepKind::Continue
1023        | StepKind::For { .. }
1024        | StepKind::If { .. }
1025        | StepKind::Timeout { .. }
1026        | StepKind::Isolated { .. }
1027        | StepKind::WithIo { .. }
1028        | StepKind::AssignCapture { .. } => {
1029            unreachable!("compound steps dispatch before this match")
1030        }
1031    }?;
1032    Ok(Flow::Done)
1033}
1034
1035#[allow(clippy::too_many_arguments)]
1036/// Position context wrapping a failing step's error: `step N` plus
1037/// `line L` / `col C` when the step carries coordinates (parsed
1038/// scripts do; hand-built steps keep the historical bare rendering).
1039/// Applied once per dispatch level, so nested bodies chain outer and
1040/// inner positions like a call path.
1041fn step_error(step: &Step, idx: usize, err: anyhow::Error) -> anyhow::Error {
1042    let mut loc = format!("step {}", idx + 1);
1043    if step.line > 0 {
1044        loc.push_str(&format!(", line {}", step.line));
1045        if step.col > 0 {
1046            loc.push_str(&format!(", col {}", step.col));
1047        }
1048    }
1049    err.context(loc)
1050}
1051
1052/// Bundled inputs for [`execute_steps_inner`]. One struct parameter
1053/// keeps the function under the argument-count lint without an
1054/// override; call sites construct it from the same values.
1055struct InnerArgs<'a, P: ProcessManager> {
1056    state: &'a mut ExecState<P>,
1057    process: &'a mut P,
1058    generation: usize,
1059    steps: &'a [Step],
1060    stdin: CommandStdin,
1061    expose_stdin: bool,
1062    out: Option<StreamHandle>,
1063    err: Option<StreamHandle>,
1064    out_pipe: Option<Arc<PipeInner>>,
1065    stdin_pipe: Option<Arc<PipeInner>>,
1066    wait_at_end: bool,
1067}
1068
1069fn execute_steps_inner<P: ProcessManager>(args: InnerArgs<'_, P>) -> Result<Flow> {
1070    let InnerArgs {
1071        state,
1072        process,
1073        generation,
1074        steps,
1075        stdin,
1076        expose_stdin,
1077        out,
1078        err,
1079        out_pipe,
1080        stdin_pipe,
1081        wait_at_end,
1082    } = args;
1083    // Pre-register assertion windows for this generation
1084    pre_register_assertions(state, steps, generation)?;
1085
1086    for (idx, step) in steps.iter().enumerate() {
1087        // Check for cancellation before each step
1088        if state.cancel_token.load(Ordering::SeqCst) {
1089            bail!("ASYNC task cancelled");
1090        }
1091        if step.scope_enter > 0 {
1092            for _ in 0..step.scope_enter {
1093                state.push_scope();
1094            }
1095        }
1096
1097        let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1098        // One position wrap per iteration: the closure funnels every
1099        // error path (including `?` inside match arms, which would
1100        // otherwise return past a post-hoc wrap) through `step_error`.
1101        let flow_result: Result<Flow> = (|| {
1102            if !should_run {
1103                Ok(Flow::Done)
1104            } else {
1105                let mut cx = StepCtx {
1106                    state,
1107                    process,
1108                    stdin: stdin.clone(),
1109                    expose_stdin,
1110                    out: out.clone(),
1111                    err: err.clone(),
1112                    out_pipe: out_pipe.clone(),
1113                    stdin_pipe: stdin_pipe.clone(),
1114                    tty: None,
1115                };
1116                // Function/loop control steps dispatch through the Flow path;
1117                // every other variant runs the leaf pipeline and yields Done.
1118                let flow_result: Result<Flow> = match &step.kind {
1119                    StepKind::FuncDef { .. }
1120                    | StepKind::Call { .. }
1121                    | StepKind::Return { .. }
1122                    | StepKind::ImportFile { .. }
1123                    | StepKind::ImportFuncs { .. }
1124                    | StepKind::While { .. }
1125                    | StepKind::Break
1126                    | StepKind::Continue
1127                    | StepKind::For { .. }
1128                    | StepKind::If { .. }
1129                    | StepKind::Timeout { .. }
1130                    | StepKind::Isolated { .. }
1131                    | StepKind::WithIo { .. }
1132                    | StepKind::AssignCapture { .. } => {
1133                        dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1134                    }
1135                    _ => {
1136                        match &step.kind {
1137                            StepKind::InheritEnv { keys } => {
1138                                handlers::inherit_env(&mut cx, keys)?;
1139                                sync_iteration_assert_needles(cx.state, steps, generation)?;
1140                                Ok(())
1141                            }
1142                            StepKind::IsolatedInheritEnv { keys } => {
1143                                handlers::isolated_inherit_env(&mut cx, keys)?;
1144                                Ok(())
1145                            }
1146                            StepKind::Workdir(arg) => {
1147                                let path = super::args::resolve_arg(arg, &mut cx)?;
1148                                handlers::workdir(&mut cx, &path)
1149                            }
1150                            StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
1151                            StepKind::RemoteBlock {
1152                                target,
1153                                vars,
1154                                env,
1155                                body,
1156                            } => super::remote::run_remote_block(&mut cx, target, vars, env, body),
1157                            StepKind::Env { key, value } => {
1158                                let resolved = super::args::resolve_arg(value, &mut cx)?;
1159                                handlers::env(&mut cx, key, &resolved)?;
1160                                sync_iteration_assert_needles(cx.state, steps, generation)?;
1161                                Ok(())
1162                            }
1163                            StepKind::Run(arg) => {
1164                                let cmd = super::args::resolve_arg(arg, &mut cx)?;
1165                                let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
1166                                handlers::run(&mut cx, &cmd)
1167                            }
1168                            StepKind::RunExec { argv } => {
1169                                let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
1170                                handlers::run_argv(&mut cx, &resolved)
1171                            }
1172                            StepKind::Echo(arg) => {
1173                                let msg = super::args::resolve_arg(arg, &mut cx)?;
1174                                handlers::echo(&mut cx, &msg)
1175                            }
1176                            StepKind::AsyncBlock { .. } => {
1177                                handlers::dispatch_async_block(&step.kind, &mut cx)
1178                            }
1179                            StepKind::Copy {
1180                                from_workspace,
1181                                from_host,
1182                                to_host,
1183                                from,
1184                                to,
1185                            } => {
1186                                if *from_host || *to_host {
1187                                    super::remote::copy_transfer(
1188                                        &mut cx, *from_host, *to_host, from, to,
1189                                    )
1190                                } else {
1191                                    let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1192                                    let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1193                                    handlers::copy(
1194                                        &mut cx,
1195                                        from_workspace.clone(),
1196                                        &from_resolved,
1197                                        &to_resolved,
1198                                    )
1199                                }
1200                            }
1201                            StepKind::CopyGit {
1202                                rev,
1203                                from,
1204                                to,
1205                                include_dirty,
1206                            } => {
1207                                let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
1208                                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1209                                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1210                                handlers::copy_git(
1211                                    &mut cx,
1212                                    &rev_resolved,
1213                                    &from_resolved,
1214                                    &to_resolved,
1215                                    *include_dirty,
1216                                )
1217                            }
1218                            StepKind::Archive { src, dst, raw } => {
1219                                let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1220                                let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1221                                handlers::archive(&mut cx, &src_resolved, &dst_resolved, *raw)
1222                            }
1223                            StepKind::Unarchive {
1224                                src,
1225                                dst,
1226                                max_bytes,
1227                            } => {
1228                                let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1229                                let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1230                                let cap_resolved =
1231                                    super::args::resolve_arg_opt(max_bytes, &mut cx)?;
1232                                handlers::unarchive(
1233                                    &mut cx,
1234                                    &src_resolved,
1235                                    &dst_resolved,
1236                                    cap_resolved.as_deref(),
1237                                )
1238                            }
1239                            StepKind::Symlink {
1240                                from_workspace,
1241                                from,
1242                                to,
1243                            } => {
1244                                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1245                                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1246                                handlers::symlink(
1247                                    &mut cx,
1248                                    from_workspace.clone(),
1249                                    &from_resolved,
1250                                    &to_resolved,
1251                                )
1252                            }
1253                            StepKind::Mkdir(arg) => {
1254                                let path = super::args::resolve_arg(arg, &mut cx)?;
1255                                handlers::mkdir(&mut cx, &path)
1256                            }
1257                            StepKind::Install { from, to } => {
1258                                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1259                                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1260                                handlers::install(&mut cx, &from_resolved, &to_resolved)
1261                            }
1262                            StepKind::Ls(arg) => {
1263                                let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1264                                handlers::ls(&mut cx, &resolved)
1265                            }
1266                            StepKind::Read(arg) => {
1267                                let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1268                                handlers::read(&mut cx, &resolved)
1269                            }
1270                            StepKind::ReadLine { var } => handlers::read_line(&mut cx, var),
1271                            StepKind::Prompt {
1272                                var,
1273                                message,
1274                                default,
1275                            } => {
1276                                let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1277                                let default_resolved = match default {
1278                                    Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1279                                    None => None,
1280                                };
1281                                handlers::prompt(
1282                                    &mut cx,
1283                                    var,
1284                                    &message_resolved,
1285                                    default_resolved.as_deref(),
1286                                )
1287                            }
1288                            StepKind::ListAppend { list, item } => {
1289                                let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1290                                handlers::push_into(&mut cx, list, value)
1291                            }
1292                            StepKind::Write { path, contents } => {
1293                                let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1294                                let contents_resolved =
1295                                    super::args::resolve_arg_opt(contents, &mut cx)?;
1296                                handlers::write(
1297                                    &mut cx,
1298                                    &path_resolved,
1299                                    contents_resolved.as_deref(),
1300                                )
1301                            }
1302                            StepKind::Append { path, contents } => {
1303                                let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1304                                let contents_resolved =
1305                                    super::args::resolve_arg_opt(contents, &mut cx)?;
1306                                handlers::append(
1307                                    &mut cx,
1308                                    &path_resolved,
1309                                    contents_resolved.as_deref(),
1310                                )
1311                            }
1312                            StepKind::Remove { path, recursive } => {
1313                                let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1314                                handlers::remove(&mut cx, &path_resolved, *recursive)
1315                            }
1316                            StepKind::Expand { path, overrides } => {
1317                                let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1318                                let overrides_resolved =
1319                                    super::args::resolve_overrides(overrides, &mut cx)?;
1320                                handlers::replace(&mut cx, &path_resolved, &overrides_resolved)
1321                            }
1322                            StepKind::AssertEq {
1323                                hash,
1324                                actual,
1325                                expected,
1326                            } => {
1327                                let target = resolve_assert_target(actual, &mut cx)?;
1328                                let expected_resolved = match expected {
1329                                    Some(e) => {
1330                                        Some(super::args::evaluate_assert_operand(e, &mut cx)?)
1331                                    }
1332                                    None => None,
1333                                };
1334                                handlers::assert_eq(
1335                                    &mut cx,
1336                                    generation,
1337                                    hash,
1338                                    &target,
1339                                    expected_resolved.as_ref(),
1340                                )
1341                            }
1342                            StepKind::AssertContains { haystack, needle } => {
1343                                let target = resolve_assert_target(haystack, &mut cx)?;
1344                                handlers::assert_contains(&mut cx, generation, idx, &target, needle)
1345                            }
1346                            StepKind::WithIoBlock { .. } => {
1347                                bail!("WITH_IO block should have been expanded during parsing")
1348                            }
1349                            StepKind::Exit(code) => {
1350                                let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1351                                handlers::exit(&mut cx, code)
1352                            }
1353                            StepKind::Assign {
1354                                var,
1355                                decl_type,
1356                                expr,
1357                            } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1358                            StepKind::Set { var, expr } => {
1359                                handlers::set_var_value(&mut cx, var, expr)
1360                            }
1361                            StepKind::AssignAsync {
1362                                var,
1363                                decl_type,
1364                                body,
1365                            } => handlers::dispatch_assign_async(
1366                                var,
1367                                decl_type.clone(),
1368                                body,
1369                                &mut cx,
1370                            ),
1371                            StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1372                            StepKind::AwaitCapture {
1373                                out_var,
1374                                out_type,
1375                                task_var,
1376                            } => handlers::dispatch_await_capture(
1377                                out_var,
1378                                out_type.clone(),
1379                                task_var,
1380                                &mut cx,
1381                            ),
1382                            StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1383                            StepKind::Sleep { duration } => {
1384                                let duration =
1385                                    super::args::resolve_arg_as_duration(duration, &mut cx)?;
1386                                handlers::sleep(&mut cx, &duration)
1387                            }
1388                            StepKind::TypeAlias { .. } => {
1389                                // Static declaration: collected before the run and
1390                                // resolved at first coercion. Nothing to execute.
1391                                Ok(())
1392                            }
1393                            StepKind::FuncDef { .. }
1394                            | StepKind::Call { .. }
1395                            | StepKind::Return { .. }
1396                            | StepKind::ImportFile { .. }
1397                            | StepKind::ImportFuncs { .. }
1398                            | StepKind::While { .. }
1399                            | StepKind::Break
1400                            | StepKind::Continue
1401                            | StepKind::For { .. }
1402                            | StepKind::If { .. }
1403                            | StepKind::Timeout { .. }
1404                            | StepKind::Isolated { .. }
1405                            | StepKind::WithIo { .. }
1406                            | StepKind::AssignCapture { .. } => {
1407                                unreachable!("compound steps dispatch in the outer match")
1408                            }
1409                        }?;
1410                        Ok(Flow::Done)
1411                    }
1412                };
1413                flow_result
1414            }
1415        })()
1416        .map_err(|err| step_error(step, idx, err));
1417
1418        let restore_result = restore_scopes(state, step.scope_exit);
1419        // Keeper expiry: drop spawn-time pins whose final producer step
1420        // just completed, so later consumer steps in the same task observe
1421        // EOF. Gated on slice identity, so nested bodies executing through
1422        // this same loop never discharge the worker's top-level map.
1423        let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1424            expiry.expire_step(steps, idx)
1425        } else {
1426            false
1427        };
1428        if expiry_drained {
1429            state.keeper_expiry = None;
1430        }
1431        let flow = flow_result?;
1432        restore_result?;
1433        match flow {
1434            Flow::Done => {}
1435            Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1436                return Ok(flow);
1437            }
1438        }
1439    }
1440
1441    // Poll anonymous background handles at end-of-pipeline. The shared
1442    // named_tasks entries are reaped only by the root context: task threads
1443    // must never block on sibling tasks, which may depend on this thread
1444    // via AWAIT (three-way deadlock). Un-awaited named tasks are still
1445    // reaped by the root end-poll, and explicitly awaited tasks join via
1446    // AWAIT. Entries are retained as Cancelled/Completed tombstones so
1447    // later AWAIT/CANCEL report precise errors.
1448    let reap_named = !state.inside_async;
1449    // Scope floor for `TIMEOUT`: only tasks at or above the floor join
1450    // at scope end. Older tasks keep running past the scope instead of
1451    // holding it open; `None` (pipeline top, every other scope) joins
1452    // everything, exactly as before.
1453    let floor = state.reap_floor;
1454    let in_scope = |id: u64| floor.map(|f| id >= f).unwrap_or(true);
1455    let has_bg = state.bg_children.iter().any(|c| in_scope(c.task_id));
1456    let named_pending = |state: &ExecState<P>| {
1457        reap_named
1458            && state
1459                .named_tasks
1460                .lock()
1461                .unwrap_or_else(|e| e.into_inner())
1462                .iter()
1463                .any(|(id, entry)| {
1464                    in_scope(*id) && !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped
1465                })
1466    };
1467    let has_named = named_pending(state);
1468    if wait_at_end && (has_bg || has_named) {
1469        loop {
1470            let mut failed_status: Option<anyhow::Error> = None;
1471
1472            // Cancellation (deadline watcher or parent teardown) must break
1473            // the poll loop: without this, a stuck background handle would
1474            // hang the reaper forever. Flows into the shared fail-fast
1475            // teardown below.
1476            if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1477                failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1478            }
1479
1480            // 1. Poll anonymous background handles. Handles below the
1481            // scope floor belong to outer work: never poll them here, or
1482            // the scope would wait out tasks it did not spawn.
1483            let mut i = 0;
1484            while i < state.bg_children.len() {
1485                if !in_scope(state.bg_children[i].task_id) {
1486                    i += 1;
1487                    continue;
1488                }
1489                match state.bg_children[i].handle.try_wait() {
1490                    Ok(Some(status)) => {
1491                        if !status.success() && failed_status.is_none() {
1492                            failed_status =
1493                                Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1494                            break;
1495                        }
1496                        state.bg_children.swap_remove(i);
1497                    }
1498                    Ok(None) => {
1499                        i += 1;
1500                    }
1501                    Err(e) => {
1502                        if failed_status.is_none() {
1503                            failed_status = Some(e);
1504                        }
1505                        break;
1506                    }
1507                }
1508            }
1509
1510            // 2. Poll un-awaited named tasks (root context only). Each entry
1511            // is probed under a short entry lock; terminal entries are
1512            // retained as tombstones, never removed.
1513            if failed_status.is_none() && reap_named {
1514                let entries: Vec<(u64, Arc<TaskEntry>)> = {
1515                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1516                    named
1517                        .iter()
1518                        .map(|(id, entry)| (*id, Arc::clone(entry)))
1519                        .collect()
1520                };
1521                for (id, entry) in &entries {
1522                    if !in_scope(*id) {
1523                        continue;
1524                    }
1525                    enum Poll {
1526                        Pending,
1527                        CompletedOk,
1528                        CompletedErr(anyhow::Error),
1529                    }
1530                    let poll = {
1531                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1532                        match guard.phase {
1533                            TaskPhase::Running | TaskPhase::Awaiting => {
1534                                match guard.handle.as_mut() {
1535                                    Some(handle) => match handle.try_wait() {
1536                                        Ok(Some(status)) => {
1537                                            let _ = guard.handle.take();
1538                                            guard.phase = TaskPhase::Completed;
1539                                            if status.success() {
1540                                                Poll::CompletedOk
1541                                            } else {
1542                                                Poll::CompletedErr(anyhow::anyhow!(
1543                                                    "named ASYNC task {id} exited with status {status}"
1544                                                ))
1545                                            }
1546                                        }
1547                                        Ok(None) => Poll::Pending,
1548                                        Err(e) => {
1549                                            let _ = guard.handle.take();
1550                                            guard.phase = TaskPhase::Completed;
1551                                            Poll::CompletedErr(e)
1552                                        }
1553                                    },
1554                                    // Handle taken by a concurrent CANCEL/AWAIT
1555                                    // teardown; the barrier below rendezvouses.
1556                                    None => Poll::Pending,
1557                                }
1558                            }
1559                            TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1560                        }
1561                    };
1562                    match poll {
1563                        Poll::Pending => {}
1564                        Poll::CompletedOk => {
1565                            entry.finish_teardown();
1566                        }
1567                        Poll::CompletedErr(e) => {
1568                            entry.finish_teardown();
1569                            if failed_status.is_none() {
1570                                failed_status = Some(e);
1571                            }
1572                            break;
1573                        }
1574                    }
1575                }
1576            }
1577
1578            // 3. Fail-fast teardown (named entries are root-owned; task
1579            // threads only tear down their own anonymous children).
1580            // Handles are taken under short locks and killed outside every
1581            // lock; tombstones are retained.
1582            if let Some(err) = failed_status {
1583                for survivor in state.bg_children.iter_mut() {
1584                    if in_scope(survivor.task_id) {
1585                        let _ = survivor.handle.kill();
1586                    }
1587                }
1588                if reap_named {
1589                    let entries: Vec<(u64, Arc<TaskEntry>)> = {
1590                        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1591                        named
1592                            .iter()
1593                            .map(|(id, entry)| (*id, Arc::clone(entry)))
1594                            .collect()
1595                    };
1596                    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1597                    for (id, entry) in &entries {
1598                        if !in_scope(*id) {
1599                            continue;
1600                        }
1601                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1602                        match guard.phase {
1603                            TaskPhase::Running | TaskPhase::Awaiting => {
1604                                guard.phase = TaskPhase::Cancelled;
1605                                if let Some(handle) = guard.handle.take() {
1606                                    to_kill.push((Arc::clone(entry), handle));
1607                                }
1608                            }
1609                            TaskPhase::Cancelled | TaskPhase::Completed => {}
1610                        }
1611                    }
1612                    for (entry, mut handle) in to_kill {
1613                        let _ = handle.kill();
1614                        entry.finish_teardown();
1615                    }
1616                }
1617                // Drop only the scope's own handles: outer work keeps
1618                // running past a scope teardown, and the pipeline-top
1619                // teardown still owns it.
1620                state.bg_children.retain(|c| !in_scope(c.task_id));
1621                return Err(err);
1622            }
1623
1624            let bg_empty = !state.bg_children.iter().any(|c| in_scope(c.task_id));
1625            if bg_empty && !named_pending(state) {
1626                return Ok(Flow::Done);
1627            }
1628            // Rendezvous: a concurrent CANCEL/AWAIT on another thread may
1629            // own teardown of a Cancelled-but-unreaped entry. Wait for it
1630            // instead of spinning, so this thread never outruns the join.
1631            if reap_named {
1632                let unreaped: Vec<Arc<TaskEntry>> = {
1633                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1634                    named
1635                        .iter()
1636                        .filter(|(id, entry)| {
1637                            if !in_scope(**id) {
1638                                return false;
1639                            }
1640                            let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1641                            matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1642                        })
1643                        .map(|(_, entry)| Arc::clone(entry))
1644                        .collect()
1645                };
1646                for entry in &unreaped {
1647                    entry.wait_reaped();
1648                }
1649            }
1650            std::thread::sleep(std::time::Duration::from_millis(10));
1651        }
1652    }
1653
1654    Ok(Flow::Done)
1655}
1656
1657fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1658    for _ in 0..count {
1659        state.pop_scope()?;
1660    }
1661    Ok(())
1662}
1663
1664/// Execute a `REMOTE` body locally inside a fresh lexical scope: the
1665/// guest-mode path, where the shipped text keeps its `REMOTE` wrapper and
1666/// the session already fulfilled the transfer declarations. Scope,
1667/// pipes, and filesystem effects behave exactly like any local block;
1668/// control-flow signals crossing the block edge become step-numbered
1669/// errors, mirroring the pipeline-top mapping.
1670#[allow(clippy::too_many_arguments)]
1671pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1672    state: &mut ExecState<P>,
1673    process: &mut P,
1674    steps: &[Step],
1675    stdin: CommandStdin,
1676    expose_stdin: bool,
1677    out: Option<StreamHandle>,
1678    err: Option<StreamHandle>,
1679    out_pipe: Option<Arc<PipeInner>>,
1680    stdin_pipe: Option<Arc<PipeInner>>,
1681) -> Result<()> {
1682    let flow = execute_scoped_steps(
1683        state,
1684        process,
1685        steps,
1686        stdin,
1687        expose_stdin,
1688        out,
1689        err,
1690        out_pipe,
1691        stdin_pipe,
1692        true,
1693    )?;
1694    match flow {
1695        Flow::Done => Ok(()),
1696        Flow::Break { idx } => {
1697            bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1698        }
1699        Flow::Continue { idx } => {
1700            bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1701        }
1702        Flow::Return { idx, .. } => {
1703            bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1704        }
1705    }
1706}
1707
1708/// Execute steps inside a fresh lexical scope (IF branches, TIMEOUT bodies).
1709/// Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE); only pipes and
1710/// filesystem effects cross. Restores even when the body fails. Propagates
1711/// Flow signals (BREAK/CONTINUE/RETURN) to the caller after restoring.
1712#[allow(clippy::too_many_arguments)]
1713pub(super) fn execute_scoped_steps<P: ProcessManager>(
1714    state: &mut ExecState<P>,
1715    process: &mut P,
1716    steps: &[Step],
1717    stdin: CommandStdin,
1718    expose_stdin: bool,
1719    out: Option<StreamHandle>,
1720    err: Option<StreamHandle>,
1721    out_pipe: Option<Arc<PipeInner>>,
1722    stdin_pipe: Option<Arc<PipeInner>>,
1723    wait_at_end: bool,
1724) -> Result<Flow> {
1725    state.push_scope();
1726    let res = execute_steps(
1727        state,
1728        process,
1729        steps,
1730        stdin,
1731        expose_stdin,
1732        out,
1733        err,
1734        out_pipe,
1735        stdin_pipe,
1736        wait_at_end,
1737    );
1738    // Restore the scope even when the body failed, but never let an
1739    // unwinding failure mask the body's own error.
1740    let pop_res = state.pop_scope();
1741    match (res, pop_res) {
1742        (Ok(flow), Ok(())) => Ok(flow),
1743        (Err(e), _) => Err(e),
1744        (Ok(_), Err(e)) => Err(e),
1745    }
1746}
1747
1748/// Dispatch one compound step (loops, functions, scoped wrappers) through
1749/// the Flow path. Called with the caller's generation/idx so assertion
1750/// windows and error attribution match the leaf pipeline.
1751fn dispatch_flow_step<P: ProcessManager>(
1752    cmd: &StepKind,
1753    cx: &mut StepCtx<'_, P>,
1754    generation: usize,
1755    idx: usize,
1756) -> Result<Flow> {
1757    match cmd {
1758        StepKind::FuncDef {
1759            name, params, body, ..
1760        } => {
1761            handlers::define_func(cx, name, params, body)?;
1762            Ok(Flow::Done)
1763        }
1764        StepKind::Call { name, args } => {
1765            let _ = handlers::call_func_value(cx, name, args)?;
1766            Ok(Flow::Done)
1767        }
1768        StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1769        StepKind::ImportFile { path, alias } => {
1770            let _ = super::import::import_file(cx, path, alias)?;
1771            Ok(Flow::Done)
1772        }
1773        StepKind::ImportFuncs {
1774            path,
1775            alias,
1776            func_names,
1777            type_names,
1778        } => {
1779            super::import::import_funcs(cx, path, alias.as_deref(), func_names, type_names)?;
1780            Ok(Flow::Done)
1781        }
1782        StepKind::While { cond, body } => handlers::while_loop(cx, cond, body),
1783        StepKind::Break => Ok(Flow::Break { idx }),
1784        StepKind::Continue => Ok(Flow::Continue { idx }),
1785        StepKind::For {
1786            key_var,
1787            key_type,
1788            var,
1789            var_type,
1790            in_expr,
1791            body,
1792        } => handlers::for_loop(
1793            cx,
1794            key_var.as_deref(),
1795            key_type.clone(),
1796            var,
1797            var_type.clone(),
1798            in_expr,
1799            body,
1800        ),
1801        StepKind::If {
1802            cond,
1803            then_body,
1804            else_ifs,
1805            else_body,
1806        } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1807        StepKind::Timeout { duration, body } => {
1808            let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1809            handlers::timeout(cx, &duration, body)
1810        }
1811        StepKind::Isolated { body } => handlers::isolated(cx, body),
1812        StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1813        StepKind::AssignCapture {
1814            var,
1815            decl_type,
1816            cmd,
1817        } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1818        _ => {
1819            unreachable!("dispatch_flow_step handles only compound steps")
1820        }
1821    }
1822}