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_async_block, dispatch_await_step,
36    dispatch_bind_step, dispatch_break, dispatch_call, dispatch_cancel_step, dispatch_continue,
37    dispatch_copy, dispatch_copy_git, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand,
38    dispatch_fail, dispatch_for_loop, dispatch_func_def, dispatch_if_then, dispatch_import_file,
39    dispatch_import_funcs, dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env,
40    dispatch_isolated_step, dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step,
41    dispatch_read, dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return,
42    dispatch_run, dispatch_run_exec, dispatch_set, dispatch_set_executable, dispatch_sleep_step,
43    dispatch_switch, dispatch_symlink, dispatch_timeout_step, dispatch_unarchive,
44    dispatch_while_loop, dispatch_with_io, dispatch_with_io_block, dispatch_workdir,
45    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::state::const_mutation_error;
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 entry_seed_envs = (*seed).clone();
439    let entry_cwd = cwd.clone();
440    let mut state = ExecState {
441        fs,
442        cargo_scratch,
443        seed,
444        cwd: cwd.clone(),
445        envs,
446        bg_children: Vec::new(),
447        scope_stack: Vec::new(),
448        isolated_stack: Vec::new(),
449        io,
450        assert_windows: assert_windows.clone(),
451        assert_windows_stderr: assert_windows_stderr.clone(),
452        exact_stdout: exact_stdout.clone(),
453        var_scopes: Vec::new(),
454        const_scopes: Vec::new(),
455        cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
456        cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
457        active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
458        named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
459        next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
460        live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
461        inside_async: false,
462        keeper_expiry: None,
463        cancellable: false,
464        reap_floor: None,
465        functions: self::native::FunctionRegistry::with_builtins(),
466        entry_file: None,
467        import_stack: Vec::new(),
468        executed_alias_targets: std::collections::HashMap::new(),
469        call_alias_frames: Vec::new(),
470        scope_alias_frames: Vec::new(),
471        init_scope_depths: Vec::new(),
472        func_floors: Vec::new(),
473        harvest_map: std::collections::HashMap::new(),
474        modules: std::collections::HashMap::from([(
475            self::import::ENTRY_UNIT.to_string(),
476            self::state::ModuleRecord::entry_record(entry_seed_envs, entry_cwd),
477        )]),
478        validated_modules: std::collections::HashSet::new(),
479        module_stack: Vec::new(),
480        module_table: self::native::std_module_table(),
481        types: self::typing::startup_type_map(),
482        record_schemas: std::collections::HashMap::new(),
483        module_states: std::collections::HashMap::new(),
484        type_aliases: std::collections::HashMap::new(),
485        type_env_digest: 0,
486        call_depth: 0,
487        init_inherit_stack: Vec::new(),
488        // Root flow is task 0; worker ids start at 1 (see next_task_id).
489        task_id: 0,
490        push_manifest: Vec::new(),
491        _marker: std::marker::PhantomData,
492    };
493
494    // Push a global variable scope so top-level LET assignments are captured.
495    state.push_var_scope();
496
497    Ok(state)
498}
499
500/// Parse-time module table for `state`: stock `STD` builtins plus every
501/// staged host module, mirroring [`Engine::module_table`]. Imported files
502/// (#115) parse with this table so their `IMPORT [STD]` and qualified
503/// calls resolve exactly like the entry script's.
504fn build_module_table<P: ProcessManager>(
505    modules: &[self::native::HostModule<P>],
506) -> oxdock_parser::ModuleTable {
507    let mut table = self::native::std_module_table();
508    for module in modules {
509        let mut func_names = std::collections::HashSet::new();
510        for registration in &module.funcs {
511            let name = match registration {
512                self::native::HostRegistration::Stateful { name, .. } => name,
513                self::native::HostRegistration::Pure { name, .. } => name,
514                self::native::HostRegistration::Both { name, .. } => name,
515            };
516            func_names.insert(name.clone());
517        }
518        table.modules.insert(
519            module.name.clone(),
520            Some(oxdock_parser::ModuleFuncs { func_names }),
521        );
522    }
523    table
524}
525
526/// Shared validation-only entry: builds no snapshot output, runs no
527/// steps. Dry-run calls this before printing the closure so it fails
528/// where execution and `--mcp` would on script errors. Service
529/// mapping (`check_pre_run`) is deliberately excluded: dry-run
530/// previews without binding sockets, and mappings are a deployment
531/// concern validated at execution and MCP-init time.
532pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
533    fs: Box<dyn WorkspaceFs>,
534    steps: &[Step],
535    modules: Vec<HostModule<P>>,
536    types: Vec<&'static TypeDescriptor>,
537    entry_file: Option<GuardedPath>,
538) -> Result<()> {
539    let mut state = new_state(fs, ExecIo::new())?;
540    state.entry_file = entry_file;
541    state.module_table = build_module_table(&modules);
542    for module in modules {
543        state.register_module(module);
544    }
545    for descriptor in types {
546        state.register_type(descriptor);
547    }
548    validate_closure_for_run(&mut state, steps).map(|_| ())
549}
550
551/// Shared run boundary: typo'd param and return tags plus the full
552/// script-side closure check (terminal unification, MissingReturn,
553/// undeclared variables, ungated ANY). Every entry point funnels
554/// through here so `--dry-run`, execution, and `--mcp` agree. Restores
555/// type aliases on success. Returns every type name exported anywhere
556/// in the closure for callers needing export metadata (the closure
557/// itself stays private to the module).
558pub fn validate_closure_for_run<P: ProcessManager>(
559    state: &mut ExecState<P>,
560    steps: &[Step],
561) -> Result<Vec<String>> {
562    state.restore_aliases(self::typing::collect_type_aliases(steps, state)?);
563    state.validate_function_type_tags()?;
564    // Entry Frame-1 file scope (#322): index the entry top-level
565    // `FUNC`s once. Every execution path (Engine, MCP, dry run)
566    // funnels through here with the steps it is about to run, so
567    // one build covers them all and entry calls resolve their own
568    // file without scanning steps. The entry is one `ModuleRecord`
569    // under the entry sentinel, so frame walks read entry and
570    // modules through the same `unit_top_funcs` lookup.
571    let top_funcs = self::import::collect_top_funcs(steps);
572    // In-place entry refresh: re-validation must keep the live
573    // prelude (`init`) and any sealed jails, updating only the
574    // freshly indexed steps and file frame.
575    let entry_record = state
576        .modules
577        .entry(self::import::ENTRY_UNIT.to_string())
578        .or_default();
579    entry_record.steps = steps.to_vec();
580    entry_record.top_funcs = top_funcs;
581    let saved_aliases = state.type_aliases.clone();
582    let closure = self::import::expand_import_closure(state, steps)?;
583    static_check::validate_script_closure(steps, &closure, state)?;
584    state.restore_aliases(saved_aliases);
585    let mut exported = Vec::new();
586    for file in &closure {
587        exported.extend(file.exports.types.iter().cloned());
588    }
589    Ok(exported)
590}
591
592#[allow(clippy::type_complexity)]
593fn finish_run<P: ProcessManager>(
594    mut state: ExecState<P>,
595    process: P,
596    steps: &[Step],
597) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
598    validate_closure_for_run(&mut state, steps)?;
599    let assert_windows = Arc::clone(&state.assert_windows);
600    let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
601    let exact_stdout = Arc::clone(&state.exact_stdout);
602    let _default_stdout = std::io::stdout();
603    let stdin = state.io.stdin().into();
604    // Every emitted byte flows through the tee so stream assertions see both
605    // interpreter output and streamed child output, even when no capture
606    // sink was configured (forwarding to real stdout in that case).
607    let stdout = Some(StreamHandle::Stream(teed_stdout(
608        state.io.stdout(),
609        assert_windows,
610        exact_stdout,
611        None,
612    )));
613    let stderr = state
614        .io
615        .stderr()
616        .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
617    let mut proc_mgr = process;
618    let flow = execute_steps(
619        &mut state,
620        &mut proc_mgr,
621        steps,
622        stdin,
623        false,
624        stdout,
625        stderr,
626        None,
627        None,
628        true,
629    )?;
630    match flow {
631        // Concretize on the way out so a bare pending anchor never escapes as
632        // the reported final directory (shell entry / OUT_DIR sync need real
633        // paths; a pending run reports the local root or concretizes after
634        // shell-entry materialization through the returned fs handle).
635        self::steps::Flow::Done => {
636            // Root-scope isolation: at Done all blocks have popped, so the
637            // first scope is the global one. Read it explicitly (rather than
638            // a flattened all-scopes view) and strip declared types so hosts
639            // see plain values.
640            let bindings: BTreeMap<String, Value> = state
641                .var_scopes
642                .first()
643                .map(|scope| {
644                    scope
645                        .iter()
646                        .map(|(k, (_, v))| (k.clone(), v.clone()))
647                        .collect()
648                })
649                .unwrap_or_default();
650            Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
651        }
652        self::steps::Flow::Break { idx } => {
653            anyhow::bail!("step {}: BREAK outside loop", idx + 1)
654        }
655        self::steps::Flow::Continue { idx } => {
656            anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
657        }
658        self::steps::Flow::Return { idx, .. } => {
659            // Values only cross a boundary: a function call, an ASYNC
660            // task, or an inline LET block. With none enclosing, the
661            // pipeline top rejects it like any other escaped flow.
662            anyhow::bail!(
663                "step {}: RETURN outside function, ASYNC task, or LET block",
664                idx + 1
665            )
666        }
667    }
668}