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::SHELL_REEXEC).ok().as_deref() == Some("1") {
849        return Ok(());
850    }
851
852    let self_path = std::env::current_exe().context("determine current executable")?;
853    let base_temp =
854        GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
855    let ts = std::time::SystemTime::now()
856        .duration_since(std::time::UNIX_EPOCH)
857        .unwrap_or_default()
858        .as_millis();
859    let temp_file = base_temp
860        .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
861        .context("construct temp shell path")?;
862
863    // Copy the current executable into the temporary location via a
864    // resolver whose root is the temp directory. The source may live
865    // outside the temp dir, so use `copy_file_from_external`.
866    let temp_root_guard = temp_file
867        .parent()
868        .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
869    let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
870    let dest = temp_file;
871    #[allow(clippy::disallowed_types)]
872    let source = oxdock_fs::UnguardedPath::external(self_path);
873    resolver_temp
874        .copy_file_from_unguarded(&source, &dest)
875        .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
876
877    let mut cmd = CommandBuilder::new(dest.as_path());
878    cmd.args(std::env::args_os().skip(1));
879    cmd.env(oxdock_env::SHELL_REEXEC, "1");
880    cmd.spawn()
881        .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
882
883    // Exit immediately so the original binary can be rebuilt while the shell child stays running.
884    std::process::exit(0);
885}
886
887pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
888    run_steps_with_context(workspace_root, workspace_root, steps)
889}
890
891fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
892    #[cfg(windows)]
893    let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
894    #[cfg(windows)]
895    let workspace_disp = oxdock_fs::command_path(workspace_root)
896        .as_ref()
897        .display()
898        .to_string();
899
900    #[cfg(not(windows))]
901    let cwd_disp = cwd.display().to_string();
902    #[cfg(not(windows))]
903    let workspace_disp = workspace_root.display().to_string();
904
905    let pkg = env::var(oxdock_env::CARGO_PKG_NAME)
906        .unwrap_or_else(|_| oxdock_env::FALLBACK_APP_NAME.to_string());
907    indoc::formatdoc! {"
908        {pkg} shell workspace
909          cwd: {cwd_disp}
910          source: workspace root at {workspace_disp}
911          lifetime: temporary directory created for this shell session; it disappears when you exit
912          creation: temp workspace starts empty unless your script copies files into it
913
914          WARNING: This shell still runs on your host filesystem and is **not** isolated!
915    "}
916}
917
918fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
919    oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
920}
921
922// `command_path` now lives in `oxdock-fs` to centralize Path usage.
923
924#[cfg(test)]
925mod tests {
926    use super::*;
927    use indoc::indoc;
928    use oxdock_fs::PathResolver;
929    use std::cell::{Cell, RefCell};
930
931    #[cfg_attr(
932        miri,
933        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
934    )]
935    #[test]
936    fn shell_runner_receives_final_workdir() -> Result<()> {
937        let workspace = GuardedPath::tempdir()?;
938        let workspace_root = workspace.as_guarded_path().clone();
939        let script_path = workspace_root.join("script.ox")?;
940        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
941        let script = indoc! {"
942            WRITE temp.txt 123
943            WORKDIR sub
944        "};
945        resolver.write_file(&script_path, script.as_bytes())?;
946
947        let opts = Options {
948            script: ScriptSource::Path(script_path),
949            shell: true,
950            endpoints: EndpointFlags::default(),
951            remote_serve: false,
952            remotes: Vec::new(),
953        };
954
955        let observed = Cell::new(false);
956        execute_for_test(opts, workspace_root.clone(), |cwd, _| {
957            assert!(
958                cwd.as_path().ends_with("sub"),
959                "final cwd should end in WORKDIR target, got {}",
960                cwd.display()
961            );
962
963            let temp_root = GuardedPath::new_root(cwd.root())
964                .context("construct guard for temp workspace root")?;
965            let sub_dir = temp_root.join("sub")?;
966            assert_eq!(
967                cwd.as_path(),
968                sub_dir.as_path(),
969                "shell runner cwd should match guarded sub dir"
970            );
971            let temp_file = temp_root.join("temp.txt")?;
972            let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
973            let contents = temp_resolver.read_to_string(&temp_file)?;
974            assert!(
975                contents.contains("123"),
976                "expected WRITE command to materialize temp file"
977            );
978            observed.set(true);
979            Ok(())
980        })?;
981
982        assert!(
983            observed.into_inner(),
984            "shell runner closure should have been invoked"
985        );
986        Ok(())
987    }
988
989    #[cfg_attr(
990        miri,
991        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
992    )]
993    #[test]
994    fn options_parse_requires_script_path_value() {
995        let workspace = GuardedPath::tempdir().expect("tempdir");
996        let mut args = vec!["--script".to_string()].into_iter();
997        let err = Options::parse(&mut args, workspace.as_guarded_path())
998            .expect_err("expected missing path error");
999        assert!(err.to_string().contains("--script requires a path"));
1000    }
1001
1002    #[cfg_attr(
1003        miri,
1004        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1005    )]
1006    #[test]
1007    fn options_parse_script_path_and_shell() {
1008        let workspace = GuardedPath::tempdir().expect("tempdir");
1009        let workspace_root = workspace.as_guarded_path().clone();
1010        let script_path = workspace_root.join("script.txt").expect("script path");
1011        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1012            .expect("resolver");
1013        resolver
1014            .write_file(&script_path, b"WRITE out.txt hi")
1015            .expect("write script");
1016        let mut args = vec![
1017            "--script".to_string(),
1018            "script.txt".to_string(),
1019            "--shell".to_string(),
1020        ]
1021        .into_iter();
1022        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1023        assert!(opts.shell);
1024        match opts.script {
1025            ScriptSource::Path(path) => assert_eq!(path, script_path),
1026            ScriptSource::Stdin => panic!("expected path script"),
1027        }
1028    }
1029
1030    #[cfg_attr(
1031        miri,
1032        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1033    )]
1034    #[test]
1035    fn options_parse_positional_script_path() {
1036        let workspace = GuardedPath::tempdir().expect("tempdir");
1037        let workspace_root = workspace.as_guarded_path().clone();
1038        let mut args = vec!["script.txt".to_string()].into_iter();
1039        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1040        assert!(!opts.shell);
1041        match opts.script {
1042            ScriptSource::Path(path) => assert_eq!(
1043                path,
1044                workspace_root.join("script.txt").expect("script path")
1045            ),
1046            ScriptSource::Stdin => panic!("expected path script"),
1047        }
1048    }
1049
1050    #[cfg_attr(
1051        miri,
1052        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1053    )]
1054    #[test]
1055    fn options_parse_positional_dash_reads_stdin() {
1056        let workspace = GuardedPath::tempdir().expect("tempdir");
1057        let mut args = vec!["-".to_string()].into_iter();
1058        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1059        assert!(matches!(opts.script, ScriptSource::Stdin));
1060    }
1061
1062    #[cfg_attr(
1063        miri,
1064        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1065    )]
1066    #[test]
1067    fn options_parse_rejects_duplicate_script_sources() {
1068        let workspace = GuardedPath::tempdir().expect("tempdir");
1069        let workspace_root = workspace.as_guarded_path().clone();
1070        let mut args = vec![
1071            "a.ox".to_string(),
1072            "--script".to_string(),
1073            "b.ox".to_string(),
1074        ]
1075        .into_iter();
1076        let err = Options::parse(&mut args, &workspace_root)
1077            .expect_err("expected duplicate script error");
1078        assert!(err.to_string().contains("multiple times"), "{err:?}");
1079
1080        let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1081        let err = Options::parse(&mut args, &workspace_root)
1082            .expect_err("expected duplicate script error");
1083        assert!(err.to_string().contains("multiple times"), "{err:?}");
1084    }
1085
1086    #[cfg_attr(
1087        miri,
1088        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1089    )]
1090    #[test]
1091    fn options_parse_absolute_script_outside_execution_workspace_loads() {
1092        // Stdin parity: an explicit absolute location loads wherever
1093        // it lives; only relative paths resolve under the workspace.
1094        let workspace = GuardedPath::tempdir().expect("tempdir");
1095        let outside = GuardedPath::tempdir().expect("outside");
1096        let target = outside
1097            .as_guarded_path()
1098            .as_path()
1099            .join("step.ox")
1100            .to_string_lossy()
1101            .into_owned();
1102        let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1103        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1104        match opts.script {
1105            ScriptSource::Path(path) => {
1106                assert_eq!(path.as_path().to_string_lossy(), target);
1107                assert_eq!(path.root(), outside.as_guarded_path().as_path());
1108            }
1109            ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1110        }
1111    }
1112
1113    #[cfg_attr(
1114        miri,
1115        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1116    )]
1117    #[test]
1118    fn options_parse_relative_escape_stays_rejected() {
1119        let workspace = GuardedPath::tempdir().expect("tempdir");
1120        let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1121        let err =
1122            Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1123        assert!(err.to_string().contains("guard script path"), "{err:?}");
1124    }
1125
1126    #[cfg_attr(
1127        miri,
1128        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1129    )]
1130    #[test]
1131    fn options_parse_rejects_unknown_flags() {
1132        let workspace = GuardedPath::tempdir().expect("tempdir");
1133        let mut args = vec!["--frobnicate".to_string()].into_iter();
1134        let err = Options::parse(&mut args, workspace.as_guarded_path())
1135            .expect_err("expected unknown flag error");
1136        assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1137    }
1138
1139    #[test]
1140    fn usage_describes_positional_script_and_help() {
1141        let text = usage();
1142        assert!(text.contains("Usage: oxdock"), "{text}");
1143        assert!(text.contains("SCRIPT"), "{text}");
1144        assert!(text.contains("--script"), "{text}");
1145        assert!(text.contains("--help"), "{text}");
1146        assert!(text.contains("--offline"), "{text}");
1147        #[cfg(feature = "net")]
1148        {
1149            assert!(text.contains("--listen"), "{text}");
1150            assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1151        }
1152        #[cfg(not(feature = "net"))]
1153        {
1154            assert!(!text.contains("--listen <addr>"), "{text}");
1155            assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1156            assert!(text.contains("require the `net` feature"), "{text}");
1157        }
1158        // Tagline is single-sourced from the package manifest, not hardcoded.
1159        assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1160    }
1161
1162    #[cfg(feature = "net")]
1163    #[cfg_attr(
1164        miri,
1165        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1166    )]
1167    #[test]
1168    fn options_parse_endpoint_flags() {
1169        // Pure flag parsing: no sockets open, but tempdir keeps the
1170        // ignore uniform with the neighboring parse tests.
1171        let workspace = GuardedPath::tempdir().expect("tempdir");
1172        let mut args = vec![
1173            "--listen".to_string(),
1174            "0.0.0.0:2251".to_string(),
1175            "-p".to_string(),
1176            "2222:demo-proxy".to_string(),
1177            "-p".to_string(),
1178            "0:2252".to_string(),
1179            "-".to_string(),
1180        ]
1181        .into_iter();
1182        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1183        assert_eq!(opts.endpoints.listens.len(), 1);
1184        assert_eq!(opts.endpoints.publishes.len(), 2);
1185        assert!(!opts.endpoints.offline);
1186        assert!(matches!(opts.script, ScriptSource::Stdin));
1187    }
1188
1189    #[cfg_attr(
1190        miri,
1191        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1192    )]
1193    #[test]
1194    fn options_parse_offline_flag() {
1195        let workspace = GuardedPath::tempdir().expect("tempdir");
1196        let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1197        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1198        assert!(opts.endpoints.offline);
1199    }
1200
1201    #[cfg(feature = "net")]
1202    #[cfg_attr(
1203        miri,
1204        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1205    )]
1206    #[test]
1207    fn options_parse_rejects_bad_endpoint_flags() {
1208        let workspace = GuardedPath::tempdir().expect("tempdir");
1209        for args in [
1210            vec!["--listen"],
1211            vec!["--listen", "0.0.0.0:0"],
1212            vec!["-p"],
1213            vec!["-p", "2222"],
1214            vec!["-p", "2222:0"],
1215        ] {
1216            let mut args = args.into_iter().map(str::to_string);
1217            Options::parse(&mut args, workspace.as_guarded_path())
1218                .expect_err("bad endpoint flag must fail");
1219        }
1220    }
1221
1222    #[cfg_attr(
1223        miri,
1224        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1225    )]
1226    #[test]
1227    fn options_parse_empty_values_hold_token_boundaries() {
1228        // Regression: explicit empty values must not shift the stream.
1229        // `--script ""` bails instead of consuming the next token, and a
1230        // bare empty positional is skipped like before.
1231        let workspace = GuardedPath::tempdir().expect("tempdir");
1232        let mut args = vec![
1233            "--script".to_string(),
1234            "".to_string(),
1235            "--shell".to_string(),
1236        ]
1237        .into_iter();
1238        let err = Options::parse(&mut args, workspace.as_guarded_path())
1239            .expect_err("empty script path must fail");
1240        assert!(
1241            err.to_string().contains("--script requires a path"),
1242            "{err:?}"
1243        );
1244        let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1245        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1246        assert!(matches!(opts.script, ScriptSource::Stdin));
1247    }
1248
1249    #[cfg(feature = "net")]
1250    #[cfg_attr(
1251        miri,
1252        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1253    )]
1254    #[test]
1255    fn options_parse_accepts_equals_and_attached_forms() {
1256        // lexopt-native spellings: `--flag=value`, attached short values,
1257        // and `--` separating positionals.
1258        let workspace = GuardedPath::tempdir().expect("tempdir");
1259        let workspace_root = workspace.as_guarded_path().clone();
1260        let mut args = vec![
1261            "--listen=0.0.0.0:2251".to_string(),
1262            "-p2222:demo-proxy".to_string(),
1263            "--".to_string(),
1264            "script.ox".to_string(),
1265        ]
1266        .into_iter();
1267        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1268        assert_eq!(opts.endpoints.listens.len(), 1);
1269        assert_eq!(opts.endpoints.publishes.len(), 1);
1270        match opts.script {
1271            ScriptSource::Path(path) => {
1272                assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1273            }
1274            ScriptSource::Stdin => panic!("expected path script after --"),
1275        }
1276    }
1277
1278    #[cfg_attr(
1279        miri,
1280        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1281    )]
1282    #[test]
1283    fn options_parse_version_returns_version_without_exiting() {
1284        // Same contract as --help: version surfaces as the parse error
1285        // (parse must not exit the process itself: it is public library
1286        // API). Print it and succeed so the binary exits 0.
1287        let workspace = GuardedPath::tempdir().expect("tempdir");
1288        for flag in ["--version", "-V"] {
1289            let mut args = vec![flag.to_string()].into_iter();
1290            let err = Options::parse(&mut args, workspace.as_guarded_path())
1291                .expect_err("version flag must not parse as options");
1292            assert_eq!(err.to_string(), version());
1293        }
1294    }
1295
1296    #[cfg_attr(
1297        miri,
1298        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1299    )]
1300    #[test]
1301    fn options_parse_help_returns_usage_error_without_exiting() {
1302        // Regression: parse is public library API and must return instead of
1303        // terminating the process; `run()` turns this error into a clean exit 0.
1304        let workspace = GuardedPath::tempdir().expect("tempdir");
1305        for flag in ["--help", "-h"] {
1306            let mut args = vec![flag.to_string()].into_iter();
1307            let err = Options::parse(&mut args, workspace.as_guarded_path())
1308                .expect_err("help flag must not parse as options");
1309            assert_eq!(err.to_string(), usage());
1310        }
1311    }
1312
1313    #[cfg_attr(
1314        miri,
1315        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1316    )]
1317    #[test]
1318    fn options_parse_rejects_remote_script_with_input_intact() {
1319        let workspace = GuardedPath::tempdir().expect("tempdir");
1320        for args in [
1321            vec!["https://example.com/process.oxfile".to_string()],
1322            vec![
1323                "--script".to_string(),
1324                "https://example.com/process.oxfile".to_string(),
1325            ],
1326        ] {
1327            let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1328                .expect_err("remote script must not parse as a path");
1329            let rendered = format!("{err:#}");
1330            assert!(
1331                rendered.contains("not a local path")
1332                    && rendered.contains("https://example.com/process.oxfile"),
1333                "rejection names the intact input: {rendered}"
1334            );
1335            assert!(
1336                !rendered.contains("https:/example.com"),
1337                "scheme must never come out mangled: {rendered}"
1338            );
1339        }
1340    }
1341
1342    #[test]
1343    fn execute_with_result_runs_script() {
1344        let workspace = GuardedPath::tempdir().expect("tempdir");
1345        let workspace_root = workspace.as_guarded_path().clone();
1346        let script_path = workspace_root.join("script.txt").expect("script path");
1347        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1348            .expect("resolver");
1349        resolver
1350            .write_file(&script_path, b"WRITE out.txt hi")
1351            .expect("write script");
1352        let opts = Options {
1353            script: ScriptSource::Path(script_path),
1354            shell: false,
1355            endpoints: EndpointFlags::default(),
1356            remote_serve: false,
1357            remotes: Vec::new(),
1358        };
1359        let result = execute_with_result(opts, workspace_root).expect("execute");
1360        let snapshot = result
1361            .snapshot_path()
1362            .expect("default WRITE materializes the snapshot");
1363        assert_eq!(snapshot, &result.final_cwd);
1364        let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1365        let out = snapshot.join("out.txt").expect("out path");
1366        let contents = temp_resolver.read_to_string(&out).expect("read out");
1367        assert_eq!(contents.trim(), "hi");
1368    }
1369
1370    #[cfg_attr(
1371        miri,
1372        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1373    )]
1374    #[test]
1375    fn execute_with_result_local_only_creates_no_snapshot() {
1376        let workspace = GuardedPath::tempdir().expect("tempdir");
1377        let workspace_root = workspace.as_guarded_path().clone();
1378        let script_path = workspace_root.join("script.txt").expect("script path");
1379        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1380            .expect("resolver");
1381        resolver
1382            .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1383            .expect("write script");
1384        let opts = Options {
1385            script: ScriptSource::Path(script_path),
1386            shell: false,
1387            endpoints: EndpointFlags::default(),
1388            remote_serve: false,
1389            remotes: Vec::new(),
1390        };
1391        let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1392        assert!(
1393            !result.has_snapshot(),
1394            "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1395        );
1396        assert!(result.snapshot_path().is_none());
1397        // The write landed in the live workspace tree instead.
1398        let out = workspace_root.join("out.txt").expect("out path");
1399        let contents = resolver.read_to_string(&out).expect("read out");
1400        assert_eq!(contents.trim(), "hi");
1401        // The reported cwd stays under the workspace root.
1402        assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1403    }
1404
1405    #[cfg_attr(
1406        miri,
1407        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1408    )]
1409    #[test]
1410    fn execute_with_result_empty_script_creates_no_snapshot() {
1411        let workspace = GuardedPath::tempdir().expect("tempdir");
1412        let workspace_root = workspace.as_guarded_path().clone();
1413        let script_path = workspace_root.join("empty.txt").expect("script path");
1414        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1415            .expect("resolver");
1416        resolver
1417            .write_file(&script_path, b"")
1418            .expect("write script");
1419        let opts = Options {
1420            script: ScriptSource::Path(script_path),
1421            shell: false,
1422            endpoints: EndpointFlags::default(),
1423            remote_serve: false,
1424            remotes: Vec::new(),
1425        };
1426        let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1427        assert!(
1428            !result.has_snapshot(),
1429            "empty script must not create a snapshot tempdir"
1430        );
1431        assert_eq!(result.final_cwd, workspace_root);
1432    }
1433
1434    #[cfg_attr(
1435        miri,
1436        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1437    )]
1438    #[test]
1439    fn execute_for_test_invokes_shell_runner() -> Result<()> {
1440        let workspace = GuardedPath::tempdir()?;
1441        let workspace_root = workspace.as_guarded_path().clone();
1442        let script_path = workspace_root.join("empty.txt")?;
1443        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1444        resolver.write_file(&script_path, b"")?;
1445        let opts = Options {
1446            script: ScriptSource::Path(script_path),
1447            shell: true,
1448            endpoints: EndpointFlags::default(),
1449            remote_serve: false,
1450            remotes: Vec::new(),
1451        };
1452        let called = RefCell::new(None::<(String, String)>);
1453        execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1454            called.replace(Some((cwd.display(), workspace.display())));
1455            // Shell entry converges onto a concrete, existing directory even
1456            // when the script never touched the snapshot (issue #131).
1457            assert!(
1458                cwd.exists(),
1459                "shell cwd must exist on disk, got {}",
1460                cwd.display()
1461            );
1462            Ok(())
1463        })?;
1464        let seen = called.borrow().clone().expect("shell runner called");
1465        assert_eq!(seen.1, workspace_root.display());
1466        Ok(())
1467    }
1468
1469    /// The `ssh` feature wires the SSH host module into the real CLI
1470    /// runner: serve an ephemeral server and close it through
1471    /// `execute_with_result`, no client needed.
1472    #[cfg(feature = "ssh")]
1473    #[cfg_attr(
1474        miri,
1475        ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1476    )]
1477    #[test]
1478    fn ssh_feature_serves_and_closes() -> Result<()> {
1479        let workspace = GuardedPath::tempdir()?;
1480        let workspace_root = workspace.as_guarded_path().clone();
1481        let script_path = workspace_root.join("ssh-serve.ox")?;
1482        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1483        let script = indoc! {"
1484            IMPORT [STD, SSH]
1485            LET $m: SSH_SERVE_INFO = SSH_SERVE(\"cli-ssh-svc\", {username: \"test\", password: \"test123\"})
1486            SSH_CLOSE($m.server)
1487        "};
1488        resolver.write_file(&script_path, script.as_bytes())?;
1489        let opts = Options {
1490            script: ScriptSource::Path(script_path),
1491            shell: false,
1492            endpoints: EndpointFlags {
1493                publishes: vec![(
1494                    std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1495                    "cli-ssh-svc".to_string(),
1496                )],
1497                ..EndpointFlags::default()
1498            },
1499            remote_serve: false,
1500            remotes: Vec::new(),
1501        };
1502        execute_with_result(opts, workspace_root)?;
1503        Ok(())
1504    }
1505
1506    /// The NET module ships with the `net` feature: bind an ephemeral
1507    /// loopback port and close it through `execute_with_result`, no
1508    /// client needed.
1509    #[cfg(feature = "net")]
1510    #[cfg_attr(
1511        miri,
1512        ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1513    )]
1514    #[test]
1515    fn net_module_listens_and_closes() -> Result<()> {
1516        let workspace = GuardedPath::tempdir()?;
1517        let workspace_root = workspace.as_guarded_path().clone();
1518        let script_path = workspace_root.join("net-listen.ox")?;
1519        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1520        let script = indoc! {"
1521            IMPORT [STD, NET]
1522            LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1523            NET_CLOSE($l.listener)
1524        "};
1525        resolver.write_file(&script_path, script.as_bytes())?;
1526        let opts = Options {
1527            script: ScriptSource::Path(script_path),
1528            shell: false,
1529            // The port key is only a registry name here: the outer bind
1530            // is ephemeral, so no fixed host port is ever touched.
1531            endpoints: EndpointFlags {
1532                publishes: vec![(
1533                    std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1534                    "23501".to_string(),
1535                )],
1536                ..EndpointFlags::default()
1537            },
1538            remote_serve: false,
1539            remotes: Vec::new(),
1540        };
1541        execute_with_result(opts, workspace_root)?;
1542        Ok(())
1543    }
1544
1545    /// A `-p`-mapped outer port is observable in-script: route an
1546    /// ephemeral `-p 0:<name>` resolution through `NET_PORT`/`NET_ADDR`
1547    /// into files an inner `RUN` could equally consume via `ENV`.
1548    #[cfg(feature = "net")]
1549    #[cfg_attr(
1550        miri,
1551        ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1552    )]
1553    #[test]
1554    fn net_port_addr_observe_publish_mapping() -> Result<()> {
1555        let workspace = GuardedPath::tempdir()?;
1556        let workspace_root = workspace.as_guarded_path().clone();
1557        let script_path = workspace_root.join("net-port.ox")?;
1558        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1559        let script = indoc! {"
1560            IMPORT [STD, NET]
1561            LET $port: INT = NET_PORT(\"routed-svc\")
1562            WRITE port.txt \"{{ $port }}\"
1563            LET $addr: STRING = NET_ADDR(\"routed-svc\")
1564            WRITE addr.txt \"{{ $addr }}\"
1565        "};
1566        resolver.write_file(&script_path, script.as_bytes())?;
1567        let opts = Options {
1568            script: ScriptSource::Path(script_path),
1569            shell: false,
1570            endpoints: EndpointFlags {
1571                publishes: vec![(
1572                    std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
1573                    "routed-svc".to_string(),
1574                )],
1575                ..EndpointFlags::default()
1576            },
1577            remote_serve: false,
1578            remotes: Vec::new(),
1579        };
1580        let result = execute_with_result(opts, workspace_root)?;
1581        let snapshot = result
1582            .snapshot_path()
1583            .expect("WRITE materializes the snapshot");
1584        let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
1585        let port_path = snapshot.join("port.txt")?;
1586        let port_text = snapshot_resolver.read_to_string(&port_path)?;
1587        let port: u16 = port_text
1588            .trim()
1589            .parse()
1590            .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
1591        assert_ne!(port, 0, "ephemeral outer port must resolve");
1592        let addr_path = snapshot.join("addr.txt")?;
1593        let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
1594        assert!(
1595            addr_text.trim().ends_with(&format!(":{port}")),
1596            "dial string must carry the resolved port, got {addr_text:?}"
1597        );
1598        Ok(())
1599    }
1600
1601    /// Without the `ssh` feature the same script must fail to parse:
1602    /// SSH names stay unknown instead of silently changing meaning.
1603    #[cfg(not(feature = "ssh"))]
1604    #[cfg_attr(
1605        miri,
1606        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1607    )]
1608    #[test]
1609    fn ssh_scripts_rejected_without_feature() -> Result<()> {
1610        let workspace = GuardedPath::tempdir()?;
1611        let workspace_root = workspace.as_guarded_path().clone();
1612        let script_path = workspace_root.join("ssh-serve.ox")?;
1613        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1614        let script = indoc! {"
1615            IMPORT [STD, SSH]
1616            LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1617            SSH_CLOSE($m.server)
1618        "};
1619        resolver.write_file(&script_path, script.as_bytes())?;
1620        let opts = Options {
1621            script: ScriptSource::Path(script_path),
1622            shell: false,
1623            endpoints: EndpointFlags::default(),
1624            remote_serve: false,
1625            remotes: Vec::new(),
1626        };
1627        let err = match execute_with_result(opts, workspace_root) {
1628            Ok(_) => panic!("SSH names must be unknown without the feature"),
1629            Err(err) => err,
1630        };
1631        assert!(err.to_string().contains("SSH"), "{err}");
1632        Ok(())
1633    }
1634
1635    /// Without the `net` feature `--listen`/`-p` are rejected with the
1636    /// feature message, while `--offline` stays accepted as trivially
1637    /// satisfied.
1638    #[cfg(not(feature = "net"))]
1639    #[cfg_attr(
1640        miri,
1641        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1642    )]
1643    #[test]
1644    fn net_flags_rejected_without_feature() {
1645        let workspace = GuardedPath::tempdir().expect("tempdir");
1646        for args in [
1647            vec!["--listen", "0.0.0.0:2251", "-"],
1648            vec!["-p", "2222:2251", "-"],
1649            vec!["--listen=0.0.0.0:2251", "-"],
1650        ] {
1651            let mut args = args.into_iter().map(str::to_string);
1652            let err = Options::parse(&mut args, workspace.as_guarded_path())
1653                .expect_err("endpoint flag must fail without net");
1654            assert!(
1655                err.to_string().contains("require the `net` feature"),
1656                "{err:?}"
1657            );
1658        }
1659        let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1660        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1661        assert!(opts.endpoints.offline);
1662    }
1663
1664    /// Without the `net` feature the same script must fail to parse:
1665    /// NET names stay unknown instead of silently changing meaning.
1666    #[cfg(not(feature = "net"))]
1667    #[cfg_attr(
1668        miri,
1669        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1670    )]
1671    #[test]
1672    fn net_scripts_rejected_without_feature() -> Result<()> {
1673        let workspace = GuardedPath::tempdir()?;
1674        let workspace_root = workspace.as_guarded_path().clone();
1675        let script_path = workspace_root.join("net-listen.ox")?;
1676        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1677        let script = indoc! {"
1678            IMPORT [STD, NET]
1679            LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1680            LET $body: STRING = NET_FETCH(\"https://example.com/x\")
1681            NET_CLOSE($l.listener)
1682        "};
1683        resolver.write_file(&script_path, script.as_bytes())?;
1684        let opts = Options {
1685            script: ScriptSource::Path(script_path),
1686            shell: false,
1687            endpoints: EndpointFlags::default(),
1688            remote_serve: false,
1689            remotes: Vec::new(),
1690        };
1691        let err = match execute_with_result(opts, workspace_root) {
1692            Ok(_) => panic!("NET names must be unknown without the feature"),
1693            Err(err) => err,
1694        };
1695        assert!(err.to_string().contains("NET"), "{err}");
1696        Ok(())
1697    }
1698
1699    #[test]
1700    fn process_exit_code_relays_exit_requests() {
1701        let exit = anyhow::Error::new(ExitRequest(3));
1702        assert_eq!(process_exit_code(&exit), 3);
1703        let relayed =
1704            anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' exited with code 3");
1705        assert_eq!(process_exit_code(&relayed), 3);
1706        assert_eq!(process_exit_code(&anyhow::anyhow!("boom")), 1);
1707        assert_eq!(
1708            process_exit_code(&anyhow::Error::new(ExitRequest(300))),
1709            255,
1710            "codes clamp to the portable range"
1711        );
1712        assert_eq!(
1713            process_exit_code(&anyhow::Error::new(ExitRequest(-1))),
1714            0,
1715            "negative codes clamp to zero"
1716        );
1717    }
1718}
1719
1720#[cfg(all(test, windows))]
1721mod windows_shell_tests {
1722    use super::*;
1723
1724    #[test]
1725    fn command_path_strips_verbatim_prefix() -> Result<()> {
1726        let temp = GuardedPath::tempdir()?;
1727        let converted = oxdock_fs::command_path(temp.as_guarded_path());
1728        let as_str = converted.as_ref().display().to_string();
1729        assert!(
1730            !as_str.starts_with(r"\\?\"),
1731            "expected non-verbatim path, got {as_str}"
1732        );
1733        Ok(())
1734    }
1735}