Skip to main content

oxdock_core/exec/
mod.rs

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