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