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