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