Skip to main content

oxdock_cli/
lib.rs

1use anyhow::{Context, Result, bail};
2use oxdock_fs::{
3    GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, discover_workspace_root,
4    env as oxdock_env, init_temp_gc,
5};
6#[cfg(windows)]
7use oxdock_process::CommandBuilder;
8use oxdock_process::{DefaultProcessManager, SharedInput};
9use std::env;
10use std::io::{self, IsTerminal, Read};
11use std::sync::{Arc, Mutex};
12
13pub use oxdock_core::{
14    Engine, EngineOutput, ExecState, ExitRequest, FuncKind, FuncMeta, FuncParam, HostModule,
15    HostRegistration, NativeFn, OxDockFn, OxDockType, PureFn, PushManifestSink, StepCtx,
16    TypeDescriptor, Value, exit_code_of, parse_script, parse_script_with_modules, run_steps,
17    run_steps_with_context, run_steps_with_context_result, run_steps_with_manager_with_modules,
18};
19use oxdock_core::{ExecIo, run_steps_with_lazy_snapshot_and_modules};
20pub use oxdock_parser::{Guard, Step, StepKind};
21pub use oxdock_process::shell_program;
22use std::collections::BTreeMap;
23
24mod endpoints;
25pub use endpoints::EndpointFlags;
26
27// CLI usage bodies, one file per Cargo feature variant: statically
28// compiled assets cannot branch on Cargo features, so the script
29// renders both variants (version line included, through inherited
30// Cargo metadata) and Rust `#[cfg]` picks the live one.
31use oxdock_macros::oxdock_embed;
32oxdock_embed! {
33    name: UsageAssets,
34    script: {
35        INHERIT_ENV [CARGO_PKG_VERSION, CARGO_PKG_DESCRIPTION]
36        FUNC EMIT_BODY($is_net: BOOL) {
37            ECHO "oxdock {{ env:CARGO_PKG_VERSION }} — {{ env:CARGO_PKG_DESCRIPTION }}"
38            ECHO ""
39            ECHO "Usage: oxdock [OPTIONS] [SCRIPT]"
40            ECHO "  SCRIPT             script file path (same as `--script <file>`); `-` reads stdin"
41            ECHO "  --script <file|->  script file (relative resolves under the OxDock workspace root), or `-` for stdin"
42            ECHO "  --shell            run the script, then drop into an interactive shell (requires a TTY)"
43            IF $is_net {
44                ECHO "  --listen <addr>    expose a logical service port ([host:]port, repeatable)"
45                ECHO "  -p <[host:]outer:inner>  map outer port to an inner service port or name (repeatable; outer 0 is ephemeral; bare outer binds loopback, prefix 0.0.0.0: for all interfaces)"
46                ECHO "  --offline          open no sockets (conflicts with --listen/-p)"
47                ECHO "  --remote TARGET=CMD    bind a REMOTE target to a stdio transport command (repeatable)"
48            } ELSE {
49                ECHO "  --offline          open no sockets (endpoint flags require the `net` feature)"
50            }
51            ECHO "  --help, -h         print this help and exit"
52            ECHO "  --version, -V      print the version and exit"
53            ECHO ""
54            ECHO "With no script given, reads the script from stdin (must be piped unless `--shell`)."
55            IF $is_net {
56                ECHO "Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces."
57            } ELSE {
58                ECHO "Endpoint flags (--listen/-p) require the `net` feature (rebuild with --features net)."
59            }
60        }
61        LET $p: PIPE
62        WITH_IO [stdout=$p] {
63            EMIT_BODY(true)
64        }
65        WITH_IO [stdin=$p] WRITE dist/usage-net.txt
66        WITH_IO [stdout=$p] {
67            EMIT_BODY(false)
68        }
69        WITH_IO [stdin=$p] WRITE dist/usage-lean.txt
70    },
71    out_dir: "usage-prebuilt",
72}
73#[cfg(feature = "net")]
74pub use endpoints::build_registry;
75#[cfg(feature = "net")]
76use oxdock_net_plugin::EndpointRegistry;
77#[cfg(feature = "net")]
78mod serve;
79
80/// Host modules bundled into the CLI runner. With `net` this exposes STD
81/// plus the NET virtual-endpoint toolkit (`NET_LISTEN`, `NET_ACCEPT`,
82/// `NET_CLOSE`, `NET_CONNECT`, `NET_PORT`, `NET_ADDR`); with `--features
83/// ssh` it additionally registers the SSH server and client (`SSH_SERVE`,
84/// `SSH_ACCEPT`, `SSH_DEQUEUE`, `SSH_PUMP_CHANNEL`, `SSH_CLOSE`,
85/// `SSH_CONNECT`, `SSH_PUMP`) from oxdock-ssh-plugin; with `--features
86/// markdown` it registers the MARKDOWN helpers (`MAP_TO_MD_TABLE`,
87/// `TOC`, `PARSE`, `SECTION`). Without features only STD builtins remain.
88fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
89    cli_host_modules_with(None)
90}
91
92/// Module surface for the guest serve loop: identical to the host runner
93/// surface so handshake language-surface identity actually compares the
94/// same tables both ends run.
95#[cfg(feature = "net")]
96fn cli_host_modules_for_serve() -> Vec<HostModule<DefaultProcessManager>> {
97    cli_host_modules_with(None)
98}
99
100/// Module-table digest for the remote handshake: sha256 over sorted
101/// `module::function` entries from the serve surface.
102#[cfg(feature = "net")]
103fn remote_session_module_hash(entries: &[(String, Vec<String>)]) -> String {
104    oxdock_net_plugin::module_hash(entries)
105}
106
107/// Host modules resolving virtual endpoints through `registry`: the CLI
108/// builds it from `--listen`/`-p`/`--offline` before parsing so bind
109/// conflicts fail fast. `None` registers default module instances (enough
110/// for parse-time name resolution); without `net` no modules are pushed.
111/// The parameter type is feature-dependent because the registry type only
112/// exists with `net`; callers pass `Some` with `net` and `None` without.
113fn cli_host_modules_with(
114    #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
115    #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
116) -> Vec<HostModule<DefaultProcessManager>> {
117    #[cfg(any(feature = "net", feature = "markdown"))]
118    let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
119    #[cfg(not(any(feature = "net", feature = "markdown")))]
120    let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
121    #[cfg(feature = "net")]
122    {
123        let net_module = match registry {
124            Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
125            None => oxdock_net_plugin::module(),
126        };
127        modules.push(net_module);
128        #[cfg(feature = "ssh")]
129        {
130            let ssh_module = match registry {
131                Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
132                None => oxdock_ssh_plugin::module(),
133            };
134            modules.push(ssh_module);
135        }
136    }
137    #[cfg(feature = "markdown")]
138    modules.push(oxdock_markdown_plugin::module());
139    let _ = registry;
140    modules
141}
142
143/// Host types bundled into the CLI runner alongside [`cli_host_modules`].
144fn cli_host_types() -> Vec<&'static TypeDescriptor> {
145    #[cfg(feature = "net")]
146    let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
147    #[cfg(not(feature = "net"))]
148    let net: &[&'static TypeDescriptor] = &[];
149    #[cfg(feature = "ssh")]
150    let ssh: &[&'static TypeDescriptor] = &[
151        oxdock_ssh_plugin::SshServerTag::descriptor(),
152        oxdock_ssh_plugin::SshSessionTag::descriptor(),
153    ];
154    #[cfg(not(feature = "ssh"))]
155    let ssh: &[&'static TypeDescriptor] = &[];
156    net.iter().chain(ssh.iter()).copied().collect()
157}
158
159/// Parse a CLI script against STD plus any bundled host modules. Without
160/// extra modules this is exactly `parse_script`, so base-build behavior
161/// never changes.
162fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
163    let modules = cli_host_modules();
164    if modules.is_empty() {
165        parse_script(script)
166    } else {
167        let mut engine = Engine::new();
168        for module in modules {
169            engine.register_module(module);
170        }
171        parse_script_with_modules(script, engine.module_table())
172    }
173}
174
175pub fn run() -> Result<()> {
176    init_temp_gc();
177    let workspace_root = discover_workspace_root().context("guard workspace root")?;
178
179    let mut args = std::env::args().skip(1);
180    // `--help`/`-h` and `--version`/`-V` surface as text in the parse
181    // error (parse must not exit the process itself: it is public
182    // library API). Print it and succeed so the binary exits 0.
183    let opts = match Options::parse(&mut args, &workspace_root) {
184        Ok(opts) => opts,
185        Err(err) if err.to_string() == version() => {
186            println!("{err}");
187            return Ok(());
188        }
189        Err(err) if err.to_string() == usage() => {
190            print!("{err}");
191            return Ok(());
192        }
193        Err(err) => return Err(err),
194    };
195    // Guest serve mode short-circuits everything: no script, no snapshot,
196    // no shell. Binary stdio contract enforced inside.
197    #[cfg(feature = "net")]
198    if opts.remote_serve {
199        if opts.shell || !opts.remotes.is_empty() || !matches!(opts.script, ScriptSource::Stdin) {
200            bail!("--remote-serve runs alone (no --script, --shell, or --remote)");
201        }
202        return serve::serve();
203    }
204    #[cfg(not(feature = "net"))]
205    if opts.remote_serve {
206        bail!("--remote-serve requires the `net` feature (rebuild with --features net)");
207    }
208    execute(opts, workspace_root)
209}
210
211/// Process exit status for a failed CLI run: relays an `EXIT` code (host
212/// or guest-relayed) clamped to the portable 0..=255 range, 1 for every
213/// other failure.
214pub fn process_exit_code(err: &anyhow::Error) -> i32 {
215    exit_code_of(err)
216        .map(|code| code.clamp(0, 255) as i32)
217        .unwrap_or(1)
218}
219
220#[derive(Debug, Clone)]
221pub enum ScriptSource {
222    Path(GuardedPath),
223    Stdin,
224}
225
226/// URLs never resolve to workspace files: fail with the input intact
227/// instead of letting normalization mangle the scheme. Present fact
228/// about this argument, not a claim about imports.
229fn reject_url_script(text: &str) -> Result<()> {
230    if text.contains("://") {
231        bail!("not a local path: {text:?} (pass a workspace path or `-` for stdin)");
232    }
233    Ok(())
234}
235
236#[derive(Debug, Clone)]
237pub struct Options {
238    pub script: ScriptSource,
239    pub shell: bool,
240    pub endpoints: EndpointFlags,
241    pub remote_serve: bool,
242    /// Raw `--remote <target>="<command>"` pairs, in flag order. Validated
243    /// and tokenized at inventory build; empty in lean builds (flag bails).
244    pub remotes: Vec<(String, String)>,
245}
246
247impl Options {
248    pub fn parse(
249        args: &mut impl Iterator<Item = String>,
250        workspace_root: &GuardedPath,
251    ) -> Result<Self> {
252        use lexopt::Arg::{Long, Short, Value};
253
254        let mut script: Option<ScriptSource> = None;
255        let mut shell = false;
256        let mut endpoints = EndpointFlags::default();
257        let mut remote_serve = false;
258        // Pushed only under `net`; without it the binding never mutates.
259        #[cfg_attr(not(feature = "net"), allow(unused_mut))]
260        let mut remotes: Vec<(String, String)> = Vec::new();
261        let mut set_script = |source: ScriptSource, origin: &str| -> Result<()> {
262            if script.is_some() {
263                bail!("script given multiple times ({origin})");
264            }
265            script = Some(source);
266            Ok(())
267        };
268        // Pass the stream unfiltered: an explicit empty value (for
269        // example `--script ""`) is a real token boundary, so stripping
270        // empties up front would shift every following value. Bare empty
271        // positionals are skipped in the `Value` arm instead.
272        let mut parser = lexopt::Parser::from_args(args.by_ref());
273        while let Some(arg) = parser.next()? {
274            match arg {
275                Long("script") => {
276                    let path = value_string(
277                        parser
278                            .value()
279                            .map_err(|_| anyhow::anyhow!("--script requires a path"))?,
280                    )?;
281                    if path.is_empty() {
282                        bail!("--script requires a path");
283                    }
284                    if path == "-" {
285                        set_script(ScriptSource::Stdin, "--script -")?;
286                    } else {
287                        reject_url_script(&path)?;
288                        set_script(
289                            ScriptSource::Path(
290                                workspace_root
291                                    .join_script(&path)
292                                    .with_context(|| format!("guard script path {path}"))?,
293                            ),
294                            "--script",
295                        )?;
296                    }
297                }
298                Long("shell") => {
299                    shell = true;
300                }
301                Long("listen") => {
302                    let raw = value_string(
303                        parser
304                            .value()
305                            .map_err(|_| anyhow::anyhow!("--listen requires an address"))?,
306                    )?;
307                    #[cfg(not(feature = "net"))]
308                    {
309                        // Evaluate the pure validator so it stays compiled
310                        // and covered in lean builds; the feature error below
311                        // still wins regardless of the value.
312                        let _ = endpoints::parse_listen_arg(&raw);
313                        bail!(
314                            "--listen/-p require the `net` feature (rebuild with --features net)"
315                        );
316                    }
317                    #[cfg(feature = "net")]
318                    endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
319                }
320                Short('p') => {
321                    let raw = value_string(
322                        parser
323                            .value()
324                            .map_err(|_| anyhow::anyhow!("-p requires outer:inner"))?,
325                    )?;
326                    #[cfg(not(feature = "net"))]
327                    {
328                        // Same as `--listen` above: keep the pure outer
329                        // validation live in lean builds; the feature error
330                        // below still wins.
331                        let _ = endpoints::parse_publish_arg(&raw);
332                        bail!(
333                            "--listen/-p require the `net` feature (rebuild with --features net)"
334                        );
335                    }
336                    #[cfg(feature = "net")]
337                    endpoints
338                        .publishes
339                        .push(endpoints::parse_publish_arg(&raw)?);
340                }
341                Long("offline") => {
342                    endpoints.offline = true;
343                }
344                Long("remote-serve") => {
345                    remote_serve = true;
346                }
347                Long("remote") => {
348                    let raw = value_string(parser.value().map_err(|_| {
349                        anyhow::anyhow!("--remote requires <target>=\"<command>\"")
350                    })?)?;
351                    #[cfg(not(feature = "net"))]
352                    {
353                        // Keep the pure validator live in lean builds; the
354                        // feature error below still wins.
355                        let _ = oxdock_net_plugin_stub_parse_remote(&raw);
356                        bail!("--remote requires the `net` feature (rebuild with --features net)");
357                    }
358                    #[cfg(feature = "net")]
359                    remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
360                }
361                Long("help") | Short('h') => {
362                    bail!("{}", usage());
363                }
364                Long("version") | Short('V') => {
365                    bail!("{}", version());
366                }
367                Value(value) => {
368                    let text = value_string(value)?;
369                    if text.is_empty() {
370                        continue;
371                    }
372                    if text == "-" {
373                        set_script(ScriptSource::Stdin, "positional `-`")?;
374                    } else {
375                        reject_url_script(&text)?;
376                        set_script(
377                            ScriptSource::Path(
378                                workspace_root
379                                    .join_script(&text)
380                                    .with_context(|| format!("guard script path {text}"))?,
381                            ),
382                            "positional argument",
383                        )?;
384                    }
385                }
386                Long(other) => bail!("unexpected flag: --{other}"),
387                Short(other) => bail!("unexpected flag: -{other}"),
388            }
389        }
390
391        let script = script.unwrap_or(ScriptSource::Stdin);
392
393        Ok(Self {
394            script,
395            shell,
396            endpoints,
397            remote_serve,
398            remotes,
399        })
400    }
401}
402
403/// Option/positional text out of a lexopt value. Inputs arrive as
404/// `String`, so non-UTF8 is unreachable in practice; fail loudly anyway.
405fn value_string(value: std::ffi::OsString) -> Result<String> {
406    value
407        .into_string()
408        .map_err(|_| anyhow::anyhow!("argument must be UTF-8"))
409}
410
411/// Human-readable CLI version, printed for `--version`/`-V`.
412pub fn version() -> String {
413    format!("oxdock {}", env!("CARGO_PKG_VERSION"))
414}
415
416/// Human-readable CLI usage, printed for `--help`/`-h`. The full
417/// text, version line included, is rendered once at compile time by
418/// the `UsageAssets` script above. Feature selection stays in Rust
419/// `#[cfg]`: the DSL has no feature namespace, so each variant lives
420/// in its own asset file.
421pub fn usage() -> String {
422    #[cfg(feature = "net")]
423    let asset = "dist/usage-net.txt";
424    #[cfg(not(feature = "net"))]
425    let asset = "dist/usage-lean.txt";
426    let file = UsageAssets::get(asset).expect("usage must be embedded");
427    str::from_utf8(file.data.as_ref())
428        .expect("usage is UTF-8")
429        .to_string()
430}
431
432pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
433    init_temp_gc();
434    execute_with_shell_runner(opts, workspace_root, run_shell, true)
435}
436
437/// Output of a script execution (issue #131).
438///
439/// The snapshot directory is created lazily: [`ExecutionResult::snapshot`]
440/// stays unmaterialized when the script never touches snapshot-rooted state
441/// (e.g. `WORKSPACE LOCAL`-only or empty scripts), in which case
442/// [`ExecutionResult::has_snapshot`] is false and `final_cwd` points under
443/// the workspace root.
444pub struct ExecutionResult {
445    /// Shared ownership of the snapshot backing dir. The physical directory
446    /// lives exactly as long as the last surviving clone (normally this
447    /// struct, since execution-internal clones are dropped before return).
448    pub snapshot: Arc<LazyGuardedTempDir>,
449    /// Actual final cwd: inside the snapshot when materialized, otherwise
450    /// under the workspace/local root.
451    pub final_cwd: GuardedPath,
452    /// Top-level script variable bindings captured at completion, keyed by
453    /// variable name. Empty when the script is empty. Populated exclusively
454    /// by [`execute_with_result`]; `--shell` runs never produce one.
455    pub bindings: BTreeMap<String, Value>,
456}
457
458impl ExecutionResult {
459    /// Whether the run materialized the snapshot tempdir.
460    pub fn has_snapshot(&self) -> bool {
461        self.snapshot.is_materialized()
462    }
463
464    /// Borrow the snapshot root iff materialized.
465    pub fn snapshot_path(&self) -> Option<&GuardedPath> {
466        self.snapshot.get()
467    }
468}
469
470pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
471    if opts.shell {
472        bail!("execute_with_result does not support --shell");
473    }
474
475    // Read + parse BEFORE any tempdir exists so LOCAL-only scripts never
476    // create a snapshot directory they never use (issue #131).
477    let script = read_script(&opts.script)?;
478
479    let mut final_cwd = workspace_root.clone();
480    let snapshot = Arc::new(LazyGuardedTempDir::new());
481    if !script.trim().is_empty() {
482        // Bind endpoint sockets before parsing: conflicts fail fast,
483        // never parse-then-fail-on-bind.
484        #[cfg(feature = "net")]
485        let registry = build_registry(&opts.endpoints)?;
486        #[cfg(not(feature = "net"))]
487        check_no_net_endpoints(&opts.endpoints)?;
488        #[cfg(not(feature = "net"))]
489        check_no_net_remotes(&opts.remotes)?;
490        let steps = parse_cli_script(&script)?;
491        // Validate REMOTE targets against inventory after parsing (targets
492        // live in AST nodes) and before execution: unknown targets fail
493        // here, never mid-run.
494        #[cfg(feature = "net")]
495        let inventory = {
496            let pairs = opts.remotes.clone();
497            let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
498            inventory.log_resolutions();
499            inventory.validate_script(&steps)?;
500            inventory
501        };
502        #[cfg(feature = "net")]
503        let output = {
504            let mut io_cfg = ExecIo::new();
505            register_remote_runners(&mut io_cfg, &inventory);
506            run_steps_with_lazy_snapshot_and_modules(
507                &workspace_root,
508                &steps,
509                io_cfg,
510                cli_host_modules_with(Some(&registry)),
511                cli_host_types(),
512            )?
513        };
514        #[cfg(not(feature = "net"))]
515        let output = run_steps_with_lazy_snapshot_and_modules(
516            &workspace_root,
517            &steps,
518            ExecIo::new(),
519            cli_host_modules_with(None),
520            cli_host_types(),
521        )?;
522        final_cwd = output.final_cwd;
523        return Ok(ExecutionResult {
524            snapshot: output.snapshot,
525            final_cwd,
526            bindings: output.bindings,
527        });
528    }
529
530    Ok(ExecutionResult {
531        snapshot,
532        final_cwd,
533        bindings: BTreeMap::new(),
534    })
535}
536
537/// Register one SSH stdio session per inventory target on the run IO.
538/// Lazy spawn still applies (no process exists until a block entry), but
539/// registration happens up front so `REMOTE` interception always finds a
540/// runner when the target validated.
541#[cfg(feature = "net")]
542fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
543    use std::sync::Arc;
544    let entries = surface_entries();
545    let module_hash = oxdock_net_plugin::module_hash(&entries);
546    let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
547    for target in inventory.targets() {
548        let Some(argv) = inventory.argv(&target) else {
549            continue;
550        };
551        let config = oxdock_net_plugin::SessionConfig {
552            argv: argv.to_vec(),
553            oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
554            modules: modules.clone(),
555            module_hash: module_hash.clone(),
556        };
557        io.set_remote_runner_for_target(
558            target,
559            Arc::new(oxdock_net_plugin::StdioSession::new(config)),
560        );
561    }
562}
563
564/// Module-table surface for handshake identity and session config: the
565/// same tables the run executes against.
566#[cfg(feature = "net")]
567fn surface_entries() -> Vec<(String, Vec<String>)> {
568    let mut engine = Engine::new();
569    for module in cli_host_modules() {
570        engine.register_module(module);
571    }
572    let table = engine.module_table();
573    let mut entries: Vec<(String, Vec<String>)> = table
574        .modules
575        .into_iter()
576        .map(|(name, funcs)| {
577            let mut functions: Vec<String> = funcs
578                .map(|surface| surface.functions.into_iter().collect())
579                .unwrap_or_default();
580            functions.sort();
581            (name, functions)
582        })
583        .collect();
584    entries.sort();
585    entries
586}
587#[cfg(feature = "net")]
588fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
589    use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
590    for (outer, inner) in &flags.publishes {
591        if outer.port() != 0 {
592            continue;
593        }
594        let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
595            continue;
596        };
597        let key = EndpointKey {
598            protocol: protocol.unwrap_or(Protocol::Tcp),
599            endpoint,
600        };
601        match registry.resolve_endpoint(&key) {
602            Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
603            Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
604        }
605    }
606}
607
608/// Without `net`, remote targets cannot exist: `--remote` is rejected
609/// at flag parse time; this covers programmatic `Options` carrying pairs.
610#[cfg(not(feature = "net"))]
611fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> Result<(String, String)> {
612    // Mirror the NET plugin's shape check without the dependency so the
613    // flag stays diagnosed (not silently swallowed) in lean builds.
614    match raw.split_once('=') {
615        Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
616            Ok((target.trim().to_string(), command.to_string()))
617        }
618        _ => bail!("invalid --remote {raw:?}: expected <target>=\"<command>\""),
619    }
620}
621
622/// Without `net`, remote targets cannot exist.
623#[cfg(not(feature = "net"))]
624fn check_no_net_remotes(remotes: &[(String, String)]) -> Result<()> {
625    if !remotes.is_empty() {
626        bail!("--remote requires the `net` feature (rebuild with --features net)");
627    }
628    Ok(())
629}
630
631/// Without `net`, endpoint sockets cannot exist: `--listen`/`-p` are
632/// rejected (parse time already bails; this covers programmatic `Options`),
633/// while `--offline` or no flags proceed socketless.
634#[cfg(not(feature = "net"))]
635fn check_no_net_endpoints(flags: &EndpointFlags) -> Result<()> {
636    if !flags.listens.is_empty() || !flags.publishes.is_empty() {
637        bail!("--listen/-p require the `net` feature (rebuild with --features net)");
638    }
639    Ok(())
640}
641
642/// Read the script source without creating any execution state. The
643/// read resolves against the script path's own root, so scripts
644/// outside the execution workspace load exactly like scripts inside it.
645fn read_script(source: &ScriptSource) -> Result<String> {
646    match source {
647        ScriptSource::Path(path) => {
648            let resolver = PathResolver::new(path.root(), path.root())?;
649            resolver
650                .read_to_string(path)
651                .with_context(|| format!("failed to read script at {}", path.display()))
652        }
653        ScriptSource::Stdin => {
654            let mut buf = String::new();
655            io::stdin()
656                .lock()
657                .read_to_string(&mut buf)
658                .context("failed to read script from stdin")?;
659            Ok(buf)
660        }
661    }
662}
663
664fn execute_with_shell_runner<F>(
665    opts: Options,
666    workspace_root: GuardedPath,
667    shell_runner: F,
668    require_tty: bool,
669) -> Result<()>
670where
671    F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
672{
673    #[cfg(windows)]
674    maybe_reexec_shell_to_temp(&opts)?;
675
676    // Interpret a tiny Dockerfile-ish script. No tempdir exists yet: the
677    // snapshot materializes lazily on first snapshot-targeted step, so an
678    // empty non-shell run creates nothing at all (issue #131).
679    let script = match &opts.script {
680        ScriptSource::Path(_) => read_script(&opts.script)?,
681        ScriptSource::Stdin => {
682            let stdin = io::stdin();
683            if stdin.is_terminal() {
684                // No piped script provided. If the caller requested `--shell`
685                // allow running with an initially-empty script so we can either
686                // drop into the interactive shell or open the editor later.
687                // Otherwise, require a script on stdin.
688                if opts.shell {
689                    String::new()
690                } else {
691                    bail!(
692                        "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
693                    );
694                }
695            } else {
696                let mut buf = String::new();
697                stdin
698                    .lock()
699                    .read_to_string(&mut buf)
700                    .context("failed to read script from stdin")?;
701                buf
702            }
703        }
704    };
705
706    // Parse and run steps if we have a non-empty script. Empty scripts are
707    // valid when `--shell` is requested and the caller didn't pipe a script.
708    // Use the caller's workspace as the build context so WORKSPACE LOCAL can
709    // hop back and so COPY can source from the original tree if needed.
710    // Capture the final working directory so shells inherit whatever WORKDIR
711    // the script ended on.
712    let mut final_cwd = workspace_root.clone();
713    let mut snapshot = Arc::new(LazyGuardedTempDir::new());
714    let mut fs: Option<Box<dyn WorkspaceFs>> = None;
715    if !script.trim().is_empty() {
716        // Bind endpoint sockets before parsing: conflicts fail fast,
717        // never parse-then-fail-on-bind.
718        #[cfg(feature = "net")]
719        let registry = build_registry(&opts.endpoints)?;
720        #[cfg(not(feature = "net"))]
721        check_no_net_endpoints(&opts.endpoints)?;
722        #[cfg(not(feature = "net"))]
723        check_no_net_remotes(&opts.remotes)?;
724        #[cfg(feature = "net")]
725        report_ephemeral_publishes(&opts.endpoints, &registry);
726        let steps = parse_cli_script(&script)?;
727        // Validate REMOTE targets against inventory after parsing (targets
728        // live in AST nodes) and before execution: unknown targets fail
729        // here, never mid-run.
730        #[cfg(feature = "net")]
731        let inventory = {
732            let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
733            inventory.log_resolutions();
734            inventory.validate_script(&steps)?;
735            inventory
736        };
737        // If we are running a script from a file, we might have stdin available for the script itself.
738        // If we read the script from stdin, then stdin is consumed.
739        // But if opts.script is ScriptSource::Path, stdin is still available.
740
741        let mut stdin_handle: Option<SharedInput> = None;
742        if let ScriptSource::Path(_) = opts.script {
743            let stdin = io::stdin();
744            if !stdin.is_terminal() {
745                // Wrap stdin in SharedInput (Arc<Mutex<dyn Read + Send>>)
746                // Note: std::io::Stdin is a handle, but we need an owned Read + Send.
747                // std::io::stdin() returns Stdin, which implements Read + Send.
748                // However, we need to be careful about locking.
749                // We can wrap the Stdin struct directly.
750                stdin_handle = Some(Arc::new(Mutex::new(stdin)));
751            }
752        }
753
754        let mut io_cfg = ExecIo::new();
755        io_cfg.set_stdin(stdin_handle);
756        #[cfg(feature = "net")]
757        register_remote_runners(&mut io_cfg, &inventory);
758        #[cfg(feature = "net")]
759        let output = run_steps_with_lazy_snapshot_and_modules(
760            &workspace_root,
761            &steps,
762            io_cfg,
763            cli_host_modules_with(Some(&registry)),
764            cli_host_types(),
765        )?;
766        #[cfg(not(feature = "net"))]
767        let output = run_steps_with_lazy_snapshot_and_modules(
768            &workspace_root,
769            &steps,
770            io_cfg,
771            cli_host_modules_with(None),
772            cli_host_types(),
773        )?;
774        final_cwd = output.final_cwd;
775        snapshot = output.snapshot;
776        fs = Some(output.fs);
777    }
778
779    // If requested, drop into an interactive shell after running the script.
780    if opts.shell {
781        if require_tty && !has_controlling_tty() {
782            bail!("--shell requires a tty (no controlling tty available)");
783        }
784        // The shell needs a concrete directory: materialize here at shell
785        // entry (not at startup) when the script left the snapshot pending,
786        // then converge the cwd onto the shared concrete root. An empty
787        // script starts the shell in a fresh snapshot directory.
788        match fs.as_ref() {
789            Some(fs) => {
790                if fs.is_snapshot_pending() {
791                    snapshot
792                        .materialize()
793                        .context("failed to create shell temp dir")?;
794                }
795                final_cwd = fs.concretize_cwd(&final_cwd);
796            }
797            None => {
798                snapshot
799                    .materialize()
800                    .context("failed to create shell temp dir")?;
801                final_cwd = snapshot
802                    .get()
803                    .cloned()
804                    .expect("shell snapshot materialized above");
805            }
806        }
807        return shell_runner(&final_cwd, &workspace_root);
808    }
809
810    Ok(())
811}
812
813#[cfg(test)]
814fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
815where
816    F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
817{
818    execute_with_shell_runner(opts, workspace_root, shell_runner, false)
819}
820
821fn has_controlling_tty() -> bool {
822    // Prefer checking whether stdin or stderr is a terminal. This avoids
823    // directly opening device files via `std::fs` while still detecting
824    // whether an interactive tty is available in the common cases.
825    #[cfg(unix)]
826    {
827        io::stdin().is_terminal() || io::stderr().is_terminal()
828    }
829
830    #[cfg(windows)]
831    {
832        io::stdin().is_terminal() || io::stderr().is_terminal()
833    }
834
835    #[cfg(not(any(unix, windows)))]
836    {
837        false
838    }
839}
840
841#[cfg(windows)]
842fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
843    // Only used for interactive shells. Copy the binary to a temp path and run it there so the
844    // original target exe is free for rebuilding while the shell stays open.
845    if !opts.shell {
846        return Ok(());
847    }
848    if std::env::var(oxdock_env::oxdock::SHELL_REEXEC)
849        .ok()
850        .as_deref()
851        == Some("1")
852    {
853        return Ok(());
854    }
855
856    let self_path = std::env::current_exe().context("determine current executable")?;
857    let base_temp =
858        GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
859    let ts = std::time::SystemTime::now()
860        .duration_since(std::time::UNIX_EPOCH)
861        .unwrap_or_default()
862        .as_millis();
863    let temp_file = base_temp
864        .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
865        .context("construct temp shell path")?;
866
867    // Copy the current executable into the temporary location via a
868    // resolver whose root is the temp directory. The source may live
869    // outside the temp dir, so use `copy_file_from_external`.
870    let temp_root_guard = temp_file
871        .parent()
872        .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
873    let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
874    let dest = temp_file;
875    #[allow(clippy::disallowed_types)]
876    let source = oxdock_fs::UnguardedPath::external(self_path);
877    resolver_temp
878        .copy_file_from_unguarded(&source, &dest)
879        .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
880
881    let mut cmd = CommandBuilder::new(dest.as_path());
882    cmd.args(std::env::args_os().skip(1));
883    cmd.env(oxdock_env::oxdock::SHELL_REEXEC, "1");
884    cmd.spawn()
885        .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
886
887    // Exit immediately so the original binary can be rebuilt while the shell child stays running.
888    std::process::exit(0);
889}
890
891pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
892    run_steps_with_context(workspace_root, workspace_root, steps)
893}
894
895fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
896    #[cfg(windows)]
897    let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
898    #[cfg(windows)]
899    let workspace_disp = oxdock_fs::command_path(workspace_root)
900        .as_ref()
901        .display()
902        .to_string();
903
904    #[cfg(not(windows))]
905    let cwd_disp = cwd.display().to_string();
906    #[cfg(not(windows))]
907    let workspace_disp = workspace_root.display().to_string();
908
909    let pkg = env::var(oxdock_env::cargo::PKG_NAME)
910        .unwrap_or_else(|_| oxdock_env::oxdock::FALLBACK_APP_NAME.to_string());
911    indoc::formatdoc! {"
912        {pkg} shell workspace
913          cwd: {cwd_disp}
914          source: workspace root at {workspace_disp}
915          lifetime: temporary directory created for this shell session; it disappears when you exit
916          creation: temp workspace starts empty unless your script copies files into it
917
918          WARNING: This shell still runs on your host filesystem and is **not** isolated!
919    "}
920}
921
922fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
923    oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
924}
925
926// `command_path` now lives in `oxdock-fs` to centralize Path usage.
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931    use indoc::indoc;
932    use oxdock_fs::PathResolver;
933    use std::cell::{Cell, RefCell};
934
935    #[cfg_attr(
936        miri,
937        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
938    )]
939    #[test]
940    fn shell_runner_receives_final_workdir() -> Result<()> {
941        let workspace = GuardedPath::tempdir()?;
942        let workspace_root = workspace.as_guarded_path().clone();
943        let script_path = workspace_root.join("script.ox")?;
944        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
945        let script = indoc! {"
946            WRITE temp.txt 123
947            WORKDIR sub
948        "};
949        resolver.write_file(&script_path, script.as_bytes())?;
950
951        let opts = Options {
952            script: ScriptSource::Path(script_path),
953            shell: true,
954            endpoints: EndpointFlags::default(),
955            remote_serve: false,
956            remotes: Vec::new(),
957        };
958
959        let observed = Cell::new(false);
960        execute_for_test(opts, workspace_root.clone(), |cwd, _| {
961            assert!(
962                cwd.as_path().ends_with("sub"),
963                "final cwd should end in WORKDIR target, got {}",
964                cwd.display()
965            );
966
967            let temp_root = GuardedPath::new_root(cwd.root())
968                .context("construct guard for temp workspace root")?;
969            let sub_dir = temp_root.join("sub")?;
970            assert_eq!(
971                cwd.as_path(),
972                sub_dir.as_path(),
973                "shell runner cwd should match guarded sub dir"
974            );
975            let temp_file = temp_root.join("temp.txt")?;
976            let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
977            let contents = temp_resolver.read_to_string(&temp_file)?;
978            assert!(
979                contents.contains("123"),
980                "expected WRITE command to materialize temp file"
981            );
982            observed.set(true);
983            Ok(())
984        })?;
985
986        assert!(
987            observed.into_inner(),
988            "shell runner closure should have been invoked"
989        );
990        Ok(())
991    }
992
993    #[cfg_attr(
994        miri,
995        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
996    )]
997    #[test]
998    fn options_parse_requires_script_path_value() {
999        let workspace = GuardedPath::tempdir().expect("tempdir");
1000        let mut args = vec!["--script".to_string()].into_iter();
1001        let err = Options::parse(&mut args, workspace.as_guarded_path())
1002            .expect_err("expected missing path error");
1003        assert!(err.to_string().contains("--script requires a path"));
1004    }
1005
1006    #[cfg_attr(
1007        miri,
1008        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1009    )]
1010    #[test]
1011    fn options_parse_script_path_and_shell() {
1012        let workspace = GuardedPath::tempdir().expect("tempdir");
1013        let workspace_root = workspace.as_guarded_path().clone();
1014        let script_path = workspace_root.join("script.txt").expect("script path");
1015        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1016            .expect("resolver");
1017        resolver
1018            .write_file(&script_path, b"WRITE out.txt hi")
1019            .expect("write script");
1020        let mut args = vec![
1021            "--script".to_string(),
1022            "script.txt".to_string(),
1023            "--shell".to_string(),
1024        ]
1025        .into_iter();
1026        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1027        assert!(opts.shell);
1028        match opts.script {
1029            ScriptSource::Path(path) => assert_eq!(path, script_path),
1030            ScriptSource::Stdin => panic!("expected path script"),
1031        }
1032    }
1033
1034    #[cfg_attr(
1035        miri,
1036        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1037    )]
1038    #[test]
1039    fn options_parse_positional_script_path() {
1040        let workspace = GuardedPath::tempdir().expect("tempdir");
1041        let workspace_root = workspace.as_guarded_path().clone();
1042        let mut args = vec!["script.txt".to_string()].into_iter();
1043        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1044        assert!(!opts.shell);
1045        match opts.script {
1046            ScriptSource::Path(path) => assert_eq!(
1047                path,
1048                workspace_root.join("script.txt").expect("script path")
1049            ),
1050            ScriptSource::Stdin => panic!("expected path script"),
1051        }
1052    }
1053
1054    #[cfg_attr(
1055        miri,
1056        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1057    )]
1058    #[test]
1059    fn options_parse_positional_dash_reads_stdin() {
1060        let workspace = GuardedPath::tempdir().expect("tempdir");
1061        let mut args = vec!["-".to_string()].into_iter();
1062        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1063        assert!(matches!(opts.script, ScriptSource::Stdin));
1064    }
1065
1066    #[cfg_attr(
1067        miri,
1068        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1069    )]
1070    #[test]
1071    fn options_parse_rejects_duplicate_script_sources() {
1072        let workspace = GuardedPath::tempdir().expect("tempdir");
1073        let workspace_root = workspace.as_guarded_path().clone();
1074        let mut args = vec![
1075            "a.ox".to_string(),
1076            "--script".to_string(),
1077            "b.ox".to_string(),
1078        ]
1079        .into_iter();
1080        let err = Options::parse(&mut args, &workspace_root)
1081            .expect_err("expected duplicate script error");
1082        assert!(err.to_string().contains("multiple times"), "{err:?}");
1083
1084        let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1085        let err = Options::parse(&mut args, &workspace_root)
1086            .expect_err("expected duplicate script error");
1087        assert!(err.to_string().contains("multiple times"), "{err:?}");
1088    }
1089
1090    #[cfg_attr(
1091        miri,
1092        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1093    )]
1094    #[test]
1095    fn options_parse_absolute_script_outside_execution_workspace_loads() {
1096        // Stdin parity: an explicit absolute location loads wherever
1097        // it lives; only relative paths resolve under the workspace.
1098        let workspace = GuardedPath::tempdir().expect("tempdir");
1099        let outside = GuardedPath::tempdir().expect("outside");
1100        let target = outside
1101            .as_guarded_path()
1102            .as_path()
1103            .join("step.ox")
1104            .to_string_lossy()
1105            .into_owned();
1106        let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1107        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1108        match opts.script {
1109            ScriptSource::Path(path) => {
1110                assert_eq!(path.as_path().to_string_lossy(), target);
1111                assert_eq!(path.root(), outside.as_guarded_path().as_path());
1112            }
1113            ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1114        }
1115    }
1116
1117    #[cfg_attr(
1118        miri,
1119        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1120    )]
1121    #[test]
1122    fn options_parse_relative_escape_stays_rejected() {
1123        let workspace = GuardedPath::tempdir().expect("tempdir");
1124        let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1125        let err =
1126            Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1127        assert!(err.to_string().contains("guard script path"), "{err:?}");
1128    }
1129
1130    #[cfg_attr(
1131        miri,
1132        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1133    )]
1134    #[test]
1135    fn options_parse_rejects_unknown_flags() {
1136        let workspace = GuardedPath::tempdir().expect("tempdir");
1137        let mut args = vec!["--frobnicate".to_string()].into_iter();
1138        let err = Options::parse(&mut args, workspace.as_guarded_path())
1139            .expect_err("expected unknown flag error");
1140        assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1141    }
1142
1143    #[test]
1144    fn usage_describes_positional_script_and_help() {
1145        let text = usage();
1146        assert!(text.contains("Usage: oxdock"), "{text}");
1147        assert!(text.contains("SCRIPT"), "{text}");
1148        assert!(text.contains("--script"), "{text}");
1149        assert!(text.contains("--help"), "{text}");
1150        assert!(text.contains("--offline"), "{text}");
1151        #[cfg(feature = "net")]
1152        {
1153            assert!(text.contains("--listen"), "{text}");
1154            assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1155        }
1156        #[cfg(not(feature = "net"))]
1157        {
1158            assert!(!text.contains("--listen <addr>"), "{text}");
1159            assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1160            assert!(text.contains("require the `net` feature"), "{text}");
1161        }
1162        // Tagline is single-sourced from the package manifest, not hardcoded.
1163        assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1164    }
1165
1166    #[cfg(feature = "net")]
1167    #[cfg_attr(
1168        miri,
1169        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1170    )]
1171    #[test]
1172    fn options_parse_endpoint_flags() {
1173        // Pure flag parsing: no sockets open, but tempdir keeps the
1174        // ignore uniform with the neighboring parse tests.
1175        let workspace = GuardedPath::tempdir().expect("tempdir");
1176        let mut args = vec![
1177            "--listen".to_string(),
1178            "0.0.0.0:2251".to_string(),
1179            "-p".to_string(),
1180            "2222:demo-proxy".to_string(),
1181            "-p".to_string(),
1182            "0:2252".to_string(),
1183            "-".to_string(),
1184        ]
1185        .into_iter();
1186        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1187        assert_eq!(opts.endpoints.listens.len(), 1);
1188        assert_eq!(opts.endpoints.publishes.len(), 2);
1189        assert!(!opts.endpoints.offline);
1190        assert!(matches!(opts.script, ScriptSource::Stdin));
1191    }
1192
1193    #[cfg_attr(
1194        miri,
1195        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1196    )]
1197    #[test]
1198    fn options_parse_offline_flag() {
1199        let workspace = GuardedPath::tempdir().expect("tempdir");
1200        let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1201        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1202        assert!(opts.endpoints.offline);
1203    }
1204
1205    #[cfg(feature = "net")]
1206    #[cfg_attr(
1207        miri,
1208        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1209    )]
1210    #[test]
1211    fn options_parse_rejects_bad_endpoint_flags() {
1212        let workspace = GuardedPath::tempdir().expect("tempdir");
1213        for args in [
1214            vec!["--listen"],
1215            vec!["--listen", "0.0.0.0:0"],
1216            vec!["-p"],
1217            vec!["-p", "2222"],
1218            vec!["-p", "2222:0"],
1219        ] {
1220            let mut args = args.into_iter().map(str::to_string);
1221            Options::parse(&mut args, workspace.as_guarded_path())
1222                .expect_err("bad endpoint flag must fail");
1223        }
1224    }
1225
1226    #[cfg_attr(
1227        miri,
1228        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1229    )]
1230    #[test]
1231    fn options_parse_empty_values_hold_token_boundaries() {
1232        // Regression: explicit empty values must not shift the stream.
1233        // `--script ""` bails instead of consuming the next token, and a
1234        // bare empty positional is skipped like before.
1235        let workspace = GuardedPath::tempdir().expect("tempdir");
1236        let mut args = vec![
1237            "--script".to_string(),
1238            "".to_string(),
1239            "--shell".to_string(),
1240        ]
1241        .into_iter();
1242        let err = Options::parse(&mut args, workspace.as_guarded_path())
1243            .expect_err("empty script path must fail");
1244        assert!(
1245            err.to_string().contains("--script requires a path"),
1246            "{err:?}"
1247        );
1248        let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1249        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1250        assert!(matches!(opts.script, ScriptSource::Stdin));
1251    }
1252
1253    #[cfg(feature = "net")]
1254    #[cfg_attr(
1255        miri,
1256        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1257    )]
1258    #[test]
1259    fn options_parse_accepts_equals_and_attached_forms() {
1260        // lexopt-native spellings: `--flag=value`, attached short values,
1261        // and `--` separating positionals.
1262        let workspace = GuardedPath::tempdir().expect("tempdir");
1263        let workspace_root = workspace.as_guarded_path().clone();
1264        let mut args = vec![
1265            "--listen=0.0.0.0:2251".to_string(),
1266            "-p2222:demo-proxy".to_string(),
1267            "--".to_string(),
1268            "script.ox".to_string(),
1269        ]
1270        .into_iter();
1271        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1272        assert_eq!(opts.endpoints.listens.len(), 1);
1273        assert_eq!(opts.endpoints.publishes.len(), 1);
1274        match opts.script {
1275            ScriptSource::Path(path) => {
1276                assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1277            }
1278            ScriptSource::Stdin => panic!("expected path script after --"),
1279        }
1280    }
1281
1282    #[cfg_attr(
1283        miri,
1284        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1285    )]
1286    #[test]
1287    fn options_parse_version_returns_version_without_exiting() {
1288        // Same contract as --help: version surfaces as the parse error
1289        // (parse must not exit the process itself: it is public library
1290        // API). Print it and succeed so the binary exits 0.
1291        let workspace = GuardedPath::tempdir().expect("tempdir");
1292        for flag in ["--version", "-V"] {
1293            let mut args = vec![flag.to_string()].into_iter();
1294            let err = Options::parse(&mut args, workspace.as_guarded_path())
1295                .expect_err("version flag must not parse as options");
1296            assert_eq!(err.to_string(), version());
1297        }
1298    }
1299
1300    #[cfg_attr(
1301        miri,
1302        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1303    )]
1304    #[test]
1305    fn options_parse_help_returns_usage_error_without_exiting() {
1306        // Regression: parse is public library API and must return instead of
1307        // terminating the process; `run()` turns this error into a clean exit 0.
1308        let workspace = GuardedPath::tempdir().expect("tempdir");
1309        for flag in ["--help", "-h"] {
1310            let mut args = vec![flag.to_string()].into_iter();
1311            let err = Options::parse(&mut args, workspace.as_guarded_path())
1312                .expect_err("help flag must not parse as options");
1313            assert_eq!(err.to_string(), usage());
1314        }
1315    }
1316
1317    #[cfg_attr(
1318        miri,
1319        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1320    )]
1321    #[test]
1322    fn options_parse_rejects_remote_script_with_input_intact() {
1323        let workspace = GuardedPath::tempdir().expect("tempdir");
1324        for args in [
1325            vec!["https://example.com/process.oxfile".to_string()],
1326            vec![
1327                "--script".to_string(),
1328                "https://example.com/process.oxfile".to_string(),
1329            ],
1330        ] {
1331            let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1332                .expect_err("remote script must not parse as a path");
1333            let rendered = format!("{err:#}");
1334            assert!(
1335                rendered.contains("not a local path")
1336                    && rendered.contains("https://example.com/process.oxfile"),
1337                "rejection names the intact input: {rendered}"
1338            );
1339            assert!(
1340                !rendered.contains("https:/example.com"),
1341                "scheme must never come out mangled: {rendered}"
1342            );
1343        }
1344    }
1345
1346    #[test]
1347    fn execute_with_result_runs_script() {
1348        let workspace = GuardedPath::tempdir().expect("tempdir");
1349        let workspace_root = workspace.as_guarded_path().clone();
1350        let script_path = workspace_root.join("script.txt").expect("script path");
1351        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1352            .expect("resolver");
1353        resolver
1354            .write_file(&script_path, b"WRITE out.txt hi")
1355            .expect("write script");
1356        let opts = Options {
1357            script: ScriptSource::Path(script_path),
1358            shell: false,
1359            endpoints: EndpointFlags::default(),
1360            remote_serve: false,
1361            remotes: Vec::new(),
1362        };
1363        let result = execute_with_result(opts, workspace_root).expect("execute");
1364        let snapshot = result
1365            .snapshot_path()
1366            .expect("default WRITE materializes the snapshot");
1367        assert_eq!(snapshot, &result.final_cwd);
1368        let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1369        let out = snapshot.join("out.txt").expect("out path");
1370        let contents = temp_resolver.read_to_string(&out).expect("read out");
1371        assert_eq!(contents.trim(), "hi");
1372    }
1373
1374    #[cfg_attr(
1375        miri,
1376        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1377    )]
1378    #[test]
1379    fn execute_with_result_local_only_creates_no_snapshot() {
1380        let workspace = GuardedPath::tempdir().expect("tempdir");
1381        let workspace_root = workspace.as_guarded_path().clone();
1382        let script_path = workspace_root.join("script.txt").expect("script path");
1383        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1384            .expect("resolver");
1385        resolver
1386            .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1387            .expect("write script");
1388        let opts = Options {
1389            script: ScriptSource::Path(script_path),
1390            shell: false,
1391            endpoints: EndpointFlags::default(),
1392            remote_serve: false,
1393            remotes: Vec::new(),
1394        };
1395        let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1396        assert!(
1397            !result.has_snapshot(),
1398            "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1399        );
1400        assert!(result.snapshot_path().is_none());
1401        // The write landed in the live workspace tree instead.
1402        let out = workspace_root.join("out.txt").expect("out path");
1403        let contents = resolver.read_to_string(&out).expect("read out");
1404        assert_eq!(contents.trim(), "hi");
1405        // The reported cwd stays under the workspace root.
1406        assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1407    }
1408
1409    #[cfg_attr(
1410        miri,
1411        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1412    )]
1413    #[test]
1414    fn execute_with_result_empty_script_creates_no_snapshot() {
1415        let workspace = GuardedPath::tempdir().expect("tempdir");
1416        let workspace_root = workspace.as_guarded_path().clone();
1417        let script_path = workspace_root.join("empty.txt").expect("script path");
1418        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1419            .expect("resolver");
1420        resolver
1421            .write_file(&script_path, b"")
1422            .expect("write script");
1423        let opts = Options {
1424            script: ScriptSource::Path(script_path),
1425            shell: false,
1426            endpoints: EndpointFlags::default(),
1427            remote_serve: false,
1428            remotes: Vec::new(),
1429        };
1430        let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1431        assert!(
1432            !result.has_snapshot(),
1433            "empty script must not create a snapshot tempdir"
1434        );
1435        assert_eq!(result.final_cwd, workspace_root);
1436    }
1437
1438    #[cfg_attr(
1439        miri,
1440        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1441    )]
1442    #[test]
1443    fn execute_for_test_invokes_shell_runner() -> Result<()> {
1444        let workspace = GuardedPath::tempdir()?;
1445        let workspace_root = workspace.as_guarded_path().clone();
1446        let script_path = workspace_root.join("empty.txt")?;
1447        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1448        resolver.write_file(&script_path, b"")?;
1449        let opts = Options {
1450            script: ScriptSource::Path(script_path),
1451            shell: true,
1452            endpoints: EndpointFlags::default(),
1453            remote_serve: false,
1454            remotes: Vec::new(),
1455        };
1456        let called = RefCell::new(None::<(String, String)>);
1457        execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1458            called.replace(Some((cwd.display(), workspace.display())));
1459            // Shell entry converges onto a concrete, existing directory even
1460            // when the script never touched the snapshot (issue #131).
1461            assert!(
1462                cwd.exists(),
1463                "shell cwd must exist on disk, got {}",
1464                cwd.display()
1465            );
1466            Ok(())
1467        })?;
1468        let seen = called.borrow().clone().expect("shell runner called");
1469        assert_eq!(seen.1, workspace_root.display());
1470        Ok(())
1471    }
1472
1473    /// The `ssh` feature wires the SSH host module into the real CLI
1474    /// runner: serve an ephemeral server and close it through
1475    /// `execute_with_result`, no client needed.
1476    #[cfg(feature = "ssh")]
1477    #[cfg_attr(
1478        miri,
1479        ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1480    )]
1481    #[test]
1482    fn ssh_feature_serves_and_closes() -> Result<()> {
1483        let workspace = GuardedPath::tempdir()?;
1484        let workspace_root = workspace.as_guarded_path().clone();
1485        let script_path = workspace_root.join("ssh-serve.ox")?;
1486        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1487        let script = indoc! {"
1488            IMPORT [STD, SSH]
1489            LET $m: SSH_SERVE_INFO = SSH_SERVE(\"cli-ssh-svc\", {username: \"test\", password: \"test123\"})
1490            SSH_CLOSE($m.server)
1491        "};
1492        resolver.write_file(&script_path, script.as_bytes())?;
1493        let opts = Options {
1494            script: ScriptSource::Path(script_path),
1495            shell: false,
1496            endpoints: EndpointFlags {
1497                publishes: vec![(
1498                    std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1499                    "cli-ssh-svc".to_string(),
1500                )],
1501                ..EndpointFlags::default()
1502            },
1503            remote_serve: false,
1504            remotes: Vec::new(),
1505        };
1506        execute_with_result(opts, workspace_root)?;
1507        Ok(())
1508    }
1509
1510    /// The NET module ships with the `net` feature: bind an ephemeral
1511    /// loopback port and close it through `execute_with_result`, no
1512    /// client needed.
1513    #[cfg(feature = "net")]
1514    #[cfg_attr(
1515        miri,
1516        ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1517    )]
1518    #[test]
1519    fn net_module_listens_and_closes() -> Result<()> {
1520        let workspace = GuardedPath::tempdir()?;
1521        let workspace_root = workspace.as_guarded_path().clone();
1522        let script_path = workspace_root.join("net-listen.ox")?;
1523        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1524        let script = indoc! {"
1525            IMPORT [STD, NET]
1526            LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1527            NET_CLOSE($l.listener)
1528        "};
1529        resolver.write_file(&script_path, script.as_bytes())?;
1530        let opts = Options {
1531            script: ScriptSource::Path(script_path),
1532            shell: false,
1533            // The port key is only a registry name here: the outer bind
1534            // is ephemeral, so no fixed host port is ever touched.
1535            endpoints: EndpointFlags {
1536                publishes: vec![(
1537                    std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1538                    "23501".to_string(),
1539                )],
1540                ..EndpointFlags::default()
1541            },
1542            remote_serve: false,
1543            remotes: Vec::new(),
1544        };
1545        execute_with_result(opts, workspace_root)?;
1546        Ok(())
1547    }
1548
1549    /// A `-p`-mapped outer port is observable in-script: route an
1550    /// ephemeral `-p 0:<name>` resolution through `NET_PORT`/`NET_ADDR`
1551    /// into files an inner `RUN` could equally consume via `ENV`.
1552    #[cfg(feature = "net")]
1553    #[cfg_attr(
1554        miri,
1555        ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1556    )]
1557    #[test]
1558    fn net_port_addr_observe_publish_mapping() -> Result<()> {
1559        let workspace = GuardedPath::tempdir()?;
1560        let workspace_root = workspace.as_guarded_path().clone();
1561        let script_path = workspace_root.join("net-port.ox")?;
1562        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1563        let script = indoc! {"
1564            IMPORT [STD, NET]
1565            LET $port: INT = NET_PORT(\"routed-svc\")
1566            WRITE port.txt \"{{ $port }}\"
1567            LET $addr: STRING = NET_ADDR(\"routed-svc\")
1568            WRITE addr.txt \"{{ $addr }}\"
1569        "};
1570        resolver.write_file(&script_path, script.as_bytes())?;
1571        let opts = Options {
1572            script: ScriptSource::Path(script_path),
1573            shell: false,
1574            endpoints: EndpointFlags {
1575                publishes: vec![(
1576                    std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
1577                    "routed-svc".to_string(),
1578                )],
1579                ..EndpointFlags::default()
1580            },
1581            remote_serve: false,
1582            remotes: Vec::new(),
1583        };
1584        let result = execute_with_result(opts, workspace_root)?;
1585        let snapshot = result
1586            .snapshot_path()
1587            .expect("WRITE materializes the snapshot");
1588        let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
1589        let port_path = snapshot.join("port.txt")?;
1590        let port_text = snapshot_resolver.read_to_string(&port_path)?;
1591        let port: u16 = port_text
1592            .trim()
1593            .parse()
1594            .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
1595        assert_ne!(port, 0, "ephemeral outer port must resolve");
1596        let addr_path = snapshot.join("addr.txt")?;
1597        let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
1598        assert!(
1599            addr_text.trim().ends_with(&format!(":{port}")),
1600            "dial string must carry the resolved port, got {addr_text:?}"
1601        );
1602        Ok(())
1603    }
1604
1605    /// Without the `ssh` feature the same script must fail to parse:
1606    /// SSH names stay unknown instead of silently changing meaning.
1607    #[cfg(not(feature = "ssh"))]
1608    #[cfg_attr(
1609        miri,
1610        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1611    )]
1612    #[test]
1613    fn ssh_scripts_rejected_without_feature() -> Result<()> {
1614        let workspace = GuardedPath::tempdir()?;
1615        let workspace_root = workspace.as_guarded_path().clone();
1616        let script_path = workspace_root.join("ssh-serve.ox")?;
1617        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1618        let script = indoc! {"
1619            IMPORT [STD, SSH]
1620            LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1621            SSH_CLOSE($m.server)
1622        "};
1623        resolver.write_file(&script_path, script.as_bytes())?;
1624        let opts = Options {
1625            script: ScriptSource::Path(script_path),
1626            shell: false,
1627            endpoints: EndpointFlags::default(),
1628            remote_serve: false,
1629            remotes: Vec::new(),
1630        };
1631        let err = match execute_with_result(opts, workspace_root) {
1632            Ok(_) => panic!("SSH names must be unknown without the feature"),
1633            Err(err) => err,
1634        };
1635        assert!(err.to_string().contains("SSH"), "{err}");
1636        Ok(())
1637    }
1638
1639    /// Without the `net` feature `--listen`/`-p` are rejected with the
1640    /// feature message, while `--offline` stays accepted as trivially
1641    /// satisfied.
1642    #[cfg(not(feature = "net"))]
1643    #[cfg_attr(
1644        miri,
1645        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1646    )]
1647    #[test]
1648    fn net_flags_rejected_without_feature() {
1649        let workspace = GuardedPath::tempdir().expect("tempdir");
1650        for args in [
1651            vec!["--listen", "0.0.0.0:2251", "-"],
1652            vec!["-p", "2222:2251", "-"],
1653            vec!["--listen=0.0.0.0:2251", "-"],
1654        ] {
1655            let mut args = args.into_iter().map(str::to_string);
1656            let err = Options::parse(&mut args, workspace.as_guarded_path())
1657                .expect_err("endpoint flag must fail without net");
1658            assert!(
1659                err.to_string().contains("require the `net` feature"),
1660                "{err:?}"
1661            );
1662        }
1663        let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1664        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1665        assert!(opts.endpoints.offline);
1666    }
1667
1668    /// Without the `net` feature the same script must fail to parse:
1669    /// NET names stay unknown instead of silently changing meaning.
1670    #[cfg(not(feature = "net"))]
1671    #[cfg_attr(
1672        miri,
1673        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1674    )]
1675    #[test]
1676    fn net_scripts_rejected_without_feature() -> Result<()> {
1677        let workspace = GuardedPath::tempdir()?;
1678        let workspace_root = workspace.as_guarded_path().clone();
1679        let script_path = workspace_root.join("net-listen.ox")?;
1680        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1681        let script = indoc! {"
1682            IMPORT [STD, NET]
1683            LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1684            LET $body: STRING = NET_FETCH(\"https://example.com/x\")
1685            NET_CLOSE($l.listener)
1686        "};
1687        resolver.write_file(&script_path, script.as_bytes())?;
1688        let opts = Options {
1689            script: ScriptSource::Path(script_path),
1690            shell: false,
1691            endpoints: EndpointFlags::default(),
1692            remote_serve: false,
1693            remotes: Vec::new(),
1694        };
1695        let err = match execute_with_result(opts, workspace_root) {
1696            Ok(_) => panic!("NET names must be unknown without the feature"),
1697            Err(err) => err,
1698        };
1699        assert!(err.to_string().contains("NET"), "{err}");
1700        Ok(())
1701    }
1702
1703    #[test]
1704    fn process_exit_code_relays_exit_requests() {
1705        let exit = anyhow::Error::new(ExitRequest(3));
1706        assert_eq!(process_exit_code(&exit), 3);
1707        let relayed =
1708            anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' exited with code 3");
1709        assert_eq!(process_exit_code(&relayed), 3);
1710        assert_eq!(process_exit_code(&anyhow::anyhow!("boom")), 1);
1711        assert_eq!(
1712            process_exit_code(&anyhow::Error::new(ExitRequest(300))),
1713            255,
1714            "codes clamp to the portable range"
1715        );
1716        assert_eq!(
1717            process_exit_code(&anyhow::Error::new(ExitRequest(-1))),
1718            0,
1719            "negative codes clamp to zero"
1720        );
1721    }
1722}
1723
1724#[cfg(all(test, windows))]
1725mod windows_shell_tests {
1726    use super::*;
1727
1728    #[test]
1729    fn command_path_strips_verbatim_prefix() -> Result<()> {
1730        let temp = GuardedPath::tempdir()?;
1731        let converted = oxdock_fs::command_path(temp.as_guarded_path());
1732        let as_str = converted.as_ref().display().to_string();
1733        assert!(
1734            !as_str.starts_with(r"\\?\"),
1735            "expected non-verbatim path, got {as_str}"
1736        );
1737        Ok(())
1738    }
1739}