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 and no
149                // anyhow fallback: `exit_code_of_diag` reads the code.
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)
879        }
880        StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
881        StepKind::Workdir(arg) => {
882            let path = super::args::resolve_arg(arg, &mut cx)?;
883            handlers::workdir(&mut cx, &path)
884        }
885        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
886        StepKind::RemoteBlock {
887            target,
888            vars,
889            env,
890            body,
891        } => super::remote::run_remote_block(&mut cx, target, vars, env, body),
892        StepKind::Env { key, value } => {
893            let resolved = super::args::resolve_arg(value, &mut cx)?;
894            handlers::env(&mut cx, key, &resolved)
895        }
896        StepKind::InheritEnv { keys } => {
897            handlers::inherit_env(&mut cx, keys)?;
898            sync_iteration_assert_needles(
899                cx.state,
900                &[Step {
901                    guard: None,
902                    kind: cmd.clone(),
903                    scope_enter: 0,
904                    scope_exit: 0,
905                    line: 0,
906                    col: 0,
907                }],
908                generation,
909            )?;
910            Ok(())
911        }
912        StepKind::IsolatedInheritEnv { keys } => {
913            handlers::isolated_inherit_env(&mut cx, keys)?;
914            Ok(())
915        }
916        StepKind::Copy {
917            from_workspace,
918            from_host,
919            to_host,
920            from,
921            to,
922        } => {
923            if *from_host || *to_host {
924                super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
925            } else {
926                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
927                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
928                handlers::copy(
929                    &mut cx,
930                    from_workspace.clone(),
931                    &from_resolved,
932                    &to_resolved,
933                )
934            }
935        }
936        StepKind::CopyGit {
937            rev,
938            from,
939            to,
940            include_dirty,
941        } => {
942            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
943            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
944            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
945            handlers::copy_git(
946                &mut cx,
947                &rev_resolved,
948                &from_resolved,
949                &to_resolved,
950                *include_dirty,
951            )
952        }
953        StepKind::Archive { src, dst, raw } => {
954            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
955            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
956            handlers::archive(&mut cx, &src_resolved, &dst_resolved, *raw)
957        }
958        StepKind::Unarchive {
959            src,
960            dst,
961            max_bytes,
962        } => {
963            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
964            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
965            let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
966            handlers::unarchive(
967                &mut cx,
968                &src_resolved,
969                &dst_resolved,
970                cap_resolved.as_deref(),
971            )
972        }
973        StepKind::Symlink {
974            from_workspace,
975            from,
976            to,
977        } => {
978            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
979            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
980            handlers::symlink(
981                &mut cx,
982                from_workspace.clone(),
983                &from_resolved,
984                &to_resolved,
985            )
986        }
987        StepKind::Mkdir(arg) => {
988            let path = super::args::resolve_arg(arg, &mut cx)?;
989            handlers::mkdir(&mut cx, &path)
990        }
991        StepKind::Install { from, to } => {
992            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
993            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
994            handlers::install(&mut cx, &from_resolved, &to_resolved)
995        }
996        StepKind::SetExecutable { path } => {
997            let resolved = super::args::resolve_arg(path, &mut cx)?;
998            handlers::set_executable(&mut cx, &resolved)
999        }
1000        StepKind::Ls(arg) => {
1001            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1002            handlers::ls(&mut cx, &resolved)
1003        }
1004        StepKind::Read(arg) => {
1005            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1006            handlers::read(&mut cx, &resolved)
1007        }
1008        StepKind::ReadLine { var } => handlers::read_line(&mut cx, var),
1009        StepKind::Prompt {
1010            var,
1011            message,
1012            default,
1013        } => {
1014            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1015            let default_resolved = match default {
1016                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1017                None => None,
1018            };
1019            handlers::prompt(&mut cx, var, &message_resolved, default_resolved.as_deref())
1020        }
1021        StepKind::ListAppend { list, item } => {
1022            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1023            handlers::push_into(&mut cx, list, value)
1024        }
1025        StepKind::Write { path, contents } => {
1026            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1027            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
1028            handlers::write(&mut cx, &path_resolved, contents_resolved.as_deref())
1029        }
1030        StepKind::Append { path, contents } => {
1031            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1032            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
1033            handlers::append(&mut cx, &path_resolved, contents_resolved.as_deref())
1034        }
1035        StepKind::AppendLine { path, contents } => {
1036            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1037            let contents_resolved = super::args::resolve_arg(contents, &mut cx)?;
1038            handlers::append_line(&mut cx, &path_resolved, &contents_resolved)
1039        }
1040        StepKind::Remove { path, recursive } => {
1041            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1042            handlers::remove(&mut cx, &path_resolved, *recursive)
1043        }
1044        StepKind::Expand { path, overrides } => {
1045            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1046            let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
1047            handlers::replace(&mut cx, &path_resolved, &overrides_resolved)
1048        }
1049        StepKind::AssertEq {
1050            hash,
1051            actual,
1052            expected,
1053        }
1054        | StepKind::AssertNe {
1055            hash,
1056            actual,
1057            expected,
1058        } => {
1059            let (verb, expect_equal) = match cmd {
1060                StepKind::AssertEq { .. } => (Command::AssertEq.as_str(), true),
1061                _ => (Command::AssertNe.as_str(), false),
1062            };
1063            let target = resolve_assert_target(actual, &mut cx)?;
1064            let expected_resolved = match expected {
1065                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1066                None => None,
1067            };
1068            handlers::assert_equality(
1069                &mut cx,
1070                generation,
1071                verb,
1072                expect_equal,
1073                hash,
1074                &target,
1075                expected_resolved.as_ref(),
1076            )
1077        }
1078        StepKind::AssertContains { haystack, needle } => {
1079            let target = resolve_assert_target(haystack, &mut cx)?;
1080            handlers::assert_contains(&mut cx, generation, idx, &target, needle)
1081        }
1082        StepKind::WithIoBlock { .. } => Err(step_diag::eval_with_io_unexpanded()),
1083        StepKind::Exit(code) => {
1084            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1085            handlers::exit(&mut cx, code)
1086        }
1087        StepKind::Bind {
1088            var,
1089            decl_type,
1090            is_const,
1091            rhs: oxdock_parser::BindRhs::Expr(expr),
1092        } => handlers::assign(&mut cx, var, decl_type.clone(), expr, *is_const),
1093        StepKind::Bind {
1094            var,
1095            decl_type,
1096            is_const,
1097            rhs: oxdock_parser::BindRhs::Async(body),
1098        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx, *is_const),
1099        StepKind::Bind {
1100            var,
1101            decl_type,
1102            is_const,
1103            rhs: oxdock_parser::BindRhs::Await { task_var, .. },
1104        } => handlers::dispatch_await_capture(var, decl_type.clone(), task_var, &mut cx, *is_const),
1105        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1106        StepKind::Await { var, .. } => handlers::dispatch_await(var, &mut cx),
1107        StepKind::Cancel { var, .. } => handlers::dispatch_cancel(var, &mut cx),
1108        StepKind::Sleep { duration } => {
1109            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1110            handlers::sleep(&mut cx, &duration)
1111        }
1112        StepKind::TypeAlias { .. } => {
1113            // Static declaration: collected before the run and
1114            // resolved at first coercion. Nothing to execute.
1115            Ok(())
1116        }
1117        StepKind::FuncDef { .. }
1118        | StepKind::Call { .. }
1119        | StepKind::Return { .. }
1120        | StepKind::ImportFile { .. }
1121        | StepKind::ImportFuncs { .. }
1122        | StepKind::While { .. }
1123        | StepKind::Break
1124        | StepKind::Continue
1125        | StepKind::For { .. }
1126        | StepKind::If { .. }
1127        | StepKind::Switch { .. }
1128        | StepKind::Timeout { .. }
1129        | StepKind::Fail { .. }
1130        | StepKind::Isolated { .. }
1131        | StepKind::WithIo { .. }
1132        | StepKind::Bind {
1133            rhs: oxdock_parser::BindRhs::Capture(_),
1134            ..
1135        } => {
1136            unreachable!("compound steps dispatch before this match")
1137        }
1138    }?;
1139    Ok(Flow::Done)
1140}
1141
1142#[allow(clippy::too_many_arguments)]
1143/// Position context wrapping a failing step's error: `step N` plus
1144/// `line L` / `col C` when the step carries coordinates (parsed
1145/// scripts do; hand-built steps keep the historical bare rendering).
1146/// Applied once per dispatch level, so nested bodies chain outer and
1147/// inner positions like a call path. The text prefix stays
1148/// byte-identical; when the step carries coordinates the position
1149/// also attaches natively via `with_span` on the reclaimed
1150/// diagnostic (innermost wins: span-less only, so outer dispatch
1151/// levels never clobber the inner span).
1152fn step_error(step: &Step, idx: usize, mut err: Diagnostic) -> Diagnostic {
1153    let mut loc = format!("step {}", idx + 1);
1154    if step.line > 0 {
1155        loc.push_str(&format!(", line {}", step.line));
1156        if step.col > 0 {
1157            loc.push_str(&format!(", col {}", step.col));
1158        }
1159    }
1160    if step.line > 0 {
1161        let span = if step.col > 0 {
1162            Span::line_col(step.line, step.col)
1163        } else {
1164            Span::line_only(step.line)
1165        };
1166        // Innermost wins: outer dispatch levels never clobber the
1167        // inner span, so the position stays at the failure site.
1168        if err.span().is_none() {
1169            err = err.with_span(span);
1170        }
1171    }
1172    // Native frame storage (outermost first via prepend): renders
1173    // byte-identical to the historic anyhow `.context(loc)` chain.
1174    err.with_contexts(vec![loc])
1175}
1176
1177/// Bundled inputs for [`execute_steps_inner`]. One struct parameter
1178/// keeps the function under the argument-count lint without an
1179/// override; call sites construct it from the same values.
1180struct InnerArgs<'a, P: ProcessManager> {
1181    state: &'a mut ExecState<P>,
1182    process: &'a mut P,
1183    generation: usize,
1184    steps: &'a [Step],
1185    stdin: CommandStdin,
1186    expose_stdin: bool,
1187    out: Option<StreamHandle>,
1188    err: Option<StreamHandle>,
1189    out_pipe: Option<Arc<PipeInner>>,
1190    stdin_pipe: Option<Arc<PipeInner>>,
1191    wait_at_end: bool,
1192}
1193
1194fn execute_steps_inner<P: ProcessManager>(args: InnerArgs<'_, P>) -> DiagnosticResult<Flow> {
1195    let InnerArgs {
1196        state,
1197        process,
1198        generation,
1199        steps,
1200        stdin,
1201        expose_stdin,
1202        out,
1203        err,
1204        out_pipe,
1205        stdin_pipe,
1206        wait_at_end,
1207    } = args;
1208    // Pre-register assertion windows for this generation
1209    pre_register_assertions(state, steps, generation)?;
1210
1211    for (idx, step) in steps.iter().enumerate() {
1212        // Check for cancellation before each step
1213        if state.cancel_token.load(Ordering::SeqCst) {
1214            return Err(step_diag::eval_async_cancelled());
1215        }
1216        if step.scope_enter > 0 {
1217            for _ in 0..step.scope_enter {
1218                state.push_scope();
1219            }
1220        }
1221
1222        let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1223        // One position wrap per iteration: the closure funnels every
1224        // error path (including `?` inside match arms, which would
1225        // otherwise return past a post-hoc wrap) through `step_error`.
1226        let flow_result: DiagnosticResult<Flow> = (|| {
1227            if !should_run {
1228                Ok(Flow::Done)
1229            } else {
1230                // Single dispatch table: compound steps run the Flow path;
1231                // every other variant runs the shared leaf pipeline in
1232                // `execute_single_step_with_generation`, so the two loops
1233                // can never drift.
1234                let flow_result: DiagnosticResult<Flow> = match &step.kind {
1235                    StepKind::FuncDef { .. }
1236                    | StepKind::Call { .. }
1237                    | StepKind::Return { .. }
1238                    | StepKind::ImportFile { .. }
1239                    | StepKind::ImportFuncs { .. }
1240                    | StepKind::While { .. }
1241                    | StepKind::Break
1242                    | StepKind::Continue
1243                    | StepKind::For { .. }
1244                    | StepKind::If { .. }
1245                    | StepKind::Switch { .. }
1246                    | StepKind::Timeout { .. }
1247                    | StepKind::Fail { .. }
1248                    | StepKind::Isolated { .. }
1249                    | StepKind::WithIo { .. }
1250                    | StepKind::Bind {
1251                        rhs: oxdock_parser::BindRhs::Capture(_),
1252                        ..
1253                    } => {
1254                        let mut cx = StepCtx {
1255                            state,
1256                            process,
1257                            stdin: stdin.clone(),
1258                            expose_stdin,
1259                            out: out.clone(),
1260                            err: err.clone(),
1261                            out_pipe: out_pipe.clone(),
1262                            stdin_pipe: stdin_pipe.clone(),
1263                            tty: None,
1264                        };
1265                        dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1266                    }
1267                    _ => {
1268                        let flow = execute_single_step_with_generation(
1269                            state,
1270                            process,
1271                            &step.kind,
1272                            generation,
1273                            idx,
1274                            stdin.clone(),
1275                            expose_stdin,
1276                            out.clone(),
1277                            err.clone(),
1278                            out_pipe.clone(),
1279                            stdin_pipe.clone(),
1280                            None,
1281                        )?;
1282                        if matches!(
1283                            &step.kind,
1284                            StepKind::Env { .. }
1285                                | StepKind::InheritEnv { .. }
1286                                | StepKind::IsolatedInheritEnv { .. }
1287                        ) {
1288                            sync_iteration_assert_needles(state, steps, generation)?;
1289                        }
1290                        Ok(flow)
1291                    }
1292                };
1293                flow_result
1294            }
1295        })()
1296        .map_err(|err| step_error(step, idx, err));
1297
1298        let restore_result = restore_scopes(state, step.scope_exit);
1299        // Keeper expiry: drop spawn-time pins whose final producer step
1300        // just completed, so later consumer steps in the same task observe
1301        // EOF. Gated on slice identity, so nested bodies executing through
1302        // this same loop never discharge the worker's top-level map.
1303        let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1304            expiry.expire_step(steps, idx)
1305        } else {
1306            false
1307        };
1308        if expiry_drained {
1309            state.keeper_expiry = None;
1310        }
1311        let flow = flow_result?;
1312        restore_result?;
1313        match flow {
1314            Flow::Done => {}
1315            Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1316                return Ok(flow);
1317            }
1318        }
1319    }
1320
1321    // Poll anonymous background handles at end-of-pipeline. The shared
1322    // named_tasks entries are reaped only by the root context: task threads
1323    // must never block on sibling tasks, which may depend on this thread
1324    // via AWAIT (three-way deadlock). Un-awaited named tasks are still
1325    // reaped by the root end-poll, and explicitly awaited tasks join via
1326    // AWAIT. Entries are retained as Cancelled/Completed tombstones so
1327    // later AWAIT/CANCEL report precise errors.
1328    let reap_named = !state.inside_async;
1329    // Scope floor for `TIMEOUT`: only tasks at or above the floor join
1330    // at scope end. Older tasks keep running past the scope instead of
1331    // holding it open; `None` (pipeline top, every other scope) joins
1332    // everything, exactly as before.
1333    let floor = state.reap_floor;
1334    let in_scope = |id: u64| floor.map(|f| id >= f).unwrap_or(true);
1335    let has_bg = state.bg_children.iter().any(|c| in_scope(c.task_id));
1336    let named_pending = |state: &ExecState<P>| {
1337        reap_named
1338            && state
1339                .named_tasks
1340                .lock()
1341                .unwrap_or_else(|e| e.into_inner())
1342                .iter()
1343                .any(|(id, entry)| {
1344                    in_scope(*id) && !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped
1345                })
1346    };
1347    let has_named = named_pending(state);
1348    if wait_at_end && (has_bg || has_named) {
1349        loop {
1350            let mut failed_status: Option<Diagnostic> = None;
1351
1352            // Cancellation (deadline watcher or parent teardown) must break
1353            // the poll loop: without this, a stuck background handle would
1354            // hang the reaper forever. Flows into the shared fail-fast
1355            // teardown below.
1356            if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1357                failed_status = Some(step_diag::eval_async_cancelled());
1358            }
1359
1360            // 1. Poll anonymous background handles. Handles below the
1361            // scope floor belong to outer work: never poll them here, or
1362            // the scope would wait out tasks it did not spawn.
1363            let mut i = 0;
1364            while i < state.bg_children.len() {
1365                if !in_scope(state.bg_children[i].task_id) {
1366                    i += 1;
1367                    continue;
1368                }
1369                match state.bg_children[i].handle.try_wait() {
1370                    Ok(Some(status)) => {
1371                        if !status.success() && failed_status.is_none() {
1372                            failed_status = Some(step_diag::eval_async_exit_status(None, &status));
1373                            break;
1374                        }
1375                        state.bg_children.swap_remove(i);
1376                    }
1377                    Ok(None) => {
1378                        i += 1;
1379                    }
1380                    Err(e) => {
1381                        if failed_status.is_none() {
1382                            failed_status = Some(e);
1383                        }
1384                        break;
1385                    }
1386                }
1387            }
1388
1389            // 2. Poll un-awaited named tasks (root context only). Each entry
1390            // is probed under a short entry lock; terminal entries are
1391            // retained as tombstones, never removed.
1392            if failed_status.is_none() && reap_named {
1393                let entries: Vec<(u64, Arc<TaskEntry>)> = {
1394                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1395                    named
1396                        .iter()
1397                        .map(|(id, entry)| (*id, Arc::clone(entry)))
1398                        .collect()
1399                };
1400                for (id, entry) in &entries {
1401                    if !in_scope(*id) {
1402                        continue;
1403                    }
1404                    enum Poll {
1405                        Pending,
1406                        CompletedOk,
1407                        CompletedErr(Diagnostic),
1408                    }
1409                    let poll = {
1410                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1411                        match guard.phase {
1412                            TaskPhase::Running | TaskPhase::Awaiting => {
1413                                match guard.handle.as_mut() {
1414                                    Some(handle) => match handle.try_wait() {
1415                                        Ok(Some(status)) => {
1416                                            let _ = guard.handle.take();
1417                                            guard.phase = TaskPhase::Completed;
1418                                            if status.success() {
1419                                                Poll::CompletedOk
1420                                            } else {
1421                                                Poll::CompletedErr(
1422                                                    step_diag::eval_async_exit_status(
1423                                                        Some(*id),
1424                                                        &status,
1425                                                    ),
1426                                                )
1427                                            }
1428                                        }
1429                                        Ok(None) => Poll::Pending,
1430                                        Err(e) => {
1431                                            let _ = guard.handle.take();
1432                                            guard.phase = TaskPhase::Completed;
1433                                            Poll::CompletedErr(e)
1434                                        }
1435                                    },
1436                                    // Handle taken by a concurrent CANCEL/AWAIT
1437                                    // teardown; the barrier below rendezvouses.
1438                                    None => Poll::Pending,
1439                                }
1440                            }
1441                            TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1442                        }
1443                    };
1444                    match poll {
1445                        Poll::Pending => {}
1446                        Poll::CompletedOk => {
1447                            entry.finish_teardown();
1448                        }
1449                        Poll::CompletedErr(e) => {
1450                            entry.finish_teardown();
1451                            if failed_status.is_none() {
1452                                failed_status = Some(e);
1453                            }
1454                            break;
1455                        }
1456                    }
1457                }
1458            }
1459
1460            // 3. Fail-fast teardown (named entries are root-owned; task
1461            // threads only tear down their own anonymous children).
1462            // Handles are taken under short locks and killed outside every
1463            // lock; tombstones are retained.
1464            if let Some(err) = failed_status {
1465                for survivor in state.bg_children.iter_mut() {
1466                    if in_scope(survivor.task_id) {
1467                        let _ = survivor.handle.kill();
1468                    }
1469                }
1470                if reap_named {
1471                    let entries: Vec<(u64, Arc<TaskEntry>)> = {
1472                        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1473                        named
1474                            .iter()
1475                            .map(|(id, entry)| (*id, Arc::clone(entry)))
1476                            .collect()
1477                    };
1478                    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1479                    for (id, entry) in &entries {
1480                        if !in_scope(*id) {
1481                            continue;
1482                        }
1483                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1484                        match guard.phase {
1485                            TaskPhase::Running | TaskPhase::Awaiting => {
1486                                guard.phase = TaskPhase::Cancelled;
1487                                if let Some(handle) = guard.handle.take() {
1488                                    to_kill.push((Arc::clone(entry), handle));
1489                                }
1490                            }
1491                            TaskPhase::Cancelled | TaskPhase::Completed => {}
1492                        }
1493                    }
1494                    for (entry, mut handle) in to_kill {
1495                        let _ = handle.kill();
1496                        entry.finish_teardown();
1497                    }
1498                }
1499                // Drop only the scope's own handles: outer work keeps
1500                // running past a scope teardown, and the pipeline-top
1501                // teardown still owns it.
1502                state.bg_children.retain(|c| !in_scope(c.task_id));
1503                return Err(err);
1504            }
1505
1506            let bg_empty = !state.bg_children.iter().any(|c| in_scope(c.task_id));
1507            if bg_empty && !named_pending(state) {
1508                return Ok(Flow::Done);
1509            }
1510            // Rendezvous: a concurrent CANCEL/AWAIT on another thread may
1511            // own teardown of a Cancelled-but-unreaped entry. Wait for it
1512            // instead of spinning, so this thread never outruns the join.
1513            if reap_named {
1514                let unreaped: Vec<Arc<TaskEntry>> = {
1515                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1516                    named
1517                        .iter()
1518                        .filter(|(id, entry)| {
1519                            if !in_scope(**id) {
1520                                return false;
1521                            }
1522                            let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1523                            matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1524                        })
1525                        .map(|(_, entry)| Arc::clone(entry))
1526                        .collect()
1527                };
1528                for entry in &unreaped {
1529                    entry.wait_reaped();
1530                }
1531            }
1532            std::thread::sleep(std::time::Duration::from_millis(10));
1533        }
1534    }
1535
1536    Ok(Flow::Done)
1537}
1538
1539fn restore_scopes<P: ProcessManager>(
1540    state: &mut ExecState<P>,
1541    count: usize,
1542) -> DiagnosticResult<()> {
1543    for _ in 0..count {
1544        state.pop_scope()?;
1545    }
1546    Ok(())
1547}
1548
1549/// Execute a `REMOTE` body locally inside a fresh lexical scope: the
1550/// guest-mode path, where the shipped text keeps its `REMOTE` wrapper and
1551/// the session already fulfilled the transfer declarations. Scope,
1552/// pipes, and filesystem effects behave exactly like any local block;
1553/// control-flow signals crossing the block edge become step-numbered
1554/// errors, mirroring the pipeline-top mapping.
1555#[allow(clippy::too_many_arguments)]
1556pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1557    state: &mut ExecState<P>,
1558    process: &mut P,
1559    steps: &[Step],
1560    stdin: CommandStdin,
1561    expose_stdin: bool,
1562    out: Option<StreamHandle>,
1563    err: Option<StreamHandle>,
1564    out_pipe: Option<Arc<PipeInner>>,
1565    stdin_pipe: Option<Arc<PipeInner>>,
1566) -> DiagnosticResult<()> {
1567    let flow = execute_scoped_steps(
1568        state,
1569        process,
1570        steps,
1571        stdin,
1572        expose_stdin,
1573        out,
1574        err,
1575        out_pipe,
1576        stdin_pipe,
1577        true,
1578    )?;
1579    match flow {
1580        Flow::Done => Ok(()),
1581        Flow::Break { idx } => Err(step_diag::eval_flow_crosses_remote(idx + 1, KEYWORD_BREAK)),
1582        Flow::Continue { idx } => Err(step_diag::eval_flow_crosses_remote(
1583            idx + 1,
1584            KEYWORD_CONTINUE,
1585        )),
1586        Flow::Return { idx, .. } => {
1587            Err(step_diag::eval_flow_crosses_remote(idx + 1, KEYWORD_RETURN))
1588        }
1589    }
1590}
1591
1592/// Execute steps inside a fresh lexical scope (IF branches, TIMEOUT bodies).
1593/// Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE); only pipes and
1594/// filesystem effects cross. Restores even when the body fails. Propagates
1595/// Flow signals (BREAK/CONTINUE/RETURN) to the caller after restoring.
1596#[allow(clippy::too_many_arguments)]
1597pub(super) fn execute_scoped_steps<P: ProcessManager>(
1598    state: &mut ExecState<P>,
1599    process: &mut P,
1600    steps: &[Step],
1601    stdin: CommandStdin,
1602    expose_stdin: bool,
1603    out: Option<StreamHandle>,
1604    err: Option<StreamHandle>,
1605    out_pipe: Option<Arc<PipeInner>>,
1606    stdin_pipe: Option<Arc<PipeInner>>,
1607    wait_at_end: bool,
1608) -> DiagnosticResult<Flow> {
1609    state.push_scope();
1610    let res = execute_steps(
1611        state,
1612        process,
1613        steps,
1614        stdin,
1615        expose_stdin,
1616        out,
1617        err,
1618        out_pipe,
1619        stdin_pipe,
1620        wait_at_end,
1621    );
1622    // Restore the scope even when the body failed, but never let an
1623    // unwinding failure mask the body's own error.
1624    let pop_res = state.pop_scope();
1625    match (res, pop_res) {
1626        (Ok(flow), Ok(())) => Ok(flow),
1627        (Err(e), _) => Err(e),
1628        (Ok(_), Err(e)) => Err(e),
1629    }
1630}
1631
1632/// Dispatch one compound step (loops, functions, scoped wrappers) through
1633/// the Flow path. Called with the caller's generation/idx so assertion
1634/// windows and error attribution match the leaf pipeline.
1635fn dispatch_flow_step<P: ProcessManager>(
1636    cmd: &StepKind,
1637    cx: &mut StepCtx<'_, P>,
1638    generation: usize,
1639    idx: usize,
1640) -> DiagnosticResult<Flow> {
1641    match cmd {
1642        StepKind::FuncDef {
1643            name,
1644            params,
1645            return_type,
1646            is_async,
1647            body,
1648            ..
1649        } => {
1650            handlers::define_func(cx, name, params, return_type, *is_async, body)?;
1651            Ok(Flow::Done)
1652        }
1653        StepKind::Call { name, args } => {
1654            let _ = handlers::call_func_value(cx, name, args)?;
1655            Ok(Flow::Done)
1656        }
1657        StepKind::Return { expr, .. } => handlers::handle_return(cx, idx, expr),
1658        StepKind::ImportFile { path, alias } => {
1659            let _ = super::import::import_file(cx, path, alias)?;
1660            Ok(Flow::Done)
1661        }
1662        StepKind::ImportFuncs {
1663            path,
1664            alias,
1665            func_names,
1666            type_names,
1667        } => {
1668            super::import::import_funcs(cx, path, alias.as_deref(), func_names, type_names)?;
1669            Ok(Flow::Done)
1670        }
1671        StepKind::While { cond, body } => handlers::while_loop(cx, cond, body),
1672        StepKind::Break => Ok(Flow::Break { idx }),
1673        StepKind::Continue => Ok(Flow::Continue { idx }),
1674        StepKind::For {
1675            key_var,
1676            key_type,
1677            var,
1678            var_type,
1679            in_expr,
1680            body,
1681        } => handlers::for_loop(
1682            cx,
1683            key_var.as_deref(),
1684            key_type.clone(),
1685            var,
1686            var_type.clone(),
1687            in_expr,
1688            body,
1689        ),
1690        StepKind::If {
1691            cond,
1692            then_body,
1693            else_ifs,
1694            else_body,
1695        } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1696        StepKind::Switch {
1697            discriminant,
1698            cases,
1699            default_body,
1700        } => handlers::switch_run(cx, discriminant, cases, default_body),
1701        StepKind::Timeout { duration, body } => {
1702            let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1703            handlers::timeout(cx, &duration, body)
1704        }
1705        StepKind::Fail {
1706            code,
1707            message,
1708            body,
1709        } => handlers::fail(cx, code, message, body),
1710        StepKind::Isolated { body } => handlers::isolated(cx, body),
1711        StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1712        StepKind::Bind {
1713            var,
1714            decl_type,
1715            is_const,
1716            rhs: oxdock_parser::BindRhs::Capture(cmd),
1717        } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd, *is_const),
1718        _ => {
1719            unreachable!("dispatch_flow_step handles only compound steps")
1720        }
1721    }
1722}
1723
1724#[cfg(test)]
1725mod thread_handle_tests {
1726    use super::super::exit::exit_code_of_diag;
1727    use super::*;
1728
1729    fn bare_handle(
1730        join: Option<std::thread::JoinHandle<DiagnosticResult<()>>>,
1731    ) -> ThreadJoinHandle {
1732        ThreadJoinHandle {
1733            join,
1734            cancel_token: Arc::new(AtomicBool::new(false)),
1735            cancel_hub: Arc::new(oxdock_process::CancelHub::new()),
1736            active_process: Arc::new(Mutex::new(None)),
1737            worker: Arc::new(Mutex::new(None)),
1738            thread_error: None,
1739            thread_context: Vec::new(),
1740            thread_exit_code: None,
1741        }
1742    }
1743
1744    #[test]
1745    fn panic_payload_reports_thread_panicked_key() {
1746        let join = std::thread::spawn(|| -> DiagnosticResult<()> {
1747            panic!("boom-payload");
1748        });
1749        let mut handle = bare_handle(Some(join));
1750        let diag = handle.wait().expect_err("panic must surface");
1751        assert_eq!(diag.key(), "dsl.eval.async_thread_panicked");
1752        assert!(diag.message().contains("boom-payload"));
1753    }
1754
1755    #[test]
1756    fn wrapped_diagnostic_keeps_key_and_outer_context() {
1757        let leaf = step_diag::eval_async_cancelled();
1758        let join = std::thread::spawn(|| -> DiagnosticResult<()> {
1759            Err(leaf.with_contexts(vec!["step 1".to_string(), "step 2".to_string()]))
1760        });
1761        let mut handle = bare_handle(Some(join));
1762        let diag = handle.wait().expect_err("wrapped failure must surface");
1763        assert_eq!(diag.key(), "dsl.eval.async_cancelled");
1764        assert_eq!(
1765            diag.contexts(),
1766            &["step 1".to_string(), "step 2".to_string()],
1767            "each outer frame replays natively in order: {diag:#}"
1768        );
1769        assert_eq!(diag.to_string(), "step 1: step 2: ASYNC task cancelled");
1770    }
1771
1772    #[test]
1773    fn sourceless_diagnostic_keeps_key_and_exit_code() {
1774        let mut handle = bare_handle(None);
1775        handle.thread_error = Some(step_diag::eval_async_cancelled());
1776        handle.thread_exit_code = Some(7);
1777        let diag = handle.reemit_error();
1778        assert_eq!(exit_code_of_diag(&diag), Some(7));
1779        assert_eq!(diag.key(), "dsl.eval.async_cancelled");
1780    }
1781
1782    #[test]
1783    fn sourced_diagnostic_keeps_key_source_and_exit_code() {
1784        let sourced = step_diag::eval_async_cancelled().with_source(Arc::new(std::io::Error::new(
1785            std::io::ErrorKind::NotFound,
1786            "gone",
1787        )));
1788        assert!(
1789            std::error::Error::source(&sourced).is_some(),
1790            "fixture must carry a source to cover the chained branch"
1791        );
1792        let mut handle = bare_handle(None);
1793        handle.thread_error = Some(sourced);
1794        handle.thread_exit_code = Some(7);
1795        let diag = handle.reemit_error();
1796        let err = anyhow::Error::new(diag.clone());
1797        assert_eq!(exit_code_of_diag(&diag), Some(7));
1798        assert_eq!(diag.key(), "dsl.eval.async_cancelled");
1799        let io = err
1800            .chain()
1801            .find_map(|cause| cause.downcast_ref::<std::io::Error>())
1802            .expect("original source survives behind the exit code");
1803        assert_eq!(io.kind(), std::io::ErrorKind::NotFound);
1804        assert_eq!(
1805            format!("{err:#}"),
1806            "ASYNC task cancelled: EXIT requested with code 7: gone"
1807        );
1808    }
1809
1810    #[test]
1811    fn bare_exit_request_relays_as_keyed_diagnostic() {
1812        // Workers return `DiagnosticResult`, so a guest/host EXIT
1813        // arrives already keyed (dispatch lifts every `ExitRequest`
1814        // onto the carrier); the join reads the code natively.
1815        let join = std::thread::spawn(|| -> DiagnosticResult<()> {
1816            Err(step_diag::eval_exit_requested(7).with_contexts(vec!["step 2".to_string()]))
1817        });
1818        let mut handle = bare_handle(Some(join));
1819        let diag = handle.wait().expect_err("exit request must surface");
1820        assert_eq!(exit_code_of_diag(&diag), Some(7));
1821        assert_eq!(diag.key(), "dsl.eval.exit_requested");
1822        assert_eq!(diag.fields().get("code"), Some(&"7".to_string()));
1823        assert_eq!(format!("{diag:#}"), "step 2: EXIT requested with code 7");
1824    }
1825
1826    #[test]
1827    fn bare_exit_code_without_diagnostic_reemits_exit_requested() {
1828        // Directly-constructed handles (never worker threads, which
1829        // always return a keyed carrier) keep the bare-exit relay.
1830        let mut handle = bare_handle(None);
1831        handle.thread_exit_code = Some(7);
1832        let diag = handle.reemit_error();
1833        assert_eq!(exit_code_of_diag(&diag), Some(7));
1834        assert_eq!(diag.key(), "dsl.eval.exit_requested");
1835        assert_eq!(diag.fields().get("code"), Some(&"7".to_string()));
1836    }
1837}
1838
1839#[cfg(test)]
1840mod step_error_tests {
1841    use super::*;
1842    use oxdock_parser::StepKind;
1843
1844    fn step_at(line: usize, col: usize) -> Step {
1845        Step {
1846            guard: None,
1847            kind: StepKind::Break,
1848            scope_enter: 0,
1849            scope_exit: 0,
1850            line,
1851            col,
1852        }
1853    }
1854
1855    #[test]
1856    fn coordinates_attach_span_and_keep_text_prefix() {
1857        let leaf = step_diag::eval_async_cancelled();
1858        assert!(leaf.span().is_none());
1859        let err = step_error(&step_at(5, 3), 0, leaf);
1860        let span = err.span().expect("coordinates attach natively");
1861        assert_eq!(span.line, 5);
1862        assert_eq!(span.col_start, Some(3));
1863        assert!(
1864            format!("{err:#}").starts_with("step 1, line 5, col 3: "),
1865            "text prefix stays byte-identical: {err:#}"
1866        );
1867    }
1868
1869    #[test]
1870    fn innermost_span_wins_on_nested_dispatch() {
1871        let leaf = step_diag::eval_async_cancelled();
1872        let inner = step_error(&step_at(5, 3), 1, leaf);
1873        let outer = step_error(&step_at(9, 1), 0, inner);
1874        let span = outer.span().expect("span survives");
1875        assert_eq!((span.line, span.col_start), (5, Some(3)));
1876        assert!(
1877            format!("{outer:#}").starts_with("step 1, line 9, col 1: step 2, line 5, col 3: "),
1878            "both text frames chain like a call path: {outer:#}"
1879        );
1880    }
1881
1882    #[test]
1883    fn unknown_position_keeps_bare_prefix_without_span() {
1884        let leaf = step_diag::eval_async_cancelled();
1885        let err = step_error(&step_at(0, 0), 0, leaf);
1886        assert!(err.span().is_none());
1887        assert_eq!(format!("{err:#}"), "step 1: ASYNC task cancelled");
1888    }
1889
1890    #[test]
1891    fn prespanned_outermost_diagnostic_keeps_its_span() {
1892        // Innermost wins: a prespanned head keeps its span, the outer
1893        // step only prepends its text frame.
1894        let leaf = step_diag::eval_async_cancelled().with_span(Span::line_col(2, 4));
1895        let err = step_error(&step_at(9, 1), 0, leaf);
1896        let span = err.span().expect("span survives");
1897        assert_eq!((span.line, span.col_start), (2, Some(4)));
1898    }
1899
1900    #[test]
1901    fn synthetic_inner_yields_to_parsed_outer_coordinates() {
1902        // The inner step carries no coordinates, so its wrap leaves the
1903        // diagnostic span-less; the outer parsed step still attaches
1904        // natively.
1905        let leaf = step_diag::eval_async_cancelled();
1906        let inner = step_error(&step_at(0, 0), 1, leaf);
1907        let outer = step_error(&step_at(9, 1), 0, inner);
1908        let span = outer.span().expect("outer coordinates attach");
1909        assert_eq!((span.line, span.col_start), (9, Some(1)));
1910        assert!(
1911            format!("{outer:#}").starts_with("step 1, line 9, col 1: step 2: "),
1912            "inner text frame replays under the outer prefix: {outer:#}"
1913        );
1914    }
1915
1916    #[test]
1917    fn line_without_column_attaches_line_only_span() {
1918        let leaf = step_diag::eval_async_cancelled();
1919        let err = step_error(&step_at(7, 0), 0, leaf);
1920        let span = err.span().expect("line-only span attaches");
1921        assert_eq!(span.line, 7);
1922        assert_eq!(span.col_start, None);
1923        assert!(
1924            format!("{err:#}").starts_with("step 1, line 7: "),
1925            "prefix names the line with no column: {err:#}"
1926        );
1927    }
1928}