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