oxdock-core 0.44.0-alpha

Core engine for OxDock's Dockerfile-inspired compile-time DSL, orchestrating workspace snapshots and asset embedding.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
mod args;
mod capture;
#[cfg(any(test, feature = "test-harness"))]
pub mod conformance;
mod engine;
mod exit;
mod fs_ops;
mod handlers;
mod import;
mod io;
pub mod mcp;
mod native;
pub mod remote;
mod state;
mod static_check;
mod steps;
#[cfg(test)]
mod tests;
mod typing;

pub use self::remote::{
    RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
    apply_push_symlink,
};

pub use self::args::{
    json_to_value, json_to_value_typed, strip_json_comments, value_to_json, value_to_json_typed,
};
#[cfg(any(test, feature = "test-harness"))]
pub use self::conformance::assert_module_returns_conformance;
pub use self::engine::{Engine, EngineOutput};
pub use self::exit::{ExitRequest, exit_code_of};
pub(crate) use self::handlers::{
    dispatch_append, dispatch_append_line, dispatch_archive, dispatch_assert_contains,
    dispatch_assert_eq, dispatch_assert_ne, dispatch_async_block, dispatch_await_step,
    dispatch_bind_step, dispatch_break, dispatch_call, dispatch_cancel_step, dispatch_continue,
    dispatch_copy, dispatch_copy_git, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand,
    dispatch_fail, dispatch_for_loop, dispatch_func_def, dispatch_if_then, dispatch_import_file,
    dispatch_import_funcs, dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env,
    dispatch_isolated_step, dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step,
    dispatch_read, dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return,
    dispatch_run, dispatch_run_exec, dispatch_set, dispatch_set_executable, dispatch_sleep_step,
    dispatch_switch, dispatch_symlink, dispatch_timeout_step, dispatch_unarchive,
    dispatch_while_loop, dispatch_with_io, dispatch_with_io_block, dispatch_workdir,
    dispatch_workspace, dispatch_write,
};
pub use self::import::{DryRunStep, dry_run_closure};
pub use self::io::ExecIo;
pub use self::io::PipeStream;
pub use self::io::PushManifestSink;
pub use self::io::{StreamChunk, StreamHook, TeeStream};
pub use self::mcp::{McpCallOutput, McpSession};
pub use self::native::{
    FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
    OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
    builtin_function_names, check_script_param_tags, fill_optional_args, optional_zero_value,
    placeholder_resolver, required_arity, resolve_script_params, std_module_table,
};
pub use self::state::ExecState;
pub use self::state::MAX_RUNNING_TASKS;
pub use self::state::const_mutation_error;
pub use self::steps::StepCtx;
pub use self::typing::{
    Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
    check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
    drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
    load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
    unshare_shared,
};

use anyhow::Result;
use oxdock_fs::{
    GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
};
use oxdock_parser::Step;
use oxdock_process::{
    BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
    default_process_manager,
};

use std::collections::BTreeMap;
use std::sync::Arc;

use self::fs_ops::describe_dir;
use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
use self::steps::execute_steps;

/// Display text emitted by `CWD` while the snapshot root is selected but not
/// yet materialized (issue #131). Single source of truth: the `cwd` handler
/// prints this value, and the logic-test harness resolves the same value
/// from `@SNAPSHOT_PENDING@` fixture tokens.
pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";

/// Fallback tree body used when a materialized snapshot cannot be described
/// while building a run error (issue #131). Single source of truth for the
/// lazy error path.
pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";

/// Execute the DSL with the CLI default: a lazily-created snapshot.
/// No temporary directory exists until the first snapshot-targeted
/// resolution. Reads of existing workspace files fall through to the
/// build context, but directory listings (GLOB, LS) are snapshot-scoped,
/// so workspace discovery belongs before the lazy run or under
/// `WORKSPACE LOCAL`. Fire-and-forget form of
/// [`run_steps_with_lazy_snapshot`]: for bindings and the snapshot
/// handle, call that directly. For runs that must land exactly in a
/// given root with no snapshot, use [`run_steps_without_snapshot`].
pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> Result<()> {
    run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
}

