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