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