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