/// Without snapshot: execute directly against `fs_root` with no snapshot, so
/// writes land exactly in the given root and read-backs observe them.
/// Tests pinning on-disk state and hosts with caller-built filesystems
/// want this; interactive runs want [`run_steps`].
pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
    run_steps_with_context(fs_root, fs_root, steps)
}

pub fn run_steps_with_context(
    fs_root: &GuardedPath,
    build_context: &GuardedPath,
    steps: &[Step],
) -> Result<()> {
    run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
}

/// Execute the DSL and return the final working directory after all steps.
pub fn run_steps_with_context_result(
    fs_root: &GuardedPath,
    build_context: &GuardedPath,
    steps: &[Step],
    stdin: Option<SharedInput>,
    stdout: Option<SharedOutput>,
) -> Result<GuardedPath> {
    let io = assemble_default_io(stdin, stdout);
    run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
}

pub fn run_steps_with_context_result_with_io(
    fs_root: &GuardedPath,
    build_context: &GuardedPath,
    steps: &[Step],
    io: ExecIo,
) -> Result<GuardedPath> {
    match run_steps_inner(fs_root, build_context, steps, io) {
        Ok(final_cwd) => Ok(final_cwd),
        Err(err) => {
            let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
            let tree = describe_dir(&fs, fs_root, 2, 24);
            let snapshot = format!(
                "filesystem snapshot (root {}):\n{}",
                fs_root.display(),
                tree
            );
            Err(error_with_snapshot(err, snapshot))
        }
    }
}

/// Build a single error message with the top cause plus a caller-provided
/// filesystem-snapshot section. Shared by the eager and lazy runners so both
/// render identical chains and only differ in the snapshot section.
fn error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
    // Build a single error message with the top cause plus a compact fs snapshot.
    let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
    let mut primary = chain
        .first()
        .cloned()
        .unwrap_or_else(|| "unknown error".into());
    let rest = if chain.len() > 1 {
        let first_cause = chain[1].clone();
        primary = format!("{primary} ({first_cause})");
        if chain.len() > 2 {
            let causes = chain
                .iter()
                .skip(2)
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join("\n  ");
            format!("\ncauses:\n  {}", causes)
        } else {
            String::new()
        }
    } else {
        String::new()
    };
    let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
    // The snapshot renderer flattens the chain into one message for CLI
    // rendering. Re-attach a relayed EXIT code as the inner error under
    // that message: the text stays byte-identical while the code stays
    // machine readable (context values are invisible to chain traversal,
    // so the typed request must ride as a real error, not as context).
    match exit::exit_code_of(&err) {
        Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
        None => anyhow::anyhow!(msg),
    }
}

fn run_steps_inner(
    fs_root: &GuardedPath,
    build_context: &GuardedPath,
    steps: &[Step],
    io: ExecIo,
) -> Result<GuardedPath> {
    let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
    resolver.set_workspace_root(build_context.clone());
    run_steps_with_fs_with_io(Box::new(resolver), steps, io)
}

/// Output of a lazily-executed run (issue #131): the final working directory
/// (concretized as of return), shared ownership of the snapshot backing dir,
/// and the filesystem handle for post-hoc convergence (e.g. concretizing the
/// cwd after shell-entry materialization).
pub struct LazyRunOutput {
    pub final_cwd: GuardedPath,
    pub snapshot: Arc<LazyGuardedTempDir>,
    pub fs: Box<dyn WorkspaceFs>,
    /// Top-level script variable bindings captured at `Flow::Done`, keyed by
    /// variable name with deterministic ordering. Read-only introspection for
    /// hosts that assert on in-memory evaluation without file round trips.
    /// Ephemeral block scopes are excluded; see `run_steps_with_manager`.
    pub bindings: BTreeMap<String, Value>,
}

