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