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