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