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