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 AliasTarget, AliasTargets, FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule,
57 HostRegistration, NativeFn, OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable,
58 RecordSchema, builtin_function_metas, builtin_function_names, check_script_param_tags,
59 fill_optional_args, optional_zero_value, placeholder_resolver, required_arity,
60 resolve_script_params, resolve_script_params_for_unit, resolve_script_params_with_targets,
61 std_module_table,
62};
63pub use self::state::{
64 ExecState, HostTypeEntry, MAX_RUNNING_TASKS, RecordSchemaEntry, TypeRegistry, TypeSnapshot,
65 const_mutation_error,
66};
67pub use self::static_check::check_exact_tags;
68pub use self::steps::StepCtx;
69pub use self::typing::{
70 Field, HarvestRequest, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value,
71 ValuePayload, build_unit_tables, check_options, check_value, check_value_at, clone_boxed,
72 clone_copy, clone_shared, collect_type_aliases, drop_boxed, drop_noop, drop_shared, eq_boxed,
73 eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared, load_inline, startup_descriptors,
74 store_inline, type_anchor, unshare_boxed, unshare_inline, unshare_shared,
75};
76
77use oxdock_diagnostics::{Diagnostic, DiagnosticResult};
78use oxdock_fs::{
79 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
80};
81use oxdock_parser::Step;
82use oxdock_parser::{KEYWORD_BREAK, KEYWORD_CONTINUE};
83use oxdock_process::{
84 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
85 default_process_manager,
86};
87
88use std::collections::BTreeMap;
89use std::sync::Arc;
90
91use self::fs_ops::describe_dir;
92use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
93use self::steps::execute_steps;
94
95pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
100
101pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
105
106pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> DiagnosticResult<()> {
116 run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
117}
118
119pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> DiagnosticResult<()> {
124 run_steps_with_context(fs_root, fs_root, steps)
125}
126
127pub fn run_steps_with_context(
128 fs_root: &GuardedPath,
129 build_context: &GuardedPath,
130 steps: &[Step],
131) -> DiagnosticResult<()> {
132 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
133}
134
135pub fn run_steps_with_context_result(
137 fs_root: &GuardedPath,
138 build_context: &GuardedPath,
139 steps: &[Step],
140 stdin: Option<SharedInput>,
141 stdout: Option<SharedOutput>,
142) -> DiagnosticResult<GuardedPath> {
143 let io = assemble_default_io(stdin, stdout);
144 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
145}
146
147pub fn run_steps_with_context_result_with_io(
148 fs_root: &GuardedPath,
149 build_context: &GuardedPath,
150 steps: &[Step],
151 io: ExecIo,
152) -> DiagnosticResult<GuardedPath> {
153 match run_steps_inner(fs_root, build_context, steps, io) {
154 Ok(final_cwd) => Ok(final_cwd),
155 Err(err) => {
156 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
157 let tree = describe_dir(&fs, fs_root, 2, 24);
158 let snapshot = format!(
159 "filesystem snapshot (root {}):\n{}",
160 fs_root.display(),
161 tree
162 );
163 Err(error_with_snapshot(err, snapshot))
164 }
165 }
166}
167
168fn error_with_snapshot(diag: Diagnostic, snapshot_section: String) -> Diagnostic {
172 diag.with_snapshot(&snapshot_section)
183}
184
185fn run_steps_inner(
186 fs_root: &GuardedPath,
187 build_context: &GuardedPath,
188 steps: &[Step],
189 io: ExecIo,
190) -> DiagnosticResult<GuardedPath> {
191 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
192 resolver.set_workspace_root(build_context.clone());
193 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
194}
195
196pub struct LazyRunOutput {
201 pub final_cwd: GuardedPath,
202 pub snapshot: Arc<LazyGuardedTempDir>,
203 pub fs: Box<dyn WorkspaceFs>,
204 pub bindings: BTreeMap<String, Value>,
209}
210
211pub fn run_steps_with_lazy_snapshot(
215 build_context: &GuardedPath,
216 steps: &[Step],
217 io: ExecIo,
218) -> DiagnosticResult<LazyRunOutput> {
219 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
220}
221
222pub fn run_steps_with_lazy_snapshot_and_modules(
227 build_context: &GuardedPath,
228 steps: &[Step],
229 io: ExecIo,
230 modules: Vec<HostModule<DefaultProcessManager>>,
231 types: Vec<&'static TypeDescriptor>,
232) -> DiagnosticResult<LazyRunOutput> {
233 run_steps_with_lazy_snapshot_and_modules_and_entry(
234 build_context,
235 steps,
236 io,
237 modules,
238 types,
239 None,
240 )
241}
242
243pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
247 build_context: &GuardedPath,
248 steps: &[Step],
249 io: ExecIo,
250 modules: Vec<HostModule<DefaultProcessManager>>,
251 types: Vec<&'static TypeDescriptor>,
252 entry_file: Option<GuardedPath>,
253) -> DiagnosticResult<LazyRunOutput> {
254 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
255 resolver.set_workspace_root(build_context.clone());
256 let snapshot = resolver.snapshot_handle();
257 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
258 match run_steps_with_manager_with_modules_and_entry(
259 fs,
260 steps,
261 default_process_manager(),
262 io,
263 modules,
264 types,
265 entry_file,
266 ) {
267 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
268 final_cwd,
269 snapshot,
270 fs,
271 bindings,
272 }),
273 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
274 }
275}
276
277pub fn enrich_lazy_error(
282 snapshot: &Arc<LazyGuardedTempDir>,
283 build_context: &GuardedPath,
284 err: Diagnostic,
285) -> Diagnostic {
286 match snapshot.get() {
287 Some(concrete) => {
288 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
289 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
290 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
291 };
292 let snapshot_msg = format!(
293 "filesystem snapshot (root {}):\n{}",
294 concrete.display(),
295 tree
296 );
297 error_with_snapshot(err, snapshot_msg)
298 }
299 None => error_with_snapshot(
300 err,
301 String::from(
302 "filesystem snapshot: never materialized (no snapshot directory was created)",
303 ),
304 ),
305 }
306}
307
308pub fn run_steps_with_fs(
309 fs: Box<dyn WorkspaceFs>,
310 steps: &[Step],
311 stdin: Option<SharedInput>,
312 stdout: Option<SharedOutput>,
313) -> DiagnosticResult<GuardedPath> {
314 let io = assemble_default_io(stdin, stdout);
315 run_steps_with_fs_with_io(fs, steps, io)
316}
317
318pub fn run_steps_with_fs_with_io(
319 fs: Box<dyn WorkspaceFs>,
320 steps: &[Step],
321 io: ExecIo,
322) -> DiagnosticResult<GuardedPath> {
323 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
324}
325
326pub(crate) use oxdock_parser::base_name;
331
332#[allow(clippy::type_complexity)]
340pub fn run_steps_with_manager<P: ProcessManager>(
341 fs: Box<dyn WorkspaceFs>,
342 steps: &[Step],
343 process: P,
344 io: ExecIo,
345) -> DiagnosticResult<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
346 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
347}
348
349#[allow(clippy::type_complexity)]
357pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
358 fs: Box<dyn WorkspaceFs>,
359 steps: &[Step],
360 process: P,
361 io: ExecIo,
362 modules: Vec<HostModule<P>>,
363 types: Vec<&'static self::typing::TypeDescriptor>,
364) -> DiagnosticResult<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
365 run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
366}
367
368#[allow(clippy::type_complexity)]
372#[allow(clippy::too_many_arguments)]
373pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
374 fs: Box<dyn WorkspaceFs>,
375 steps: &[Step],
376 process: P,
377 io: ExecIo,
378 modules: Vec<HostModule<P>>,
379 types: Vec<&'static self::typing::TypeDescriptor>,
380 entry_file: Option<GuardedPath>,
381) -> DiagnosticResult<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
382 let mut state = new_state(fs, io)?;
383 state.entry_file = entry_file;
384 state.module_table = build_module_table(&modules);
385 for module in &modules {
386 module.check_pre_run(steps)?;
389 }
390 for module in modules {
391 state.register_module(module);
392 }
393 for descriptor in types {
394 state.register_type(descriptor);
395 }
396 finish_run(state, process, steps)
397}
398
399pub(crate) fn new_state<P: ProcessManager>(
400 fs: Box<dyn WorkspaceFs>,
401 io: ExecIo,
402) -> DiagnosticResult<ExecState<P>> {
403 let cwd = fs.root().clone();
404 let build_context = fs.build_context().clone();
405 let cargo_scratch = reserve_cargo_scratch()?;
406 let seed = Arc::new(oxdock_process::seed_defaults());
411 let mut envs = (*seed).clone();
412 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
413 for (key, value) in io.inherit_env_overrides() {
414 envs.insert(key.clone(), value.clone());
415 }
416 let envs = Arc::new(envs);
417 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
418 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
419 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
420 let worker_counter = io.worker_counter();
423 let entry_seed_envs = (*seed).clone();
424 let entry_cwd = cwd.clone();
425 let mut state = ExecState {
426 fs,
427 cargo_scratch,
428 seed,
429 cwd: cwd.clone(),
430 envs,
431 bg_children: Vec::new(),
432 scope_stack: Vec::new(),
433 isolated_stack: Vec::new(),
434 io,
435 assert_windows: assert_windows.clone(),
436 assert_windows_stderr: assert_windows_stderr.clone(),
437 exact_stdout: exact_stdout.clone(),
438 var_scopes: Vec::new(),
439 const_scopes: Vec::new(),
440 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
441 cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
442 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
443 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
444 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
445 live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
446 inside_async: false,
447 keeper_expiry: None,
448 cancellable: false,
449 reap_floor: None,
450 functions: self::native::FunctionRegistry::with_builtins(),
451 entry_file: None,
452 import_stack: Vec::new(),
453 executed_alias_targets: std::collections::HashMap::new(),
454 call_alias_frames: Vec::new(),
455 scope_alias_frames: Vec::new(),
456 init_scope_depths: Vec::new(),
457 func_floors: Vec::new(),
458 harvest_map: std::collections::HashMap::new(),
459 modules: std::collections::HashMap::from([(
460 self::import::ENTRY_UNIT.to_string(),
461 self::state::ModuleRecord::entry_record(entry_seed_envs, entry_cwd),
462 )]),
463 validated_modules: std::collections::HashSet::new(),
464 module_stack: Vec::new(),
465 module_table: self::native::std_module_table(),
466 type_env: self::state::TypeSnapshot::new(),
467 module_states: std::collections::HashMap::new(),
468 call_depth: 0,
469 init_inherit_stack: Vec::new(),
470 task_id: 0,
472 push_manifest: Vec::new(),
473 _marker: std::marker::PhantomData,
474 };
475
476 state.push_var_scope();
478
479 Ok(state)
480}
481
482fn build_module_table<P: ProcessManager>(
487 modules: &[self::native::HostModule<P>],
488) -> oxdock_parser::ModuleTable {
489 let mut table = self::native::std_module_table();
490 for module in modules {
491 let mut func_names = std::collections::HashSet::new();
492 for registration in &module.funcs {
493 let name = match registration {
494 self::native::HostRegistration::Stateful { name, .. } => name,
495 self::native::HostRegistration::Pure { name, .. } => name,
496 self::native::HostRegistration::Both { name, .. } => name,
497 };
498 func_names.insert(name.clone());
499 }
500 table.modules.insert(
501 module.name.clone(),
502 Some(oxdock_parser::ModuleFuncs { func_names }),
503 );
504 }
505 table
506}
507
508pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
515 fs: Box<dyn WorkspaceFs>,
516 steps: &[Step],
517 modules: Vec<HostModule<P>>,
518 types: Vec<&'static TypeDescriptor>,
519 entry_file: Option<GuardedPath>,
520) -> DiagnosticResult<()> {
521 let mut state = new_state(fs, ExecIo::new())?;
522 state.entry_file = entry_file;
523 state.module_table = build_module_table(&modules);
524 for module in modules {
525 state.register_module(module);
526 }
527 for descriptor in types {
528 state.register_type(descriptor);
529 }
530 validate_closure_for_run(&mut state, steps).map(|_| ())
531}
532
533pub fn validate_closure_for_run<P: ProcessManager>(
541 state: &mut ExecState<P>,
542 steps: &[Step],
543) -> DiagnosticResult<Vec<String>> {
544 let aliases = self::typing::collect_type_aliases(steps, &state.type_env)?;
545 state.restore_aliases(aliases);
546 state.validate_function_type_tags()?;
547 let top_funcs = self::import::collect_top_funcs(steps);
555 let entry_record = state
559 .modules
560 .entry(self::import::ENTRY_UNIT.to_string())
561 .or_default();
562 entry_record.steps = steps.to_vec();
563 entry_record.top_funcs = top_funcs;
564 let saved_aliases = state.type_env.type_aliases.clone();
565 let closure = self::import::expand_import_closure(state, steps)?;
566 static_check::validate_script_closure(steps, &closure, state)?;
567 state.restore_aliases(saved_aliases);
568 let mut exported = Vec::new();
569 for file in &closure {
570 exported.extend(file.exports.types.iter().cloned());
571 }
572 Ok(exported)
573}
574
575#[allow(clippy::type_complexity)]
576fn finish_run<P: ProcessManager>(
577 mut state: ExecState<P>,
578 process: P,
579 steps: &[Step],
580) -> DiagnosticResult<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
581 validate_closure_for_run(&mut state, steps)?;
582 let assert_windows = Arc::clone(&state.assert_windows);
583 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
584 let exact_stdout = Arc::clone(&state.exact_stdout);
585 let _default_stdout = std::io::stdout();
586 let stdin = state.io.stdin().into();
587 let stdout = Some(StreamHandle::Stream(teed_stdout(
591 state.io.stdout(),
592 assert_windows,
593 exact_stdout,
594 None,
595 )));
596 let stderr = state
597 .io
598 .stderr()
599 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
600 let mut proc_mgr = process;
601 let flow = execute_steps(
602 &mut state,
603 &mut proc_mgr,
604 steps,
605 stdin,
606 false,
607 stdout,
608 stderr,
609 None,
610 None,
611 true,
612 )?;
613 match flow {
614 self::steps::Flow::Done => {
619 let bindings: BTreeMap<String, Value> = state
624 .var_scopes
625 .first()
626 .map(|scope| {
627 scope
628 .iter()
629 .map(|(k, (_, v))| (k.clone(), v.clone()))
630 .collect()
631 })
632 .unwrap_or_default();
633 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
634 }
635 self::steps::Flow::Break { idx } => Err(self::diagnostics::check_flow_outside_loop(
636 idx + 1,
637 KEYWORD_BREAK,
638 )),
639 self::steps::Flow::Continue { idx } => Err(self::diagnostics::check_flow_outside_loop(
640 idx + 1,
641 KEYWORD_CONTINUE,
642 )),
643 self::steps::Flow::Return { idx, .. } => {
644 Err(self::diagnostics::check_return_outside(idx + 1))
648 }
649 }
650}