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