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