Skip to main content

oxdock_core/exec/
steps.rs

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