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