/// Execute the DSL against a lazily-created snapshot: no temporary directory
/// exists until the first snapshot-targeted resolution. The snapshot handle
/// is shared with the resolver, so all clones observe the same directory.
pub fn run_steps_with_lazy_snapshot(
    build_context: &GuardedPath,
    steps: &[Step],
    io: ExecIo,
) -> Result<LazyRunOutput> {
    run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
}

/// Same as [`run_steps_with_lazy_snapshot`], plus host modules and types
/// (see [`run_steps_with_manager_with_modules`]). Lets binary hosts that
/// run on the lazy snapshot path expose plugin surface without changing
/// CLI semantics.
pub fn run_steps_with_lazy_snapshot_and_modules(
    build_context: &GuardedPath,
    steps: &[Step],
    io: ExecIo,
    modules: Vec<HostModule<DefaultProcessManager>>,
    types: Vec<&'static TypeDescriptor>,
) -> Result<LazyRunOutput> {
    run_steps_with_lazy_snapshot_and_modules_and_entry(
        build_context,
        steps,
        io,
        modules,
        types,
        None,
    )
}

/// Same as [`run_steps_with_lazy_snapshot_and_modules`], plus the entry
/// script file (#115): top-level relative `IMPORT` paths resolve against
/// its parent directory.
pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
    build_context: &GuardedPath,
    steps: &[Step],
    io: ExecIo,
    modules: Vec<HostModule<DefaultProcessManager>>,
    types: Vec<&'static TypeDescriptor>,
    entry_file: Option<GuardedPath>,
) -> Result<LazyRunOutput> {
    let mut resolver = PathResolver::new_lazy(build_context.clone())?;
    resolver.set_workspace_root(build_context.clone());
    let snapshot = resolver.snapshot_handle();
    let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
    match run_steps_with_manager_with_modules_and_entry(
        fs,
        steps,
        default_process_manager(),
        io,
        modules,
        types,
        entry_file,
    ) {
        Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
            final_cwd,
            snapshot,
            fs,
            bindings,
        }),
        Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
    }
}

/// Error enrichment for lazy runs: a materialized snapshot gets the same
/// filesystem-snapshot treatment as eager runs; a pending one reports that
/// no snapshot directory was ever created instead of describing a tree.
/// Chain rendering is identical to the eager path (shared renderer).
pub fn enrich_lazy_error(
    snapshot: &Arc<LazyGuardedTempDir>,
    build_context: &GuardedPath,
    err: anyhow::Error,
) -> anyhow::Error {
    match snapshot.get() {
        Some(concrete) => {
            let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
                Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
                Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
            };
            let snapshot_msg = format!(
                "filesystem snapshot (root {}):\n{}",
                concrete.display(),
                tree
            );
            error_with_snapshot(err, snapshot_msg)
        }
        None => error_with_snapshot(
            err,
            String::from(
                "filesystem snapshot: never materialized (no snapshot directory was created)",
            ),
        ),
    }
}

pub fn run_steps_with_fs(
    fs: Box<dyn WorkspaceFs>,
    steps: &[Step],
    stdin: Option<SharedInput>,
    stdout: Option<SharedOutput>,
) -> Result<GuardedPath> {
    let io = assemble_default_io(stdin, stdout);
    run_steps_with_fs_with_io(fs, steps, io)
}

pub fn run_steps_with_fs_with_io(
    fs: Box<dyn WorkspaceFs>,
    steps: &[Step],
    io: ExecIo,
) -> Result<GuardedPath> {
    run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
}

/// Base name of a qualified `MODULE::NAME` reference for human-facing
/// errors. Single source lives in `oxdock-parser`; listings (`FUNCTIONS()`,
/// `DESCRIBE`) keep the qualified form while step errors name the callable
/// as written.
pub(crate) use oxdock_parser::base_name;

