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