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