/// Host introspection entry point: execute the DSL against a caller-provided
/// filesystem and return the final working directory, the filesystem handle,
/// and the top-level script variable bindings captured at `Flow::Done`.
/// Bindings are read from the root variable scope only, so ephemeral
/// variables from `FUNC` bodies, `FOR`/`WHILE` iterations, and `ASYNC` blocks
/// are excluded. On script failure the scope is discarded with the error and
/// no bindings are returned.
#[allow(clippy::type_complexity)]
pub fn run_steps_with_manager<P: ProcessManager>(
    fs: Box<dyn WorkspaceFs>,
    steps: &[Step],
    process: P,
    io: ExecIo,
) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
    run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
}

/// Same as [`run_steps_with_manager`], plus host modules and types. Each
/// module's functions become callable as `MODULE::NAME` with full step
/// context; each type descriptor becomes visible to `TYPES()` and valid for
/// `LET $x: NAME` declarations carrying same-named opaque payloads.
/// Authors should derive entries with `#[oxdock_func]` / `#[oxdock_type]`
/// (see `oxdock-func-macro`) and group them into [`HostModule`] instead of
/// hand-writing metadata and glue.
#[allow(clippy::type_complexity)]
pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
    fs: Box<dyn WorkspaceFs>,
    steps: &[Step],
    process: P,
    io: ExecIo,
    modules: Vec<HostModule<P>>,
    types: Vec<&'static self::typing::TypeDescriptor>,
) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
    run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
}

/// Same as [`run_steps_with_manager_with_modules`], plus the entry script
/// file (#115): top-level relative `IMPORT` paths resolve against its
/// parent directory. `None` resolves imports against the workspace root.
#[allow(clippy::type_complexity)]
#[allow(clippy::too_many_arguments)]
pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
    fs: Box<dyn WorkspaceFs>,
    steps: &[Step],
    process: P,
    io: ExecIo,
    modules: Vec<HostModule<P>>,
    types: Vec<&'static self::typing::TypeDescriptor>,
    entry_file: Option<GuardedPath>,
) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
    let mut state = new_state(fs, io)?;
    state.entry_file = entry_file;
    state.module_table = build_module_table(&modules);
    for module in &modules {
        // Pre-run checks first: unmapped services fail here, before the
        // first step executes and with zero side effects.
        module.check_pre_run(steps)?;
    }
    for module in modules {
        state.register_module(module);
    }
    for descriptor in types {
        state.register_type(descriptor);
    }
    finish_run(state, process, steps)
}

