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