Skip to main content

oxdock_core/exec/
mod.rs

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