Skip to main content

oxdock_core/exec/
mod.rs

1mod args;
2mod capture;
3#[cfg(any(test, feature = "test-harness"))]
4pub mod conformance;
5mod engine;
6mod exit;
7mod fs_ops;
8mod handlers;
9mod io;
10pub mod mcp;
11mod native;
12pub mod remote;
13mod state;
14mod static_check;
15mod steps;
16#[cfg(test)]
17mod tests;
18mod typing;
19
20pub use self::remote::{
21    RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
22    apply_push_symlink,
23};
24
25pub use self::args::{json_to_value, json_to_value_typed, value_to_json, value_to_json_typed};
26#[cfg(any(test, feature = "test-harness"))]
27pub use self::conformance::assert_module_returns_conformance;
28pub use self::engine::{Engine, EngineOutput};
29pub use self::exit::{ExitRequest, exit_code_of};
30pub(crate) use self::handlers::{
31    dispatch_append, dispatch_archive, dispatch_assert_contains, dispatch_assert_eq,
32    dispatch_assign, dispatch_assign_async_step, dispatch_assign_capture_step,
33    dispatch_async_block, dispatch_await_capture_step, dispatch_await_step, dispatch_break,
34    dispatch_call, dispatch_cancel_step, dispatch_continue, dispatch_copy, dispatch_copy_git,
35    dispatch_cwd, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand, dispatch_for_loop,
36    dispatch_func_def, dispatch_hash_sha256, dispatch_if_then, dispatch_inherit_env,
37    dispatch_install, dispatch_isolated_inherit_env, dispatch_isolated_step, dispatch_ls,
38    dispatch_mkdir, dispatch_prompt, dispatch_push_into_step, dispatch_read, dispatch_read_line,
39    dispatch_remote, dispatch_remove, dispatch_return, dispatch_run, dispatch_run_exec,
40    dispatch_set, dispatch_sleep_step, dispatch_symlink, dispatch_timeout_step, dispatch_unarchive,
41    dispatch_while_loop, dispatch_with_io, dispatch_with_io_block, dispatch_workdir,
42    dispatch_workspace, dispatch_write,
43};
44pub use self::io::ExecIo;
45pub use self::io::PipeStream;
46pub use self::io::PushManifestSink;
47pub use self::io::{StreamChunk, StreamHook, TeeStream};
48pub use self::mcp::{McpCallOutput, McpSession};
49pub use self::native::{
50    FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
51    OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
52    builtin_function_names, fill_optional_args, required_arity, std_module_table,
53};
54pub use self::state::ExecState;
55pub use self::state::MAX_RUNNING_TASKS;
56pub use self::steps::StepCtx;
57pub use self::typing::{
58    Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
59    check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
60    drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
61    load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
62    unshare_shared,
63};
64
65use anyhow::Result;
66use oxdock_fs::{
67    GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
68};
69use oxdock_parser::Step;
70use oxdock_process::{
71    BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
72    default_process_manager,
73};
74
75use std::collections::BTreeMap;
76use std::sync::Arc;
77
78use self::fs_ops::describe_dir;
79use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
80use self::steps::execute_steps;
81
82/// Display text emitted by `CWD` while the snapshot root is selected but not
83/// yet materialized (issue #131). Single source of truth: the `cwd` handler
84/// prints this value, and the logic-test harness resolves the same value
85/// from `@SNAPSHOT_PENDING@` fixture tokens.
86pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
87
88/// Fallback tree body used when a materialized snapshot cannot be described
89/// while composing a run error (issue #131). Single source of truth for the
90/// lazy error path.
91pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
92
93pub fn run_steps(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
94    run_steps_with_context(fs_root, fs_root, steps)
95}
96
97pub fn run_steps_with_context(
98    fs_root: &GuardedPath,
99    build_context: &GuardedPath,
100    steps: &[Step],
101) -> Result<()> {
102    run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
103}
104
105/// Execute the DSL and return the final working directory after all steps.
106pub fn run_steps_with_context_result(
107    fs_root: &GuardedPath,
108    build_context: &GuardedPath,
109    steps: &[Step],
110    stdin: Option<SharedInput>,
111    stdout: Option<SharedOutput>,
112) -> Result<GuardedPath> {
113    let io = assemble_default_io(stdin, stdout);
114    run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
115}
116
117pub fn run_steps_with_context_result_with_io(
118    fs_root: &GuardedPath,
119    build_context: &GuardedPath,
120    steps: &[Step],
121    io: ExecIo,
122) -> Result<GuardedPath> {
123    match run_steps_inner(fs_root, build_context, steps, io) {
124        Ok(final_cwd) => Ok(final_cwd),
125        Err(err) => {
126            let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
127            let tree = describe_dir(&fs, fs_root, 2, 24);
128            let snapshot = format!(
129                "filesystem snapshot (root {}):\n{}",
130                fs_root.display(),
131                tree
132            );
133            Err(compose_error_with_snapshot(err, snapshot))
134        }
135    }
136}
137
138/// Compose a single error message with the top cause plus a caller-provided
139/// filesystem-snapshot section. Shared by the eager and lazy runners so both
140/// render identical chains and only differ in the snapshot section.
141fn compose_error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
142    // Compose a single error message with the top cause plus a compact fs snapshot.
143    let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
144    let mut primary = chain
145        .first()
146        .cloned()
147        .unwrap_or_else(|| "unknown error".into());
148    let rest = if chain.len() > 1 {
149        let first_cause = chain[1].clone();
150        primary = format!("{primary} ({first_cause})");
151        if chain.len() > 2 {
152            let causes = chain
153                .iter()
154                .skip(2)
155                .map(|s| s.as_str())
156                .collect::<Vec<_>>()
157                .join("\n  ");
158            format!("\ncauses:\n  {}", causes)
159        } else {
160            String::new()
161        }
162    } else {
163        String::new()
164    };
165    let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
166    // The snapshot composer flattens the chain into one message for CLI
167    // rendering. Re-attach a relayed EXIT code as the inner error under
168    // that message: the text stays byte-identical while the code stays
169    // machine readable (context values are invisible to chain traversal,
170    // so the typed request must ride as a real error, not as context).
171    match exit::exit_code_of(&err) {
172        Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
173        None => anyhow::anyhow!(msg),
174    }
175}
176
177fn run_steps_inner(
178    fs_root: &GuardedPath,
179    build_context: &GuardedPath,
180    steps: &[Step],
181    io: ExecIo,
182) -> Result<GuardedPath> {
183    let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
184    resolver.set_workspace_root(build_context.clone());
185    run_steps_with_fs_with_io(Box::new(resolver), steps, io)
186}
187
188/// Output of a lazily-executed run (issue #131): the final working directory
189/// (concretized as of return), shared ownership of the snapshot backing dir,
190/// and the filesystem handle for post-hoc convergence (e.g. concretizing the
191/// cwd after shell-entry materialization).
192pub struct LazyRunOutput {
193    pub final_cwd: GuardedPath,
194    pub snapshot: Arc<LazyGuardedTempDir>,
195    pub fs: Box<dyn WorkspaceFs>,
196    /// Top-level script variable bindings captured at `Flow::Done`, keyed by
197    /// variable name with deterministic ordering. Read-only introspection for
198    /// hosts that assert on in-memory evaluation without file round trips.
199    /// Ephemeral block scopes are excluded; see `run_steps_with_manager`.
200    pub bindings: BTreeMap<String, Value>,
201}
202
203/// Execute the DSL against a lazily-created snapshot: no temporary directory
204/// exists until the first snapshot-targeted resolution. The snapshot handle
205/// is shared with the resolver, so all clones observe the same directory.
206pub fn run_steps_with_lazy_snapshot(
207    build_context: &GuardedPath,
208    steps: &[Step],
209    io: ExecIo,
210) -> Result<LazyRunOutput> {
211    run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
212}
213
214/// Same as [`run_steps_with_lazy_snapshot`], plus host modules and types
215/// (see [`run_steps_with_manager_with_modules`]). Lets binary hosts that
216/// run on the lazy snapshot path expose plugin surface without changing
217/// CLI semantics.
218pub fn run_steps_with_lazy_snapshot_and_modules(
219    build_context: &GuardedPath,
220    steps: &[Step],
221    io: ExecIo,
222    modules: Vec<HostModule<DefaultProcessManager>>,
223    types: Vec<&'static TypeDescriptor>,
224) -> Result<LazyRunOutput> {
225    let mut resolver = PathResolver::new_lazy(build_context.clone())?;
226    resolver.set_workspace_root(build_context.clone());
227    let snapshot = resolver.snapshot_handle();
228    let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
229    match run_steps_with_manager_with_modules(
230        fs,
231        steps,
232        default_process_manager(),
233        io,
234        modules,
235        types,
236    ) {
237        Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
238            final_cwd,
239            snapshot,
240            fs,
241            bindings,
242        }),
243        Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
244    }
245}
246
247/// Error enrichment for lazy runs: a materialized snapshot gets the same
248/// filesystem-snapshot treatment as eager runs; a pending one reports that
249/// no snapshot directory was ever created instead of describing a tree.
250/// Chain rendering is identical to the eager path (shared composer).
251pub fn enrich_lazy_error(
252    snapshot: &Arc<LazyGuardedTempDir>,
253    build_context: &GuardedPath,
254    err: anyhow::Error,
255) -> anyhow::Error {
256    match snapshot.get() {
257        Some(concrete) => {
258            let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
259                Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
260                Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
261            };
262            let snapshot_msg = format!(
263                "filesystem snapshot (root {}):\n{}",
264                concrete.display(),
265                tree
266            );
267            compose_error_with_snapshot(err, snapshot_msg)
268        }
269        None => compose_error_with_snapshot(
270            err,
271            String::from(
272                "filesystem snapshot: never materialized (no snapshot directory was created)",
273            ),
274        ),
275    }
276}
277
278pub fn run_steps_with_fs(
279    fs: Box<dyn WorkspaceFs>,
280    steps: &[Step],
281    stdin: Option<SharedInput>,
282    stdout: Option<SharedOutput>,
283) -> Result<GuardedPath> {
284    let io = assemble_default_io(stdin, stdout);
285    run_steps_with_fs_with_io(fs, steps, io)
286}
287
288pub fn run_steps_with_fs_with_io(
289    fs: Box<dyn WorkspaceFs>,
290    steps: &[Step],
291    io: ExecIo,
292) -> Result<GuardedPath> {
293    run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
294}
295
296/// Base name of a qualified `MODULE::NAME` reference for human-facing
297/// errors. Single source lives in `oxdock-parser`; listings (`FUNCTIONS()`,
298/// `DESCRIBE`) keep the qualified form while step errors name the callable
299/// as written.
300pub(crate) use oxdock_parser::base_name;
301
302/// Host introspection entry point: execute the DSL against a caller-provided
303/// filesystem and return the final working directory, the filesystem handle,
304/// and the top-level script variable bindings captured at `Flow::Done`.
305/// Bindings are read from the root variable scope only, so ephemeral
306/// variables from `FUNC` bodies, `FOR`/`WHILE` iterations, and `ASYNC` blocks
307/// are excluded. On script failure the scope is discarded with the error and
308/// no bindings are returned.
309#[allow(clippy::type_complexity)]
310pub fn run_steps_with_manager<P: ProcessManager>(
311    fs: Box<dyn WorkspaceFs>,
312    steps: &[Step],
313    process: P,
314    io: ExecIo,
315) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
316    run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
317}
318
319/// Same as [`run_steps_with_manager`], plus host modules and types. Each
320/// module's functions become callable as `MODULE::NAME` with full step
321/// context; each type descriptor becomes visible to `TYPES()` and valid for
322/// `LET $x: NAME` declarations carrying same-named opaque payloads.
323/// Authors should derive entries with `#[oxdock_func]` / `#[oxdock_type]`
324/// (see `oxdock-func-macro`) and group them into [`HostModule`] instead of
325/// hand-writing metadata and glue.
326#[allow(clippy::type_complexity)]
327pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
328    fs: Box<dyn WorkspaceFs>,
329    steps: &[Step],
330    process: P,
331    io: ExecIo,
332    modules: Vec<HostModule<P>>,
333    types: Vec<&'static self::typing::TypeDescriptor>,
334) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
335    let mut state = new_state(fs, io)?;
336    for module in &modules {
337        // Pre-run checks first: unmapped services fail here, before the
338        // first step executes and with zero side effects.
339        module.check_pre_run(steps)?;
340    }
341    for module in modules {
342        state.register_module(module);
343    }
344    for descriptor in types {
345        state.register_type(descriptor);
346    }
347    finish_run(state, process, steps)
348}
349
350pub(crate) fn new_state<P: ProcessManager>(
351    fs: Box<dyn WorkspaceFs>,
352    io: ExecIo,
353) -> Result<ExecState<P>> {
354    let cwd = fs.root().clone();
355    let build_context = fs.build_context().clone();
356    let cargo_scratch = reserve_cargo_scratch()?;
357    // Seeded script environment: sandbox defaults first, then explicit
358    // layers win (BuiltinEnv sanctions, `io` overrides route host
359    // entries). The pure seed is stored alongside for `ISOLATED`
360    // resets and transport sanitize.
361    let seed = Arc::new(oxdock_process::seed_defaults(
362        &cargo_scratch.tmp_seed_display(),
363        &cargo_scratch.target_seed_display(),
364    ));
365    let mut envs = (*seed).clone();
366    envs.extend(BuiltinEnv::collect(&build_context).into_envs());
367    for (key, value) in io.inherit_env_overrides() {
368        envs.insert(key.clone(), value.clone());
369    }
370    let envs = Arc::new(envs);
371    let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
372    let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
373    let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
374    // Run-scoped worker telemetry: the root hub adopts the staged
375    // counter so every pump worker this run spawns attributes to it.
376    let worker_counter = io.worker_counter();
377    let mut state = ExecState {
378        fs,
379        cargo_scratch,
380        seed,
381        cwd,
382        envs,
383        bg_children: Vec::new(),
384        scope_stack: Vec::new(),
385        isolated_stack: Vec::new(),
386        io,
387        assert_windows: assert_windows.clone(),
388        assert_windows_stderr: assert_windows_stderr.clone(),
389        exact_stdout: exact_stdout.clone(),
390        var_scopes: Vec::new(),
391        cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
392        cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
393        active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
394        named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
395        next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
396        live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
397        inside_async: false,
398        keeper_expiry: None,
399        cancellable: false,
400        functions: self::native::FunctionRegistry::with_builtins(),
401        types: self::typing::startup_type_map(),
402        record_schemas: std::collections::HashMap::new(),
403        module_states: std::collections::HashMap::new(),
404        type_aliases: std::collections::HashMap::new(),
405        call_depth: 0,
406        // Root flow is task 0; worker ids start at 1 (see next_task_id).
407        task_id: 0,
408        push_manifest: Vec::new(),
409        _marker: std::marker::PhantomData,
410    };
411
412    // Push a global variable scope so top-level LET assignments are captured.
413    state.push_var_scope();
414
415    Ok(state)
416}
417
418#[allow(clippy::type_complexity)]
419fn finish_run<P: ProcessManager>(
420    mut state: ExecState<P>,
421    process: P,
422    steps: &[Step],
423) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
424    // Execution boundary: every run entry point funnels through here, so
425    // typo'd param and return type tags fail before any step runs. A bad
426    // label is a programmer error, never a runtime value.
427    state.type_aliases = self::typing::collect_type_aliases(steps, &state)?;
428    state.validate_function_type_tags()?;
429    // Script-side counterpart: terminal unification, MissingReturn,
430    // undeclared variables, and ungated ANY flow fail here too,
431    // before any step runs.
432    static_check::validate_script_types(steps, &state)?;
433    let assert_windows = Arc::clone(&state.assert_windows);
434    let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
435    let exact_stdout = Arc::clone(&state.exact_stdout);
436    let _default_stdout = std::io::stdout();
437    let stdin = state.io.stdin().into();
438    // Every emitted byte flows through the tee so stream assertions see both
439    // interpreter output and streamed child output, even when no capture
440    // sink was configured (forwarding to real stdout in that case).
441    let stdout = Some(StreamHandle::Stream(teed_stdout(
442        state.io.stdout(),
443        assert_windows,
444        exact_stdout,
445        None,
446    )));
447    let stderr = state
448        .io
449        .stderr()
450        .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
451    let mut proc_mgr = process;
452    let flow = execute_steps(
453        &mut state,
454        &mut proc_mgr,
455        steps,
456        stdin,
457        false,
458        stdout,
459        stderr,
460        None,
461        None,
462        true,
463    )?;
464    match flow {
465        // Concretize on the way out so a bare pending anchor never escapes as
466        // the reported final directory (shell entry / OUT_DIR sync need real
467        // paths; a pending run reports the local root or concretizes after
468        // shell-entry materialization through the returned fs handle).
469        self::steps::Flow::Done => {
470            // Root-scope isolation: at Done all blocks have popped, so the
471            // first scope is the global one. Read it explicitly (rather than
472            // a flattened all-scopes view) and strip declared types so hosts
473            // see plain values.
474            let bindings: BTreeMap<String, Value> = state
475                .var_scopes
476                .first()
477                .map(|scope| {
478                    scope
479                        .iter()
480                        .map(|(k, (_, v))| (k.clone(), v.clone()))
481                        .collect()
482                })
483                .unwrap_or_default();
484            Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
485        }
486        self::steps::Flow::Break { idx } => {
487            anyhow::bail!("step {}: BREAK outside loop", idx + 1)
488        }
489        self::steps::Flow::Continue { idx } => {
490            anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
491        }
492        self::steps::Flow::Return { idx, .. } => {
493            // Values only cross a boundary: a function call, an ASYNC
494            // task, or an inline LET block. With none enclosing, the
495            // pipeline top rejects it like any other escaped flow.
496            anyhow::bail!(
497                "step {}: RETURN outside function, ASYNC task, or LET block",
498                idx + 1
499            )
500        }
501    }
502}