1use anyhow::{Context, Result, bail};
2use oxdock_fs::{
3 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, discover_workspace_root,
4 env as oxdock_env, init_temp_gc,
5};
6#[cfg(windows)]
7use oxdock_process::CommandBuilder;
8use oxdock_process::{DefaultProcessManager, SharedInput};
9use std::env;
10use std::io::{self, IsTerminal, Read};
11use std::sync::{Arc, Mutex};
12
13use oxdock_core::ExecIo;
14pub use oxdock_core::{
15 Engine, EngineOutput, ExecState, ExitRequest, FuncKind, FuncMeta, FuncParam, HostModule,
16 HostRegistration, NativeFn, OxDockFn, OxDockType, PureFn, PushManifestSink, StepCtx,
17 TypeDescriptor, Value, dry_run_closure, exit_code_of, parse_script, parse_script_with_modules,
18 run_steps, run_steps_with_context, run_steps_with_context_result,
19 run_steps_with_lazy_snapshot_and_modules_and_entry, run_steps_with_manager_with_modules,
20 run_steps_with_manager_with_modules_and_entry, run_steps_without_snapshot,
21};
22pub use oxdock_parser::{Guard, Step, StepKind};
23pub use oxdock_process::shell_program;
24use std::collections::BTreeMap;
25
26mod endpoints;
27pub use endpoints::EndpointFlags;
28#[cfg(feature = "mcp")]
29mod mcp;
30
31use oxdock_macros::oxdock_embed;
36oxdock_embed! {
37 name: UsageAssets,
38 script: {
39 INHERIT_ENV [CARGO_PKG_VERSION, CARGO_PKG_DESCRIPTION]
40 FUNC EMIT_BODY($is_net: BOOL) {
41 LET $net_flags: STRING = """
42 --offline open no sockets (endpoint flags require the `net` feature)
43 """
44
45 LET $tail: STRING = """
46 Endpoint flags (--listen/-p) require the `net` feature (rebuild with --features net).
47 """
48
49 IF $is_net {
50 $net_flags = """
51 --listen <addr> expose a logical service port ([host:]port, repeatable)
52 -p <[host:]outer:inner> map outer port to an inner service port or name (repeatable; outer 0 is ephemeral; bare outer binds loopback, prefix 0.0.0.0: for all interfaces)
53 --offline open no sockets (conflicts with --listen/-p)
54 --remote TARGET=CMD bind a REMOTE target to a stdio transport command (repeatable)
55 """
56 $tail = "Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces."
57 }
58
59 ECHO """
60 oxdock {{ env:CARGO_PKG_VERSION }} — {{ env:CARGO_PKG_DESCRIPTION }}
61
62 Usage: oxdock [OPTIONS] [SCRIPT]
63 SCRIPT script file path (same as `--script <file>`); `-` reads stdin
64 --script <file|-> script file (relative resolves under the OxDock workspace root), or `-` for stdin
65 --shell run the script, then drop into an interactive shell (requires a TTY)
66 --dry-run print the transitive import closure (file:line CMD) instead of running
67 --mcp serve EXPORTed FUNCs as MCP tools over stdio (requires the `mcp` feature)
68 {{ $net_flags }}
69 --help, -h print this help and exit
70 --version, -V print the version and exit
71
72 With no script given, reads the script from stdin (must be piped unless `--shell`).
73 {{ $tail }}
74 """
75 }
76
77 LET $p: PIPE
78 WITH_IO [stdout=$p] {
79 EMIT_BODY(true)
80 }
81 WITH_IO [stdin=$p] WRITE dist/usage-net.txt
82 WITH_IO [stdout=$p] {
83 EMIT_BODY(false)
84 }
85 WITH_IO [stdin=$p] WRITE dist/usage-lean.txt
86 },
87 out_dir: "usage-prebuilt",
88}
89#[cfg(feature = "net")]
90pub use endpoints::build_registry;
91#[cfg(feature = "net")]
92use oxdock_net_plugin::EndpointRegistry;
93#[cfg(feature = "net")]
94mod serve;
95
96fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
105 cli_host_modules_with(None)
106}
107
108#[cfg(feature = "net")]
112fn cli_host_modules_for_serve() -> Vec<HostModule<DefaultProcessManager>> {
113 cli_host_modules_with(None)
114}
115
116#[cfg(feature = "net")]
119fn remote_session_module_hash(entries: &[(String, Vec<String>)]) -> String {
120 oxdock_net_plugin::module_hash(entries)
121}
122
123fn cli_host_modules_with(
130 #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
131 #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
132) -> Vec<HostModule<DefaultProcessManager>> {
133 #[cfg(any(feature = "net", feature = "markdown"))]
134 let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
135 #[cfg(not(any(feature = "net", feature = "markdown")))]
136 let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
137 #[cfg(feature = "net")]
138 {
139 let net_module = match registry {
140 Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
141 None => oxdock_net_plugin::module(),
142 };
143 modules.push(net_module);
144 #[cfg(feature = "ssh")]
145 {
146 let ssh_module = match registry {
147 Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
148 None => oxdock_ssh_plugin::module(),
149 };
150 modules.push(ssh_module);
151 }
152 }
153 #[cfg(feature = "markdown")]
154 modules.push(oxdock_markdown_plugin::module());
155 let _ = registry;
156 modules
157}
158
159fn cli_host_types() -> Vec<&'static TypeDescriptor> {
161 #[cfg(feature = "net")]
162 let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
163 #[cfg(not(feature = "net"))]
164 let net: &[&'static TypeDescriptor] = &[];
165 #[cfg(feature = "ssh")]
166 let ssh: &[&'static TypeDescriptor] = &[
167 oxdock_ssh_plugin::SshServerTag::descriptor(),
168 oxdock_ssh_plugin::SshSessionTag::descriptor(),
169 ];
170 #[cfg(not(feature = "ssh"))]
171 let ssh: &[&'static TypeDescriptor] = &[];
172 net.iter().chain(ssh.iter()).copied().collect()
173}
174
175fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
179 parse_script_with_modules(script, cli_module_table())
180}
181
182fn cli_module_table() -> oxdock_parser::ModuleTable {
185 let modules = cli_host_modules();
186 if modules.is_empty() {
187 return oxdock_core::std_module_table();
188 }
189 let mut engine = Engine::new();
190 for module in modules {
191 engine.register_module(module);
192 }
193 engine.module_table()
194}
195
196fn entry_file_of(script: &ScriptSource) -> Option<GuardedPath> {
199 match script {
200 ScriptSource::Path(path) => Some(path.clone()),
201 ScriptSource::Stdin => None,
202 }
203}
204
205fn print_dry_run(
209 steps: &[Step],
210 script: &ScriptSource,
211 workspace_root: &GuardedPath,
212) -> Result<()> {
213 let table = cli_module_table();
214 let (label, base) = match script {
215 ScriptSource::Path(path) => (
216 path.display(),
217 path.parent().unwrap_or_else(|| workspace_root.clone()),
218 ),
219 ScriptSource::Stdin => ("<stdin>".to_string(), workspace_root.clone()),
220 };
221 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
222 let listing = dry_run_closure(steps, &label, &base, &resolver, &table)?;
223 for item in listing {
224 println!("{}:{} {}", item.file, item.step.line, item.step.kind);
225 }
226 Ok(())
227}
228
229pub fn run() -> Result<()> {
230 init_temp_gc();
231 let workspace_root = discover_workspace_root().context("guard workspace root")?;
232
233 let mut args = std::env::args().skip(1);
234 let opts = match Options::parse(&mut args, &workspace_root) {
238 Ok(opts) => opts,
239 Err(err) if err.to_string() == version() => {
240 println!("{err}");
241 return Ok(());
242 }
243 Err(err) if err.to_string() == usage() => {
244 print!("{err}");
245 return Ok(());
246 }
247 Err(err) => return Err(err),
248 };
249 #[cfg(feature = "net")]
252 if opts.remote_serve {
253 if opts.shell || !opts.remotes.is_empty() || !matches!(opts.script, ScriptSource::Stdin) {
254 bail!("--remote-serve runs alone (no --script, --shell, or --remote)");
255 }
256 return serve::serve();
257 }
258 #[cfg(not(feature = "net"))]
259 if opts.remote_serve {
260 bail!("--remote-serve requires the `net` feature (rebuild with --features net)");
261 }
262 if opts.mcp {
265 #[cfg(feature = "mcp")]
266 {
267 if opts.shell || opts.remote_serve || !opts.remotes.is_empty() {
268 bail!("--mcp runs alone (no --shell, --remote-serve, or --remote)");
269 }
270 if !opts.endpoints.listens.is_empty() || !opts.endpoints.publishes.is_empty() {
271 bail!("--mcp runs alone (no --listen/-p)");
272 }
273 if opts.dry_run {
274 bail!("--mcp runs alone (no --dry-run)");
275 }
276 return mcp::serve_mcp(opts, workspace_root);
277 }
278 #[cfg(not(feature = "mcp"))]
279 {
280 bail!("--mcp requires the `mcp` feature (rebuild with --features mcp)");
281 }
282 }
283 execute(opts, workspace_root)
284}
285
286pub fn process_exit_code(err: &anyhow::Error) -> i32 {
290 exit_code_of(err)
291 .map(|code| code.clamp(0, 255) as i32)
292 .unwrap_or(1)
293}
294
295#[derive(Debug, Clone)]
296pub enum ScriptSource {
297 Path(GuardedPath),
298 Stdin,
299}
300
301fn reject_url_script(text: &str) -> Result<()> {
305 if text.contains("://") {
306 bail!("not a local path: {text:?} (pass a workspace path or `-` for stdin)");
307 }
308 Ok(())
309}
310
311#[derive(Debug, Clone)]
312pub struct Options {
313 pub script: ScriptSource,
314 pub shell: bool,
315 pub dry_run: bool,
318 pub endpoints: EndpointFlags,
319 pub remote_serve: bool,
320 pub mcp: bool,
323 pub remotes: Vec<(String, String)>,
326}
327
328impl Options {
329 pub fn parse(
330 args: &mut impl Iterator<Item = String>,
331 workspace_root: &GuardedPath,
332 ) -> Result<Self> {
333 use lexopt::Arg::{Long, Short, Value};
334
335 let mut script: Option<ScriptSource> = None;
336 let mut shell = false;
337 let mut dry_run = false;
338 let mut endpoints = EndpointFlags::default();
339 let mut remote_serve = false;
340 let mut mcp = false;
341 #[cfg_attr(not(feature = "net"), allow(unused_mut))]
343 let mut remotes: Vec<(String, String)> = Vec::new();
344 let mut set_script = |source: ScriptSource, origin: &str| -> Result<()> {
345 if script.is_some() {
346 bail!("script given multiple times ({origin})");
347 }
348 script = Some(source);
349 Ok(())
350 };
351 let mut parser = lexopt::Parser::from_args(args.by_ref());
356 while let Some(arg) = parser.next()? {
357 match arg {
358 Long("script") => {
359 let path = value_string(
360 parser
361 .value()
362 .map_err(|_| anyhow::anyhow!("--script requires a path"))?,
363 )?;
364 if path.is_empty() {
365 bail!("--script requires a path");
366 }
367 if path == "-" {
368 set_script(ScriptSource::Stdin, "--script -")?;
369 } else {
370 reject_url_script(&path)?;
371 set_script(
372 ScriptSource::Path(
373 workspace_root
374 .join_script(&path)
375 .with_context(|| format!("guard script path {path}"))?,
376 ),
377 "--script",
378 )?;
379 }
380 }
381 Long("shell") => {
382 shell = true;
383 }
384 Long("dry-run") => {
385 dry_run = true;
386 }
387 Long("listen") => {
388 let raw = value_string(
389 parser
390 .value()
391 .map_err(|_| anyhow::anyhow!("--listen requires an address"))?,
392 )?;
393 #[cfg(not(feature = "net"))]
394 {
395 let _ = endpoints::parse_listen_arg(&raw);
399 bail!(
400 "--listen/-p require the `net` feature (rebuild with --features net)"
401 );
402 }
403 #[cfg(feature = "net")]
404 endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
405 }
406 Short('p') => {
407 let raw = value_string(
408 parser
409 .value()
410 .map_err(|_| anyhow::anyhow!("-p requires outer:inner"))?,
411 )?;
412 #[cfg(not(feature = "net"))]
413 {
414 let _ = endpoints::parse_publish_arg(&raw);
418 bail!(
419 "--listen/-p require the `net` feature (rebuild with --features net)"
420 );
421 }
422 #[cfg(feature = "net")]
423 endpoints
424 .publishes
425 .push(endpoints::parse_publish_arg(&raw)?);
426 }
427 Long("offline") => {
428 endpoints.offline = true;
429 }
430 Long("remote-serve") => {
431 remote_serve = true;
432 }
433 Long("mcp") => {
434 mcp = true;
435 }
436 Long("remote") => {
437 let raw = value_string(parser.value().map_err(|_| {
438 anyhow::anyhow!("--remote requires <target>=\"<command>\"")
439 })?)?;
440 #[cfg(not(feature = "net"))]
441 {
442 let _ = oxdock_net_plugin_stub_parse_remote(&raw);
445 bail!("--remote requires the `net` feature (rebuild with --features net)");
446 }
447 #[cfg(feature = "net")]
448 remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
449 }
450 Long("help") | Short('h') => {
451 bail!("{}", usage());
452 }
453 Long("version") | Short('V') => {
454 bail!("{}", version());
455 }
456 Value(value) => {
457 let text = value_string(value)?;
458 if text.is_empty() {
459 continue;
460 }
461 if text == "-" {
462 set_script(ScriptSource::Stdin, "positional `-`")?;
463 } else {
464 reject_url_script(&text)?;
465 set_script(
466 ScriptSource::Path(
467 workspace_root
468 .join_script(&text)
469 .with_context(|| format!("guard script path {text}"))?,
470 ),
471 "positional argument",
472 )?;
473 }
474 }
475 Long(other) => bail!("unexpected flag: --{other}"),
476 Short(other) => bail!("unexpected flag: -{other}"),
477 }
478 }
479
480 let script = script.unwrap_or(ScriptSource::Stdin);
481
482 Ok(Self {
483 script,
484 shell,
485 dry_run,
486 endpoints,
487 remote_serve,
488 mcp,
489 remotes,
490 })
491 }
492}
493
494fn value_string(value: std::ffi::OsString) -> Result<String> {
497 value
498 .into_string()
499 .map_err(|_| anyhow::anyhow!("argument must be UTF-8"))
500}
501
502pub fn version() -> String {
504 format!("oxdock {}", env!("CARGO_PKG_VERSION"))
505}
506
507pub fn usage() -> String {
513 #[cfg(feature = "net")]
514 let asset = "dist/usage-net.txt";
515 #[cfg(not(feature = "net"))]
516 let asset = "dist/usage-lean.txt";
517 let file = UsageAssets::get(asset).expect("usage must be embedded");
518 str::from_utf8(file.data.as_ref())
519 .expect("usage is UTF-8")
520 .to_string()
521}
522
523pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
524 init_temp_gc();
525 execute_with_shell_runner(opts, workspace_root, run_shell, true)
526}
527
528pub struct ExecutionResult {
536 pub snapshot: Arc<LazyGuardedTempDir>,
540 pub final_cwd: GuardedPath,
543 pub bindings: BTreeMap<String, Value>,
547}
548
549impl ExecutionResult {
550 pub fn has_snapshot(&self) -> bool {
552 self.snapshot.is_materialized()
553 }
554
555 pub fn snapshot_path(&self) -> Option<&GuardedPath> {
557 self.snapshot.get()
558 }
559}
560
561pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
562 if opts.shell {
563 bail!("execute_with_result does not support --shell");
564 }
565
566 let script = read_script(&opts.script)?;
569
570 let mut final_cwd = workspace_root.clone();
571 let snapshot = Arc::new(LazyGuardedTempDir::new());
572 if !script.trim().is_empty() {
573 let steps = parse_cli_script(&script)?;
574 if opts.dry_run {
577 print_dry_run(&steps, &opts.script, &workspace_root)?;
578 return Ok(ExecutionResult {
579 snapshot,
580 final_cwd,
581 bindings: BTreeMap::new(),
582 });
583 }
584 #[cfg(feature = "net")]
587 let registry = build_registry(&opts.endpoints)?;
588 #[cfg(not(feature = "net"))]
589 check_no_net_endpoints(&opts.endpoints)?;
590 #[cfg(not(feature = "net"))]
591 check_no_net_remotes(&opts.remotes)?;
592 #[cfg(feature = "net")]
596 let inventory = {
597 let pairs = opts.remotes.clone();
598 let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
599 inventory.log_resolutions();
600 inventory.validate_script(&steps)?;
601 inventory
602 };
603 let entry_file = entry_file_of(&opts.script);
604 #[cfg(feature = "net")]
605 let output = {
606 let mut io_cfg = ExecIo::new();
607 register_remote_runners(&mut io_cfg, &inventory);
608 run_steps_with_lazy_snapshot_and_modules_and_entry(
609 &workspace_root,
610 &steps,
611 io_cfg,
612 cli_host_modules_with(Some(®istry)),
613 cli_host_types(),
614 entry_file,
615 )?
616 };
617 #[cfg(not(feature = "net"))]
618 let output = run_steps_with_lazy_snapshot_and_modules_and_entry(
619 &workspace_root,
620 &steps,
621 ExecIo::new(),
622 cli_host_modules_with(None),
623 cli_host_types(),
624 entry_file,
625 )?;
626 final_cwd = output.final_cwd;
627 return Ok(ExecutionResult {
628 snapshot: output.snapshot,
629 final_cwd,
630 bindings: output.bindings,
631 });
632 }
633
634 Ok(ExecutionResult {
635 snapshot,
636 final_cwd,
637 bindings: BTreeMap::new(),
638 })
639}
640
641#[cfg(feature = "net")]
646fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
647 use std::sync::Arc;
648 let entries = surface_entries();
649 let module_hash = oxdock_net_plugin::module_hash(&entries);
650 let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
651 for target in inventory.targets() {
652 let Some(argv) = inventory.argv(&target) else {
653 continue;
654 };
655 let config = oxdock_net_plugin::SessionConfig {
656 argv: argv.to_vec(),
657 oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
658 modules: modules.clone(),
659 module_hash: module_hash.clone(),
660 };
661 io.set_remote_runner_for_target(
662 target,
663 Arc::new(oxdock_net_plugin::StdioSession::new(config)),
664 );
665 }
666}
667
668#[cfg(feature = "net")]
671fn surface_entries() -> Vec<(String, Vec<String>)> {
672 let mut engine = Engine::new();
673 for module in cli_host_modules() {
674 engine.register_module(module);
675 }
676 let table = engine.module_table();
677 let mut entries: Vec<(String, Vec<String>)> = table
678 .modules
679 .into_iter()
680 .map(|(name, module_funcs)| {
681 let mut func_names: Vec<String> = module_funcs
682 .map(|surface| surface.func_names.into_iter().collect())
683 .unwrap_or_default();
684 func_names.sort();
685 (name, func_names)
686 })
687 .collect();
688 entries.sort();
689 entries
690}
691#[cfg(feature = "net")]
692fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
693 use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
694 for (outer, inner) in &flags.publishes {
695 if outer.port() != 0 {
696 continue;
697 }
698 let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
699 continue;
700 };
701 let key = EndpointKey {
702 protocol: protocol.unwrap_or(Protocol::Tcp),
703 endpoint,
704 };
705 match registry.resolve_endpoint(&key) {
706 Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
707 Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
708 }
709 }
710}
711
712#[cfg(not(feature = "net"))]
715fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> Result<(String, String)> {
716 match raw.split_once('=') {
719 Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
720 Ok((target.trim().to_string(), command.to_string()))
721 }
722 _ => bail!("invalid --remote {raw:?}: expected <target>=\"<command>\""),
723 }
724}
725
726#[cfg(not(feature = "net"))]
728fn check_no_net_remotes(remotes: &[(String, String)]) -> Result<()> {
729 if !remotes.is_empty() {
730 bail!("--remote requires the `net` feature (rebuild with --features net)");
731 }
732 Ok(())
733}
734
735#[cfg(not(feature = "net"))]
739fn check_no_net_endpoints(flags: &EndpointFlags) -> Result<()> {
740 if !flags.listens.is_empty() || !flags.publishes.is_empty() {
741 bail!("--listen/-p require the `net` feature (rebuild with --features net)");
742 }
743 Ok(())
744}
745
746fn read_script(source: &ScriptSource) -> Result<String> {
750 match source {
751 ScriptSource::Path(path) => {
752 let resolver = PathResolver::new(path.root(), path.root())?;
753 resolver
754 .read_to_string(path)
755 .with_context(|| format!("failed to read script at {}", path.display()))
756 }
757 ScriptSource::Stdin => {
758 let mut buf = String::new();
759 io::stdin()
760 .lock()
761 .read_to_string(&mut buf)
762 .context("failed to read script from stdin")?;
763 Ok(buf)
764 }
765 }
766}
767
768fn execute_with_shell_runner<F>(
769 opts: Options,
770 workspace_root: GuardedPath,
771 shell_runner: F,
772 require_tty: bool,
773) -> Result<()>
774where
775 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
776{
777 #[cfg(windows)]
778 maybe_reexec_shell_to_temp(&opts)?;
779
780 let script = match &opts.script {
784 ScriptSource::Path(_) => read_script(&opts.script)?,
785 ScriptSource::Stdin => {
786 let stdin = io::stdin();
787 if stdin.is_terminal() {
788 if opts.shell {
793 String::new()
794 } else {
795 bail!(
796 "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
797 );
798 }
799 } else {
800 let mut buf = String::new();
801 stdin
802 .lock()
803 .read_to_string(&mut buf)
804 .context("failed to read script from stdin")?;
805 buf
806 }
807 }
808 };
809
810 let mut final_cwd = workspace_root.clone();
817 let mut snapshot = Arc::new(LazyGuardedTempDir::new());
818 let mut fs: Option<Box<dyn WorkspaceFs>> = None;
819 if !script.trim().is_empty() {
820 let steps = parse_cli_script(&script)?;
821 if opts.dry_run {
824 print_dry_run(&steps, &opts.script, &workspace_root)?;
825 return Ok(());
826 }
827 #[cfg(feature = "net")]
830 let registry = build_registry(&opts.endpoints)?;
831 #[cfg(not(feature = "net"))]
832 check_no_net_endpoints(&opts.endpoints)?;
833 #[cfg(not(feature = "net"))]
834 check_no_net_remotes(&opts.remotes)?;
835 #[cfg(feature = "net")]
836 report_ephemeral_publishes(&opts.endpoints, ®istry);
837 #[cfg(feature = "net")]
841 let inventory = {
842 let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
843 inventory.log_resolutions();
844 inventory.validate_script(&steps)?;
845 inventory
846 };
847 let mut stdin_handle: Option<SharedInput> = None;
852 if let ScriptSource::Path(_) = opts.script {
853 let stdin = io::stdin();
854 if !stdin.is_terminal() {
855 stdin_handle = Some(Arc::new(Mutex::new(stdin)));
861 }
862 }
863
864 let mut io_cfg = ExecIo::new();
865 io_cfg.set_stdin(stdin_handle);
866 #[cfg(feature = "net")]
867 register_remote_runners(&mut io_cfg, &inventory);
868 let entry_file = entry_file_of(&opts.script);
869 #[cfg(feature = "net")]
870 let output = run_steps_with_lazy_snapshot_and_modules_and_entry(
871 &workspace_root,
872 &steps,
873 io_cfg,
874 cli_host_modules_with(Some(®istry)),
875 cli_host_types(),
876 entry_file,
877 )?;
878 #[cfg(not(feature = "net"))]
879 let output = run_steps_with_lazy_snapshot_and_modules_and_entry(
880 &workspace_root,
881 &steps,
882 io_cfg,
883 cli_host_modules_with(None),
884 cli_host_types(),
885 entry_file,
886 )?;
887 final_cwd = output.final_cwd;
888 snapshot = output.snapshot;
889 fs = Some(output.fs);
890 }
891
892 if opts.shell {
894 if require_tty && !has_controlling_tty() {
895 bail!("--shell requires a tty (no controlling tty available)");
896 }
897 match fs.as_ref() {
902 Some(fs) => {
903 if fs.is_snapshot_pending() {
904 snapshot
905 .materialize()
906 .context("failed to create shell temp dir")?;
907 }
908 final_cwd = fs.concretize_cwd(&final_cwd);
909 }
910 None => {
911 snapshot
912 .materialize()
913 .context("failed to create shell temp dir")?;
914 final_cwd = snapshot
915 .get()
916 .cloned()
917 .expect("shell snapshot materialized above");
918 }
919 }
920 return shell_runner(&final_cwd, &workspace_root);
921 }
922
923 Ok(())
924}
925
926#[cfg(test)]
927fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
928where
929 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
930{
931 execute_with_shell_runner(opts, workspace_root, shell_runner, false)
932}
933
934fn has_controlling_tty() -> bool {
935 #[cfg(unix)]
939 {
940 io::stdin().is_terminal() || io::stderr().is_terminal()
941 }
942
943 #[cfg(windows)]
944 {
945 io::stdin().is_terminal() || io::stderr().is_terminal()
946 }
947
948 #[cfg(not(any(unix, windows)))]
949 {
950 false
951 }
952}
953
954#[cfg(windows)]
955fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
956 if !opts.shell {
959 return Ok(());
960 }
961 if std::env::var(oxdock_env::oxdock::SHELL_REEXEC)
962 .ok()
963 .as_deref()
964 == Some("1")
965 {
966 return Ok(());
967 }
968
969 let self_path = std::env::current_exe().context("determine current executable")?;
970 let base_temp =
971 GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
972 let ts = std::time::SystemTime::now()
973 .duration_since(std::time::UNIX_EPOCH)
974 .unwrap_or_default()
975 .as_millis();
976 let temp_file = base_temp
977 .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
978 .context("construct temp shell path")?;
979
980 let temp_root_guard = temp_file
984 .parent()
985 .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
986 let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
987 let dest = temp_file;
988 #[allow(clippy::disallowed_types)]
989 let source = oxdock_fs::UnguardedPath::external(self_path);
990 resolver_temp
991 .copy_file_from_unguarded(&source, &dest)
992 .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
993
994 let mut cmd = CommandBuilder::new(dest.as_path());
995 cmd.args(std::env::args_os().skip(1));
996 cmd.env(oxdock_env::oxdock::SHELL_REEXEC, "1");
997 cmd.spawn()
998 .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
999
1000 std::process::exit(0);
1002}
1003
1004pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
1005 run_steps_with_context(workspace_root, workspace_root, steps)
1006}
1007
1008fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
1009 #[cfg(windows)]
1010 let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
1011 #[cfg(windows)]
1012 let workspace_disp = oxdock_fs::command_path(workspace_root)
1013 .as_ref()
1014 .display()
1015 .to_string();
1016
1017 #[cfg(not(windows))]
1018 let cwd_disp = cwd.display().to_string();
1019 #[cfg(not(windows))]
1020 let workspace_disp = workspace_root.display().to_string();
1021
1022 let pkg = env::var(oxdock_env::cargo::PKG_NAME)
1023 .unwrap_or_else(|_| oxdock_env::oxdock::FALLBACK_APP_NAME.to_string());
1024 indoc::formatdoc! {"
1025 {pkg} shell workspace
1026 cwd: {cwd_disp}
1027 source: workspace root at {workspace_disp}
1028 lifetime: temporary directory created for this shell session; it disappears when you exit
1029 creation: temp workspace starts empty unless your script copies files into it
1030
1031 WARNING: This shell still runs on your host filesystem and is **not** isolated!
1032 "}
1033}
1034
1035fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
1036 oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
1037}
1038
1039#[cfg(test)]
1042mod tests {
1043 use super::*;
1044 use indoc::indoc;
1045 use oxdock_fs::PathResolver;
1046 use std::cell::{Cell, RefCell};
1047
1048 #[cfg_attr(
1049 miri,
1050 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1051 )]
1052 #[test]
1053 fn shell_runner_receives_final_workdir() -> Result<()> {
1054 let workspace = GuardedPath::tempdir()?;
1055 let workspace_root = workspace.as_guarded_path().clone();
1056 let script_path = workspace_root.join("script.ox")?;
1057 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1058 let script = indoc! {"
1059 WRITE temp.txt 123
1060 WORKDIR sub
1061 "};
1062 resolver.write_file(&script_path, script.as_bytes())?;
1063
1064 let opts = Options {
1065 script: ScriptSource::Path(script_path),
1066 shell: true,
1067 dry_run: false,
1068 endpoints: EndpointFlags::default(),
1069 remote_serve: false,
1070 mcp: false,
1071 remotes: Vec::new(),
1072 };
1073
1074 let observed = Cell::new(false);
1075 execute_for_test(opts, workspace_root.clone(), |cwd, _| {
1076 assert!(
1077 cwd.as_path().ends_with("sub"),
1078 "final cwd should end in WORKDIR target, got {}",
1079 cwd.display()
1080 );
1081
1082 let temp_root = GuardedPath::new_root(cwd.root())
1083 .context("construct guard for temp workspace root")?;
1084 let sub_dir = temp_root.join("sub")?;
1085 assert_eq!(
1086 cwd.as_path(),
1087 sub_dir.as_path(),
1088 "shell runner cwd should match guarded sub dir"
1089 );
1090 let temp_file = temp_root.join("temp.txt")?;
1091 let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
1092 let contents = temp_resolver.read_to_string(&temp_file)?;
1093 assert!(
1094 contents.contains("123"),
1095 "expected WRITE command to materialize temp file"
1096 );
1097 observed.set(true);
1098 Ok(())
1099 })?;
1100
1101 assert!(
1102 observed.into_inner(),
1103 "shell runner closure should have been invoked"
1104 );
1105 Ok(())
1106 }
1107
1108 #[cfg_attr(
1109 miri,
1110 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1111 )]
1112 #[test]
1113 fn options_parse_requires_script_path_value() {
1114 let workspace = GuardedPath::tempdir().expect("tempdir");
1115 let mut args = vec!["--script".to_string()].into_iter();
1116 let err = Options::parse(&mut args, workspace.as_guarded_path())
1117 .expect_err("expected missing path error");
1118 assert!(err.to_string().contains("--script requires a path"));
1119 }
1120
1121 #[cfg_attr(
1122 miri,
1123 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1124 )]
1125 #[test]
1126 fn options_parse_script_path_and_shell() {
1127 let workspace = GuardedPath::tempdir().expect("tempdir");
1128 let workspace_root = workspace.as_guarded_path().clone();
1129 let script_path = workspace_root.join("script.txt").expect("script path");
1130 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1131 .expect("resolver");
1132 resolver
1133 .write_file(&script_path, b"WRITE out.txt hi")
1134 .expect("write script");
1135 let mut args = vec![
1136 "--script".to_string(),
1137 "script.txt".to_string(),
1138 "--shell".to_string(),
1139 ]
1140 .into_iter();
1141 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1142 assert!(opts.shell);
1143 match opts.script {
1144 ScriptSource::Path(path) => assert_eq!(path, script_path),
1145 ScriptSource::Stdin => panic!("expected path script"),
1146 }
1147 }
1148
1149 #[cfg_attr(
1150 miri,
1151 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1152 )]
1153 #[test]
1154 fn options_parse_mcp_flag() {
1155 let workspace = GuardedPath::tempdir().expect("tempdir");
1156 let workspace_root = workspace.as_guarded_path().clone();
1157 let mut args = vec!["--mcp".to_string(), "tools.oxdock".to_string()].into_iter();
1158 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1159 assert!(opts.mcp);
1160 match opts.script {
1161 ScriptSource::Path(path) => assert_eq!(
1162 path,
1163 workspace_root.join("tools.oxdock").expect("script path")
1164 ),
1165 ScriptSource::Stdin => panic!("expected path script"),
1166 }
1167 }
1168
1169 #[cfg_attr(
1170 miri,
1171 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1172 )]
1173 #[test]
1174 fn options_parse_mcp_defaults_off() {
1175 let workspace = GuardedPath::tempdir().expect("tempdir");
1176 let workspace_root = workspace.as_guarded_path().clone();
1177 let mut args = vec!["script.txt".to_string()].into_iter();
1178 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1179 assert!(!opts.mcp);
1180 }
1181
1182 #[cfg_attr(
1183 miri,
1184 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1185 )]
1186 #[test]
1187 fn options_parse_positional_script_path() {
1188 let workspace = GuardedPath::tempdir().expect("tempdir");
1189 let workspace_root = workspace.as_guarded_path().clone();
1190 let mut args = vec!["script.txt".to_string()].into_iter();
1191 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1192 assert!(!opts.shell);
1193 match opts.script {
1194 ScriptSource::Path(path) => assert_eq!(
1195 path,
1196 workspace_root.join("script.txt").expect("script path")
1197 ),
1198 ScriptSource::Stdin => panic!("expected path script"),
1199 }
1200 }
1201
1202 #[cfg_attr(
1203 miri,
1204 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1205 )]
1206 #[test]
1207 fn options_parse_positional_dash_reads_stdin() {
1208 let workspace = GuardedPath::tempdir().expect("tempdir");
1209 let mut args = vec!["-".to_string()].into_iter();
1210 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1211 assert!(matches!(opts.script, ScriptSource::Stdin));
1212 }
1213
1214 #[cfg_attr(
1215 miri,
1216 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1217 )]
1218 #[test]
1219 fn options_parse_rejects_duplicate_script_sources() {
1220 let workspace = GuardedPath::tempdir().expect("tempdir");
1221 let workspace_root = workspace.as_guarded_path().clone();
1222 let mut args = vec![
1223 "a.ox".to_string(),
1224 "--script".to_string(),
1225 "b.ox".to_string(),
1226 ]
1227 .into_iter();
1228 let err = Options::parse(&mut args, &workspace_root)
1229 .expect_err("expected duplicate script error");
1230 assert!(err.to_string().contains("multiple times"), "{err:?}");
1231
1232 let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1233 let err = Options::parse(&mut args, &workspace_root)
1234 .expect_err("expected duplicate script error");
1235 assert!(err.to_string().contains("multiple times"), "{err:?}");
1236 }
1237
1238 #[cfg_attr(
1239 miri,
1240 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1241 )]
1242 #[test]
1243 fn options_parse_absolute_script_outside_execution_workspace_loads() {
1244 let workspace = GuardedPath::tempdir().expect("tempdir");
1247 let outside = GuardedPath::tempdir().expect("outside");
1248 let target = outside
1249 .as_guarded_path()
1250 .as_path()
1251 .join("step.ox")
1252 .to_string_lossy()
1253 .into_owned();
1254 let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1255 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1256 match opts.script {
1257 ScriptSource::Path(path) => {
1258 assert_eq!(path.as_path().to_string_lossy(), target);
1259 assert_eq!(path.root(), outside.as_guarded_path().as_path());
1260 }
1261 ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1262 }
1263 }
1264
1265 #[cfg_attr(
1266 miri,
1267 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1268 )]
1269 #[test]
1270 fn options_parse_relative_escape_stays_rejected() {
1271 let workspace = GuardedPath::tempdir().expect("tempdir");
1272 let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1273 let err =
1274 Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1275 assert!(err.to_string().contains("guard script path"), "{err:?}");
1276 }
1277
1278 #[cfg_attr(
1279 miri,
1280 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1281 )]
1282 #[test]
1283 fn options_parse_rejects_unknown_flags() {
1284 let workspace = GuardedPath::tempdir().expect("tempdir");
1285 let mut args = vec!["--frobnicate".to_string()].into_iter();
1286 let err = Options::parse(&mut args, workspace.as_guarded_path())
1287 .expect_err("expected unknown flag error");
1288 assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1289 }
1290
1291 #[test]
1292 fn usage_describes_positional_script_and_help() {
1293 let text = usage();
1294 assert!(text.contains("Usage: oxdock"), "{text}");
1295 assert!(text.contains("SCRIPT"), "{text}");
1296 assert!(text.contains("--script"), "{text}");
1297 assert!(text.contains("--help"), "{text}");
1298 assert!(text.contains("--offline"), "{text}");
1299 #[cfg(feature = "net")]
1300 {
1301 assert!(text.contains("--listen"), "{text}");
1302 assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1303 }
1304 #[cfg(not(feature = "net"))]
1305 {
1306 assert!(!text.contains("--listen <addr>"), "{text}");
1307 assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1308 assert!(text.contains("require the `net` feature"), "{text}");
1309 }
1310 assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1312 }
1313
1314 #[cfg(feature = "net")]
1315 #[cfg_attr(
1316 miri,
1317 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1318 )]
1319 #[test]
1320 fn options_parse_endpoint_flags() {
1321 let workspace = GuardedPath::tempdir().expect("tempdir");
1324 let mut args = vec![
1325 "--listen".to_string(),
1326 "0.0.0.0:2251".to_string(),
1327 "-p".to_string(),
1328 "2222:demo-proxy".to_string(),
1329 "-p".to_string(),
1330 "0:2252".to_string(),
1331 "-".to_string(),
1332 ]
1333 .into_iter();
1334 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1335 assert_eq!(opts.endpoints.listens.len(), 1);
1336 assert_eq!(opts.endpoints.publishes.len(), 2);
1337 assert!(!opts.endpoints.offline);
1338 assert!(matches!(opts.script, ScriptSource::Stdin));
1339 }
1340
1341 #[cfg_attr(
1342 miri,
1343 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1344 )]
1345 #[test]
1346 fn options_parse_offline_flag() {
1347 let workspace = GuardedPath::tempdir().expect("tempdir");
1348 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1349 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1350 assert!(opts.endpoints.offline);
1351 }
1352
1353 #[cfg(feature = "net")]
1354 #[cfg_attr(
1355 miri,
1356 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1357 )]
1358 #[test]
1359 fn options_parse_rejects_bad_endpoint_flags() {
1360 let workspace = GuardedPath::tempdir().expect("tempdir");
1361 for args in [
1362 vec!["--listen"],
1363 vec!["--listen", "0.0.0.0:0"],
1364 vec!["-p"],
1365 vec!["-p", "2222"],
1366 vec!["-p", "2222:0"],
1367 ] {
1368 let mut args = args.into_iter().map(str::to_string);
1369 Options::parse(&mut args, workspace.as_guarded_path())
1370 .expect_err("bad endpoint flag must fail");
1371 }
1372 }
1373
1374 #[cfg_attr(
1375 miri,
1376 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1377 )]
1378 #[test]
1379 fn options_parse_empty_values_hold_token_boundaries() {
1380 let workspace = GuardedPath::tempdir().expect("tempdir");
1384 let mut args = vec![
1385 "--script".to_string(),
1386 "".to_string(),
1387 "--shell".to_string(),
1388 ]
1389 .into_iter();
1390 let err = Options::parse(&mut args, workspace.as_guarded_path())
1391 .expect_err("empty script path must fail");
1392 assert!(
1393 err.to_string().contains("--script requires a path"),
1394 "{err:?}"
1395 );
1396 let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1397 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1398 assert!(matches!(opts.script, ScriptSource::Stdin));
1399 }
1400
1401 #[cfg(feature = "net")]
1402 #[cfg_attr(
1403 miri,
1404 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1405 )]
1406 #[test]
1407 fn options_parse_accepts_equals_and_attached_forms() {
1408 let workspace = GuardedPath::tempdir().expect("tempdir");
1411 let workspace_root = workspace.as_guarded_path().clone();
1412 let mut args = vec![
1413 "--listen=0.0.0.0:2251".to_string(),
1414 "-p2222:demo-proxy".to_string(),
1415 "--".to_string(),
1416 "script.ox".to_string(),
1417 ]
1418 .into_iter();
1419 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1420 assert_eq!(opts.endpoints.listens.len(), 1);
1421 assert_eq!(opts.endpoints.publishes.len(), 1);
1422 match opts.script {
1423 ScriptSource::Path(path) => {
1424 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1425 }
1426 ScriptSource::Stdin => panic!("expected path script after --"),
1427 }
1428 }
1429
1430 #[cfg_attr(
1431 miri,
1432 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1433 )]
1434 #[test]
1435 fn options_parse_version_returns_version_without_exiting() {
1436 let workspace = GuardedPath::tempdir().expect("tempdir");
1440 for flag in ["--version", "-V"] {
1441 let mut args = vec![flag.to_string()].into_iter();
1442 let err = Options::parse(&mut args, workspace.as_guarded_path())
1443 .expect_err("version flag must not parse as options");
1444 assert_eq!(err.to_string(), version());
1445 }
1446 }
1447
1448 #[cfg_attr(
1449 miri,
1450 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1451 )]
1452 #[test]
1453 fn options_parse_help_returns_usage_error_without_exiting() {
1454 let workspace = GuardedPath::tempdir().expect("tempdir");
1457 for flag in ["--help", "-h"] {
1458 let mut args = vec![flag.to_string()].into_iter();
1459 let err = Options::parse(&mut args, workspace.as_guarded_path())
1460 .expect_err("help flag must not parse as options");
1461 assert_eq!(err.to_string(), usage());
1462 }
1463 }
1464
1465 #[cfg_attr(
1466 miri,
1467 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1468 )]
1469 #[test]
1470 fn options_parse_rejects_remote_script_with_input_intact() {
1471 let workspace = GuardedPath::tempdir().expect("tempdir");
1472 for args in [
1473 vec!["https://example.com/process.oxfile".to_string()],
1474 vec![
1475 "--script".to_string(),
1476 "https://example.com/process.oxfile".to_string(),
1477 ],
1478 ] {
1479 let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1480 .expect_err("remote script must not parse as a path");
1481 let rendered = format!("{err:#}");
1482 assert!(
1483 rendered.contains("not a local path")
1484 && rendered.contains("https://example.com/process.oxfile"),
1485 "rejection names the intact input: {rendered}"
1486 );
1487 assert!(
1488 !rendered.contains("https:/example.com"),
1489 "scheme must never come out mangled: {rendered}"
1490 );
1491 }
1492 }
1493
1494 #[test]
1495 fn execute_with_result_runs_script() {
1496 let workspace = GuardedPath::tempdir().expect("tempdir");
1497 let workspace_root = workspace.as_guarded_path().clone();
1498 let script_path = workspace_root.join("script.txt").expect("script path");
1499 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1500 .expect("resolver");
1501 resolver
1502 .write_file(&script_path, b"WRITE out.txt hi")
1503 .expect("write script");
1504 let opts = Options {
1505 script: ScriptSource::Path(script_path),
1506 shell: false,
1507 dry_run: false,
1508 endpoints: EndpointFlags::default(),
1509 remote_serve: false,
1510 mcp: false,
1511 remotes: Vec::new(),
1512 };
1513 let result = execute_with_result(opts, workspace_root).expect("execute");
1514 let snapshot = result
1515 .snapshot_path()
1516 .expect("default WRITE materializes the snapshot");
1517 assert_eq!(snapshot, &result.final_cwd);
1518 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1519 let out = snapshot.join("out.txt").expect("out path");
1520 let contents = temp_resolver.read_to_string(&out).expect("read out");
1521 assert_eq!(contents.trim(), "hi");
1522 }
1523
1524 #[cfg_attr(
1525 miri,
1526 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1527 )]
1528 #[test]
1529 fn execute_with_result_local_only_creates_no_snapshot() {
1530 let workspace = GuardedPath::tempdir().expect("tempdir");
1531 let workspace_root = workspace.as_guarded_path().clone();
1532 let script_path = workspace_root.join("script.txt").expect("script path");
1533 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1534 .expect("resolver");
1535 resolver
1536 .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1537 .expect("write script");
1538 let opts = Options {
1539 script: ScriptSource::Path(script_path),
1540 shell: false,
1541 dry_run: false,
1542 endpoints: EndpointFlags::default(),
1543 remote_serve: false,
1544 mcp: false,
1545 remotes: Vec::new(),
1546 };
1547 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1548 assert!(
1549 !result.has_snapshot(),
1550 "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1551 );
1552 assert!(result.snapshot_path().is_none());
1553 let out = workspace_root.join("out.txt").expect("out path");
1555 let contents = resolver.read_to_string(&out).expect("read out");
1556 assert_eq!(contents.trim(), "hi");
1557 assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1559 }
1560
1561 #[cfg_attr(
1562 miri,
1563 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1564 )]
1565 #[test]
1566 fn execute_with_result_empty_script_creates_no_snapshot() {
1567 let workspace = GuardedPath::tempdir().expect("tempdir");
1568 let workspace_root = workspace.as_guarded_path().clone();
1569 let script_path = workspace_root.join("empty.txt").expect("script path");
1570 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1571 .expect("resolver");
1572 resolver
1573 .write_file(&script_path, b"")
1574 .expect("write script");
1575 let opts = Options {
1576 script: ScriptSource::Path(script_path),
1577 shell: false,
1578 dry_run: false,
1579 endpoints: EndpointFlags::default(),
1580 remote_serve: false,
1581 mcp: false,
1582 remotes: Vec::new(),
1583 };
1584 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1585 assert!(
1586 !result.has_snapshot(),
1587 "empty script must not create a snapshot tempdir"
1588 );
1589 assert_eq!(result.final_cwd, workspace_root);
1590 }
1591
1592 #[cfg_attr(
1593 miri,
1594 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1595 )]
1596 #[test]
1597 fn execute_for_test_invokes_shell_runner() -> Result<()> {
1598 let workspace = GuardedPath::tempdir()?;
1599 let workspace_root = workspace.as_guarded_path().clone();
1600 let script_path = workspace_root.join("empty.txt")?;
1601 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1602 resolver.write_file(&script_path, b"")?;
1603 let opts = Options {
1604 script: ScriptSource::Path(script_path),
1605 shell: true,
1606 dry_run: false,
1607 endpoints: EndpointFlags::default(),
1608 remote_serve: false,
1609 mcp: false,
1610 remotes: Vec::new(),
1611 };
1612 let called = RefCell::new(None::<(String, String)>);
1613 execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1614 called.replace(Some((cwd.display(), workspace.display())));
1615 assert!(
1618 cwd.exists(),
1619 "shell cwd must exist on disk, got {}",
1620 cwd.display()
1621 );
1622 Ok(())
1623 })?;
1624 let seen = called.borrow().clone().expect("shell runner called");
1625 assert_eq!(seen.1, workspace_root.display());
1626 Ok(())
1627 }
1628
1629 #[cfg(feature = "ssh")]
1633 #[cfg_attr(
1634 miri,
1635 ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1636 )]
1637 #[test]
1638 fn ssh_feature_serves_and_closes() -> Result<()> {
1639 let workspace = GuardedPath::tempdir()?;
1640 let workspace_root = workspace.as_guarded_path().clone();
1641 let script_path = workspace_root.join("ssh-serve.ox")?;
1642 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1643 let script = indoc! {"
1644 IMPORT [STD, SSH]
1645 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"cli-ssh-svc\", {username: \"test\", password: \"test123\"})
1646 SSH_CLOSE($m.server)
1647 "};
1648 resolver.write_file(&script_path, script.as_bytes())?;
1649 let opts = Options {
1650 script: ScriptSource::Path(script_path),
1651 shell: false,
1652 dry_run: false,
1653 endpoints: EndpointFlags {
1654 publishes: vec![(
1655 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1656 "cli-ssh-svc".to_string(),
1657 )],
1658 ..EndpointFlags::default()
1659 },
1660 remote_serve: false,
1661 mcp: false,
1662 remotes: Vec::new(),
1663 };
1664 execute_with_result(opts, workspace_root)?;
1665 Ok(())
1666 }
1667
1668 #[cfg(feature = "net")]
1672 #[cfg_attr(
1673 miri,
1674 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1675 )]
1676 #[test]
1677 fn net_module_listens_and_closes() -> Result<()> {
1678 let workspace = GuardedPath::tempdir()?;
1679 let workspace_root = workspace.as_guarded_path().clone();
1680 let script_path = workspace_root.join("net-listen.ox")?;
1681 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1682 let script = indoc! {"
1683 IMPORT [STD, NET]
1684 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1685 NET_CLOSE($l.listener)
1686 "};
1687 resolver.write_file(&script_path, script.as_bytes())?;
1688 let opts = Options {
1689 script: ScriptSource::Path(script_path),
1690 shell: false,
1691 dry_run: false,
1692 endpoints: EndpointFlags {
1695 publishes: vec![(
1696 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1697 "23501".to_string(),
1698 )],
1699 ..EndpointFlags::default()
1700 },
1701 remote_serve: false,
1702 mcp: false,
1703 remotes: Vec::new(),
1704 };
1705 execute_with_result(opts, workspace_root)?;
1706 Ok(())
1707 }
1708
1709 #[cfg(feature = "net")]
1713 #[cfg_attr(
1714 miri,
1715 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1716 )]
1717 #[test]
1718 fn net_port_addr_observe_publish_mapping() -> Result<()> {
1719 let workspace = GuardedPath::tempdir()?;
1720 let workspace_root = workspace.as_guarded_path().clone();
1721 let script_path = workspace_root.join("net-port.ox")?;
1722 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1723 let script = indoc! {"
1724 IMPORT [STD, NET]
1725 LET $port: INT = NET_PORT(\"routed-svc\")
1726 WRITE port.txt \"{{ $port }}\"
1727 LET $addr: STRING = NET_ADDR(\"routed-svc\")
1728 WRITE addr.txt \"{{ $addr }}\"
1729 "};
1730 resolver.write_file(&script_path, script.as_bytes())?;
1731 let opts = Options {
1732 script: ScriptSource::Path(script_path),
1733 shell: false,
1734 dry_run: false,
1735 endpoints: EndpointFlags {
1736 publishes: vec![(
1737 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
1738 "routed-svc".to_string(),
1739 )],
1740 ..EndpointFlags::default()
1741 },
1742 remote_serve: false,
1743 mcp: false,
1744 remotes: Vec::new(),
1745 };
1746 let result = execute_with_result(opts, workspace_root)?;
1747 let snapshot = result
1748 .snapshot_path()
1749 .expect("WRITE materializes the snapshot");
1750 let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
1751 let port_path = snapshot.join("port.txt")?;
1752 let port_text = snapshot_resolver.read_to_string(&port_path)?;
1753 let port: u16 = port_text
1754 .trim()
1755 .parse()
1756 .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
1757 assert_ne!(port, 0, "ephemeral outer port must resolve");
1758 let addr_path = snapshot.join("addr.txt")?;
1759 let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
1760 assert!(
1761 addr_text.trim().ends_with(&format!(":{port}")),
1762 "dial string must carry the resolved port, got {addr_text:?}"
1763 );
1764 Ok(())
1765 }
1766
1767 #[cfg(not(feature = "ssh"))]
1770 #[cfg_attr(
1771 miri,
1772 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1773 )]
1774 #[test]
1775 fn ssh_scripts_rejected_without_feature() -> Result<()> {
1776 let workspace = GuardedPath::tempdir()?;
1777 let workspace_root = workspace.as_guarded_path().clone();
1778 let script_path = workspace_root.join("ssh-serve.ox")?;
1779 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1780 let script = indoc! {"
1781 IMPORT [STD, SSH]
1782 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1783 SSH_CLOSE($m.server)
1784 "};
1785 resolver.write_file(&script_path, script.as_bytes())?;
1786 let opts = Options {
1787 script: ScriptSource::Path(script_path),
1788 shell: false,
1789 dry_run: false,
1790 endpoints: EndpointFlags::default(),
1791 remote_serve: false,
1792 mcp: false,
1793 remotes: Vec::new(),
1794 };
1795 let err = match execute_with_result(opts, workspace_root) {
1796 Ok(_) => panic!("SSH names must be unknown without the feature"),
1797 Err(err) => err,
1798 };
1799 assert!(err.to_string().contains("SSH"), "{err}");
1800 Ok(())
1801 }
1802
1803 #[cfg(not(feature = "net"))]
1807 #[cfg_attr(
1808 miri,
1809 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1810 )]
1811 #[test]
1812 fn net_flags_rejected_without_feature() {
1813 let workspace = GuardedPath::tempdir().expect("tempdir");
1814 for args in [
1815 vec!["--listen", "0.0.0.0:2251", "-"],
1816 vec!["-p", "2222:2251", "-"],
1817 vec!["--listen=0.0.0.0:2251", "-"],
1818 ] {
1819 let mut args = args.into_iter().map(str::to_string);
1820 let err = Options::parse(&mut args, workspace.as_guarded_path())
1821 .expect_err("endpoint flag must fail without net");
1822 assert!(
1823 err.to_string().contains("require the `net` feature"),
1824 "{err:?}"
1825 );
1826 }
1827 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1828 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1829 assert!(opts.endpoints.offline);
1830 }
1831
1832 #[cfg(not(feature = "net"))]
1835 #[cfg_attr(
1836 miri,
1837 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1838 )]
1839 #[test]
1840 fn net_scripts_rejected_without_feature() -> Result<()> {
1841 let workspace = GuardedPath::tempdir()?;
1842 let workspace_root = workspace.as_guarded_path().clone();
1843 let script_path = workspace_root.join("net-listen.ox")?;
1844 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1845 let script = indoc! {"
1846 IMPORT [STD, NET]
1847 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1848 LET $body: STRING = NET_FETCH(\"https://example.com/x\")
1849 NET_CLOSE($l.listener)
1850 "};
1851 resolver.write_file(&script_path, script.as_bytes())?;
1852 let opts = Options {
1853 script: ScriptSource::Path(script_path),
1854 shell: false,
1855 dry_run: false,
1856 endpoints: EndpointFlags::default(),
1857 remote_serve: false,
1858 mcp: false,
1859 remotes: Vec::new(),
1860 };
1861 let err = match execute_with_result(opts, workspace_root) {
1862 Ok(_) => panic!("NET names must be unknown without the feature"),
1863 Err(err) => err,
1864 };
1865 assert!(err.to_string().contains("NET"), "{err}");
1866 Ok(())
1867 }
1868
1869 #[test]
1870 fn process_exit_code_relays_exit_requests() {
1871 let exit = anyhow::Error::new(ExitRequest(3));
1872 assert_eq!(process_exit_code(&exit), 3);
1873 let relayed =
1874 anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' exited with code 3");
1875 assert_eq!(process_exit_code(&relayed), 3);
1876 assert_eq!(process_exit_code(&anyhow::anyhow!("boom")), 1);
1877 assert_eq!(
1878 process_exit_code(&anyhow::Error::new(ExitRequest(300))),
1879 255,
1880 "codes clamp to the portable range"
1881 );
1882 assert_eq!(
1883 process_exit_code(&anyhow::Error::new(ExitRequest(-1))),
1884 0,
1885 "negative codes clamp to zero"
1886 );
1887 }
1888}
1889
1890#[cfg(all(test, windows))]
1891mod windows_shell_tests {
1892 use super::*;
1893
1894 #[test]
1895 fn command_path_strips_verbatim_prefix() -> Result<()> {
1896 let temp = GuardedPath::tempdir()?;
1897 let converted = oxdock_fs::command_path(temp.as_guarded_path());
1898 let as_str = converted.as_ref().display().to_string();
1899 assert!(
1900 !as_str.starts_with(r"\\?\"),
1901 "expected non-verbatim path, got {as_str}"
1902 );
1903 Ok(())
1904 }
1905}