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): VOID {
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] [-- script-args...]
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, -v print the version and exit
71
72 With no script given, reads the script from stdin (must be piped unless `--shell`).
73 Everything after SCRIPT is a verbatim script arg (read via `STD::ARGV()`); one leading `--` there is a separator and dropped, so `--dry-run` after the script stays data.
74 {{ $tail }}
75 """
76 }
77
78 LET $p: PIPE
79 WITH_IO [stdout=$p] {
80 EMIT_BODY(true)
81 }
82 WITH_IO [stdin=$p] WRITE dist/usage-net.txt
83 WITH_IO [stdout=$p] {
84 EMIT_BODY(false)
85 }
86 WITH_IO [stdin=$p] WRITE dist/usage-lean.txt
87 },
88 out_dir: "usage-prebuilt",
89}
90#[cfg(feature = "net")]
91pub use endpoints::build_registry;
92#[cfg(feature = "net")]
93use oxdock_net_plugin::EndpointRegistry;
94#[cfg(feature = "net")]
95mod serve;
96
97fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
106 cli_host_modules_with(None)
107}
108
109#[cfg(feature = "net")]
113fn cli_host_modules_for_serve() -> Vec<HostModule<DefaultProcessManager>> {
114 cli_host_modules_with(None)
115}
116
117#[cfg(feature = "net")]
120fn remote_session_module_hash(entries: &[(String, Vec<String>)]) -> String {
121 oxdock_net_plugin::module_hash(entries)
122}
123
124fn cli_host_modules_with(
131 #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
132 #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
133) -> Vec<HostModule<DefaultProcessManager>> {
134 #[cfg(any(feature = "net", feature = "markdown"))]
135 let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
136 #[cfg(not(any(feature = "net", feature = "markdown")))]
137 let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
138 #[cfg(feature = "net")]
139 {
140 let net_module = match registry {
141 Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
142 None => oxdock_net_plugin::module(),
143 };
144 modules.push(net_module);
145 #[cfg(feature = "ssh")]
146 {
147 let ssh_module = match registry {
148 Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
149 None => oxdock_ssh_plugin::module(),
150 };
151 modules.push(ssh_module);
152 }
153 }
154 #[cfg(feature = "markdown")]
155 modules.push(oxdock_markdown_plugin::module());
156 let _ = registry;
157 modules
158}
159
160fn cli_host_types() -> Vec<&'static TypeDescriptor> {
162 #[cfg(feature = "net")]
163 let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
164 #[cfg(not(feature = "net"))]
165 let net: &[&'static TypeDescriptor] = &[];
166 #[cfg(feature = "ssh")]
167 let ssh: &[&'static TypeDescriptor] = &[
168 oxdock_ssh_plugin::SshServerTag::descriptor(),
169 oxdock_ssh_plugin::SshSessionTag::descriptor(),
170 ];
171 #[cfg(not(feature = "ssh"))]
172 let ssh: &[&'static TypeDescriptor] = &[];
173 net.iter().chain(ssh.iter()).copied().collect()
174}
175
176fn run_cli_steps(
182 workspace_root: &GuardedPath,
183 steps: &[Step],
184 io: ExecIo,
185 #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
186 #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
187 entry_file: Option<GuardedPath>,
188) -> Result<oxdock_core::exec::LazyRunOutput> {
189 run_steps_with_lazy_snapshot_and_modules_and_entry(
190 workspace_root,
191 steps,
192 io,
193 cli_host_modules_with(registry),
194 cli_host_types(),
195 entry_file,
196 )
197}
198
199fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
203 parse_script_with_modules(script, cli_module_table())
204}
205
206fn cli_module_table() -> oxdock_parser::ModuleTable {
209 let modules = cli_host_modules();
210 if modules.is_empty() {
211 return oxdock_core::std_module_table();
212 }
213 let mut engine = Engine::new();
214 for module in modules {
215 engine.register_module(module);
216 }
217 engine.module_table()
218}
219
220fn entry_file_of(script: &ScriptSource) -> Option<GuardedPath> {
223 match script {
224 ScriptSource::Path(path) => Some(path.clone()),
225 ScriptSource::Stdin => None,
226 }
227}
228
229fn print_dry_run(
235 steps: &[Step],
236 script: &ScriptSource,
237 workspace_root: &GuardedPath,
238) -> Result<()> {
239 let table = cli_module_table();
240 let entry_file = entry_file_of(script);
241 {
245 let resolver = PathResolver::new_lazy(workspace_root.clone())?;
246 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
247 oxdock_core::validate_steps_with_fs_modules_and_entry(
248 fs,
249 steps,
250 cli_host_modules_with(None),
251 cli_host_types(),
252 entry_file.clone(),
253 )?;
254 }
255 let (label, base) = match script {
256 ScriptSource::Path(path) => (
257 path.display(),
258 path.parent().unwrap_or_else(|| workspace_root.clone()),
259 ),
260 ScriptSource::Stdin => ("<stdin>".to_string(), workspace_root.clone()),
261 };
262 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
263 let listing = dry_run_closure(steps, &label, &base, &resolver, &table)?;
264 for item in listing {
265 println!("{}:{} {}", item.file, item.step.line, item.step.kind);
266 }
267 Ok(())
268}
269
270pub fn run() -> Result<()> {
271 init_temp_gc();
272 let workspace_root = discover_workspace_root().context("guard workspace root")?;
273
274 let mut args = std::env::args().skip(1);
275 let opts = match Options::parse(&mut args, &workspace_root) {
279 Ok(opts) => opts,
280 Err(err) if err.to_string() == version() => {
281 println!("{err}");
282 return Ok(());
283 }
284 Err(err) if err.to_string() == usage() => {
285 print!("{err}");
286 return Ok(());
287 }
288 Err(err) => return Err(err),
289 };
290 #[cfg(feature = "net")]
293 if opts.remote_serve {
294 if opts.shell
295 || !opts.remotes.is_empty()
296 || !matches!(opts.script, ScriptSource::Stdin)
297 || !opts.script_args.is_empty()
298 {
299 bail!("--remote-serve runs alone (no --script, --shell, --remote, or script args)");
300 }
301 return serve::serve();
302 }
303 #[cfg(not(feature = "net"))]
304 if opts.remote_serve {
305 bail!("--remote-serve requires the `net` feature (rebuild with --features net)");
306 }
307 if opts.mcp {
310 #[cfg(feature = "mcp")]
311 {
312 if opts.shell || opts.remote_serve || !opts.remotes.is_empty() {
313 bail!("--mcp runs alone (no --shell, --remote-serve, or --remote)");
314 }
315 if !opts.endpoints.listens.is_empty() || !opts.endpoints.publishes.is_empty() {
316 bail!("--mcp runs alone (no --listen/-p)");
317 }
318 if opts.dry_run {
319 bail!("--mcp runs alone (no --dry-run)");
320 }
321 if !opts.script_args.is_empty() {
322 bail!("--mcp runs alone (no script args)");
323 }
324 return mcp::serve_mcp(opts, workspace_root);
325 }
326 #[cfg(not(feature = "mcp"))]
327 {
328 bail!("--mcp requires the `mcp` feature (rebuild with --features mcp)");
329 }
330 }
331 execute(opts, workspace_root)
332}
333
334pub fn process_exit_code(err: &anyhow::Error) -> i32 {
338 exit_code_of(err)
339 .map(|code| code.clamp(0, 255) as i32)
340 .unwrap_or(1)
341}
342
343#[derive(Debug, Clone)]
344pub enum ScriptSource {
345 Path(GuardedPath),
346 Stdin,
347}
348
349fn reject_url_script(text: &str) -> Result<()> {
353 if text.contains("://") {
354 bail!("not a local path: {text:?} (pass a workspace path or `-` for stdin)");
355 }
356 Ok(())
357}
358
359#[derive(Debug, Clone)]
360pub struct Options {
361 pub script: ScriptSource,
362 pub shell: bool,
363 pub dry_run: bool,
366 pub endpoints: EndpointFlags,
367 pub remote_serve: bool,
368 pub mcp: bool,
371 pub remotes: Vec<(String, String)>,
374 pub script_args: Vec<String>,
379}
380
381impl Options {
382 pub fn parse(
383 args: &mut impl Iterator<Item = String>,
384 workspace_root: &GuardedPath,
385 ) -> Result<Self> {
386 use lexopt::Arg::{Long, Short, Value};
387
388 let mut script: Option<ScriptSource> = None;
389 let mut shell = false;
390 let mut dry_run = false;
391 let mut endpoints = EndpointFlags::default();
392 let mut remote_serve = false;
393 let mut mcp = false;
394 #[cfg_attr(not(feature = "net"), allow(unused_mut))]
396 let mut remotes: Vec<(String, String)> = Vec::new();
397 let mut script_args: Vec<String> = Vec::new();
398 let drain_tail =
407 |parser: &mut lexopt::Parser, strip_leading: bool| -> Result<Vec<String>> {
408 let mut raw = parser.raw_args().map_err(|e| anyhow::anyhow!("{e}"))?;
409 let Some(first_os) = raw.next() else {
410 return Ok(Vec::new());
411 };
412 let first = value_string(first_os)?;
413 if strip_leading && first == "--" {
414 raw.map(value_string).collect()
415 } else {
416 std::iter::once(Ok(first))
417 .chain(raw.map(value_string))
418 .collect()
419 }
420 };
421 let mut parser = lexopt::Parser::from_args(args.by_ref());
426 while let Some(arg) = parser.next()? {
427 match arg {
428 Long("script") => {
429 let path = value_string(
430 parser
431 .value()
432 .map_err(|_| anyhow::anyhow!("--script requires a path"))?,
433 )?;
434 if path.is_empty() {
435 bail!("--script requires a path");
436 }
437 if path == "-" {
438 script = Some(ScriptSource::Stdin);
439 } else {
440 reject_url_script(&path)?;
441 script = Some(ScriptSource::Path(
442 workspace_root
443 .join_script(&path)
444 .with_context(|| format!("guard script path {path}"))?,
445 ));
446 }
447 script_args = drain_tail(&mut parser, true)?;
450 break;
451 }
452 Long("shell") => {
453 shell = true;
454 }
455 Long("dry-run") => {
456 dry_run = true;
457 }
458 Long("listen") => {
459 let raw = value_string(
460 parser
461 .value()
462 .map_err(|_| anyhow::anyhow!("--listen requires an address"))?,
463 )?;
464 #[cfg(not(feature = "net"))]
465 {
466 let _ = endpoints::parse_listen_arg(&raw);
470 bail!(
471 "--listen/-p require the `net` feature (rebuild with --features net)"
472 );
473 }
474 #[cfg(feature = "net")]
475 endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
476 }
477 Short('p') => {
478 let raw = value_string(
479 parser
480 .value()
481 .map_err(|_| anyhow::anyhow!("-p requires outer:inner"))?,
482 )?;
483 #[cfg(not(feature = "net"))]
484 {
485 let _ = endpoints::parse_publish_arg(&raw);
489 bail!(
490 "--listen/-p require the `net` feature (rebuild with --features net)"
491 );
492 }
493 #[cfg(feature = "net")]
494 endpoints
495 .publishes
496 .push(endpoints::parse_publish_arg(&raw)?);
497 }
498 Long("offline") => {
499 endpoints.offline = true;
500 }
501 Long("remote-serve") => {
502 remote_serve = true;
503 }
504 Long("mcp") => {
505 mcp = true;
506 }
507 Long("remote") => {
508 let raw = value_string(parser.value().map_err(|_| {
509 anyhow::anyhow!("--remote requires <target>=\"<command>\"")
510 })?)?;
511 #[cfg(not(feature = "net"))]
512 {
513 let _ = oxdock_net_plugin_stub_parse_remote(&raw);
516 bail!("--remote requires the `net` feature (rebuild with --features net)");
517 }
518 #[cfg(feature = "net")]
519 remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
520 }
521 Long("help") | Short('h') => {
522 bail!("{}", usage());
523 }
524 Long("version") | Short('V') | Short('v') => {
525 bail!("{}", version());
526 }
527 Value(value) => {
528 let text = value_string(value)?;
529 if text.is_empty() {
530 continue;
531 }
532 if text == "--" {
533 script = Some(ScriptSource::Stdin);
537 script_args = drain_tail(&mut parser, false)?;
538 break;
539 }
540 if text == "-" {
541 script = Some(ScriptSource::Stdin);
542 script_args = drain_tail(&mut parser, true)?;
543 break;
544 }
545 if text.starts_with('-') {
546 script = Some(ScriptSource::Stdin);
553 let mut tail = drain_tail(&mut parser, false)?;
554 tail.insert(0, text);
555 script_args = tail;
556 break;
557 }
558 reject_url_script(&text)?;
559 script = Some(ScriptSource::Path(
560 workspace_root
561 .join_script(&text)
562 .with_context(|| format!("guard script path {text}"))?,
563 ));
564 script_args = drain_tail(&mut parser, true)?;
565 break;
566 }
567 Long(other) => bail!("unexpected flag: --{other}"),
568 Short(other) => bail!("unexpected flag: -{other}"),
569 }
570 }
571
572 let script = script.unwrap_or(ScriptSource::Stdin);
573
574 Ok(Self {
575 script,
576 shell,
577 dry_run,
578 endpoints,
579 remote_serve,
580 mcp,
581 remotes,
582 script_args,
583 })
584 }
585}
586
587fn value_string(value: std::ffi::OsString) -> Result<String> {
590 value
591 .into_string()
592 .map_err(|_| anyhow::anyhow!("argument must be UTF-8"))
593}
594
595pub fn version() -> String {
597 format!("oxdock {}", env!("CARGO_PKG_VERSION"))
598}
599
600pub fn usage() -> String {
606 #[cfg(feature = "net")]
607 let asset = "dist/usage-net.txt";
608 #[cfg(not(feature = "net"))]
609 let asset = "dist/usage-lean.txt";
610 let file = UsageAssets::get(asset).expect("usage must be embedded");
611 str::from_utf8(file.data.as_ref())
612 .expect("usage is UTF-8")
613 .to_string()
614}
615
616pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
617 init_temp_gc();
618 execute_with_shell_runner(opts, workspace_root, run_shell, true)
619}
620
621pub struct ExecutionResult {
629 pub snapshot: Arc<LazyGuardedTempDir>,
633 pub final_cwd: GuardedPath,
636 pub bindings: BTreeMap<String, Value>,
640}
641
642impl ExecutionResult {
643 pub fn has_snapshot(&self) -> bool {
645 self.snapshot.is_materialized()
646 }
647
648 pub fn snapshot_path(&self) -> Option<&GuardedPath> {
650 self.snapshot.get()
651 }
652}
653
654pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
655 if opts.shell {
656 bail!("execute_with_result does not support --shell");
657 }
658
659 let script = read_script(&opts.script)?;
662
663 let mut final_cwd = workspace_root.clone();
664 let snapshot = Arc::new(LazyGuardedTempDir::new());
665 if !script.trim().is_empty() {
666 let steps = parse_cli_script(&script)?;
667 if opts.dry_run {
670 print_dry_run(&steps, &opts.script, &workspace_root)?;
671 return Ok(ExecutionResult {
672 snapshot,
673 final_cwd,
674 bindings: BTreeMap::new(),
675 });
676 }
677 #[cfg(feature = "net")]
680 let registry = build_registry(&opts.endpoints)?;
681 #[cfg(not(feature = "net"))]
682 check_no_net_endpoints(&opts.endpoints)?;
683 #[cfg(not(feature = "net"))]
684 check_no_net_remotes(&opts.remotes)?;
685 #[cfg(feature = "net")]
689 let inventory = {
690 let pairs = opts.remotes.clone();
691 let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
692 inventory.log_resolutions();
693 inventory.validate_script(&steps)?;
694 inventory
695 };
696 let entry_file = entry_file_of(&opts.script);
697 #[cfg(feature = "net")]
698 let io_cfg = {
699 let mut io_cfg = ExecIo::new();
700 io_cfg.set_script_args(opts.script_args.clone());
701 register_remote_runners(&mut io_cfg, &inventory);
702 io_cfg
703 };
704 #[cfg(not(feature = "net"))]
705 let io_cfg = {
706 let mut io_cfg = ExecIo::new();
707 io_cfg.set_script_args(opts.script_args.clone());
708 io_cfg
709 };
710 #[cfg(feature = "net")]
711 let output = run_cli_steps(&workspace_root, &steps, io_cfg, Some(®istry), entry_file)?;
712 #[cfg(not(feature = "net"))]
713 let output = run_cli_steps(&workspace_root, &steps, io_cfg, None, entry_file)?;
714 final_cwd = output.final_cwd;
715 return Ok(ExecutionResult {
716 snapshot: output.snapshot,
717 final_cwd,
718 bindings: output.bindings,
719 });
720 }
721
722 Ok(ExecutionResult {
723 snapshot,
724 final_cwd,
725 bindings: BTreeMap::new(),
726 })
727}
728
729#[cfg(feature = "net")]
734fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
735 use std::sync::Arc;
736 let entries = surface_entries();
737 let module_hash = oxdock_net_plugin::module_hash(&entries);
738 let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
739 for target in inventory.targets() {
740 let Some(argv) = inventory.argv(&target) else {
741 continue;
742 };
743 let config = oxdock_net_plugin::SessionConfig {
744 argv: argv.to_vec(),
745 oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
746 modules: modules.clone(),
747 module_hash: module_hash.clone(),
748 };
749 io.set_remote_runner_for_target(
750 target,
751 Arc::new(oxdock_net_plugin::StdioSession::new(config)),
752 );
753 }
754}
755
756#[cfg(feature = "net")]
759fn surface_entries() -> Vec<(String, Vec<String>)> {
760 let mut engine = Engine::new();
761 for module in cli_host_modules() {
762 engine.register_module(module);
763 }
764 let table = engine.module_table();
765 let mut entries: Vec<(String, Vec<String>)> = table
766 .modules
767 .into_iter()
768 .map(|(name, module_funcs)| {
769 let mut func_names: Vec<String> = module_funcs
770 .map(|surface| surface.func_names.into_iter().collect())
771 .unwrap_or_default();
772 func_names.sort();
773 (name, func_names)
774 })
775 .collect();
776 entries.sort();
777 entries
778}
779#[cfg(feature = "net")]
780fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
781 use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
782 for (outer, inner) in &flags.publishes {
783 if outer.port() != 0 {
784 continue;
785 }
786 let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
787 continue;
788 };
789 let key = EndpointKey {
790 protocol: protocol.unwrap_or(Protocol::Tcp),
791 endpoint,
792 };
793 match registry.resolve_endpoint(&key) {
794 Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
795 Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
796 }
797 }
798}
799
800#[cfg(not(feature = "net"))]
803fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> Result<(String, String)> {
804 match raw.split_once('=') {
807 Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
808 Ok((target.trim().to_string(), command.to_string()))
809 }
810 _ => bail!("invalid --remote {raw:?}: expected <target>=\"<command>\""),
811 }
812}
813
814#[cfg(not(feature = "net"))]
816fn check_no_net_remotes(remotes: &[(String, String)]) -> Result<()> {
817 if !remotes.is_empty() {
818 bail!("--remote requires the `net` feature (rebuild with --features net)");
819 }
820 Ok(())
821}
822
823#[cfg(not(feature = "net"))]
827fn check_no_net_endpoints(flags: &EndpointFlags) -> Result<()> {
828 if !flags.listens.is_empty() || !flags.publishes.is_empty() {
829 bail!("--listen/-p require the `net` feature (rebuild with --features net)");
830 }
831 Ok(())
832}
833
834fn read_script(source: &ScriptSource) -> Result<String> {
838 match source {
839 ScriptSource::Path(path) => {
840 let resolver = PathResolver::new(path.root(), path.root())?;
841 resolver
842 .read_to_string(path)
843 .with_context(|| format!("failed to read script at {}", path.display()))
844 }
845 ScriptSource::Stdin => {
846 let mut buf = String::new();
847 io::stdin()
848 .lock()
849 .read_to_string(&mut buf)
850 .context("failed to read script from stdin")?;
851 Ok(buf)
852 }
853 }
854}
855
856fn execute_with_shell_runner<F>(
857 opts: Options,
858 workspace_root: GuardedPath,
859 shell_runner: F,
860 require_tty: bool,
861) -> Result<()>
862where
863 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
864{
865 #[cfg(windows)]
866 maybe_reexec_shell_to_temp(&opts)?;
867
868 let script = match &opts.script {
872 ScriptSource::Path(_) => read_script(&opts.script)?,
873 ScriptSource::Stdin => {
874 let stdin = io::stdin();
875 if stdin.is_terminal() {
876 if opts.shell {
881 String::new()
882 } else {
883 bail!(
884 "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
885 );
886 }
887 } else {
888 let mut buf = String::new();
889 stdin
890 .lock()
891 .read_to_string(&mut buf)
892 .context("failed to read script from stdin")?;
893 buf
894 }
895 }
896 };
897
898 let mut final_cwd = workspace_root.clone();
905 let mut snapshot = Arc::new(LazyGuardedTempDir::new());
906 let mut fs: Option<Box<dyn WorkspaceFs>> = None;
907 if !script.trim().is_empty() {
908 let steps = parse_cli_script(&script)?;
909 if opts.dry_run {
912 print_dry_run(&steps, &opts.script, &workspace_root)?;
913 return Ok(());
914 }
915 #[cfg(feature = "net")]
918 let registry = build_registry(&opts.endpoints)?;
919 #[cfg(not(feature = "net"))]
920 check_no_net_endpoints(&opts.endpoints)?;
921 #[cfg(not(feature = "net"))]
922 check_no_net_remotes(&opts.remotes)?;
923 #[cfg(feature = "net")]
924 report_ephemeral_publishes(&opts.endpoints, ®istry);
925 #[cfg(feature = "net")]
929 let inventory = {
930 let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
931 inventory.log_resolutions();
932 inventory.validate_script(&steps)?;
933 inventory
934 };
935 let mut stdin_handle: Option<SharedInput> = None;
940 if let ScriptSource::Path(_) = opts.script {
941 let stdin = io::stdin();
942 if !stdin.is_terminal() {
943 stdin_handle = Some(Arc::new(Mutex::new(stdin)));
949 }
950 }
951
952 let mut io_cfg = ExecIo::new();
953 io_cfg.set_stdin(stdin_handle);
954 io_cfg.set_script_args(opts.script_args.clone());
955 #[cfg(feature = "net")]
956 register_remote_runners(&mut io_cfg, &inventory);
957 let entry_file = entry_file_of(&opts.script);
958 #[cfg(feature = "net")]
959 let output = run_cli_steps(&workspace_root, &steps, io_cfg, Some(®istry), entry_file)?;
960 #[cfg(not(feature = "net"))]
961 let output = run_cli_steps(&workspace_root, &steps, io_cfg, None, entry_file)?;
962 final_cwd = output.final_cwd;
963 snapshot = output.snapshot;
964 fs = Some(output.fs);
965 }
966
967 if opts.shell {
969 if require_tty && !has_controlling_tty() {
970 bail!("--shell requires a tty (no controlling tty available)");
971 }
972 match fs.as_ref() {
977 Some(fs) => {
978 if fs.is_snapshot_pending() {
979 snapshot
980 .materialize()
981 .context("failed to create shell temp dir")?;
982 }
983 final_cwd = fs.concretize_cwd(&final_cwd);
984 }
985 None => {
986 snapshot
987 .materialize()
988 .context("failed to create shell temp dir")?;
989 final_cwd = snapshot
990 .get()
991 .cloned()
992 .expect("shell snapshot materialized above");
993 }
994 }
995 return shell_runner(&final_cwd, &workspace_root);
996 }
997
998 Ok(())
999}
1000
1001#[cfg(test)]
1002fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
1003where
1004 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
1005{
1006 execute_with_shell_runner(opts, workspace_root, shell_runner, false)
1007}
1008
1009fn has_controlling_tty() -> bool {
1010 #[cfg(unix)]
1014 {
1015 io::stdin().is_terminal() || io::stderr().is_terminal()
1016 }
1017
1018 #[cfg(windows)]
1019 {
1020 io::stdin().is_terminal() || io::stderr().is_terminal()
1021 }
1022
1023 #[cfg(not(any(unix, windows)))]
1024 {
1025 false
1026 }
1027}
1028
1029#[cfg(windows)]
1030fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
1031 if !opts.shell {
1034 return Ok(());
1035 }
1036 if std::env::var(oxdock_env::oxdock::SHELL_REEXEC)
1037 .ok()
1038 .as_deref()
1039 == Some("1")
1040 {
1041 return Ok(());
1042 }
1043
1044 let self_path = std::env::current_exe().context("determine current executable")?;
1045 let base_temp =
1046 GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
1047 let ts = std::time::SystemTime::now()
1048 .duration_since(std::time::UNIX_EPOCH)
1049 .unwrap_or_default()
1050 .as_millis();
1051 let temp_file = base_temp
1052 .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
1053 .context("construct temp shell path")?;
1054
1055 let temp_root_guard = temp_file
1059 .parent()
1060 .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
1061 let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
1062 let dest = temp_file;
1063 #[allow(clippy::disallowed_types)]
1064 let source = oxdock_fs::UnguardedPath::external(self_path);
1065 resolver_temp
1066 .copy_file_from_unguarded(&source, &dest)
1067 .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
1068
1069 let mut cmd = CommandBuilder::new(dest.as_path());
1070 cmd.args(std::env::args_os().skip(1));
1071 cmd.env(oxdock_env::oxdock::SHELL_REEXEC, "1");
1072 cmd.spawn()
1073 .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
1074
1075 std::process::exit(0);
1077}
1078
1079pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
1080 run_steps_with_context(workspace_root, workspace_root, steps)
1081}
1082
1083fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
1084 #[cfg(windows)]
1085 let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
1086 #[cfg(windows)]
1087 let workspace_disp = oxdock_fs::command_path(workspace_root)
1088 .as_ref()
1089 .display()
1090 .to_string();
1091
1092 #[cfg(not(windows))]
1093 let cwd_disp = cwd.display().to_string();
1094 #[cfg(not(windows))]
1095 let workspace_disp = workspace_root.display().to_string();
1096
1097 let pkg = env::var(oxdock_env::cargo::PKG_NAME)
1098 .unwrap_or_else(|_| oxdock_env::oxdock::FALLBACK_APP_NAME.to_string());
1099 indoc::formatdoc! {"
1100 {pkg} shell workspace
1101 cwd: {cwd_disp}
1102 source: workspace root at {workspace_disp}
1103 lifetime: temporary directory created for this shell session; it disappears when you exit
1104 creation: temp workspace starts empty unless your script copies files into it
1105
1106 WARNING: This shell still runs on your host filesystem and is **not** isolated!
1107 "}
1108}
1109
1110fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
1111 oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
1112}
1113
1114#[cfg(test)]
1117mod tests {
1118 use super::*;
1119 use indoc::indoc;
1120 use oxdock_fs::PathResolver;
1121 use std::cell::{Cell, RefCell};
1122
1123 #[cfg_attr(
1124 miri,
1125 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1126 )]
1127 #[test]
1128 fn shell_runner_receives_final_workdir() -> Result<()> {
1129 let workspace = GuardedPath::tempdir()?;
1130 let workspace_root = workspace.as_guarded_path().clone();
1131 let script_path = workspace_root.join("script.ox")?;
1132 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1133 let script = indoc! {"
1134 WRITE temp.txt 123
1135 WORKDIR sub
1136 "};
1137 resolver.write_file(&script_path, script.as_bytes())?;
1138
1139 let opts = Options {
1140 script: ScriptSource::Path(script_path),
1141 shell: true,
1142 dry_run: false,
1143 endpoints: EndpointFlags::default(),
1144 remote_serve: false,
1145 mcp: false,
1146 remotes: Vec::new(),
1147 script_args: Vec::new(),
1148 };
1149
1150 let observed = Cell::new(false);
1151 execute_for_test(opts, workspace_root.clone(), |cwd, _| {
1152 assert!(
1153 cwd.as_path().ends_with("sub"),
1154 "final cwd should end in WORKDIR target, got {}",
1155 cwd.display()
1156 );
1157
1158 let temp_root = GuardedPath::new_root(cwd.root())
1159 .context("construct guard for temp workspace root")?;
1160 let sub_dir = temp_root.join("sub")?;
1161 assert_eq!(
1162 cwd.as_path(),
1163 sub_dir.as_path(),
1164 "shell runner cwd should match guarded sub dir"
1165 );
1166 let temp_file = temp_root.join("temp.txt")?;
1167 let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
1168 let contents = temp_resolver.read_to_string(&temp_file)?;
1169 assert!(
1170 contents.contains("123"),
1171 "expected WRITE command to materialize temp file"
1172 );
1173 observed.set(true);
1174 Ok(())
1175 })?;
1176
1177 assert!(
1178 observed.into_inner(),
1179 "shell runner closure should have been invoked"
1180 );
1181 Ok(())
1182 }
1183
1184 #[cfg_attr(
1185 miri,
1186 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1187 )]
1188 #[test]
1189 fn options_parse_requires_script_path_value() {
1190 let workspace = GuardedPath::tempdir().expect("tempdir");
1191 let mut args = vec!["--script".to_string()].into_iter();
1192 let err = Options::parse(&mut args, workspace.as_guarded_path())
1193 .expect_err("expected missing path error");
1194 assert!(err.to_string().contains("--script requires a path"));
1195 }
1196
1197 #[cfg_attr(
1198 miri,
1199 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1200 )]
1201 #[test]
1202 fn options_parse_script_flag_takes_dash_leading_path() {
1203 let workspace = GuardedPath::tempdir().expect("tempdir");
1206 let workspace_root = workspace.as_guarded_path().clone();
1207 let mut args = vec!["--script".to_string(), "--weird.ox".to_string()].into_iter();
1208 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1209 match opts.script {
1210 ScriptSource::Path(path) => assert_eq!(
1211 path,
1212 workspace_root.join("--weird.ox").expect("script path")
1213 ),
1214 ScriptSource::Stdin => panic!("expected path script"),
1215 }
1216 assert!(opts.script_args.is_empty());
1217 }
1218
1219 #[cfg_attr(
1220 miri,
1221 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1222 )]
1223 #[test]
1224 fn options_parse_script_path_and_shell() {
1225 let workspace = GuardedPath::tempdir().expect("tempdir");
1226 let workspace_root = workspace.as_guarded_path().clone();
1227 let script_path = workspace_root.join("script.txt").expect("script path");
1228 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1229 .expect("resolver");
1230 resolver
1231 .write_file(&script_path, b"WRITE out.txt hi")
1232 .expect("write script");
1233 let mut args = vec![
1236 "--shell".to_string(),
1237 "--script".to_string(),
1238 "script.txt".to_string(),
1239 ]
1240 .into_iter();
1241 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1242 assert!(opts.shell);
1243 match opts.script {
1244 ScriptSource::Path(path) => assert_eq!(path, script_path),
1245 ScriptSource::Stdin => panic!("expected path script"),
1246 }
1247 assert!(opts.script_args.is_empty());
1248
1249 let mut args = vec![
1250 "--script".to_string(),
1251 "script.txt".to_string(),
1252 "--shell".to_string(),
1253 ]
1254 .into_iter();
1255 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1256 assert!(
1257 !opts.shell,
1258 "--shell after the script is data, not the interpreter flag"
1259 );
1260 assert_eq!(opts.script_args, vec!["--shell"]);
1261 }
1262
1263 #[cfg_attr(
1264 miri,
1265 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1266 )]
1267 #[test]
1268 fn options_parse_mcp_flag() {
1269 let workspace = GuardedPath::tempdir().expect("tempdir");
1270 let workspace_root = workspace.as_guarded_path().clone();
1271 let mut args = vec!["--mcp".to_string(), "tools.oxdock".to_string()].into_iter();
1272 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1273 assert!(opts.mcp);
1274 match opts.script {
1275 ScriptSource::Path(path) => assert_eq!(
1276 path,
1277 workspace_root.join("tools.oxdock").expect("script path")
1278 ),
1279 ScriptSource::Stdin => panic!("expected path script"),
1280 }
1281 }
1282
1283 #[cfg_attr(
1284 miri,
1285 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1286 )]
1287 #[test]
1288 fn options_parse_mcp_defaults_off() {
1289 let workspace = GuardedPath::tempdir().expect("tempdir");
1290 let workspace_root = workspace.as_guarded_path().clone();
1291 let mut args = vec!["script.txt".to_string()].into_iter();
1292 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1293 assert!(!opts.mcp);
1294 }
1295
1296 #[cfg_attr(
1297 miri,
1298 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1299 )]
1300 #[test]
1301 fn options_parse_positional_script_path() {
1302 let workspace = GuardedPath::tempdir().expect("tempdir");
1303 let workspace_root = workspace.as_guarded_path().clone();
1304 let mut args = vec!["script.txt".to_string()].into_iter();
1305 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1306 assert!(!opts.shell);
1307 match opts.script {
1308 ScriptSource::Path(path) => assert_eq!(
1309 path,
1310 workspace_root.join("script.txt").expect("script path")
1311 ),
1312 ScriptSource::Stdin => panic!("expected path script"),
1313 }
1314 }
1315
1316 #[cfg_attr(
1317 miri,
1318 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1319 )]
1320 #[test]
1321 fn options_parse_positional_dash_reads_stdin() {
1322 let workspace = GuardedPath::tempdir().expect("tempdir");
1323 let mut args = vec!["-".to_string()].into_iter();
1324 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1325 assert!(matches!(opts.script, ScriptSource::Stdin));
1326 }
1327
1328 #[cfg_attr(
1329 miri,
1330 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1331 )]
1332 #[test]
1333 fn options_parse_second_positional_is_script_arg() {
1334 let workspace = GuardedPath::tempdir().expect("tempdir");
1338 let workspace_root = workspace.as_guarded_path().clone();
1339 let mut args = vec![
1340 "a.ox".to_string(),
1341 "--script".to_string(),
1342 "b.ox".to_string(),
1343 ]
1344 .into_iter();
1345 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1346 match &opts.script {
1347 ScriptSource::Path(path) => assert_eq!(
1348 path,
1349 &workspace_root.join("a.ox").expect("script path"),
1350 "first positional fixes the script"
1351 ),
1352 ScriptSource::Stdin => panic!("expected path script"),
1353 }
1354 assert_eq!(opts.script_args, vec!["--script", "b.ox"]);
1355
1356 let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1357 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1358 assert_eq!(opts.script_args, vec!["b.ox"]);
1359 }
1360
1361 #[cfg_attr(
1362 miri,
1363 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1364 )]
1365 #[test]
1366 fn options_parse_absolute_script_outside_execution_workspace_loads() {
1367 let workspace = GuardedPath::tempdir().expect("tempdir");
1370 let outside = GuardedPath::tempdir().expect("outside");
1371 let target = outside
1372 .as_guarded_path()
1373 .as_path()
1374 .join("step.ox")
1375 .to_string_lossy()
1376 .into_owned();
1377 let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1378 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1379 match opts.script {
1380 ScriptSource::Path(path) => {
1381 assert_eq!(path.as_path().to_string_lossy(), target);
1382 assert_eq!(path.root(), outside.as_guarded_path().as_path());
1383 }
1384 ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1385 }
1386 }
1387
1388 #[cfg_attr(
1389 miri,
1390 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1391 )]
1392 #[test]
1393 fn options_parse_relative_escape_stays_rejected() {
1394 let workspace = GuardedPath::tempdir().expect("tempdir");
1395 let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1396 let err =
1397 Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1398 assert!(err.to_string().contains("guard script path"), "{err:?}");
1399 }
1400
1401 #[cfg_attr(
1402 miri,
1403 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1404 )]
1405 #[test]
1406 fn options_parse_rejects_unknown_flags() {
1407 let workspace = GuardedPath::tempdir().expect("tempdir");
1408 let mut args = vec!["--frobnicate".to_string()].into_iter();
1409 let err = Options::parse(&mut args, workspace.as_guarded_path())
1410 .expect_err("expected unknown flag error");
1411 assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1412 }
1413
1414 #[test]
1415 fn usage_describes_positional_script_and_help() {
1416 let text = usage();
1417 assert!(text.contains("Usage: oxdock"), "{text}");
1418 assert!(text.contains("SCRIPT"), "{text}");
1419 assert!(text.contains("--script"), "{text}");
1420 assert!(text.contains("--help"), "{text}");
1421 assert!(text.contains("--offline"), "{text}");
1422 #[cfg(feature = "net")]
1423 {
1424 assert!(text.contains("--listen"), "{text}");
1425 assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1426 }
1427 #[cfg(not(feature = "net"))]
1428 {
1429 assert!(!text.contains("--listen <addr>"), "{text}");
1430 assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1431 assert!(text.contains("require the `net` feature"), "{text}");
1432 }
1433 assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1435 }
1436
1437 #[cfg(feature = "net")]
1438 #[cfg_attr(
1439 miri,
1440 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1441 )]
1442 #[test]
1443 fn options_parse_endpoint_flags() {
1444 let workspace = GuardedPath::tempdir().expect("tempdir");
1447 let mut args = vec![
1448 "--listen".to_string(),
1449 "0.0.0.0:2251".to_string(),
1450 "-p".to_string(),
1451 "2222:demo-proxy".to_string(),
1452 "-p".to_string(),
1453 "0:2252".to_string(),
1454 "-".to_string(),
1455 ]
1456 .into_iter();
1457 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1458 assert_eq!(opts.endpoints.listens.len(), 1);
1459 assert_eq!(opts.endpoints.publishes.len(), 2);
1460 assert!(!opts.endpoints.offline);
1461 assert!(matches!(opts.script, ScriptSource::Stdin));
1462 }
1463
1464 #[cfg_attr(
1465 miri,
1466 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1467 )]
1468 #[test]
1469 fn options_parse_offline_flag() {
1470 let workspace = GuardedPath::tempdir().expect("tempdir");
1471 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1472 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1473 assert!(opts.endpoints.offline);
1474 }
1475
1476 #[cfg(feature = "net")]
1477 #[cfg_attr(
1478 miri,
1479 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1480 )]
1481 #[test]
1482 fn options_parse_rejects_bad_endpoint_flags() {
1483 let workspace = GuardedPath::tempdir().expect("tempdir");
1484 for args in [
1485 vec!["--listen"],
1486 vec!["--listen", "0.0.0.0:0"],
1487 vec!["-p"],
1488 vec!["-p", "2222"],
1489 vec!["-p", "2222:0"],
1490 ] {
1491 let mut args = args.into_iter().map(str::to_string);
1492 Options::parse(&mut args, workspace.as_guarded_path())
1493 .expect_err("bad endpoint flag must fail");
1494 }
1495 }
1496
1497 #[cfg_attr(
1498 miri,
1499 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1500 )]
1501 #[test]
1502 fn options_parse_empty_values_hold_token_boundaries() {
1503 let workspace = GuardedPath::tempdir().expect("tempdir");
1507 let mut args = vec![
1508 "--script".to_string(),
1509 "".to_string(),
1510 "--shell".to_string(),
1511 ]
1512 .into_iter();
1513 let err = Options::parse(&mut args, workspace.as_guarded_path())
1514 .expect_err("empty script path must fail");
1515 assert!(
1516 err.to_string().contains("--script requires a path"),
1517 "{err:?}"
1518 );
1519 let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1520 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1521 assert!(matches!(opts.script, ScriptSource::Stdin));
1522 }
1523
1524 #[cfg(feature = "net")]
1525 #[cfg_attr(
1526 miri,
1527 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1528 )]
1529 #[test]
1530 fn options_parse_accepts_equals_and_attached_forms() {
1531 let workspace = GuardedPath::tempdir().expect("tempdir");
1534 let workspace_root = workspace.as_guarded_path().clone();
1535 let mut args = vec![
1536 "--listen=0.0.0.0:2251".to_string(),
1537 "-p2222:demo-proxy".to_string(),
1538 "--".to_string(),
1539 "script.ox".to_string(),
1540 ]
1541 .into_iter();
1542 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1543 assert_eq!(opts.endpoints.listens.len(), 1);
1544 assert_eq!(opts.endpoints.publishes.len(), 1);
1545 match opts.script {
1546 ScriptSource::Path(path) => {
1547 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1548 }
1549 ScriptSource::Stdin => panic!("expected path script after --"),
1550 }
1551 assert!(opts.script_args.is_empty());
1552 }
1553
1554 #[cfg_attr(
1555 miri,
1556 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1557 )]
1558 #[test]
1559 fn options_parse_routes_verbatim_tail_to_script_args() {
1560 let workspace = GuardedPath::tempdir().expect("tempdir");
1563 let workspace_root = workspace.as_guarded_path().clone();
1564 let mut args = vec![
1565 "my.ox".to_string(),
1566 "--dry-run".to_string(),
1567 "--listen".to_string(),
1568 "0.0.0.0:2251".to_string(),
1569 ]
1570 .into_iter();
1571 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1572 assert_eq!(
1573 opts.script_args,
1574 vec!["--dry-run", "--listen", "0.0.0.0:2251"]
1575 );
1576
1577 let mut args = vec![
1578 "my.ox".to_string(),
1579 "--".to_string(),
1580 "--dry-run".to_string(),
1581 ]
1582 .into_iter();
1583 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1584 assert_eq!(opts.script_args, vec!["--dry-run"]);
1585
1586 let mut args = vec![
1587 "--script".to_string(),
1588 "my.ox".to_string(),
1589 "--".to_string(),
1590 "a".to_string(),
1591 "--".to_string(),
1592 "b".to_string(),
1593 ]
1594 .into_iter();
1595 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1596 assert_eq!(opts.script_args, vec!["a", "--", "b"]);
1597 }
1598
1599 #[cfg_attr(
1600 miri,
1601 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1602 )]
1603 #[test]
1604 fn options_parse_help_after_script_is_data() {
1605 let workspace = GuardedPath::tempdir().expect("tempdir");
1607 let workspace_root = workspace.as_guarded_path().clone();
1608 let mut args = vec!["my.ox".to_string(), "--help".to_string()].into_iter();
1609 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1610 assert_eq!(opts.script_args, vec!["--help"]);
1611 let mut args = vec!["my.ox".to_string(), "--version".to_string()].into_iter();
1612 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1613 assert_eq!(opts.script_args, vec!["--version"]);
1614 }
1615
1616 #[cfg_attr(
1617 miri,
1618 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1619 )]
1620 #[test]
1621 fn options_parse_dash_leading_after_separator_is_stdin_args() {
1622 let workspace = GuardedPath::tempdir().expect("tempdir");
1625 let workspace_root = workspace.as_guarded_path().clone();
1626 let mut args = vec!["--".to_string(), "--foo".to_string()].into_iter();
1627 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1628 assert!(matches!(opts.script, ScriptSource::Stdin));
1629 assert_eq!(opts.script_args, vec!["--foo"]);
1630
1631 let mut args = vec!["--".to_string(), "script.ox".to_string()].into_iter();
1632 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1633 match opts.script {
1634 ScriptSource::Path(path) => {
1635 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1636 }
1637 ScriptSource::Stdin => panic!("expected path script"),
1638 }
1639 assert!(opts.script_args.is_empty());
1640
1641 let mut args = vec!["--".to_string(), "--".to_string(), "a".to_string()].into_iter();
1642 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1643 assert!(matches!(opts.script, ScriptSource::Stdin));
1644 assert_eq!(opts.script_args, vec!["a"]);
1645 }
1646
1647 #[cfg_attr(
1648 miri,
1649 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1650 )]
1651 #[test]
1652 fn options_parse_preserves_inner_separators_in_tail() {
1653 let workspace = GuardedPath::tempdir().expect("tempdir");
1655 let workspace_root = workspace.as_guarded_path().clone();
1656 let mut args = vec![
1657 "--".to_string(),
1658 "--foo".to_string(),
1659 "--".to_string(),
1660 "--bar".to_string(),
1661 ]
1662 .into_iter();
1663 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1664 assert!(matches!(opts.script, ScriptSource::Stdin));
1665 assert_eq!(opts.script_args, vec!["--foo", "--", "--bar"]);
1666
1667 let mut args = vec![
1668 "my.ox".to_string(),
1669 "a".to_string(),
1670 "--".to_string(),
1671 "b".to_string(),
1672 ]
1673 .into_iter();
1674 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1675 assert_eq!(opts.script_args, vec!["a", "--", "b"]);
1676 }
1677
1678 #[cfg_attr(
1679 miri,
1680 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1681 )]
1682 #[test]
1683 fn options_parse_version_returns_version_without_exiting() {
1684 let workspace = GuardedPath::tempdir().expect("tempdir");
1688 for flag in ["--version", "-V", "-v"] {
1689 let mut args = vec![flag.to_string()].into_iter();
1690 let err = Options::parse(&mut args, workspace.as_guarded_path())
1691 .expect_err("version flag must not parse as options");
1692 assert_eq!(err.to_string(), version());
1693 }
1694 }
1695
1696 #[cfg_attr(
1697 miri,
1698 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1699 )]
1700 #[test]
1701 fn options_parse_help_returns_usage_error_without_exiting() {
1702 let workspace = GuardedPath::tempdir().expect("tempdir");
1705 for flag in ["--help", "-h"] {
1706 let mut args = vec![flag.to_string()].into_iter();
1707 let err = Options::parse(&mut args, workspace.as_guarded_path())
1708 .expect_err("help flag must not parse as options");
1709 assert_eq!(err.to_string(), usage());
1710 }
1711 }
1712
1713 #[cfg_attr(
1714 miri,
1715 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1716 )]
1717 #[test]
1718 fn options_parse_rejects_remote_script_with_input_intact() {
1719 let workspace = GuardedPath::tempdir().expect("tempdir");
1720 for args in [
1721 vec!["https://example.com/process.oxfile".to_string()],
1722 vec![
1723 "--script".to_string(),
1724 "https://example.com/process.oxfile".to_string(),
1725 ],
1726 ] {
1727 let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1728 .expect_err("remote script must not parse as a path");
1729 let rendered = format!("{err:#}");
1730 assert!(
1731 rendered.contains("not a local path")
1732 && rendered.contains("https://example.com/process.oxfile"),
1733 "rejection names the intact input: {rendered}"
1734 );
1735 assert!(
1736 !rendered.contains("https:/example.com"),
1737 "scheme must never come out mangled: {rendered}"
1738 );
1739 }
1740 }
1741
1742 #[test]
1743 fn execute_with_result_runs_script() {
1744 let workspace = GuardedPath::tempdir().expect("tempdir");
1745 let workspace_root = workspace.as_guarded_path().clone();
1746 let script_path = workspace_root.join("script.txt").expect("script path");
1747 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1748 .expect("resolver");
1749 resolver
1750 .write_file(&script_path, b"WRITE out.txt hi")
1751 .expect("write script");
1752 let opts = Options {
1753 script: ScriptSource::Path(script_path),
1754 shell: false,
1755 dry_run: false,
1756 endpoints: EndpointFlags::default(),
1757 remote_serve: false,
1758 mcp: false,
1759 remotes: Vec::new(),
1760 script_args: Vec::new(),
1761 };
1762 let result = execute_with_result(opts, workspace_root).expect("execute");
1763 let snapshot = result
1764 .snapshot_path()
1765 .expect("default WRITE materializes the snapshot");
1766 assert_eq!(snapshot, &result.final_cwd);
1767 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1768 let out = snapshot.join("out.txt").expect("out path");
1769 let contents = temp_resolver.read_to_string(&out).expect("read out");
1770 assert_eq!(contents.trim(), "hi");
1771 }
1772
1773 #[cfg_attr(
1774 miri,
1775 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1776 )]
1777 #[test]
1778 fn execute_with_result_routes_script_args_to_argv() {
1779 let workspace = GuardedPath::tempdir().expect("tempdir");
1782 let workspace_root = workspace.as_guarded_path().clone();
1783 let script_path = workspace_root.join("script.txt").expect("script path");
1784 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1785 .expect("resolver");
1786 let script = indoc! {r#"
1787 IMPORT [STD]
1788 LET $args: LIST<STRING> = ARGV()
1789 LET $n: INT = LEN($args)
1790 ASSERT_EQ $n 2
1791 ASSERT_EQ $args.0 "--dry-run"
1792 ASSERT_EQ $args.1 "serve"
1793 WRITE out.txt "ok"
1794 "#};
1795 resolver
1796 .write_file(&script_path, script.as_bytes())
1797 .expect("write script");
1798 let mut args = vec![
1801 "script.txt".to_string(),
1802 "--".to_string(),
1803 "--dry-run".to_string(),
1804 "serve".to_string(),
1805 ]
1806 .into_iter();
1807 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1808 assert_eq!(opts.script_args, vec!["--dry-run", "serve"]);
1809 let result = execute_with_result(opts, workspace_root).expect("execute");
1810 let snapshot = result
1811 .snapshot_path()
1812 .expect("WRITE materializes the snapshot");
1813 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1814 let out = snapshot.join("out.txt").expect("out path");
1815 assert_eq!(
1816 temp_resolver.read_to_string(&out).expect("read").trim(),
1817 "ok"
1818 );
1819 }
1820
1821 #[cfg_attr(
1822 miri,
1823 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1824 )]
1825 #[test]
1826 fn execute_with_result_local_only_creates_no_snapshot() {
1827 let workspace = GuardedPath::tempdir().expect("tempdir");
1828 let workspace_root = workspace.as_guarded_path().clone();
1829 let script_path = workspace_root.join("script.txt").expect("script path");
1830 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1831 .expect("resolver");
1832 resolver
1833 .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1834 .expect("write script");
1835 let opts = Options {
1836 script: ScriptSource::Path(script_path),
1837 shell: false,
1838 dry_run: false,
1839 endpoints: EndpointFlags::default(),
1840 remote_serve: false,
1841 mcp: false,
1842 remotes: Vec::new(),
1843 script_args: Vec::new(),
1844 };
1845 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1846 assert!(
1847 !result.has_snapshot(),
1848 "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1849 );
1850 assert!(result.snapshot_path().is_none());
1851 let out = workspace_root.join("out.txt").expect("out path");
1853 let contents = resolver.read_to_string(&out).expect("read out");
1854 assert_eq!(contents.trim(), "hi");
1855 assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1857 }
1858
1859 #[cfg_attr(
1860 miri,
1861 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1862 )]
1863 #[test]
1864 fn execute_with_result_empty_script_creates_no_snapshot() {
1865 let workspace = GuardedPath::tempdir().expect("tempdir");
1866 let workspace_root = workspace.as_guarded_path().clone();
1867 let script_path = workspace_root.join("empty.txt").expect("script path");
1868 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1869 .expect("resolver");
1870 resolver
1871 .write_file(&script_path, b"")
1872 .expect("write script");
1873 let opts = Options {
1874 script: ScriptSource::Path(script_path),
1875 shell: false,
1876 dry_run: false,
1877 endpoints: EndpointFlags::default(),
1878 remote_serve: false,
1879 mcp: false,
1880 remotes: Vec::new(),
1881 script_args: Vec::new(),
1882 };
1883 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1884 assert!(
1885 !result.has_snapshot(),
1886 "empty script must not create a snapshot tempdir"
1887 );
1888 assert_eq!(result.final_cwd, workspace_root);
1889 }
1890
1891 #[cfg_attr(
1892 miri,
1893 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1894 )]
1895 #[test]
1896 fn execute_for_test_invokes_shell_runner() -> Result<()> {
1897 let workspace = GuardedPath::tempdir()?;
1898 let workspace_root = workspace.as_guarded_path().clone();
1899 let script_path = workspace_root.join("empty.txt")?;
1900 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1901 resolver.write_file(&script_path, b"")?;
1902 let opts = Options {
1903 script: ScriptSource::Path(script_path),
1904 shell: true,
1905 dry_run: false,
1906 endpoints: EndpointFlags::default(),
1907 remote_serve: false,
1908 mcp: false,
1909 remotes: Vec::new(),
1910 script_args: Vec::new(),
1911 };
1912 let called = RefCell::new(None::<(String, String)>);
1913 execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1914 called.replace(Some((cwd.display(), workspace.display())));
1915 assert!(
1918 cwd.exists(),
1919 "shell cwd must exist on disk, got {}",
1920 cwd.display()
1921 );
1922 Ok(())
1923 })?;
1924 let seen = called.borrow().clone().expect("shell runner called");
1925 assert_eq!(seen.1, workspace_root.display());
1926 Ok(())
1927 }
1928
1929 #[cfg(feature = "ssh")]
1933 #[cfg_attr(
1934 miri,
1935 ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1936 )]
1937 #[test]
1938 fn ssh_feature_serves_and_closes() -> Result<()> {
1939 let workspace = GuardedPath::tempdir()?;
1940 let workspace_root = workspace.as_guarded_path().clone();
1941 let script_path = workspace_root.join("ssh-serve.ox")?;
1942 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1943 let script = indoc! {"
1944 IMPORT [STD, SSH]
1945 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"cli-ssh-svc\", {username: \"test\", password: \"test123\"})
1946 SSH_CLOSE($m.server)
1947 "};
1948 resolver.write_file(&script_path, script.as_bytes())?;
1949 let opts = Options {
1950 script: ScriptSource::Path(script_path),
1951 shell: false,
1952 dry_run: false,
1953 endpoints: EndpointFlags {
1954 publishes: vec![(
1955 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1956 "cli-ssh-svc".to_string(),
1957 )],
1958 ..EndpointFlags::default()
1959 },
1960 remote_serve: false,
1961 mcp: false,
1962 remotes: Vec::new(),
1963 script_args: Vec::new(),
1964 };
1965 execute_with_result(opts, workspace_root)?;
1966 Ok(())
1967 }
1968
1969 #[cfg(feature = "net")]
1973 #[cfg_attr(
1974 miri,
1975 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1976 )]
1977 #[test]
1978 fn net_module_listens_and_closes() -> Result<()> {
1979 let workspace = GuardedPath::tempdir()?;
1980 let workspace_root = workspace.as_guarded_path().clone();
1981 let script_path = workspace_root.join("net-listen.ox")?;
1982 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1983 let script = indoc! {"
1984 IMPORT [STD, NET]
1985 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1986 NET_CLOSE($l.listener)
1987 "};
1988 resolver.write_file(&script_path, script.as_bytes())?;
1989 let opts = Options {
1990 script: ScriptSource::Path(script_path),
1991 shell: false,
1992 dry_run: false,
1993 endpoints: EndpointFlags {
1996 publishes: vec![(
1997 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1998 "23501".to_string(),
1999 )],
2000 ..EndpointFlags::default()
2001 },
2002 remote_serve: false,
2003 mcp: false,
2004 remotes: Vec::new(),
2005 script_args: Vec::new(),
2006 };
2007 execute_with_result(opts, workspace_root)?;
2008 Ok(())
2009 }
2010
2011 #[cfg(feature = "net")]
2015 #[cfg_attr(
2016 miri,
2017 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
2018 )]
2019 #[test]
2020 fn net_port_addr_observe_publish_mapping() -> Result<()> {
2021 let workspace = GuardedPath::tempdir()?;
2022 let workspace_root = workspace.as_guarded_path().clone();
2023 let script_path = workspace_root.join("net-port.ox")?;
2024 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2025 let script = indoc! {"
2026 IMPORT [STD, NET]
2027 LET $port: INT = NET_PORT(\"routed-svc\")
2028 WRITE port.txt \"{{ $port }}\"
2029 LET $addr: STRING = NET_ADDR(\"routed-svc\")
2030 WRITE addr.txt \"{{ $addr }}\"
2031 "};
2032 resolver.write_file(&script_path, script.as_bytes())?;
2033 let opts = Options {
2034 script: ScriptSource::Path(script_path),
2035 shell: false,
2036 dry_run: false,
2037 endpoints: EndpointFlags {
2038 publishes: vec![(
2039 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
2040 "routed-svc".to_string(),
2041 )],
2042 ..EndpointFlags::default()
2043 },
2044 remote_serve: false,
2045 mcp: false,
2046 remotes: Vec::new(),
2047 script_args: Vec::new(),
2048 };
2049 let result = execute_with_result(opts, workspace_root)?;
2050 let snapshot = result
2051 .snapshot_path()
2052 .expect("WRITE materializes the snapshot");
2053 let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
2054 let port_path = snapshot.join("port.txt")?;
2055 let port_text = snapshot_resolver.read_to_string(&port_path)?;
2056 let port: u16 = port_text
2057 .trim()
2058 .parse()
2059 .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
2060 assert_ne!(port, 0, "ephemeral outer port must resolve");
2061 let addr_path = snapshot.join("addr.txt")?;
2062 let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
2063 assert!(
2064 addr_text.trim().ends_with(&format!(":{port}")),
2065 "dial string must carry the resolved port, got {addr_text:?}"
2066 );
2067 Ok(())
2068 }
2069
2070 #[cfg(not(feature = "ssh"))]
2073 #[cfg_attr(
2074 miri,
2075 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2076 )]
2077 #[test]
2078 fn ssh_scripts_rejected_without_feature() -> Result<()> {
2079 let workspace = GuardedPath::tempdir()?;
2080 let workspace_root = workspace.as_guarded_path().clone();
2081 let script_path = workspace_root.join("ssh-serve.ox")?;
2082 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2083 let script = indoc! {"
2084 IMPORT [STD, SSH]
2085 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
2086 SSH_CLOSE($m.server)
2087 "};
2088 resolver.write_file(&script_path, script.as_bytes())?;
2089 let opts = Options {
2090 script: ScriptSource::Path(script_path),
2091 shell: false,
2092 dry_run: false,
2093 endpoints: EndpointFlags::default(),
2094 remote_serve: false,
2095 mcp: false,
2096 remotes: Vec::new(),
2097 script_args: Vec::new(),
2098 };
2099 let err = match execute_with_result(opts, workspace_root) {
2100 Ok(_) => panic!("SSH names must be unknown without the feature"),
2101 Err(err) => err,
2102 };
2103 assert!(err.to_string().contains("SSH"), "{err}");
2104 Ok(())
2105 }
2106
2107 #[cfg(not(feature = "net"))]
2111 #[cfg_attr(
2112 miri,
2113 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2114 )]
2115 #[test]
2116 fn net_flags_rejected_without_feature() {
2117 let workspace = GuardedPath::tempdir().expect("tempdir");
2118 for args in [
2119 vec!["--listen", "0.0.0.0:2251", "-"],
2120 vec!["-p", "2222:2251", "-"],
2121 vec!["--listen=0.0.0.0:2251", "-"],
2122 ] {
2123 let mut args = args.into_iter().map(str::to_string);
2124 let err = Options::parse(&mut args, workspace.as_guarded_path())
2125 .expect_err("endpoint flag must fail without net");
2126 assert!(
2127 err.to_string().contains("require the `net` feature"),
2128 "{err:?}"
2129 );
2130 }
2131 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
2132 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
2133 assert!(opts.endpoints.offline);
2134 }
2135
2136 #[cfg(not(feature = "net"))]
2139 #[cfg_attr(
2140 miri,
2141 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2142 )]
2143 #[test]
2144 fn net_scripts_rejected_without_feature() -> Result<()> {
2145 let workspace = GuardedPath::tempdir()?;
2146 let workspace_root = workspace.as_guarded_path().clone();
2147 let script_path = workspace_root.join("net-listen.ox")?;
2148 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2149 let script = indoc! {"
2150 IMPORT [STD, NET]
2151 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
2152 LET $body: STRING = NET_FETCH(\"https://example.com/x\")
2153 NET_CLOSE($l.listener)
2154 "};
2155 resolver.write_file(&script_path, script.as_bytes())?;
2156 let opts = Options {
2157 script: ScriptSource::Path(script_path),
2158 shell: false,
2159 dry_run: false,
2160 endpoints: EndpointFlags::default(),
2161 remote_serve: false,
2162 mcp: false,
2163 remotes: Vec::new(),
2164 script_args: Vec::new(),
2165 };
2166 let err = match execute_with_result(opts, workspace_root) {
2167 Ok(_) => panic!("NET names must be unknown without the feature"),
2168 Err(err) => err,
2169 };
2170 assert!(err.to_string().contains("NET"), "{err}");
2171 Ok(())
2172 }
2173
2174 #[test]
2175 fn process_exit_code_relays_exit_requests() {
2176 let exit = anyhow::Error::new(ExitRequest(3));
2177 assert_eq!(process_exit_code(&exit), 3);
2178 let relayed =
2179 anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' exited with code 3");
2180 assert_eq!(process_exit_code(&relayed), 3);
2181 assert_eq!(process_exit_code(&anyhow::anyhow!("boom")), 1);
2182 assert_eq!(
2183 process_exit_code(&anyhow::Error::new(ExitRequest(300))),
2184 255,
2185 "codes clamp to the portable range"
2186 );
2187 assert_eq!(
2188 process_exit_code(&anyhow::Error::new(ExitRequest(-1))),
2189 0,
2190 "negative codes clamp to zero"
2191 );
2192 }
2193}
2194
2195#[cfg(all(test, windows))]
2196mod windows_shell_tests {
2197 use super::*;
2198
2199 #[test]
2200 fn command_path_strips_verbatim_prefix() -> Result<()> {
2201 let temp = GuardedPath::tempdir()?;
2202 let converted = oxdock_fs::command_path(temp.as_guarded_path());
2203 let as_str = converted.as_ref().display().to_string();
2204 assert!(
2205 !as_str.starts_with(r"\\?\"),
2206 "expected non-verbatim path, got {as_str}"
2207 );
2208 Ok(())
2209 }
2210}