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