1mod args;
2mod capture;
3#[cfg(any(test, feature = "test-harness"))]
4pub mod conformance;
5pub mod diagnostics;
6mod engine;
7mod exit;
8mod fs_ops;
9pub(crate) mod function_names;
10mod handlers;
11mod import;
12mod io;
13pub mod mcp;
14mod native;
15pub mod remote;
16mod state;
17mod static_check;
18mod steps;
19#[cfg(test)]
20mod tests;
21mod typing;
22
23pub use self::remote::{
24 RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
25 apply_push_symlink,
26};
27
28pub use self::args::{
29 json_to_value, json_to_value_typed, strip_json_comments, value_to_json, value_to_json_typed,
30};
31#[cfg(any(test, feature = "test-harness"))]
32pub use self::conformance::assert_module_returns_conformance;
33pub use self::engine::{Engine, EngineOutput};
34pub use self::exit::{ExitRequest, exit_code_of};
35pub(crate) use self::handlers::{
36 dispatch_append, dispatch_append_line, dispatch_archive, dispatch_assert_contains,
37 dispatch_assert_eq, dispatch_assert_ne, dispatch_async_block, dispatch_await_step,
38 dispatch_bind_step, dispatch_break, dispatch_call, dispatch_cancel_step, dispatch_continue,
39 dispatch_copy, dispatch_copy_git, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand,
40 dispatch_fail, dispatch_for_loop, dispatch_func_def, dispatch_if_then, dispatch_import_file,
41 dispatch_import_funcs, dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env,
42 dispatch_isolated_step, dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step,
43 dispatch_read, dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return,
44 dispatch_run, dispatch_run_exec, dispatch_set, dispatch_set_executable, dispatch_sleep_step,
45 dispatch_switch, dispatch_symlink, dispatch_timeout_step, dispatch_unarchive,
46 dispatch_while_loop, dispatch_with_io, dispatch_with_io_block, dispatch_workdir,
47 dispatch_workspace, dispatch_write,
48};
49pub use self::import::{DryRunStep, dry_run_closure};
50pub use self::io::ExecIo;
51pub use self::io::PipeStream;
52pub use self::io::PushManifestSink;
53pub use self::io::{StreamChunk, StreamHook, TeeStream};
54pub use self::mcp::{McpCallOutput, McpSession};
55pub use self::native::{
56 FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
57 OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
58 builtin_function_names, check_script_param_tags, fill_optional_args, optional_zero_value,
59 placeholder_resolver, required_arity, resolve_script_params, std_module_table,
60};
61pub use self::state::ExecState;
62pub use self::state::MAX_RUNNING_TASKS;
63pub use self::state::const_mutation_error;
64pub use self::steps::StepCtx;
65pub use self::typing::{
66 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
67 check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
68 drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
69 load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
70 unshare_shared,
71};
72
73use anyhow::Result;
74use oxdock_diagnostics::DiagnosticResult;
75use oxdock_fs::{
76 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
77};
78use oxdock_parser::Step;
79use oxdock_parser::{KEYWORD_BREAK, KEYWORD_CONTINUE};
80use oxdock_process::{
81 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
82 default_process_manager,
83};
84
85use std::collections::BTreeMap;
86use std::sync::Arc;
87
88use self::fs_ops::describe_dir;
89use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
90use self::steps::execute_steps;
91
92pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
97
98pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
102
103pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> Result<()> {
113 run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
114}
115
116pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
121 run_steps_with_context(fs_root, fs_root, steps)
122}
123
124pub fn run_steps_with_context(
125 fs_root: &GuardedPath,
126 build_context: &GuardedPath,
127 steps: &[Step],
128) -> Result<()> {
129 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
130}
131
132pub fn run_steps_with_context_result(
134 fs_root: &GuardedPath,
135 build_context: &GuardedPath,
136 steps: &[Step],
137 stdin: Option<SharedInput>,
138 stdout: Option<SharedOutput>,
139) -> Result<GuardedPath> {
140 let io = assemble_default_io(stdin, stdout);
141 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
142}
143
144pub fn run_steps_with_context_result_with_io(
145 fs_root: &GuardedPath,
146 build_context: &GuardedPath,
147 steps: &[Step],
148 io: ExecIo,
149) -> Result<GuardedPath> {
150 match run_steps_inner(fs_root, build_context, steps, io) {
151 Ok(final_cwd) => Ok(final_cwd),
152 Err(err) => {
153 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
154 let tree = describe_dir(&fs, fs_root, 2, 24);
155 let snapshot = format!(
156 "filesystem snapshot (root {}):\n{}",
157 fs_root.display(),
158 tree
159 );
160 Err(error_with_snapshot(err, snapshot))
161 }
162 }
163}
164
165fn error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
169 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
171 let mut primary = chain
172 .first()
173 .cloned()
174 .unwrap_or_else(|| "unknown error".into());
175 let rest = if chain.len() > 1 {
176 let first_cause = chain[1].clone();
177 primary = format!("{primary} ({first_cause})");
178 if chain.len() > 2 {
179 let causes = chain
180 .iter()
181 .skip(2)
182 .map(|s| s.as_str())
183 .collect::<Vec<_>>()
184 .join("\n ");
185 format!("\ncauses:\n {}", causes)
186 } else {
187 String::new()
188 }
189 } else {
190 String::new()
191 };
192 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
193 match exit::exit_code_of(&err) {
199 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
200 None => anyhow::anyhow!(msg),
201 }
202}
203
204fn run_steps_inner(
205 fs_root: &GuardedPath,
206 build_context: &GuardedPath,
207 steps: &[Step],
208 io: ExecIo,
209) -> Result<GuardedPath> {
210 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
211 resolver.set_workspace_root(build_context.clone());
212 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
213}
214
215pub struct LazyRunOutput {
220 pub final_cwd: GuardedPath,
221 pub snapshot: Arc<LazyGuardedTempDir>,
222 pub fs: Box<dyn WorkspaceFs>,
223 pub bindings: BTreeMap<String, Value>,
228}
229
230pub fn run_steps_with_lazy_snapshot(
234 build_context: &GuardedPath,
235 steps: &[Step],
236 io: ExecIo,
237) -> Result<LazyRunOutput> {
238 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
239}
240
241pub fn run_steps_with_lazy_snapshot_and_modules(
246 build_context: &GuardedPath,
247 steps: &[Step],
248 io: ExecIo,
249 modules: Vec<HostModule<DefaultProcessManager>>,
250 types: Vec<&'static TypeDescriptor>,
251) -> Result<LazyRunOutput> {
252 run_steps_with_lazy_snapshot_and_modules_and_entry(
253 build_context,
254 steps,
255 io,
256 modules,
257 types,
258 None,
259 )
260}
261
262pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
266 build_context: &GuardedPath,
267 steps: &[Step],
268 io: ExecIo,
269 modules: Vec<HostModule<DefaultProcessManager>>,
270 types: Vec<&'static TypeDescriptor>,
271 entry_file: Option<GuardedPath>,
272) -> Result<LazyRunOutput> {
273 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
274 resolver.set_workspace_root(build_context.clone());
275 let snapshot = resolver.snapshot_handle();
276 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
277 match run_steps_with_manager_with_modules_and_entry(
278 fs,
279 steps,
280 default_process_manager(),
281 io,
282 modules,
283 types,
284 entry_file,
285 ) {
286 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
287 final_cwd,
288 snapshot,
289 fs,
290 bindings,
291 }),
292 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
293 }
294}
295
296pub fn enrich_lazy_error(
301 snapshot: &Arc<LazyGuardedTempDir>,
302 build_context: &GuardedPath,
303 err: anyhow::Error,
304) -> anyhow::Error {
305 match snapshot.get() {
306 Some(concrete) => {
307 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
308 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
309 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
310 };
311 let snapshot_msg = format!(
312 "filesystem snapshot (root {}):\n{}",
313 concrete.display(),
314 tree
315 );
316 error_with_snapshot(err, snapshot_msg)
317 }
318 None => error_with_snapshot(
319 err,
320 String::from(
321 "filesystem snapshot: never materialized (no snapshot directory was created)",
322 ),
323 ),
324 }
325}
326
327pub fn run_steps_with_fs(
328 fs: Box<dyn WorkspaceFs>,
329 steps: &[Step],
330 stdin: Option<SharedInput>,
331 stdout: Option<SharedOutput>,
332) -> Result<GuardedPath> {
333 let io = assemble_default_io(stdin, stdout);
334 run_steps_with_fs_with_io(fs, steps, io)
335}
336
337pub fn run_steps_with_fs_with_io(
338 fs: Box<dyn WorkspaceFs>,
339 steps: &[Step],
340 io: ExecIo,
341) -> Result<GuardedPath> {
342 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
343}
344
345pub(crate) use oxdock_parser::base_name;
350
351#[allow(clippy::type_complexity)]
359pub fn run_steps_with_manager<P: ProcessManager>(
360 fs: Box<dyn WorkspaceFs>,
361 steps: &[Step],
362 process: P,
363 io: ExecIo,
364) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
365 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
366}
367
368#[allow(clippy::type_complexity)]
376pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
377 fs: Box<dyn WorkspaceFs>,
378 steps: &[Step],
379 process: P,
380 io: ExecIo,
381 modules: Vec<HostModule<P>>,
382 types: Vec<&'static self::typing::TypeDescriptor>,
383) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
384 run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
385}
386
387#[allow(clippy::type_complexity)]
391#[allow(clippy::too_many_arguments)]
392pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
393 fs: Box<dyn WorkspaceFs>,
394 steps: &[Step],
395 process: P,
396 io: ExecIo,
397 modules: Vec<HostModule<P>>,
398 types: Vec<&'static self::typing::TypeDescriptor>,
399 entry_file: Option<GuardedPath>,
400) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
401 let mut state = new_state(fs, io)?;
402 state.entry_file = entry_file;
403 state.module_table = build_module_table(&modules);
404 for module in &modules {
405 module.check_pre_run(steps)?;
408 }
409 for module in modules {
410 state.register_module(module);
411 }
412 for descriptor in types {
413 state.register_type(descriptor);
414 }
415 finish_run(state, process, steps)
416}
417
418pub(crate) fn new_state<P: ProcessManager>(
419 fs: Box<dyn WorkspaceFs>,
420 io: ExecIo,
421) -> DiagnosticResult<ExecState<P>> {
422 let cwd = fs.root().clone();
423 let build_context = fs.build_context().clone();
424 let cargo_scratch = reserve_cargo_scratch()?;
425 let seed = Arc::new(oxdock_process::seed_defaults());
430 let mut envs = (*seed).clone();
431 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
432 for (key, value) in io.inherit_env_overrides() {
433 envs.insert(key.clone(), value.clone());
434 }
435 let envs = Arc::new(envs);
436 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
437 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
438 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
439 let worker_counter = io.worker_counter();
442 let entry_seed_envs = (*seed).clone();
443 let entry_cwd = cwd.clone();
444 let mut state = ExecState {
445 fs,
446 cargo_scratch,
447 seed,
448 cwd: cwd.clone(),
449 envs,
450 bg_children: Vec::new(),
451 scope_stack: Vec::new(),
452 isolated_stack: Vec::new(),
453 io,
454 assert_windows: assert_windows.clone(),
455 assert_windows_stderr: assert_windows_stderr.clone(),
456 exact_stdout: exact_stdout.clone(),
457 var_scopes: Vec::new(),
458 const_scopes: Vec::new(),
459 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
460 cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
461 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
462 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
463 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
464 live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
465 inside_async: false,
466 keeper_expiry: None,
467 cancellable: false,
468 reap_floor: None,
469 functions: self::native::FunctionRegistry::with_builtins(),
470 entry_file: None,
471 import_stack: Vec::new(),
472 executed_alias_targets: std::collections::HashMap::new(),
473 call_alias_frames: Vec::new(),
474 scope_alias_frames: Vec::new(),
475 init_scope_depths: Vec::new(),
476 func_floors: Vec::new(),
477 harvest_map: std::collections::HashMap::new(),
478 modules: std::collections::HashMap::from([(
479 self::import::ENTRY_UNIT.to_string(),
480 self::state::ModuleRecord::entry_record(entry_seed_envs, entry_cwd),
481 )]),
482 validated_modules: std::collections::HashSet::new(),
483 module_stack: Vec::new(),
484 module_table: self::native::std_module_table(),
485 types: self::typing::startup_type_map(),
486 record_schemas: std::collections::HashMap::new(),
487 module_states: std::collections::HashMap::new(),
488 type_aliases: std::collections::HashMap::new(),
489 type_env_digest: 0,
490 call_depth: 0,
491 init_inherit_stack: Vec::new(),
492 task_id: 0,
494 push_manifest: Vec::new(),
495 _marker: std::marker::PhantomData,
496 };
497
498 state.push_var_scope();
500
501 Ok(state)
502}
503
504fn build_module_table<P: ProcessManager>(
509 modules: &[self::native::HostModule<P>],
510) -> oxdock_parser::ModuleTable {
511 let mut table = self::native::std_module_table();
512 for module in modules {
513 let mut func_names = std::collections::HashSet::new();
514 for registration in &module.funcs {
515 let name = match registration {
516 self::native::HostRegistration::Stateful { name, .. } => name,
517 self::native::HostRegistration::Pure { name, .. } => name,
518 self::native::HostRegistration::Both { name, .. } => name,
519 };
520 func_names.insert(name.clone());
521 }
522 table.modules.insert(
523 module.name.clone(),
524 Some(oxdock_parser::ModuleFuncs { func_names }),
525 );
526 }
527 table
528}
529
530pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
537 fs: Box<dyn WorkspaceFs>,
538 steps: &[Step],
539 modules: Vec<HostModule<P>>,
540 types: Vec<&'static TypeDescriptor>,
541 entry_file: Option<GuardedPath>,
542) -> DiagnosticResult<()> {
543 let mut state = new_state(fs, ExecIo::new())?;
544 state.entry_file = entry_file;
545 state.module_table = build_module_table(&modules);
546 for module in modules {
547 state.register_module(module);
548 }
549 for descriptor in types {
550 state.register_type(descriptor);
551 }
552 validate_closure_for_run(&mut state, steps).map(|_| ())
553}
554
555pub fn validate_closure_for_run<P: ProcessManager>(
563 state: &mut ExecState<P>,
564 steps: &[Step],
565) -> DiagnosticResult<Vec<String>> {
566 state.restore_aliases(self::typing::collect_type_aliases(steps, state)?);
567 state.validate_function_type_tags()?;
568 let top_funcs = self::import::collect_top_funcs(steps);
576 let entry_record = state
580 .modules
581 .entry(self::import::ENTRY_UNIT.to_string())
582 .or_default();
583 entry_record.steps = steps.to_vec();
584 entry_record.top_funcs = top_funcs;
585 let saved_aliases = state.type_aliases.clone();
586 let closure = self::import::expand_import_closure(state, steps)?;
587 static_check::validate_script_closure(steps, &closure, state)?;
588 state.restore_aliases(saved_aliases);
589 let mut exported = Vec::new();
590 for file in &closure {
591 exported.extend(file.exports.types.iter().cloned());
592 }
593 Ok(exported)
594}
595
596#[allow(clippy::type_complexity)]
597fn finish_run<P: ProcessManager>(
598 mut state: ExecState<P>,
599 process: P,
600 steps: &[Step],
601) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
602 validate_closure_for_run(&mut state, steps)?;
603 let assert_windows = Arc::clone(&state.assert_windows);
604 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
605 let exact_stdout = Arc::clone(&state.exact_stdout);
606 let _default_stdout = std::io::stdout();
607 let stdin = state.io.stdin().into();
608 let stdout = Some(StreamHandle::Stream(teed_stdout(
612 state.io.stdout(),
613 assert_windows,
614 exact_stdout,
615 None,
616 )));
617 let stderr = state
618 .io
619 .stderr()
620 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
621 let mut proc_mgr = process;
622 let flow = execute_steps(
623 &mut state,
624 &mut proc_mgr,
625 steps,
626 stdin,
627 false,
628 stdout,
629 stderr,
630 None,
631 None,
632 true,
633 )?;
634 match flow {
635 self::steps::Flow::Done => {
640 let bindings: BTreeMap<String, Value> = state
645 .var_scopes
646 .first()
647 .map(|scope| {
648 scope
649 .iter()
650 .map(|(k, (_, v))| (k.clone(), v.clone()))
651 .collect()
652 })
653 .unwrap_or_default();
654 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
655 }
656 self::steps::Flow::Break { idx } => Err(anyhow::Error::new(
657 self::diagnostics::check_flow_outside_loop(idx + 1, KEYWORD_BREAK),
658 )),
659 self::steps::Flow::Continue { idx } => Err(anyhow::Error::new(
660 self::diagnostics::check_flow_outside_loop(idx + 1, KEYWORD_CONTINUE),
661 )),
662 self::steps::Flow::Return { idx, .. } => {
663 Err(anyhow::Error::new(self::diagnostics::check_return_outside(
667 idx + 1,
668 )))
669 }
670 }
671}