Skip to main content

oxdock_core/exec/
mod.rs

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