Skip to main content

oxdock_core/exec/
mod.rs

1mod args;
2mod capture;
3#[cfg(any(test, feature = "test-harness"))]
4pub mod conformance;
5mod engine;
6mod exit;
7mod fs_ops;
8mod handlers;
9mod import;
10mod io;
11pub mod mcp;
12mod native;
13pub mod remote;
14mod state;
15mod static_check;
16mod steps;
17#[cfg(test)]
18mod tests;
19mod typing;
20
21pub use self::remote::{
22    RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
23    apply_push_symlink,
24};
25
26pub use self::args::{json_to_value, json_to_value_typed, value_to_json, value_to_json_typed};
27#[cfg(any(test, feature = "test-harness"))]
28pub use self::conformance::assert_module_returns_conformance;
29pub use self::engine::{Engine, EngineOutput};
30pub use self::exit::{ExitRequest, exit_code_of};
31pub(crate) use self::handlers::{
32    dispatch_append, dispatch_archive, dispatch_assert_contains, dispatch_assert_eq,
33    dispatch_assert_ne, dispatch_assign, dispatch_assign_async_step, dispatch_assign_capture_step,
34    dispatch_async_block, dispatch_await_capture_step, dispatch_await_step, dispatch_break,
35    dispatch_call, dispatch_cancel_step, dispatch_continue, dispatch_copy, dispatch_copy_git,
36    dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand, dispatch_for_loop,
37    dispatch_func_def, dispatch_if_then, dispatch_import_file, dispatch_import_funcs,
38    dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env, dispatch_isolated_step,
39    dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step, dispatch_read,
40    dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return, dispatch_run,
41    dispatch_run_exec, dispatch_set, dispatch_sleep_step, dispatch_symlink, dispatch_timeout_step,
42    dispatch_unarchive, dispatch_while_loop, dispatch_with_io, dispatch_with_io_block,
43    dispatch_workdir, dispatch_workspace, dispatch_write,
44};
45pub use self::import::{DryRunStep, dry_run_closure};
46pub use self::io::ExecIo;
47pub use self::io::PipeStream;
48pub use self::io::PushManifestSink;
49pub use self::io::{StreamChunk, StreamHook, TeeStream};
50pub use self::mcp::{McpCallOutput, McpSession};
51pub use self::native::{
52    FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
53    OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
54    builtin_function_names, fill_optional_args, required_arity, std_module_table,
55};
56pub use self::state::ExecState;
57pub use self::state::MAX_RUNNING_TASKS;
58pub use self::steps::StepCtx;
59pub use self::typing::{
60    Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
61    check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
62    drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
63    load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
64    unshare_shared,
65};
66
67use anyhow::Result;
68use oxdock_fs::{
69    GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
70};
71use oxdock_parser::Step;
72use oxdock_process::{
73    BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
74    default_process_manager,
75};
76
77use std::collections::BTreeMap;
78use std::sync::Arc;
79
80use self::fs_ops::describe_dir;
81use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
82use self::steps::execute_steps;
83
84/// Display text emitted by `CWD` while the snapshot root is selected but not
85/// yet materialized (issue #131). Single source of truth: the `cwd` handler
86/// prints this value, and the logic-test harness resolves the same value
87/// from `@SNAPSHOT_PENDING@` fixture tokens.
88pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
89
90/// Fallback tree body used when a materialized snapshot cannot be described
91/// while composing a run error (issue #131). Single source of truth for the
92/// lazy error path.
93pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
94
95/// Execute the DSL with the CLI default: a lazily-created snapshot.
96/// No temporary directory exists until the first snapshot-targeted
97/// resolution. Reads of existing workspace files fall through to the
98/// build context, but directory listings (GLOB, LS) are snapshot-scoped,
99/// so workspace discovery belongs before the lazy run or under
100/// `WORKSPACE LOCAL`. Fire-and-forget form of
101/// [`run_steps_with_lazy_snapshot`]: for bindings and the snapshot
102/// handle, call that directly. For runs that must land exactly in a
103/// given root with no snapshot, use [`run_steps_without_snapshot`].
104pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> Result<()> {
105    run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
106}
107
108/// Without snapshot: execute directly against `fs_root` with no snapshot, so
109/// writes land exactly in the given root and read-backs observe them.
110/// Tests pinning on-disk state and hosts with caller-built filesystems
111/// want this; interactive runs want [`run_steps`].
112pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
113    run_steps_with_context(fs_root, fs_root, steps)
114}
115
116pub fn run_steps_with_context(
117    fs_root: &GuardedPath,
118    build_context: &GuardedPath,
119    steps: &[Step],
120) -> Result<()> {
121    run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
122}
123
124/// Execute the DSL and return the final working directory after all steps.
125pub fn run_steps_with_context_result(
126    fs_root: &GuardedPath,
127    build_context: &GuardedPath,
128    steps: &[Step],
129    stdin: Option<SharedInput>,
130    stdout: Option<SharedOutput>,
131) -> Result<GuardedPath> {
132    let io = assemble_default_io(stdin, stdout);
133    run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
134}
135
136pub fn run_steps_with_context_result_with_io(
137    fs_root: &GuardedPath,
138    build_context: &GuardedPath,
139    steps: &[Step],
140    io: ExecIo,
141) -> Result<GuardedPath> {
142    match run_steps_inner(fs_root, build_context, steps, io) {
143        Ok(final_cwd) => Ok(final_cwd),
144        Err(err) => {
145            let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
146            let tree = describe_dir(&fs, fs_root, 2, 24);
147            let snapshot = format!(
148                "filesystem snapshot (root {}):\n{}",
149                fs_root.display(),
150                tree
151            );
152            Err(compose_error_with_snapshot(err, snapshot))
153        }
154    }
155}
156
157/// Compose a single error message with the top cause plus a caller-provided
158/// filesystem-snapshot section. Shared by the eager and lazy runners so both
159/// render identical chains and only differ in the snapshot section.
160fn compose_error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
161    // Compose a single error message with the top cause plus a compact fs snapshot.
162    let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
163    let mut primary = chain
164        .first()
165        .cloned()
166        .unwrap_or_else(|| "unknown error".into());
167    let rest = if chain.len() > 1 {
168        let first_cause = chain[1].clone();
169        primary = format!("{primary} ({first_cause})");
170        if chain.len() > 2 {
171            let causes = chain
172                .iter()
173                .skip(2)
174                .map(|s| s.as_str())
175                .collect::<Vec<_>>()
176                .join("\n  ");
177            format!("\ncauses:\n  {}", causes)
178        } else {
179            String::new()
180        }
181    } else {
182        String::new()
183    };
184    let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
185    // The snapshot composer flattens the chain into one message for CLI
186    // rendering. Re-attach a relayed EXIT code as the inner error under
187    // that message: the text stays byte-identical while the code stays
188    // machine readable (context values are invisible to chain traversal,
189    // so the typed request must ride as a real error, not as context).
190    match exit::exit_code_of(&err) {
191        Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
192        None => anyhow::anyhow!(msg),
193    }
194}
195
196fn run_steps_inner(
197    fs_root: &GuardedPath,
198    build_context: &GuardedPath,
199    steps: &[Step],
200    io: ExecIo,
201) -> Result<GuardedPath> {
202    let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
203    resolver.set_workspace_root(build_context.clone());
204    run_steps_with_fs_with_io(Box::new(resolver), steps, io)
205}
206
207/// Output of a lazily-executed run (issue #131): the final working directory
208/// (concretized as of return), shared ownership of the snapshot backing dir,
209/// and the filesystem handle for post-hoc convergence (e.g. concretizing the
210/// cwd after shell-entry materialization).
211pub struct LazyRunOutput {
212    pub final_cwd: GuardedPath,
213    pub snapshot: Arc<LazyGuardedTempDir>,
214    pub fs: Box<dyn WorkspaceFs>,
215    /// Top-level script variable bindings captured at `Flow::Done`, keyed by
216    /// variable name with deterministic ordering. Read-only introspection for
217    /// hosts that assert on in-memory evaluation without file round trips.
218    /// Ephemeral block scopes are excluded; see `run_steps_with_manager`.
219    pub bindings: BTreeMap<String, Value>,
220}
221
222/// Execute the DSL against a lazily-created snapshot: no temporary directory
223/// exists until the first snapshot-targeted resolution. The snapshot handle
224/// is shared with the resolver, so all clones observe the same directory.
225pub fn run_steps_with_lazy_snapshot(
226    build_context: &GuardedPath,
227    steps: &[Step],
228    io: ExecIo,
229) -> Result<LazyRunOutput> {
230    run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
231}
232
233/// Same as [`run_steps_with_lazy_snapshot`], plus host modules and types
234/// (see [`run_steps_with_manager_with_modules`]). Lets binary hosts that
235/// run on the lazy snapshot path expose plugin surface without changing
236/// CLI semantics.
237pub fn run_steps_with_lazy_snapshot_and_modules(
238    build_context: &GuardedPath,
239    steps: &[Step],
240    io: ExecIo,
241    modules: Vec<HostModule<DefaultProcessManager>>,
242    types: Vec<&'static TypeDescriptor>,
243) -> Result<LazyRunOutput> {
244    run_steps_with_lazy_snapshot_and_modules_and_entry(
245        build_context,
246        steps,
247        io,
248        modules,
249        types,
250        None,
251    )
252}
253
254/// Same as [`run_steps_with_lazy_snapshot_and_modules`], plus the entry
255/// script file (#115): top-level relative `IMPORT` paths resolve against
256/// its parent directory.
257pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
258    build_context: &GuardedPath,
259    steps: &[Step],
260    io: ExecIo,
261    modules: Vec<HostModule<DefaultProcessManager>>,
262    types: Vec<&'static TypeDescriptor>,
263    entry_file: Option<GuardedPath>,
264) -> Result<LazyRunOutput> {
265    let mut resolver = PathResolver::new_lazy(build_context.clone())?;
266    resolver.set_workspace_root(build_context.clone());
267    let snapshot = resolver.snapshot_handle();
268    let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
269    match run_steps_with_manager_with_modules_and_entry(
270        fs,
271        steps,
272        default_process_manager(),
273        io,
274        modules,
275        types,
276        entry_file,
277    ) {
278        Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
279            final_cwd,
280            snapshot,
281            fs,
282            bindings,
283        }),
284        Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
285    }
286}
287
288/// Error enrichment for lazy runs: a materialized snapshot gets the same
289/// filesystem-snapshot treatment as eager runs; a pending one reports that
290/// no snapshot directory was ever created instead of describing a tree.
291/// Chain rendering is identical to the eager path (shared composer).
292pub fn enrich_lazy_error(
293    snapshot: &Arc<LazyGuardedTempDir>,
294    build_context: &GuardedPath,
295    err: anyhow::Error,
296) -> anyhow::Error {
297    match snapshot.get() {
298        Some(concrete) => {
299            let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
300                Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
301                Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
302            };
303            let snapshot_msg = format!(
304                "filesystem snapshot (root {}):\n{}",
305                concrete.display(),
306                tree
307            );
308            compose_error_with_snapshot(err, snapshot_msg)
309        }
310        None => compose_error_with_snapshot(
311            err,
312            String::from(
313                "filesystem snapshot: never materialized (no snapshot directory was created)",
314            ),
315        ),
316    }
317}
318
319pub fn run_steps_with_fs(
320    fs: Box<dyn WorkspaceFs>,
321    steps: &[Step],
322    stdin: Option<SharedInput>,
323    stdout: Option<SharedOutput>,
324) -> Result<GuardedPath> {
325    let io = assemble_default_io(stdin, stdout);
326    run_steps_with_fs_with_io(fs, steps, io)
327}
328
329pub fn run_steps_with_fs_with_io(
330    fs: Box<dyn WorkspaceFs>,
331    steps: &[Step],
332    io: ExecIo,
333) -> Result<GuardedPath> {
334    run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
335}
336
337/// Base name of a qualified `MODULE::NAME` reference for human-facing
338/// errors. Single source lives in `oxdock-parser`; listings (`FUNCTIONS()`,
339/// `DESCRIBE`) keep the qualified form while step errors name the callable
340/// as written.
341pub(crate) use oxdock_parser::base_name;
342
343/// Host introspection entry point: execute the DSL against a caller-provided
344/// filesystem and return the final working directory, the filesystem handle,
345/// and the top-level script variable bindings captured at `Flow::Done`.
346/// Bindings are read from the root variable scope only, so ephemeral
347/// variables from `FUNC` bodies, `FOR`/`WHILE` iterations, and `ASYNC` blocks
348/// are excluded. On script failure the scope is discarded with the error and
349/// no bindings are returned.
350#[allow(clippy::type_complexity)]
351pub fn run_steps_with_manager<P: ProcessManager>(
352    fs: Box<dyn WorkspaceFs>,
353    steps: &[Step],
354    process: P,
355    io: ExecIo,
356) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
357    run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
358}
359
360/// Same as [`run_steps_with_manager`], plus host modules and types. Each
361/// module's functions become callable as `MODULE::NAME` with full step
362/// context; each type descriptor becomes visible to `TYPES()` and valid for
363/// `LET $x: NAME` declarations carrying same-named opaque payloads.
364/// Authors should derive entries with `#[oxdock_func]` / `#[oxdock_type]`
365/// (see `oxdock-func-macro`) and group them into [`HostModule`] instead of
366/// hand-writing metadata and glue.
367#[allow(clippy::type_complexity)]
368pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
369    fs: Box<dyn WorkspaceFs>,
370    steps: &[Step],
371    process: P,
372    io: ExecIo,
373    modules: Vec<HostModule<P>>,
374    types: Vec<&'static self::typing::TypeDescriptor>,
375) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
376    run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
377}
378
379/// Same as [`run_steps_with_manager_with_modules`], plus the entry script
380/// file (#115): top-level relative `IMPORT` paths resolve against its
381/// parent directory. `None` resolves imports against the workspace root.
382#[allow(clippy::type_complexity)]
383#[allow(clippy::too_many_arguments)]
384pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
385    fs: Box<dyn WorkspaceFs>,
386    steps: &[Step],
387    process: P,
388    io: ExecIo,
389    modules: Vec<HostModule<P>>,
390    types: Vec<&'static self::typing::TypeDescriptor>,
391    entry_file: Option<GuardedPath>,
392) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
393    let mut state = new_state(fs, io)?;
394    state.entry_file = entry_file;
395    state.module_table = build_module_table(&modules);
396    for module in &modules {
397        // Pre-run checks first: unmapped services fail here, before the
398        // first step executes and with zero side effects.
399        module.check_pre_run(steps)?;
400    }
401    for module in modules {
402        state.register_module(module);
403    }
404    for descriptor in types {
405        state.register_type(descriptor);
406    }
407    finish_run(state, process, steps)
408}
409
410pub(crate) fn new_state<P: ProcessManager>(
411    fs: Box<dyn WorkspaceFs>,
412    io: ExecIo,
413) -> Result<ExecState<P>> {
414    let cwd = fs.root().clone();
415    let build_context = fs.build_context().clone();
416    let cargo_scratch = reserve_cargo_scratch()?;
417    // Seeded script environment: sandbox defaults first, then explicit
418    // layers win (BuiltinEnv sanctions, `io` overrides route host
419    // entries). The pure seed is stored alongside for `ISOLATED`
420    // resets and transport sanitize.
421    let seed = Arc::new(oxdock_process::seed_defaults(
422        &cargo_scratch.tmp_seed_display(),
423        &cargo_scratch.target_seed_display(),
424    ));
425    let mut envs = (*seed).clone();
426    envs.extend(BuiltinEnv::collect(&build_context).into_envs());
427    for (key, value) in io.inherit_env_overrides() {
428        envs.insert(key.clone(), value.clone());
429    }
430    let envs = Arc::new(envs);
431    let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
432    let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
433    let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
434    // Run-scoped worker telemetry: the root hub adopts the staged
435    // counter so every pump worker this run spawns attributes to it.
436    let worker_counter = io.worker_counter();
437    let mut state = ExecState {
438        fs,
439        cargo_scratch,
440        seed,
441        cwd: cwd.clone(),
442        initial_root: cwd,
443        envs,
444        bg_children: Vec::new(),
445        scope_stack: Vec::new(),
446        isolated_stack: Vec::new(),
447        io,
448        assert_windows: assert_windows.clone(),
449        assert_windows_stderr: assert_windows_stderr.clone(),
450        exact_stdout: exact_stdout.clone(),
451        var_scopes: Vec::new(),
452        cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
453        cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
454        active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
455        named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
456        next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
457        live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
458        inside_async: false,
459        keeper_expiry: None,
460        cancellable: false,
461        reap_floor: None,
462        functions: self::native::FunctionRegistry::with_builtins(),
463        entry_file: None,
464        import_stack: Vec::new(),
465        import_alias_frame: None,
466        modules: std::collections::HashMap::new(),
467        module_stack: Vec::new(),
468        module_table: self::native::std_module_table(),
469        types: self::typing::startup_type_map(),
470        record_schemas: std::collections::HashMap::new(),
471        module_states: std::collections::HashMap::new(),
472        type_aliases: std::collections::HashMap::new(),
473        call_depth: 0,
474        // Root flow is task 0; worker ids start at 1 (see next_task_id).
475        task_id: 0,
476        push_manifest: Vec::new(),
477        _marker: std::marker::PhantomData,
478    };
479
480    // Push a global variable scope so top-level LET assignments are captured.
481    state.push_var_scope();
482
483    Ok(state)
484}
485
486/// Parse-time module table for `state`: stock `STD` builtins plus every
487/// staged host module, mirroring [`Engine::module_table`]. Imported files
488/// (#115) parse with this table so their `IMPORT [STD]` and qualified
489/// calls resolve exactly like the entry script's.
490fn build_module_table<P: ProcessManager>(
491    modules: &[self::native::HostModule<P>],
492) -> oxdock_parser::ModuleTable {
493    let mut table = self::native::std_module_table();
494    for module in modules {
495        let mut func_names = std::collections::HashSet::new();
496        for registration in &module.funcs {
497            let name = match registration {
498                self::native::HostRegistration::Stateful { name, .. } => name,
499                self::native::HostRegistration::Pure { name, .. } => name,
500                self::native::HostRegistration::Both { name, .. } => name,
501            };
502            func_names.insert(name.clone());
503        }
504        table.modules.insert(
505            module.name.clone(),
506            Some(oxdock_parser::ModuleFuncs { func_names }),
507        );
508    }
509    table
510}
511
512#[allow(clippy::type_complexity)]
513fn finish_run<P: ProcessManager>(
514    mut state: ExecState<P>,
515    process: P,
516    steps: &[Step],
517) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
518    // Execution boundary: every run entry point funnels through here, so
519    // typo'd param and return type tags fail before any step runs. A bad
520    // label is a programmer error, never a runtime value.
521    state.type_aliases = self::typing::collect_type_aliases(steps, &state)?;
522    state.validate_function_type_tags()?;
523    // Script-side counterpart: terminal unification, MissingReturn,
524    // undeclared variables, and ungated ANY flow fail here too,
525    // before any step runs. The closure pass covers the entry script
526    // plus every transitively imported file (#115): cross-file calls
527    // typecheck against the collected signatures, so no nested file
528    // can smuggle a type error past the entry gate.
529    let saved_aliases = state.type_aliases.clone();
530    let closure = self::import::expand_import_closure(&mut state, steps)?;
531    for file in &closure {
532        let aliases = self::typing::collect_type_aliases(&file.steps, &state)?;
533        // Validation is permissive (global) for v1: all file aliases
534        // merge bare, like host types. Runtime persistence stays strict
535        // (only exported + imported persist); static gating for
536        // harvests (unexported fails) lives in `collect_site`.
537        for (name, target) in &aliases {
538            state.type_aliases.insert(name.clone(), target.clone());
539        }
540    }
541    static_check::validate_script_closure(steps, &closure, &state)?;
542    state.type_aliases = saved_aliases;
543    let assert_windows = Arc::clone(&state.assert_windows);
544    let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
545    let exact_stdout = Arc::clone(&state.exact_stdout);
546    let _default_stdout = std::io::stdout();
547    let stdin = state.io.stdin().into();
548    // Every emitted byte flows through the tee so stream assertions see both
549    // interpreter output and streamed child output, even when no capture
550    // sink was configured (forwarding to real stdout in that case).
551    let stdout = Some(StreamHandle::Stream(teed_stdout(
552        state.io.stdout(),
553        assert_windows,
554        exact_stdout,
555        None,
556    )));
557    let stderr = state
558        .io
559        .stderr()
560        .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
561    let mut proc_mgr = process;
562    let flow = execute_steps(
563        &mut state,
564        &mut proc_mgr,
565        steps,
566        stdin,
567        false,
568        stdout,
569        stderr,
570        None,
571        None,
572        true,
573    )?;
574    match flow {
575        // Concretize on the way out so a bare pending anchor never escapes as
576        // the reported final directory (shell entry / OUT_DIR sync need real
577        // paths; a pending run reports the local root or concretizes after
578        // shell-entry materialization through the returned fs handle).
579        self::steps::Flow::Done => {
580            // Root-scope isolation: at Done all blocks have popped, so the
581            // first scope is the global one. Read it explicitly (rather than
582            // a flattened all-scopes view) and strip declared types so hosts
583            // see plain values.
584            let bindings: BTreeMap<String, Value> = state
585                .var_scopes
586                .first()
587                .map(|scope| {
588                    scope
589                        .iter()
590                        .map(|(k, (_, v))| (k.clone(), v.clone()))
591                        .collect()
592                })
593                .unwrap_or_default();
594            Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
595        }
596        self::steps::Flow::Break { idx } => {
597            anyhow::bail!("step {}: BREAK outside loop", idx + 1)
598        }
599        self::steps::Flow::Continue { idx } => {
600            anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
601        }
602        self::steps::Flow::Return { idx, .. } => {
603            // Values only cross a boundary: a function call, an ASYNC
604            // task, or an inline LET block. With none enclosing, the
605            // pipeline top rejects it like any other escaped flow.
606            anyhow::bail!(
607                "step {}: RETURN outside function, ASYNC task, or LET block",
608                idx + 1
609            )
610        }
611    }
612}