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(
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::While { .. }
771        | StepKind::Break
772        | StepKind::Continue
773        | StepKind::For { .. }
774        | StepKind::If { .. }
775        | StepKind::Timeout { .. }
776        | StepKind::Isolated { .. }
777        | StepKind::WithIo { .. }
778        | StepKind::AssignCapture { .. } => {
779            return dispatch_flow_step(cmd, &mut cx, generation, idx);
780        }
781        _ => {}
782    }
783    match cmd {
784        StepKind::Run(arg) => {
785            let cmd = super::args::resolve_arg(arg, &mut cx)?;
786            let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
787            handlers::run(&mut cx, idx, &cmd)
788        }
789        StepKind::RunExec { argv } => {
790            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
791            handlers::run_argv(&mut cx, idx, &resolved)
792        }
793        StepKind::Echo(arg) => {
794            let msg = super::args::resolve_arg(arg, &mut cx)?;
795            handlers::echo(&mut cx, &msg)
796        }
797        StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
798        StepKind::Workdir(arg) => {
799            let path = super::args::resolve_arg(arg, &mut cx)?;
800            handlers::workdir(&mut cx, idx, &path)
801        }
802        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
803        StepKind::RemoteBlock {
804            target,
805            vars,
806            env,
807            body,
808        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
809        StepKind::Env { key, value } => {
810            let resolved = super::args::resolve_arg(value, &mut cx)?;
811            handlers::env(&mut cx, key, &resolved)
812        }
813        StepKind::InheritEnv { keys } => {
814            handlers::inherit_env(&mut cx, keys)?;
815            sync_iteration_assert_needles(
816                cx.state,
817                &[Step {
818                    guard: None,
819                    kind: cmd.clone(),
820                    scope_enter: 0,
821                    scope_exit: 0,
822                }],
823                generation,
824            )?;
825            Ok(())
826        }
827        StepKind::IsolatedInheritEnv { keys } => {
828            handlers::isolated_inherit_env(&mut cx, keys)?;
829            Ok(())
830        }
831        StepKind::Copy {
832            from_workspace,
833            from_host,
834            to_host,
835            from,
836            to,
837        } => {
838            if *from_host || *to_host {
839                super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
840            } else {
841                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
842                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
843                handlers::copy(
844                    &mut cx,
845                    idx,
846                    from_workspace.clone(),
847                    &from_resolved,
848                    &to_resolved,
849                )
850            }
851        }
852        StepKind::CopyGit {
853            rev,
854            from,
855            to,
856            include_dirty,
857        } => {
858            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
859            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
860            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
861            handlers::copy_git(
862                &mut cx,
863                idx,
864                &rev_resolved,
865                &from_resolved,
866                &to_resolved,
867                *include_dirty,
868            )
869        }
870        StepKind::HashSha256 { path } => {
871            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
872            handlers::hash_sha256(&mut cx, idx, &path_resolved)
873        }
874        StepKind::Archive { src, dst, raw } => {
875            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
876            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
877            handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
878        }
879        StepKind::Unarchive {
880            src,
881            dst,
882            max_bytes,
883        } => {
884            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
885            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
886            let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
887            handlers::unarchive(
888                &mut cx,
889                idx,
890                &src_resolved,
891                &dst_resolved,
892                cap_resolved.as_deref(),
893            )
894        }
895        StepKind::Symlink {
896            from_workspace,
897            from,
898            to,
899        } => {
900            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
901            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
902            handlers::symlink(
903                &mut cx,
904                idx,
905                from_workspace.clone(),
906                &from_resolved,
907                &to_resolved,
908            )
909        }
910        StepKind::Mkdir(arg) => {
911            let path = super::args::resolve_arg(arg, &mut cx)?;
912            handlers::mkdir(&mut cx, idx, &path)
913        }
914        StepKind::Install { from, to } => {
915            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
916            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
917            handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
918        }
919        StepKind::Ls(arg) => {
920            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
921            handlers::ls(&mut cx, idx, &resolved)
922        }
923        StepKind::Cwd => handlers::cwd(&mut cx, idx),
924        StepKind::Read(arg) => {
925            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
926            handlers::read(&mut cx, idx, &resolved)
927        }
928        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
929        StepKind::Prompt {
930            var,
931            message,
932            default,
933        } => {
934            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
935            let default_resolved = match default {
936                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
937                None => None,
938            };
939            handlers::prompt(
940                &mut cx,
941                idx,
942                var,
943                &message_resolved,
944                default_resolved.as_deref(),
945            )
946        }
947        StepKind::ListAppend { list, item } => {
948            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
949            handlers::push_into(&mut cx, idx, list, value)
950        }
951        StepKind::Write { path, contents } => {
952            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
953            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
954            handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
955        }
956        StepKind::Append { path, contents } => {
957            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
958            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
959            handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
960        }
961        StepKind::Remove { path, recursive } => {
962            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
963            handlers::remove(&mut cx, idx, &path_resolved, *recursive)
964        }
965        StepKind::Expand { path, overrides } => {
966            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
967            let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
968            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
969        }
970        StepKind::AssertEq {
971            hash,
972            actual,
973            expected,
974        } => {
975            let target = resolve_assert_target(actual, &mut cx)?;
976            let expected_resolved = match expected {
977                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
978                None => None,
979            };
980            handlers::assert_eq(
981                &mut cx,
982                idx,
983                generation,
984                idx,
985                hash,
986                &target,
987                expected_resolved.as_ref(),
988            )
989        }
990        StepKind::AssertContains { haystack, needle } => {
991            let target = resolve_assert_target(haystack, &mut cx)?;
992            handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
993        }
994        StepKind::WithIoBlock { .. } => {
995            bail!("WITH_IO block should have been expanded during parsing")
996        }
997        StepKind::Exit(code) => {
998            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
999            handlers::exit(&mut cx, code)
1000        }
1001        StepKind::Assign {
1002            var,
1003            decl_type,
1004            expr,
1005        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1006        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1007        StepKind::AssignAsync {
1008            var,
1009            decl_type,
1010            body,
1011        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1012        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1013        StepKind::AwaitCapture {
1014            out_var,
1015            out_type,
1016            task_var,
1017        } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
1018        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1019        StepKind::Sleep { duration } => {
1020            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1021            handlers::sleep(&mut cx, idx, &duration)
1022        }
1023        StepKind::TypeAlias { .. } => {
1024            // Static declaration: collected before the run and
1025            // resolved at first coercion. Nothing to execute.
1026            Ok(())
1027        }
1028        StepKind::FuncDef { .. }
1029        | StepKind::Call { .. }
1030        | StepKind::Return { .. }
1031        | StepKind::While { .. }
1032        | StepKind::Break
1033        | StepKind::Continue
1034        | StepKind::For { .. }
1035        | StepKind::If { .. }
1036        | StepKind::Timeout { .. }
1037        | StepKind::Isolated { .. }
1038        | StepKind::WithIo { .. }
1039        | StepKind::AssignCapture { .. } => {
1040            unreachable!("compound steps dispatch before this match")
1041        }
1042    }?;
1043    Ok(Flow::Done)
1044}
1045
1046#[allow(clippy::too_many_arguments)]
1047fn execute_steps_inner<P: ProcessManager>(
1048    state: &mut ExecState<P>,
1049    process: &mut P,
1050    generation: usize,
1051    steps: &[Step],
1052    stdin: CommandStdin,
1053    expose_stdin: bool,
1054    out: Option<StreamHandle>,
1055    err: Option<StreamHandle>,
1056    out_pipe: Option<Arc<PipeInner>>,
1057    stdin_pipe: Option<Arc<PipeInner>>,
1058    wait_at_end: bool,
1059) -> Result<Flow> {
1060    // Pre-register assertion windows for this generation
1061    pre_register_assertions(state, steps, generation)?;
1062
1063    for (idx, step) in steps.iter().enumerate() {
1064        // Check for cancellation before each step
1065        if state.cancel_token.load(Ordering::SeqCst) {
1066            bail!("ASYNC task cancelled");
1067        }
1068        if step.scope_enter > 0 {
1069            for _ in 0..step.scope_enter {
1070                state.push_scope();
1071            }
1072        }
1073
1074        let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1075        let flow_result: Result<Flow> = if !should_run {
1076            Ok(Flow::Done)
1077        } else {
1078            let mut cx = StepCtx {
1079                state,
1080                process,
1081                stdin: stdin.clone(),
1082                expose_stdin,
1083                out: out.clone(),
1084                err: err.clone(),
1085                out_pipe: out_pipe.clone(),
1086                stdin_pipe: stdin_pipe.clone(),
1087                tty: None,
1088            };
1089            // Function/loop control steps dispatch through the Flow path;
1090            // every other variant runs the leaf pipeline and yields Done.
1091            let flow_result: Result<Flow> = match &step.kind {
1092                StepKind::FuncDef { .. }
1093                | StepKind::Call { .. }
1094                | StepKind::Return { .. }
1095                | StepKind::While { .. }
1096                | StepKind::Break
1097                | StepKind::Continue
1098                | StepKind::For { .. }
1099                | StepKind::If { .. }
1100                | StepKind::Timeout { .. }
1101                | StepKind::Isolated { .. }
1102                | StepKind::WithIo { .. }
1103                | StepKind::AssignCapture { .. } => {
1104                    dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1105                }
1106                _ => {
1107                    match &step.kind {
1108                        StepKind::InheritEnv { keys } => {
1109                            handlers::inherit_env(&mut cx, keys)?;
1110                            sync_iteration_assert_needles(cx.state, steps, generation)?;
1111                            Ok(())
1112                        }
1113                        StepKind::IsolatedInheritEnv { keys } => {
1114                            handlers::isolated_inherit_env(&mut cx, keys)?;
1115                            Ok(())
1116                        }
1117                        StepKind::Workdir(arg) => {
1118                            let path = super::args::resolve_arg(arg, &mut cx)?;
1119                            handlers::workdir(&mut cx, idx, &path)
1120                        }
1121                        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
1122                        StepKind::RemoteBlock {
1123                            target,
1124                            vars,
1125                            env,
1126                            body,
1127                        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
1128                        StepKind::Env { key, value } => {
1129                            let resolved = super::args::resolve_arg(value, &mut cx)?;
1130                            handlers::env(&mut cx, key, &resolved)?;
1131                            sync_iteration_assert_needles(cx.state, steps, generation)?;
1132                            Ok(())
1133                        }
1134                        StepKind::Run(arg) => {
1135                            let cmd = super::args::resolve_arg(arg, &mut cx)?;
1136                            let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
1137                            handlers::run(&mut cx, idx, &cmd)
1138                        }
1139                        StepKind::RunExec { argv } => {
1140                            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
1141                            handlers::run_argv(&mut cx, idx, &resolved)
1142                        }
1143                        StepKind::Echo(arg) => {
1144                            let msg = super::args::resolve_arg(arg, &mut cx)?;
1145                            handlers::echo(&mut cx, &msg)
1146                        }
1147                        StepKind::AsyncBlock { .. } => {
1148                            handlers::dispatch_async_block(&step.kind, &mut cx)
1149                        }
1150                        StepKind::Copy {
1151                            from_workspace,
1152                            from_host,
1153                            to_host,
1154                            from,
1155                            to,
1156                        } => {
1157                            if *from_host || *to_host {
1158                                super::remote::copy_transfer(
1159                                    &mut cx, *from_host, *to_host, from, to,
1160                                )
1161                            } else {
1162                                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1163                                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1164                                handlers::copy(
1165                                    &mut cx,
1166                                    idx,
1167                                    from_workspace.clone(),
1168                                    &from_resolved,
1169                                    &to_resolved,
1170                                )
1171                            }
1172                        }
1173                        StepKind::CopyGit {
1174                            rev,
1175                            from,
1176                            to,
1177                            include_dirty,
1178                        } => {
1179                            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
1180                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1181                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1182                            handlers::copy_git(
1183                                &mut cx,
1184                                idx,
1185                                &rev_resolved,
1186                                &from_resolved,
1187                                &to_resolved,
1188                                *include_dirty,
1189                            )
1190                        }
1191                        StepKind::HashSha256 { path } => {
1192                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1193                            handlers::hash_sha256(&mut cx, idx, &path_resolved)
1194                        }
1195                        StepKind::Archive { src, dst, raw } => {
1196                            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1197                            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1198                            handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
1199                        }
1200                        StepKind::Unarchive {
1201                            src,
1202                            dst,
1203                            max_bytes,
1204                        } => {
1205                            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1206                            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1207                            let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
1208                            handlers::unarchive(
1209                                &mut cx,
1210                                idx,
1211                                &src_resolved,
1212                                &dst_resolved,
1213                                cap_resolved.as_deref(),
1214                            )
1215                        }
1216                        StepKind::Symlink {
1217                            from_workspace,
1218                            from,
1219                            to,
1220                        } => {
1221                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1222                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1223                            handlers::symlink(
1224                                &mut cx,
1225                                idx,
1226                                from_workspace.clone(),
1227                                &from_resolved,
1228                                &to_resolved,
1229                            )
1230                        }
1231                        StepKind::Mkdir(arg) => {
1232                            let path = super::args::resolve_arg(arg, &mut cx)?;
1233                            handlers::mkdir(&mut cx, idx, &path)
1234                        }
1235                        StepKind::Install { from, to } => {
1236                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1237                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1238                            handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
1239                        }
1240                        StepKind::Ls(arg) => {
1241                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1242                            handlers::ls(&mut cx, idx, &resolved)
1243                        }
1244                        StepKind::Cwd => handlers::cwd(&mut cx, idx),
1245                        StepKind::Read(arg) => {
1246                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1247                            handlers::read(&mut cx, idx, &resolved)
1248                        }
1249                        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
1250                        StepKind::Prompt {
1251                            var,
1252                            message,
1253                            default,
1254                        } => {
1255                            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1256                            let default_resolved = match default {
1257                                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1258                                None => None,
1259                            };
1260                            handlers::prompt(
1261                                &mut cx,
1262                                idx,
1263                                var,
1264                                &message_resolved,
1265                                default_resolved.as_deref(),
1266                            )
1267                        }
1268                        StepKind::ListAppend { list, item } => {
1269                            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1270                            handlers::push_into(&mut cx, idx, list, value)
1271                        }
1272                        StepKind::Write { path, contents } => {
1273                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1274                            let contents_resolved =
1275                                super::args::resolve_arg_opt(contents, &mut cx)?;
1276                            handlers::write(
1277                                &mut cx,
1278                                idx,
1279                                &path_resolved,
1280                                contents_resolved.as_deref(),
1281                            )
1282                        }
1283                        StepKind::Append { path, contents } => {
1284                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1285                            let contents_resolved =
1286                                super::args::resolve_arg_opt(contents, &mut cx)?;
1287                            handlers::append(
1288                                &mut cx,
1289                                idx,
1290                                &path_resolved,
1291                                contents_resolved.as_deref(),
1292                            )
1293                        }
1294                        StepKind::Remove { path, recursive } => {
1295                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1296                            handlers::remove(&mut cx, idx, &path_resolved, *recursive)
1297                        }
1298                        StepKind::Expand { path, overrides } => {
1299                            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1300                            let overrides_resolved =
1301                                super::args::resolve_overrides(overrides, &mut cx)?;
1302                            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
1303                        }
1304                        StepKind::AssertEq {
1305                            hash,
1306                            actual,
1307                            expected,
1308                        } => {
1309                            let target = resolve_assert_target(actual, &mut cx)?;
1310                            let expected_resolved = match expected {
1311                                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1312                                None => None,
1313                            };
1314                            handlers::assert_eq(
1315                                &mut cx,
1316                                idx,
1317                                generation,
1318                                idx,
1319                                hash,
1320                                &target,
1321                                expected_resolved.as_ref(),
1322                            )
1323                        }
1324                        StepKind::AssertContains { haystack, needle } => {
1325                            let target = resolve_assert_target(haystack, &mut cx)?;
1326                            handlers::assert_contains(
1327                                &mut cx, idx, generation, idx, &target, needle,
1328                            )
1329                        }
1330                        StepKind::WithIoBlock { .. } => {
1331                            bail!("WITH_IO block should have been expanded during parsing")
1332                        }
1333                        StepKind::Exit(code) => {
1334                            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1335                            handlers::exit(&mut cx, code)
1336                        }
1337                        StepKind::Assign {
1338                            var,
1339                            decl_type,
1340                            expr,
1341                        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1342                        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1343                        StepKind::AssignAsync {
1344                            var,
1345                            decl_type,
1346                            body,
1347                        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1348                        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1349                        StepKind::AwaitCapture {
1350                            out_var,
1351                            out_type,
1352                            task_var,
1353                        } => handlers::dispatch_await_capture(
1354                            out_var,
1355                            out_type.clone(),
1356                            task_var,
1357                            &mut cx,
1358                        ),
1359                        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1360                        StepKind::Sleep { duration } => {
1361                            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1362                            handlers::sleep(&mut cx, idx, &duration)
1363                        }
1364                        StepKind::TypeAlias { .. } => {
1365                            // Static declaration: collected before the run and
1366                            // resolved at first coercion. Nothing to execute.
1367                            Ok(())
1368                        }
1369                        StepKind::FuncDef { .. }
1370                        | StepKind::Call { .. }
1371                        | StepKind::Return { .. }
1372                        | StepKind::While { .. }
1373                        | StepKind::Break
1374                        | StepKind::Continue
1375                        | StepKind::For { .. }
1376                        | StepKind::If { .. }
1377                        | StepKind::Timeout { .. }
1378                        | StepKind::Isolated { .. }
1379                        | StepKind::WithIo { .. }
1380                        | StepKind::AssignCapture { .. } => {
1381                            unreachable!("compound steps dispatch in the outer match")
1382                        }
1383                    }?;
1384                    Ok(Flow::Done)
1385                }
1386            };
1387            flow_result
1388        };
1389
1390        let restore_result = restore_scopes(state, step.scope_exit);
1391        // Keeper expiry: drop spawn-time pins whose final producer step
1392        // just completed, so later consumer steps in the same task observe
1393        // EOF. Gated on slice identity, so nested bodies executing through
1394        // this same loop never discharge the worker's top-level map.
1395        let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1396            expiry.expire_step(steps, idx)
1397        } else {
1398            false
1399        };
1400        if expiry_drained {
1401            state.keeper_expiry = None;
1402        }
1403        let flow = flow_result?;
1404        restore_result?;
1405        match flow {
1406            Flow::Done => {}
1407            Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1408                return Ok(flow);
1409            }
1410        }
1411    }
1412
1413    // Poll anonymous background handles at end-of-pipeline. The shared
1414    // named_tasks entries are reaped only by the root context: task threads
1415    // must never block on sibling tasks, which may depend on this thread
1416    // via AWAIT (three-way deadlock). Un-awaited named tasks are still
1417    // reaped by the root end-poll, and explicitly awaited tasks join via
1418    // AWAIT. Entries are retained as Cancelled/Completed tombstones so
1419    // later AWAIT/CANCEL report precise errors.
1420    let reap_named = !state.inside_async;
1421    // Scope floor for `TIMEOUT`: only tasks at or above the floor join
1422    // at scope end. Older tasks keep running past the scope instead of
1423    // holding it open; `None` (pipeline top, every other scope) joins
1424    // everything, exactly as before.
1425    let floor = state.reap_floor;
1426    let in_scope = |id: u64| floor.map(|f| id >= f).unwrap_or(true);
1427    let has_bg = state.bg_children.iter().any(|c| in_scope(c.task_id));
1428    let named_pending = |state: &ExecState<P>| {
1429        reap_named
1430            && state
1431                .named_tasks
1432                .lock()
1433                .unwrap_or_else(|e| e.into_inner())
1434                .iter()
1435                .any(|(id, entry)| {
1436                    in_scope(*id) && !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped
1437                })
1438    };
1439    let has_named = named_pending(state);
1440    if wait_at_end && (has_bg || has_named) {
1441        loop {
1442            let mut failed_status: Option<anyhow::Error> = None;
1443
1444            // Cancellation (deadline watcher or parent teardown) must break
1445            // the poll loop: without this, a stuck background handle would
1446            // hang the reaper forever. Flows into the shared fail-fast
1447            // teardown below.
1448            if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1449                failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1450            }
1451
1452            // 1. Poll anonymous background handles. Handles below the
1453            // scope floor belong to outer work: never poll them here, or
1454            // the scope would wait out tasks it did not spawn.
1455            let mut i = 0;
1456            while i < state.bg_children.len() {
1457                if !in_scope(state.bg_children[i].task_id) {
1458                    i += 1;
1459                    continue;
1460                }
1461                match state.bg_children[i].handle.try_wait() {
1462                    Ok(Some(status)) => {
1463                        if !status.success() && failed_status.is_none() {
1464                            failed_status =
1465                                Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1466                            break;
1467                        }
1468                        state.bg_children.swap_remove(i);
1469                    }
1470                    Ok(None) => {
1471                        i += 1;
1472                    }
1473                    Err(e) => {
1474                        if failed_status.is_none() {
1475                            failed_status = Some(e);
1476                        }
1477                        break;
1478                    }
1479                }
1480            }
1481
1482            // 2. Poll un-awaited named tasks (root context only). Each entry
1483            // is probed under a short entry lock; terminal entries are
1484            // retained as tombstones, never removed.
1485            if failed_status.is_none() && reap_named {
1486                let entries: Vec<(u64, Arc<TaskEntry>)> = {
1487                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1488                    named
1489                        .iter()
1490                        .map(|(id, entry)| (*id, Arc::clone(entry)))
1491                        .collect()
1492                };
1493                for (id, entry) in &entries {
1494                    if !in_scope(*id) {
1495                        continue;
1496                    }
1497                    enum Poll {
1498                        Pending,
1499                        CompletedOk,
1500                        CompletedErr(anyhow::Error),
1501                    }
1502                    let poll = {
1503                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1504                        match guard.phase {
1505                            TaskPhase::Running | TaskPhase::Awaiting => {
1506                                match guard.handle.as_mut() {
1507                                    Some(handle) => match handle.try_wait() {
1508                                        Ok(Some(status)) => {
1509                                            let _ = guard.handle.take();
1510                                            guard.phase = TaskPhase::Completed;
1511                                            if status.success() {
1512                                                Poll::CompletedOk
1513                                            } else {
1514                                                Poll::CompletedErr(anyhow::anyhow!(
1515                                                    "named ASYNC task {id} exited with status {status}"
1516                                                ))
1517                                            }
1518                                        }
1519                                        Ok(None) => Poll::Pending,
1520                                        Err(e) => {
1521                                            let _ = guard.handle.take();
1522                                            guard.phase = TaskPhase::Completed;
1523                                            Poll::CompletedErr(e)
1524                                        }
1525                                    },
1526                                    // Handle taken by a concurrent CANCEL/AWAIT
1527                                    // teardown; the barrier below rendezvouses.
1528                                    None => Poll::Pending,
1529                                }
1530                            }
1531                            TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1532                        }
1533                    };
1534                    match poll {
1535                        Poll::Pending => {}
1536                        Poll::CompletedOk => {
1537                            entry.finish_teardown();
1538                        }
1539                        Poll::CompletedErr(e) => {
1540                            entry.finish_teardown();
1541                            if failed_status.is_none() {
1542                                failed_status = Some(e);
1543                            }
1544                            break;
1545                        }
1546                    }
1547                }
1548            }
1549
1550            // 3. Fail-fast teardown (named entries are root-owned; task
1551            // threads only tear down their own anonymous children).
1552            // Handles are taken under short locks and killed outside every
1553            // lock; tombstones are retained.
1554            if let Some(err) = failed_status {
1555                for survivor in state.bg_children.iter_mut() {
1556                    if in_scope(survivor.task_id) {
1557                        let _ = survivor.handle.kill();
1558                    }
1559                }
1560                if reap_named {
1561                    let entries: Vec<(u64, Arc<TaskEntry>)> = {
1562                        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1563                        named
1564                            .iter()
1565                            .map(|(id, entry)| (*id, Arc::clone(entry)))
1566                            .collect()
1567                    };
1568                    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1569                    for (id, entry) in &entries {
1570                        if !in_scope(*id) {
1571                            continue;
1572                        }
1573                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1574                        match guard.phase {
1575                            TaskPhase::Running | TaskPhase::Awaiting => {
1576                                guard.phase = TaskPhase::Cancelled;
1577                                if let Some(handle) = guard.handle.take() {
1578                                    to_kill.push((Arc::clone(entry), handle));
1579                                }
1580                            }
1581                            TaskPhase::Cancelled | TaskPhase::Completed => {}
1582                        }
1583                    }
1584                    for (entry, mut handle) in to_kill {
1585                        let _ = handle.kill();
1586                        entry.finish_teardown();
1587                    }
1588                }
1589                // Drop only the scope's own handles: outer work keeps
1590                // running past a scope teardown, and the pipeline-top
1591                // teardown still owns it.
1592                state.bg_children.retain(|c| !in_scope(c.task_id));
1593                return Err(err);
1594            }
1595
1596            let bg_empty = !state.bg_children.iter().any(|c| in_scope(c.task_id));
1597            if bg_empty && !named_pending(state) {
1598                return Ok(Flow::Done);
1599            }
1600            // Rendezvous: a concurrent CANCEL/AWAIT on another thread may
1601            // own teardown of a Cancelled-but-unreaped entry. Wait for it
1602            // instead of spinning, so this thread never outruns the join.
1603            if reap_named {
1604                let unreaped: Vec<Arc<TaskEntry>> = {
1605                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1606                    named
1607                        .iter()
1608                        .filter(|(id, entry)| {
1609                            if !in_scope(**id) {
1610                                return false;
1611                            }
1612                            let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1613                            matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1614                        })
1615                        .map(|(_, entry)| Arc::clone(entry))
1616                        .collect()
1617                };
1618                for entry in &unreaped {
1619                    entry.wait_reaped();
1620                }
1621            }
1622            std::thread::sleep(std::time::Duration::from_millis(10));
1623        }
1624    }
1625
1626    Ok(Flow::Done)
1627}
1628
1629fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1630    for _ in 0..count {
1631        state.pop_scope()?;
1632    }
1633    Ok(())
1634}
1635
1636/// Execute a `REMOTE` body locally inside a fresh lexical scope: the
1637/// guest-mode path, where the shipped text keeps its `REMOTE` wrapper and
1638/// the session already fulfilled the transfer declarations. Scope,
1639/// pipes, and filesystem effects behave exactly like any local block;
1640/// control-flow signals crossing the block edge become step-numbered
1641/// errors, mirroring the pipeline-top mapping.
1642#[allow(clippy::too_many_arguments)]
1643pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1644    state: &mut ExecState<P>,
1645    process: &mut P,
1646    steps: &[Step],
1647    stdin: CommandStdin,
1648    expose_stdin: bool,
1649    out: Option<StreamHandle>,
1650    err: Option<StreamHandle>,
1651    out_pipe: Option<Arc<PipeInner>>,
1652    stdin_pipe: Option<Arc<PipeInner>>,
1653) -> Result<()> {
1654    let flow = execute_scoped_steps(
1655        state,
1656        process,
1657        steps,
1658        stdin,
1659        expose_stdin,
1660        out,
1661        err,
1662        out_pipe,
1663        stdin_pipe,
1664        true,
1665    )?;
1666    match flow {
1667        Flow::Done => Ok(()),
1668        Flow::Break { idx } => {
1669            bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1670        }
1671        Flow::Continue { idx } => {
1672            bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1673        }
1674        Flow::Return { idx, .. } => {
1675            bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1676        }
1677    }
1678}
1679
1680/// Execute steps inside a fresh lexical scope (IF branches, TIMEOUT bodies).
1681/// Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE); only pipes and
1682/// filesystem effects cross. Restores even when the body fails. Propagates
1683/// Flow signals (BREAK/CONTINUE/RETURN) to the caller after restoring.
1684#[allow(clippy::too_many_arguments)]
1685pub(super) fn execute_scoped_steps<P: ProcessManager>(
1686    state: &mut ExecState<P>,
1687    process: &mut P,
1688    steps: &[Step],
1689    stdin: CommandStdin,
1690    expose_stdin: bool,
1691    out: Option<StreamHandle>,
1692    err: Option<StreamHandle>,
1693    out_pipe: Option<Arc<PipeInner>>,
1694    stdin_pipe: Option<Arc<PipeInner>>,
1695    wait_at_end: bool,
1696) -> Result<Flow> {
1697    state.push_scope();
1698    let res = execute_steps(
1699        state,
1700        process,
1701        steps,
1702        stdin,
1703        expose_stdin,
1704        out,
1705        err,
1706        out_pipe,
1707        stdin_pipe,
1708        wait_at_end,
1709    );
1710    // Restore the scope even when the body failed, but never let an
1711    // unwinding failure mask the body's own error.
1712    let pop_res = state.pop_scope();
1713    match (res, pop_res) {
1714        (Ok(flow), Ok(())) => Ok(flow),
1715        (Err(e), _) => Err(e),
1716        (Ok(_), Err(e)) => Err(e),
1717    }
1718}
1719
1720/// Dispatch one compound step (loops, functions, scoped wrappers) through
1721/// the Flow path. Called with the caller's generation/idx so assertion
1722/// windows and error attribution match the leaf pipeline.
1723fn dispatch_flow_step<P: ProcessManager>(
1724    cmd: &StepKind,
1725    cx: &mut StepCtx<'_, P>,
1726    generation: usize,
1727    idx: usize,
1728) -> Result<Flow> {
1729    match cmd {
1730        StepKind::FuncDef { name, params, body } => {
1731            handlers::define_func(cx, name, params, body)?;
1732            Ok(Flow::Done)
1733        }
1734        StepKind::Call { name, args } => {
1735            let _ = handlers::call_func_value(cx, idx, name, args)?;
1736            Ok(Flow::Done)
1737        }
1738        StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1739        StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
1740        StepKind::Break => Ok(Flow::Break { idx }),
1741        StepKind::Continue => Ok(Flow::Continue { idx }),
1742        StepKind::For {
1743            key_var,
1744            key_type,
1745            var,
1746            var_type,
1747            in_expr,
1748            body,
1749        } => handlers::for_loop(
1750            cx,
1751            key_var.as_deref(),
1752            key_type.clone(),
1753            var,
1754            var_type.clone(),
1755            in_expr,
1756            body,
1757        ),
1758        StepKind::If {
1759            cond,
1760            then_body,
1761            else_ifs,
1762            else_body,
1763        } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1764        StepKind::Timeout { duration, body } => {
1765            let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1766            handlers::timeout(cx, idx, &duration, body)
1767        }
1768        StepKind::Isolated { body } => handlers::isolated(cx, body),
1769        StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1770        StepKind::AssignCapture {
1771            var,
1772            decl_type,
1773            cmd,
1774        } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1775        _ => {
1776            unreachable!("dispatch_flow_step handles only compound steps")
1777        }
1778    }
1779}