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