pub(crate) fn new_state<P: ProcessManager>(
    fs: Box<dyn WorkspaceFs>,
    io: ExecIo,
) -> Result<ExecState<P>> {
    let cwd = fs.root().clone();
    let build_context = fs.build_context().clone();
    let cargo_scratch = reserve_cargo_scratch()?;
    // Seeded script environment: sandbox defaults first, then explicit
    // layers win (BuiltinEnv sanctions, `io` overrides route host
    // entries). The pure seed is stored alongside for `ISOLATED`
    // resets and transport sanitize.
    let seed = Arc::new(oxdock_process::seed_defaults());
    let mut envs = (*seed).clone();
    envs.extend(BuiltinEnv::collect(&build_context).into_envs());
    for (key, value) in io.inherit_env_overrides() {
        envs.insert(key.clone(), value.clone());
    }
    let envs = Arc::new(envs);
    let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
    let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
    let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
    // Run-scoped worker telemetry: the root hub adopts the staged
    // counter so every pump worker this run spawns attributes to it.
    let worker_counter = io.worker_counter();
    let entry_seed_envs = (*seed).clone();
    let entry_cwd = cwd.clone();
    let mut state = ExecState {
        fs,
        cargo_scratch,
        seed,
        cwd: cwd.clone(),
        envs,
        bg_children: Vec::new(),
        scope_stack: Vec::new(),
        isolated_stack: Vec::new(),
        io,
        assert_windows: assert_windows.clone(),
        assert_windows_stderr: assert_windows_stderr.clone(),
        exact_stdout: exact_stdout.clone(),
        var_scopes: Vec::new(),
        const_scopes: Vec::new(),
        cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
        cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
        active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
        named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
        next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
        live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
        inside_async: false,
        keeper_expiry: None,
        cancellable: false,
        reap_floor: None,
        functions: self::native::FunctionRegistry::with_builtins(),
        entry_file: None,
        import_stack: Vec::new(),
        executed_alias_targets: std::collections::HashMap::new(),
        call_alias_frames: Vec::new(),
        scope_alias_frames: Vec::new(),
        init_scope_depths: Vec::new(),
        func_floors: Vec::new(),
        harvest_map: std::collections::HashMap::new(),
        modules: std::collections::HashMap::from([(
            self::import::ENTRY_UNIT.to_string(),
            self::state::ModuleRecord::entry_record(entry_seed_envs, entry_cwd),
        )]),
        validated_modules: std::collections::HashSet::new(),
        module_stack: Vec::new(),
        module_table: self::native::std_module_table(),
        types: self::typing::startup_type_map(),
        record_schemas: std::collections::HashMap::new(),
        module_states: std::collections::HashMap::new(),
        type_aliases: std::collections::HashMap::new(),
        type_env_digest: 0,
        call_depth: 0,
        init_inherit_stack: Vec::new(),
        // Root flow is task 0; worker ids start at 1 (see next_task_id).
        task_id: 0,
        push_manifest: Vec::new(),
        _marker: std::marker::PhantomData,
    };

    // Push a global variable scope so top-level LET assignments are captured.
    state.push_var_scope();

    Ok(state)
}

/// Parse-time module table for `state`: stock `STD` builtins plus every
/// staged host module, mirroring [`Engine::module_table`]. Imported files
/// (#115) parse with this table so their `IMPORT [STD]` and qualified
/// calls resolve exactly like the entry script's.
fn build_module_table<P: ProcessManager>(
    modules: &[self::native::HostModule<P>],
) -> oxdock_parser::ModuleTable {
    let mut table = self::native::std_module_table();
    for module in modules {
        let mut func_names = std::collections::HashSet::new();
        for registration in &module.funcs {
            let name = match registration {
                self::native::HostRegistration::Stateful { name, .. } => name,
                self::native::HostRegistration::Pure { name, .. } => name,
                self::native::HostRegistration::Both { name, .. } => name,
            };
            func_names.insert(name.clone());
        }
        table.modules.insert(
            module.name.clone(),
            Some(oxdock_parser::ModuleFuncs { func_names }),
        );
    }
    table
}

/// Shared validation-only entry: builds no snapshot output, runs no
/// steps. Dry-run calls this before printing the closure so it fails
/// where execution and `--mcp` would on script errors. Service
/// mapping (`check_pre_run`) is deliberately excluded: dry-run
/// previews without binding sockets, and mappings are a deployment
/// concern validated at execution and MCP-init time.
pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
    fs: Box<dyn WorkspaceFs>,
    steps: &[Step],
    modules: Vec<HostModule<P>>,
    types: Vec<&'static TypeDescriptor>,
    entry_file: Option<GuardedPath>,
) -> Result<()> {
    let mut state = new_state(fs, ExecIo::new())?;
    state.entry_file = entry_file;
    state.module_table = build_module_table(&modules);
    for module in modules {
        state.register_module(module);
    }
    for descriptor in types {
        state.register_type(descriptor);
    }
    validate_closure_for_run(&mut state, steps).map(|_| ())
}

