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_diag};
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 oxdock_diagnostics::{Diagnostic, DiagnosticResult};
74use oxdock_fs::{
75 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
76};
77use oxdock_parser::Step;
78use oxdock_parser::{KEYWORD_BREAK, KEYWORD_CONTINUE};
79use oxdock_process::{
80 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
81 default_process_manager,
82};
83
84use std::collections::BTreeMap;
85use std::sync::Arc;
86
87use self::fs_ops::describe_dir;
88use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
89use self::steps::execute_steps;
90
91pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
96
97pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
101
102pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> DiagnosticResult<()> {
112 run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
113}
114
115pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> DiagnosticResult<()> {
120 run_steps_with_context(fs_root, fs_root, steps)
121}
122
123pub fn run_steps_with_context(
124 fs_root: &GuardedPath,
125 build_context: &GuardedPath,
126 steps: &[Step],
127) -> DiagnosticResult<()> {
128 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
129}
130
131pub fn run_steps_with_context_result(
133 fs_root: &GuardedPath,
134 build_context: &GuardedPath,
135 steps: &[Step],
136 stdin: Option<SharedInput>,
137 stdout: Option<SharedOutput>,
138) -> DiagnosticResult<GuardedPath> {
139 let io = assemble_default_io(stdin, stdout);
140 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
141}
142
143pub fn run_steps_with_context_result_with_io(
144 fs_root: &GuardedPath,
145 build_context: &GuardedPath,
146 steps: &[Step],
147 io: ExecIo,
148) -> DiagnosticResult<GuardedPath> {
149 match run_steps_inner(fs_root, build_context, steps, io) {
150 Ok(final_cwd) => Ok(final_cwd),
151 Err(err) => {
152 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
153 let tree = describe_dir(&fs, fs_root, 2, 24);
154 let snapshot = format!(
155 "filesystem snapshot (root {}):\n{}",
156 fs_root.display(),
157 tree
158 );
159 Err(error_with_snapshot(err, snapshot))
160 }
161 }
162}
163
164fn error_with_snapshot(diag: Diagnostic, snapshot_section: String) -> Diagnostic {
168 diag.with_snapshot(&snapshot_section)
179}
180
181fn run_steps_inner(
182 fs_root: &GuardedPath,
183 build_context: &GuardedPath,
184 steps: &[Step],
185 io: ExecIo,
186) -> DiagnosticResult<GuardedPath> {
187 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
188 resolver.set_workspace_root(build_context.clone());
189 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
190}
191
192pub struct LazyRunOutput {
197 pub final_cwd: GuardedPath,
198 pub snapshot: Arc<LazyGuardedTempDir>,
199 pub fs: Box<dyn WorkspaceFs>,
200 pub bindings: BTreeMap<String, Value>,
205}
206
207pub fn run_steps_with_lazy_snapshot(
211 build_context: &GuardedPath,
212 steps: &[Step],
213 io: ExecIo,
214) -> DiagnosticResult<LazyRunOutput> {
215 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
216}
217
218pub fn run_steps_with_lazy_snapshot_and_modules(
223 build_context: &GuardedPath,
224 steps: &[Step],
225 io: ExecIo,
226 modules: Vec<HostModule<DefaultProcessManager>>,
227 types: Vec<&'static TypeDescriptor>,
228) -> DiagnosticResult<LazyRunOutput> {
229 run_steps_with_lazy_snapshot_and_modules_and_entry(
230 build_context,
231 steps,
232 io,
233 modules,
234 types,
235 None,
236 )
237}
238
239pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
243 build_context: &GuardedPath,
244 steps: &[Step],
245 io: ExecIo,
246 modules: Vec<HostModule<DefaultProcessManager>>,
247 types: Vec<&'static TypeDescriptor>,
248 entry_file: Option<GuardedPath>,
249) -> DiagnosticResult<LazyRunOutput> {
250 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
251 resolver.set_workspace_root(build_context.clone());
252 let snapshot = resolver.snapshot_handle();
253 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
254 match run_steps_with_manager_with_modules_and_entry(
255 fs,
256 steps,
257 default_process_manager(),
258 io,
259 modules,
260 types,
261 entry_file,
262 ) {
263 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
264 final_cwd,
265 snapshot,
266 fs,
267 bindings,
268 }),
269 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
270 }
271}
272
273pub fn enrich_lazy_error(
278 snapshot: &Arc<LazyGuardedTempDir>,
279 build_context: &GuardedPath,
280 err: Diagnostic,
281) -> Diagnostic {
282 match snapshot.get() {
283 Some(concrete) => {
284 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
285 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
286 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
287 };
288 let snapshot_msg = format!(
289 "filesystem snapshot (root {}):\n{}",
290 concrete.display(),
291 tree
292 );
293 error_with_snapshot(err, snapshot_msg)
294 }
295 None => error_with_snapshot(
296 err,
297 String::from(
298 "filesystem snapshot: never materialized (no snapshot directory was created)",
299 ),
300 ),
301 }
302}
303
304pub fn run_steps_with_fs(
305 fs: Box<dyn WorkspaceFs>,
306 steps: &[Step],
307 stdin: Option<SharedInput>,
308 stdout: Option<SharedOutput>,
309) -> DiagnosticResult<GuardedPath> {
310 let io = assemble_default_io(stdin, stdout);
311 run_steps_with_fs_with_io(fs, steps, io)
312}
313
314pub fn run_steps_with_fs_with_io(
315 fs: Box<dyn WorkspaceFs>,
316 steps: &[Step],
317 io: ExecIo,
318) -> DiagnosticResult<GuardedPath> {
319 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
320}
321
322pub(crate) use oxdock_parser::base_name;
327
328#[allow(clippy::type_complexity)]
336pub fn run_steps_with_manager<P: ProcessManager>(
337 fs: Box<dyn WorkspaceFs>,
338 steps: &[Step],
339 process: P,
340 io: ExecIo,
341) -> DiagnosticResult<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
342 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
343}
344
345#[allow(clippy::type_complexity)]
353pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
354 fs: Box<dyn WorkspaceFs>,
355 steps: &[Step],
356 process: P,
357 io: ExecIo,
358 modules: Vec<HostModule<P>>,
359 types: Vec<&'static self::typing::TypeDescriptor>,
360) -> DiagnosticResult<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
361 run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
362}
363
364#[allow(clippy::type_complexity)]
368#[allow(clippy::too_many_arguments)]
369pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
370 fs: Box<dyn WorkspaceFs>,
371 steps: &[Step],
372 process: P,
373 io: ExecIo,
374 modules: Vec<HostModule<P>>,
375 types: Vec<&'static self::typing::TypeDescriptor>,
376 entry_file: Option<GuardedPath>,
377) -> DiagnosticResult<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
378 let mut state = new_state(fs, io)?;
379 state.entry_file = entry_file;
380 state.module_table = build_module_table(&modules);
381 for module in &modules {
382 module.check_pre_run(steps)?;
385 }
386 for module in modules {
387 state.register_module(module);
388 }
389 for descriptor in types {
390 state.register_type(descriptor);
391 }
392 finish_run(state, process, steps)
393}
394
395pub(crate) fn new_state<P: ProcessManager>(
396 fs: Box<dyn WorkspaceFs>,
397 io: ExecIo,
398) -> DiagnosticResult<ExecState<P>> {
399 let cwd = fs.root().clone();
400 let build_context = fs.build_context().clone();
401 let cargo_scratch = reserve_cargo_scratch()?;
402 let seed = Arc::new(oxdock_process::seed_defaults());
407 let mut envs = (*seed).clone();
408 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
409 for (key, value) in io.inherit_env_overrides() {
410 envs.insert(key.clone(), value.clone());
411 }
412 let envs = Arc::new(envs);
413 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
414 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
415 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
416 let worker_counter = io.worker_counter();
419 let entry_seed_envs = (*seed).clone();
420 let entry_cwd = cwd.clone();
421 let mut state = ExecState {
422 fs,
423 cargo_scratch,
424 seed,
425 cwd: cwd.clone(),
426 envs,
427 bg_children: Vec::new(),
428 scope_stack: Vec::new(),
429 isolated_stack: Vec::new(),
430 io,
431 assert_windows: assert_windows.clone(),
432 assert_windows_stderr: assert_windows_stderr.clone(),
433 exact_stdout: exact_stdout.clone(),
434 var_scopes: Vec::new(),
435 const_scopes: Vec::new(),
436 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
437 cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
438 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
439 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
440 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
441 live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
442 inside_async: false,
443 keeper_expiry: None,
444 cancellable: false,
445 reap_floor: None,
446 functions: self::native::FunctionRegistry::with_builtins(),
447 entry_file: None,
448 import_stack: Vec::new(),
449 executed_alias_targets: std::collections::HashMap::new(),
450 call_alias_frames: Vec::new(),
451 scope_alias_frames: Vec::new(),
452 init_scope_depths: Vec::new(),
453 func_floors: Vec::new(),
454 harvest_map: std::collections::HashMap::new(),
455 modules: std::collections::HashMap::from([(
456 self::import::ENTRY_UNIT.to_string(),
457 self::state::ModuleRecord::entry_record(entry_seed_envs, entry_cwd),
458 )]),
459 validated_modules: std::collections::HashSet::new(),
460 module_stack: Vec::new(),
461 module_table: self::native::std_module_table(),
462 types: self::typing::startup_type_map(),
463 record_schemas: std::collections::HashMap::new(),
464 module_states: std::collections::HashMap::new(),
465 type_aliases: std::collections::HashMap::new(),
466 type_env_digest: 0,
467 call_depth: 0,
468 init_inherit_stack: Vec::new(),
469 task_id: 0,
471 push_manifest: Vec::new(),
472 _marker: std::marker::PhantomData,
473 };
474
475 state.push_var_scope();
477
478 Ok(state)
479}
480
481fn build_module_table<P: ProcessManager>(
486 modules: &[self::native::HostModule<P>],
487) -> oxdock_parser::ModuleTable {
488 let mut table = self::native::std_module_table();
489 for module in modules {
490 let mut func_names = std::collections::HashSet::new();
491 for registration in &module.funcs {
492 let name = match registration {
493 self::native::HostRegistration::Stateful { name, .. } => name,
494 self::native::HostRegistration::Pure { name, .. } => name,
495 self::native::HostRegistration::Both { name, .. } => name,
496 };
497 func_names.insert(name.clone());
498 }
499 table.modules.insert(
500 module.name.clone(),
501 Some(oxdock_parser::ModuleFuncs { func_names }),
502 );
503 }
504 table
505}
506
507pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
514 fs: Box<dyn WorkspaceFs>,
515 steps: &[Step],
516 modules: Vec<HostModule<P>>,
517 types: Vec<&'static TypeDescriptor>,
518 entry_file: Option<GuardedPath>,
519) -> DiagnosticResult<()> {
520 let mut state = new_state(fs, ExecIo::new())?;
521 state.entry_file = entry_file;
522 state.module_table = build_module_table(&modules);
523 for module in modules {
524 state.register_module(module);
525 }
526 for descriptor in types {
527 state.register_type(descriptor);
528 }
529 validate_closure_for_run(&mut state, steps).map(|_| ())
530}
531
532pub fn validate_closure_for_run<P: ProcessManager>(
540 state: &mut ExecState<P>,
541 steps: &[Step],
542) -> DiagnosticResult<Vec<String>> {
543 state.restore_aliases(self::typing::collect_type_aliases(steps, state)?);
544 state.validate_function_type_tags()?;
545 let top_funcs = self::import::collect_top_funcs(steps);
553 let entry_record = state
557 .modules
558 .entry(self::import::ENTRY_UNIT.to_string())
559 .or_default();
560 entry_record.steps = steps.to_vec();
561 entry_record.top_funcs = top_funcs;
562 let saved_aliases = state.type_aliases.clone();
563 let closure = self::import::expand_import_closure(state, steps)?;
564 static_check::validate_script_closure(steps, &closure, state)?;
565 state.restore_aliases(saved_aliases);
566 let mut exported = Vec::new();
567 for file in &closure {
568 exported.extend(file.exports.types.iter().cloned());
569 }
570 Ok(exported)
571}
572
573#[allow(clippy::type_complexity)]
574fn finish_run<P: ProcessManager>(
575 mut state: ExecState<P>,
576 process: P,
577 steps: &[Step],
578) -> DiagnosticResult<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
579 validate_closure_for_run(&mut state, steps)?;
580 let assert_windows = Arc::clone(&state.assert_windows);
581 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
582 let exact_stdout = Arc::clone(&state.exact_stdout);
583 let _default_stdout = std::io::stdout();
584 let stdin = state.io.stdin().into();
585 let stdout = Some(StreamHandle::Stream(teed_stdout(
589 state.io.stdout(),
590 assert_windows,
591 exact_stdout,
592 None,
593 )));
594 let stderr = state
595 .io
596 .stderr()
597 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
598 let mut proc_mgr = process;
599 let flow = execute_steps(
600 &mut state,
601 &mut proc_mgr,
602 steps,
603 stdin,
604 false,
605 stdout,
606 stderr,
607 None,
608 None,
609 true,
610 )?;
611 match flow {
612 self::steps::Flow::Done => {
617 let bindings: BTreeMap<String, Value> = state
622 .var_scopes
623 .first()
624 .map(|scope| {
625 scope
626 .iter()
627 .map(|(k, (_, v))| (k.clone(), v.clone()))
628 .collect()
629 })
630 .unwrap_or_default();
631 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
632 }
633 self::steps::Flow::Break { idx } => Err(self::diagnostics::check_flow_outside_loop(
634 idx + 1,
635 KEYWORD_BREAK,
636 )),
637 self::steps::Flow::Continue { idx } => Err(self::diagnostics::check_flow_outside_loop(
638 idx + 1,
639 KEYWORD_CONTINUE,
640 )),
641 self::steps::Flow::Return { idx, .. } => {
642 Err(self::diagnostics::check_return_outside(idx + 1))
646 }
647 }
648}