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