/// Shared run boundary: typo'd param and return tags plus the full
/// script-side closure check (terminal unification, MissingReturn,
/// undeclared variables, ungated ANY). Every entry point funnels
/// through here so `--dry-run`, execution, and `--mcp` agree. Restores
/// type aliases on success. Returns every type name exported anywhere
/// in the closure for callers needing export metadata (the closure
/// itself stays private to the module).
pub fn validate_closure_for_run<P: ProcessManager>(
    state: &mut ExecState<P>,
    steps: &[Step],
) -> Result<Vec<String>> {
    state.restore_aliases(self::typing::collect_type_aliases(steps, state)?);
    state.validate_function_type_tags()?;
    // Entry Frame-1 file scope (#322): index the entry top-level
    // `FUNC`s once. Every execution path (Engine, MCP, dry run)
    // funnels through here with the steps it is about to run, so
    // one build covers them all and entry calls resolve their own
    // file without scanning steps. The entry is one `ModuleRecord`
    // under the entry sentinel, so frame walks read entry and
    // modules through the same `unit_top_funcs` lookup.
    let top_funcs = self::import::collect_top_funcs(steps);
    // In-place entry refresh: re-validation must keep the live
    // prelude (`init`) and any sealed jails, updating only the
    // freshly indexed steps and file frame.
    let entry_record = state
        .modules
        .entry(self::import::ENTRY_UNIT.to_string())
        .or_default();
    entry_record.steps = steps.to_vec();
    entry_record.top_funcs = top_funcs;
    let saved_aliases = state.type_aliases.clone();
    let closure = self::import::expand_import_closure(state, steps)?;
    static_check::validate_script_closure(steps, &closure, state)?;
    state.restore_aliases(saved_aliases);
    let mut exported = Vec::new();
    for file in &closure {
        exported.extend(file.exports.types.iter().cloned());
    }
    Ok(exported)
}

#[allow(clippy::type_complexity)]
fn finish_run<P: ProcessManager>(
    mut state: ExecState<P>,
    process: P,
    steps: &[Step],
) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
    validate_closure_for_run(&mut state, steps)?;
    let assert_windows = Arc::clone(&state.assert_windows);
    let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
    let exact_stdout = Arc::clone(&state.exact_stdout);
    let _default_stdout = std::io::stdout();
    let stdin = state.io.stdin().into();
    // Every emitted byte flows through the tee so stream assertions see both
    // interpreter output and streamed child output, even when no capture
    // sink was configured (forwarding to real stdout in that case).
    let stdout = Some(StreamHandle::Stream(teed_stdout(
        state.io.stdout(),
        assert_windows,
        exact_stdout,
        None,
    )));
    let stderr = state
        .io
        .stderr()
        .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
    let mut proc_mgr = process;
    let flow = execute_steps(
        &mut state,
        &mut proc_mgr,
        steps,
        stdin,
        false,
        stdout,
        stderr,
        None,
        None,
        true,
    )?;
    match flow {
        // Concretize on the way out so a bare pending anchor never escapes as
        // the reported final directory (shell entry / OUT_DIR sync need real
        // paths; a pending run reports the local root or concretizes after
        // shell-entry materialization through the returned fs handle).
        self::steps::Flow::Done => {
            // Root-scope isolation: at Done all blocks have popped, so the
            // first scope is the global one. Read it explicitly (rather than
            // a flattened all-scopes view) and strip declared types so hosts
            // see plain values.
            let bindings: BTreeMap<String, Value> = state
                .var_scopes
                .first()
                .map(|scope| {
                    scope
                        .iter()
                        .map(|(k, (_, v))| (k.clone(), v.clone()))
                        .collect()
                })
                .unwrap_or_default();
            Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
        }
        self::steps::Flow::Break { idx } => {
            anyhow::bail!("step {}: BREAK outside loop", idx + 1)
        }
        self::steps::Flow::Continue { idx } => {
            anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
        }
        self::steps::Flow::Return { idx, .. } => {
            // Values only cross a boundary: a function call, an ASYNC
            // task, or an inline LET block. With none enclosing, the
            // pipeline top rejects it like any other escaped flow.
            anyhow::bail!(
                "step {}: RETURN outside function, ASYNC task, or LET block",
                idx + 1
            )
        }
    }
}