Skip to main content

oxdock_cli/
lib.rs

1pub use oxdock_diagnostics::{Diagnostic, DiagnosticResult, flatten_chain};
2use oxdock_fs::{
3    GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, discover_workspace_root,
4    env as oxdock_env, init_temp_gc,
5};
6#[cfg(windows)]
7use oxdock_process::CommandBuilder;
8use oxdock_process::{DefaultProcessManager, SharedInput};
9use std::env;
10use std::io::{self, IsTerminal, Read};
11use std::sync::{Arc, Mutex};
12
13use oxdock_core::ExecIo;
14pub use oxdock_core::{
15    Engine, EngineOutput, ExecState, ExitRequest, FuncKind, FuncMeta, FuncParam, HostModule,
16    HostRegistration, NativeFn, OxDockFn, OxDockType, PureFn, PushManifestSink, StepCtx,
17    TypeDescriptor, Value, dry_run_closure, exit_code_of_diag, parse_script,
18    parse_script_with_modules, run_steps, run_steps_with_context, run_steps_with_context_result,
19    run_steps_with_lazy_snapshot_and_modules_and_entry, run_steps_with_manager_with_modules,
20    run_steps_with_manager_with_modules_and_entry, run_steps_without_snapshot,
21};
22pub use oxdock_parser::{Guard, Step, StepKind};
23pub use oxdock_process::shell_program;
24use std::collections::BTreeMap;
25
26mod endpoints;
27pub use endpoints::EndpointFlags;
28mod errors;
29pub use errors::{
30    endpoint_duplicate_inner, endpoint_duplicate_outer, feature_required, offline_conflict, usage,
31};
32#[cfg(feature = "mcp")]
33mod mcp;
34
35// CLI usage bodies live in [`errors`]: `usage()` is user-facing CLI
36// text, so it is owned alongside the `cli.*` error templates.
37#[cfg(feature = "net")]
38pub use endpoints::build_registry;
39#[cfg(feature = "net")]
40use oxdock_net_plugin::EndpointRegistry;
41#[cfg(feature = "net")]
42mod serve;
43
44/// Host modules bundled into the CLI runner. With `net` this exposes STD
45/// plus the NET virtual-endpoint toolkit (`NET_LISTEN`, `NET_ACCEPT`,
46/// `NET_CLOSE`, `NET_CONNECT`, `NET_PORT`, `NET_ADDR`); with `--features
47/// ssh` it additionally registers the SSH server and client (`SSH_SERVE`,
48/// `SSH_ACCEPT`, `SSH_DEQUEUE`, `SSH_PUMP_CHANNEL`, `SSH_CLOSE`,
49/// `SSH_CONNECT`, `SSH_PUMP`) from oxdock-ssh-plugin; with `--features
50/// markdown` it registers the MARKDOWN helpers (`MAP_TO_MD_TABLE`,
51/// `TOC`, `PARSE`, `SECTION`). Without features only STD builtins remain.
52fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
53    cli_host_modules_with(None)
54}
55
56/// Module surface for the guest serve loop: identical to the host runner
57/// surface so handshake language-surface identity actually compares the
58/// same tables both ends run.
59#[cfg(feature = "net")]
60fn cli_host_modules_for_serve() -> Vec<HostModule<DefaultProcessManager>> {
61    cli_host_modules_with(None)
62}
63
64/// Module-table digest for the remote handshake: sha256 over sorted
65/// `module::function` entries from the serve surface.
66#[cfg(feature = "net")]
67fn remote_session_module_hash(entries: &[(String, Vec<String>)]) -> String {
68    oxdock_net_plugin::module_hash(entries)
69}
70
71/// Host modules resolving virtual endpoints through `registry`: the CLI
72/// builds it from `--listen`/`-p`/`--offline` before parsing so bind
73/// conflicts fail fast. `None` registers default module instances (enough
74/// for parse-time name resolution); without `net` no modules are pushed.
75/// The parameter type is feature-dependent because the registry type only
76/// exists with `net`; callers pass `Some` with `net` and `None` without.
77fn cli_host_modules_with(
78    #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
79    #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
80) -> Vec<HostModule<DefaultProcessManager>> {
81    #[cfg(any(feature = "net", feature = "markdown"))]
82    let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
83    #[cfg(not(any(feature = "net", feature = "markdown")))]
84    let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
85    #[cfg(feature = "net")]
86    {
87        let net_module = match registry {
88            Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
89            None => oxdock_net_plugin::module(),
90        };
91        modules.push(net_module);
92        #[cfg(feature = "ssh")]
93        {
94            let ssh_module = match registry {
95                Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
96                None => oxdock_ssh_plugin::module(),
97            };
98            modules.push(ssh_module);
99        }
100    }
101    #[cfg(feature = "markdown")]
102    modules.push(oxdock_markdown_plugin::module());
103    let _ = registry;
104    modules
105}
106
107/// Host types bundled into the CLI runner alongside [`cli_host_modules`].
108fn cli_host_types() -> Vec<&'static TypeDescriptor> {
109    #[cfg(feature = "net")]
110    let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
111    #[cfg(not(feature = "net"))]
112    let net: &[&'static TypeDescriptor] = &[];
113    #[cfg(feature = "ssh")]
114    let ssh: &[&'static TypeDescriptor] = &[
115        oxdock_ssh_plugin::SshServerTag::descriptor(),
116        oxdock_ssh_plugin::SshSessionTag::descriptor(),
117    ];
118    #[cfg(not(feature = "ssh"))]
119    let ssh: &[&'static TypeDescriptor] = &[];
120    net.iter().chain(ssh.iter()).copied().collect()
121}
122
123/// Run parsed steps with the CLI host surface under a lazy snapshot:
124/// one place where the CLI module set, types, and entry file meet the
125/// lazy-snapshot runner, so the net/non-net module wiring lives here
126/// instead of at every call site. Callers differ only in IO setup
127/// (stdin handling, remote runners) and what they do with the output.
128fn run_cli_steps(
129    workspace_root: &GuardedPath,
130    steps: &[Step],
131    io: ExecIo,
132    #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
133    #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
134    entry_file: Option<GuardedPath>,
135) -> DiagnosticResult<oxdock_core::exec::LazyRunOutput> {
136    run_steps_with_lazy_snapshot_and_modules_and_entry(
137        workspace_root,
138        steps,
139        io,
140        cli_host_modules_with(registry),
141        cli_host_types(),
142        entry_file,
143    )
144}
145
146/// Parse a CLI script against STD plus any bundled host modules. Without
147/// extra modules this is exactly `parse_script`, so base-build behavior
148/// never changes.
149fn parse_cli_script(script: &str) -> DiagnosticResult<Vec<Step>> {
150    parse_script_with_modules(script, cli_module_table()).map_err(|e| {
151        if let Some(unlinked) = unlinked_module_error(script) {
152            return unlinked;
153        }
154        e
155    })
156}
157
158/// Modules the CLI knows but this build did not link, with the Cargo
159/// feature that would link each. Empty in full-feature builds, so the
160/// scan below never fires there.
161fn unlinked_modules() -> Vec<(&'static str, &'static str)> {
162    let modules: &[(&'static str, &'static str)] = &[
163        #[cfg(not(feature = "net"))]
164        ("NET", "net"),
165        #[cfg(not(feature = "ssh"))]
166        ("SSH", "ssh"),
167    ];
168    modules.to_vec()
169}
170
171/// Known-but-unlinked module error when the script actually imports one.
172/// Matched on the lexed token stream, not raw text: comments lex as
173/// `Comment` and quoted paths as `Str`, so `// IMPORT [NET]` or
174/// `ECHO "IMPORT [NET]"` alongside an unrelated syntax error keeps its
175/// genuine parse error. Returns `None` on lex failure (broken below the
176/// token level: the genuine error rides through), in full-feature
177/// builds (nothing is unlinked), or when no unlinked module is
178/// imported (genuine parse error rides through unchanged).
179fn unlinked_module_error(script: &str) -> Option<oxdock_diagnostics::Diagnostic> {
180    let unlinked = unlinked_modules();
181    if unlinked.is_empty() {
182        return None;
183    }
184    let toks = oxdock_parser::lex_str(script).ok()?;
185    for (module, feature) in unlinked {
186        if imports_module(&toks, module) {
187            return Some(errors::module_unlinked(module, feature));
188        }
189    }
190    None
191}
192
193/// True when a token stream holds `IMPORT [...]` naming `module` as a
194/// bare word. Only `IMPORT` immediately followed by a bracket group
195/// counts (newlines/comments between are skipped); quoted file paths
196/// lex as `Str`, never `Word`, so they never match. Recurses into
197/// brace/paren groups for block-nested imports.
198fn imports_module(toks: &[oxdock_parser::Tok], module: &str) -> bool {
199    use oxdock_parser::{GroupDelim, TokKind};
200    let mut i = 0;
201    while i < toks.len() {
202        match &toks[i].kind {
203            TokKind::Word(w) if w == "IMPORT" => {
204                let mut j = i + 1;
205                while j < toks.len()
206                    && matches!(
207                        toks[j].kind,
208                        TokKind::Newline | TokKind::Comment(_) | TokKind::Semicolon
209                    )
210                {
211                    j += 1;
212                }
213                if let Some(next) = toks.get(j)
214                    && let TokKind::Group {
215                        delim: GroupDelim::Bracket,
216                        inner,
217                        ..
218                    } = &next.kind
219                    && inner
220                        .iter()
221                        .any(|t| matches!(&t.kind, TokKind::Word(w) if w == module))
222                {
223                    return true;
224                }
225            }
226            TokKind::Group { inner, .. } if imports_module(inner, module) => {
227                return true;
228            }
229            _ => {}
230        }
231        i += 1;
232    }
233    false
234}
235
236/// Module table for CLI parsing: STD plus bundled host modules.
237/// Imported files (#115) parse against this same table.
238fn cli_module_table() -> oxdock_parser::ModuleTable {
239    let modules = cli_host_modules();
240    if modules.is_empty() {
241        return oxdock_core::std_module_table();
242    }
243    let mut engine = Engine::new();
244    for module in modules {
245        engine.register_module(module);
246    }
247    engine.module_table()
248}
249
250/// Entry script file for `#115` imports, if the run started from one:
251/// top-level relative `IMPORT` paths resolve against its parent.
252fn entry_file_of(script: &ScriptSource) -> Option<GuardedPath> {
253    match script {
254        ScriptSource::Path(path) => Some(path.clone()),
255        ScriptSource::Stdin => None,
256    }
257}
258
259/// Print the transitive import closure (`file:line CMD`, #115 preview)
260/// instead of executing. Pure parser + loader: no handlers run, no
261/// processes spawn, no FS writes. Validates first through the shared
262/// run boundary so dry-run fails exactly where execution and `--mcp`
263/// would.
264fn print_dry_run(
265    steps: &[Step],
266    script: &ScriptSource,
267    workspace_root: &GuardedPath,
268) -> DiagnosticResult<()> {
269    let table = cli_module_table();
270    let entry_file = entry_file_of(script);
271    // Shared validation before any listing: same closure check as
272    // execution and MCP init, with default module instances (no socket
273    // binds, preserving the preview contract).
274    {
275        let resolver = PathResolver::new_lazy(workspace_root.clone())?;
276        let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
277        oxdock_core::validate_steps_with_fs_modules_and_entry(
278            fs,
279            steps,
280            cli_host_modules_with(None),
281            cli_host_types(),
282            entry_file.clone(),
283        )?;
284    }
285    let (label, base) = match script {
286        ScriptSource::Path(path) => (
287            path.display(),
288            path.parent().unwrap_or_else(|| workspace_root.clone()),
289        ),
290        ScriptSource::Stdin => ("<stdin>".to_string(), workspace_root.clone()),
291    };
292    let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
293    let listing = dry_run_closure(steps, &label, &base, &resolver, &table)?;
294    for item in listing {
295        println!("{}:{} {}", item.file, item.step.line, item.step.kind);
296    }
297    Ok(())
298}
299
300pub fn run() -> DiagnosticResult<()> {
301    init_temp_gc();
302    let workspace_root = discover_workspace_root().map_err(|e| errors::guard_workspace_root(&e))?;
303
304    let mut args = std::env::args().skip(1);
305    // `--help`/`-h` and `--version`/`-V` surface as keyed parse
306    // diagnostics (parse must not exit the process itself: it is
307    // public library API). Print the message and succeed so the
308    // binary exits 0.
309    let opts = match Options::parse(&mut args, &workspace_root) {
310        Ok(opts) => opts,
311        Err(err) if err.key() == "cli.version_requested" => {
312            println!("{err}");
313            return Ok(());
314        }
315        Err(err) if err.key() == "cli.help_requested" => {
316            print!("{err}");
317            return Ok(());
318        }
319        Err(err) => return Err(err),
320    };
321    // Guest serve mode short-circuits everything: no script, no snapshot,
322    // no shell. Binary stdio contract enforced inside.
323    #[cfg(feature = "net")]
324    if opts.remote_serve {
325        if opts.shell
326            || !opts.remotes.is_empty()
327            || !matches!(opts.script, ScriptSource::Stdin)
328            || !opts.script_args.is_empty()
329        {
330            return Err(errors::remote_serve_runs_alone());
331        }
332        return serve::serve();
333    }
334    #[cfg(not(feature = "net"))]
335    if opts.remote_serve {
336        return Err(errors::feature_required("--remote-serve", "net"));
337    }
338    // MCP tool hosting owns stdio like the guest serve loop: no script
339    // execution past init, no shell, no remote serve alongside it.
340    if opts.mcp {
341        #[cfg(feature = "mcp")]
342        {
343            if opts.shell || opts.remote_serve || !opts.remotes.is_empty() {
344                return Err(errors::mcp_runs_alone(&[
345                    "--shell",
346                    "--remote-serve",
347                    "--remote",
348                ]));
349            }
350            if !opts.endpoints.listens.is_empty() || !opts.endpoints.publishes.is_empty() {
351                return Err(errors::mcp_runs_alone(&["--listen/-p"]));
352            }
353            if opts.dry_run {
354                return Err(errors::mcp_runs_alone(&["--dry-run"]));
355            }
356            if !opts.script_args.is_empty() {
357                return Err(errors::mcp_runs_alone(&["script args"]));
358            }
359            return mcp::serve_mcp(opts, workspace_root);
360        }
361        #[cfg(not(feature = "mcp"))]
362        {
363            return Err(errors::feature_required("--mcp", "mcp"));
364        }
365    }
366    execute(opts, workspace_root)
367}
368
369/// Process exit status for a failed CLI run: relays an `EXIT` code (host
370/// or guest-relayed) clamped to the portable 0..=255 range, 1 for every
371/// other failure.
372pub fn process_exit_code(err: &Diagnostic) -> i32 {
373    exit_code_of_diag(err)
374        .map(|code| code.clamp(0, 255) as i32)
375        .unwrap_or(1)
376}
377
378#[derive(Debug, Clone)]
379pub enum ScriptSource {
380    Path(GuardedPath),
381    Stdin,
382}
383
384/// URLs never resolve to workspace files: fail with the input intact
385/// instead of letting normalization mangle the scheme. Present fact
386/// about this argument, not a claim about imports.
387fn reject_url_script(text: &str) -> DiagnosticResult<()> {
388    if text.contains("://") {
389        return Err(errors::script_not_local(text));
390    }
391    Ok(())
392}
393
394#[derive(Debug, Clone)]
395pub struct Options {
396    pub script: ScriptSource,
397    pub shell: bool,
398    /// Print the transitive import closure (`file:line CMD`, #115) instead
399    /// of executing. No handlers run, no processes spawn, no FS writes.
400    pub dry_run: bool,
401    pub endpoints: EndpointFlags,
402    pub remote_serve: bool,
403    /// Serve `EXPORT`ed FUNCs as MCP tools over stdio instead of running
404    /// linear steps. Requires the `mcp` feature; see `--mcp`.
405    pub mcp: bool,
406    /// Raw `--remote <target>="<command>"` pairs, in flag order. Validated
407    /// and tokenized at inventory build; empty in lean builds (flag bails).
408    pub remotes: Vec<(String, String)>,
409    /// Verbatim tail after the script position (#226): everything after
410    /// the script (or after `--script <file>`), with one leading `--`
411    /// stripped when present. Never option-parsed, so `--dry-run` after
412    /// the script stays data. Surfaced script-side via `STD::ARGV()`.
413    pub script_args: Vec<String>,
414}
415
416impl Options {
417    pub fn parse(
418        args: &mut impl Iterator<Item = String>,
419        workspace_root: &GuardedPath,
420    ) -> DiagnosticResult<Self> {
421        use lexopt::Arg::{Long, Short, Value};
422
423        let mut script: Option<ScriptSource> = None;
424        let mut shell = false;
425        let mut dry_run = false;
426        let mut endpoints = EndpointFlags::default();
427        let mut remote_serve = false;
428        let mut mcp = false;
429        // Pushed only under `net`; without it the binding never mutates.
430        #[cfg_attr(not(feature = "net"), allow(unused_mut))]
431        let mut remotes: Vec<(String, String)> = Vec::new();
432        let mut script_args: Vec<String> = Vec::new();
433        // Verbatim tail after the script is fixed (#226): drain lexopt's
434        // remaining raw args without option parsing. When the script was
435        // just fixed and the tail sits entirely in the raw stream, strip
436        // one leading `--` separator. When `text` itself already holds
437        // the tail head (`--` stdin marker or dash-leading first arg),
438        // that separator (or first arg) is already accounted for, so the
439        // remainder stays verbatim. Bare empties stay intact here: only
440        // pre-script positionals skip them.
441        let drain_tail =
442            |parser: &mut lexopt::Parser, strip_leading: bool| -> DiagnosticResult<Vec<String>> {
443                let mut raw = parser.raw_args().map_err(|e| errors::arg_lex_error(&e))?;
444                let Some(first_os) = raw.next() else {
445                    return Ok(Vec::new());
446                };
447                let first = value_string(first_os)?;
448                if strip_leading && first == "--" {
449                    raw.map(value_string).collect()
450                } else {
451                    std::iter::once(Ok(first))
452                        .chain(raw.map(value_string))
453                        .collect()
454                }
455            };
456        // Pass the stream unfiltered: an explicit empty value (for
457        // example `--script ""`) is a real token boundary, so stripping
458        // empties up front would shift every following value. Bare empty
459        // positionals are skipped in the `Value` arm instead.
460        let mut parser = lexopt::Parser::from_args(args.by_ref());
461        while let Some(arg) = parser.next().map_err(|e| errors::arg_lex_error(&e))? {
462            match arg {
463                Long("script") => {
464                    let path = value_string(
465                        parser
466                            .value()
467                            .map_err(|_| errors::script_flag_needs_path())?,
468                    )?;
469                    if path.is_empty() {
470                        return Err(errors::script_flag_needs_path());
471                    }
472                    if path == "-" {
473                        script = Some(ScriptSource::Stdin);
474                    } else {
475                        reject_url_script(&path)?;
476                        script = Some(ScriptSource::Path(
477                            workspace_root
478                                .join_script(&path)
479                                .map_err(|e| errors::guard_script_path(&path, &e))?,
480                        ));
481                    }
482                    // After the script, stop option parsing entirely:
483                    // everything else is verbatim script args.
484                    script_args = drain_tail(&mut parser, true)?;
485                    break;
486                }
487                Long("shell") => {
488                    shell = true;
489                }
490                Long("dry-run") => {
491                    dry_run = true;
492                }
493                Long("listen") => {
494                    let raw = value_string(
495                        parser
496                            .value()
497                            .map_err(|_| errors::listen_requires_address())?,
498                    )?;
499                    #[cfg(not(feature = "net"))]
500                    {
501                        // Evaluate the pure validator so it stays compiled
502                        // and covered in lean builds; the feature error below
503                        // still wins regardless of the value.
504                        let _ = endpoints::parse_listen_arg(&raw);
505                        return Err(errors::feature_required("--listen/-p", "net"));
506                    }
507                    #[cfg(feature = "net")]
508                    endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
509                }
510                Short('p') => {
511                    let raw = value_string(
512                        parser
513                            .value()
514                            .map_err(|_| errors::publish_requires_shape(""))?,
515                    )?;
516                    #[cfg(not(feature = "net"))]
517                    {
518                        // Same as `--listen` above: keep the pure outer
519                        // validation live in lean builds; the feature error
520                        // below still wins.
521                        let _ = endpoints::parse_publish_arg(&raw);
522                        return Err(errors::feature_required("--listen/-p", "net"));
523                    }
524                    #[cfg(feature = "net")]
525                    endpoints
526                        .publishes
527                        .push(endpoints::parse_publish_arg(&raw)?);
528                }
529                Long("offline") => {
530                    endpoints.offline = true;
531                }
532                Long("remote-serve") => {
533                    remote_serve = true;
534                }
535                Long("mcp") => {
536                    mcp = true;
537                }
538                Long("remote") => {
539                    let raw = value_string(
540                        parser
541                            .value()
542                            .map_err(|_| errors::remote_requires_value())?,
543                    )?;
544                    #[cfg(not(feature = "net"))]
545                    {
546                        // Keep the pure validator live in lean builds; the
547                        // feature error below still wins.
548                        let _ = oxdock_net_plugin_stub_parse_remote(&raw);
549                        return Err(errors::feature_required("--remote", "net"));
550                    }
551                    #[cfg(feature = "net")]
552                    remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
553                }
554                Long("help") | Short('h') => {
555                    return Err(errors::help_requested());
556                }
557                Long("version") | Short('V') | Short('v') => {
558                    return Err(errors::version_requested());
559                }
560                Value(value) => {
561                    let text = value_string(value)?;
562                    if text.is_empty() {
563                        continue;
564                    }
565                    if text == "--" {
566                        // Second `--` with no script yet: stdin script with
567                        // the remainder as args (`oxdock -- -- foo`). The
568                        // text itself is the one stripped separator.
569                        script = Some(ScriptSource::Stdin);
570                        script_args = drain_tail(&mut parser, false)?;
571                        break;
572                    }
573                    if text == "-" {
574                        script = Some(ScriptSource::Stdin);
575                        script_args = drain_tail(&mut parser, true)?;
576                        break;
577                    }
578                    if text.starts_with('-') {
579                        // Dash-leading Value only surfaces after lexopt's
580                        // `--` separator, so this is `oxdock -- --foo`:
581                        // stdin script with dash-leading args, not a file
582                        // named `--foo` (pass those via `--script`). The
583                        // text is already the tail head, so the remainder
584                        // stays verbatim to preserve inner `--` entries.
585                        script = Some(ScriptSource::Stdin);
586                        let mut tail = drain_tail(&mut parser, false)?;
587                        tail.insert(0, text);
588                        script_args = tail;
589                        break;
590                    }
591                    reject_url_script(&text)?;
592                    script = Some(ScriptSource::Path(
593                        workspace_root
594                            .join_script(&text)
595                            .map_err(|e| errors::guard_script_path(&text, &e))?,
596                    ));
597                    script_args = drain_tail(&mut parser, true)?;
598                    break;
599                }
600                Long(other) => {
601                    return Err(errors::unexpected_flag(other, true));
602                }
603                Short(other) => {
604                    return Err(errors::unexpected_flag(&other.to_string(), false));
605                }
606            }
607        }
608
609        let script = script.unwrap_or(ScriptSource::Stdin);
610
611        Ok(Self {
612            script,
613            shell,
614            dry_run,
615            endpoints,
616            remote_serve,
617            mcp,
618            remotes,
619            script_args,
620        })
621    }
622}
623
624/// Option/positional text out of a lexopt value. Inputs arrive as
625/// `String`, so non-UTF8 is unreachable in practice; fail loudly anyway.
626fn value_string(value: std::ffi::OsString) -> DiagnosticResult<String> {
627    value.into_string().map_err(|_| errors::arg_not_utf8())
628}
629
630/// Human-readable CLI version, printed for `--version`/`-V`/`-v`.
631pub fn version() -> String {
632    format!("oxdock {}", env!("CARGO_PKG_VERSION"))
633}
634
635pub fn execute(opts: Options, workspace_root: GuardedPath) -> DiagnosticResult<()> {
636    init_temp_gc();
637    execute_with_shell_runner(opts, workspace_root, run_shell, true)
638}
639
640/// Output of a script execution (issue #131).
641///
642/// The snapshot directory is created lazily: [`ExecutionResult::snapshot`]
643/// stays unmaterialized when the script never touches snapshot-rooted state
644/// (e.g. `WORKSPACE LOCAL`-only or empty scripts), in which case
645/// [`ExecutionResult::has_snapshot`] is false and `final_cwd` points under
646/// the workspace root.
647pub struct ExecutionResult {
648    /// Shared ownership of the snapshot backing dir. The physical directory
649    /// lives exactly as long as the last surviving clone (normally this
650    /// struct, since execution-internal clones are dropped before return).
651    pub snapshot: Arc<LazyGuardedTempDir>,
652    /// Actual final cwd: inside the snapshot when materialized, otherwise
653    /// under the workspace/local root.
654    pub final_cwd: GuardedPath,
655    /// Top-level script variable bindings captured at completion, keyed by
656    /// variable name. Empty when the script is empty. Populated exclusively
657    /// by [`execute_with_result`]; `--shell` runs never produce one.
658    pub bindings: BTreeMap<String, Value>,
659}
660
661impl ExecutionResult {
662    /// Whether the run materialized the snapshot tempdir.
663    pub fn has_snapshot(&self) -> bool {
664        self.snapshot.is_materialized()
665    }
666
667    /// Borrow the snapshot root iff materialized.
668    pub fn snapshot_path(&self) -> Option<&GuardedPath> {
669        self.snapshot.get()
670    }
671}
672
673pub fn execute_with_result(
674    opts: Options,
675    workspace_root: GuardedPath,
676) -> DiagnosticResult<ExecutionResult> {
677    if opts.shell {
678        return Err(errors::shell_unsupported_in_result());
679    }
680
681    // Read + parse BEFORE any tempdir exists so LOCAL-only scripts never
682    // create a snapshot directory they never use (issue #131).
683    let script = read_script(&opts.script)?;
684
685    let mut final_cwd = workspace_root.clone();
686    let snapshot = Arc::new(LazyGuardedTempDir::new());
687    if !script.trim().is_empty() {
688        let steps = parse_cli_script(&script)?;
689        // Dry-run previews the import closure without binding sockets,
690        // remotes, or execution state.
691        if opts.dry_run {
692            print_dry_run(&steps, &opts.script, &workspace_root)?;
693            return Ok(ExecutionResult {
694                snapshot,
695                final_cwd,
696                bindings: BTreeMap::new(),
697            });
698        }
699        // Bind endpoint sockets before running: conflicts fail fast,
700        // never parse-then-fail-on-bind.
701        #[cfg(feature = "net")]
702        let registry = build_registry(&opts.endpoints)?;
703        #[cfg(not(feature = "net"))]
704        check_no_net_endpoints(&opts.endpoints)?;
705        #[cfg(not(feature = "net"))]
706        check_no_net_remotes(&opts.remotes)?;
707        // Validate REMOTE targets against inventory after parsing (targets
708        // live in AST nodes) and before execution: unknown targets fail
709        // here, never mid-run.
710        #[cfg(feature = "net")]
711        let inventory = {
712            let pairs = opts.remotes.clone();
713            let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
714            inventory.log_resolutions();
715            inventory.validate_script(&steps)?;
716            inventory
717        };
718        let entry_file = entry_file_of(&opts.script);
719        #[cfg(feature = "net")]
720        let io_cfg = {
721            let mut io_cfg = ExecIo::new();
722            io_cfg.set_script_args(opts.script_args.clone());
723            register_remote_runners(&mut io_cfg, &inventory);
724            io_cfg
725        };
726        #[cfg(not(feature = "net"))]
727        let io_cfg = {
728            let mut io_cfg = ExecIo::new();
729            io_cfg.set_script_args(opts.script_args.clone());
730            io_cfg
731        };
732        #[cfg(feature = "net")]
733        let output = run_cli_steps(&workspace_root, &steps, io_cfg, Some(&registry), entry_file)?;
734        #[cfg(not(feature = "net"))]
735        let output = run_cli_steps(&workspace_root, &steps, io_cfg, None, entry_file)?;
736        final_cwd = output.final_cwd;
737        return Ok(ExecutionResult {
738            snapshot: output.snapshot,
739            final_cwd,
740            bindings: output.bindings,
741        });
742    }
743
744    Ok(ExecutionResult {
745        snapshot,
746        final_cwd,
747        bindings: BTreeMap::new(),
748    })
749}
750
751/// Register one SSH stdio session per inventory target on the run IO.
752/// Lazy spawn still applies (no process exists until a block entry), but
753/// registration happens up front so `REMOTE` interception always finds a
754/// runner when the target validated.
755#[cfg(feature = "net")]
756fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
757    use std::sync::Arc;
758    let entries = surface_entries();
759    let module_hash = oxdock_net_plugin::module_hash(&entries);
760    let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
761    for target in inventory.targets() {
762        let Some(argv) = inventory.argv(&target) else {
763            continue;
764        };
765        let config = oxdock_net_plugin::SessionConfig {
766            argv: argv.to_vec(),
767            oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
768            modules: modules.clone(),
769            module_hash: module_hash.clone(),
770        };
771        io.set_remote_runner_for_target(
772            target,
773            Arc::new(oxdock_net_plugin::StdioSession::new(config)),
774        );
775    }
776}
777
778/// Module-table surface for handshake identity and session config: the
779/// same tables the run executes against.
780#[cfg(feature = "net")]
781fn surface_entries() -> Vec<(String, Vec<String>)> {
782    let mut engine = Engine::new();
783    for module in cli_host_modules() {
784        engine.register_module(module);
785    }
786    let table = engine.module_table();
787    let mut entries: Vec<(String, Vec<String>)> = table
788        .modules
789        .into_iter()
790        .map(|(name, module_funcs)| {
791            let mut func_names: Vec<String> = module_funcs
792                .map(|surface| surface.func_names.into_iter().collect())
793                .unwrap_or_default();
794            func_names.sort();
795            (name, func_names)
796        })
797        .collect();
798    entries.sort();
799    entries
800}
801#[cfg(feature = "net")]
802fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
803    use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
804    for (outer, inner) in &flags.publishes {
805        if outer.port() != 0 {
806            continue;
807        }
808        let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
809            continue;
810        };
811        let key = EndpointKey {
812            protocol: protocol.unwrap_or(Protocol::Tcp),
813            endpoint,
814        };
815        match registry.resolve_endpoint(&key) {
816            Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
817            Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
818        }
819    }
820}
821
822/// Without `net`, remote targets cannot exist: `--remote` is rejected
823/// at flag parse time; this covers programmatic `Options` carrying pairs.
824#[cfg(not(feature = "net"))]
825fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> DiagnosticResult<(String, String)> {
826    // Mirror the NET plugin's shape check without the dependency so the
827    // flag stays diagnosed (not silently swallowed) in lean builds.
828    match raw.split_once('=') {
829        Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
830            Ok((target.trim().to_string(), command.to_string()))
831        }
832        _ => Err(errors::remote_requires_shape(raw)),
833    }
834}
835
836/// Without `net`, remote targets cannot exist.
837#[cfg(not(feature = "net"))]
838fn check_no_net_remotes(remotes: &[(String, String)]) -> DiagnosticResult<()> {
839    if !remotes.is_empty() {
840        return Err(errors::feature_required("--remote", "net"));
841    }
842    Ok(())
843}
844
845/// Without `net`, endpoint sockets cannot exist: `--listen`/`-p` are
846/// rejected (parse time already bails; this covers programmatic `Options`),
847/// while `--offline` or no flags proceed socketless.
848#[cfg(not(feature = "net"))]
849fn check_no_net_endpoints(flags: &EndpointFlags) -> DiagnosticResult<()> {
850    if !flags.listens.is_empty() || !flags.publishes.is_empty() {
851        return Err(errors::feature_required("--listen/-p", "net"));
852    }
853    Ok(())
854}
855
856/// Read the script source without creating any execution state. The
857/// read resolves against the script path's own root, so scripts
858/// outside the execution workspace load exactly like scripts inside it.
859fn read_script(source: &ScriptSource) -> DiagnosticResult<String> {
860    match source {
861        ScriptSource::Path(path) => {
862            let resolver = PathResolver::new(path.root(), path.root())?;
863            resolver
864                .read_to_string(path)
865                .map_err(|e| errors::read_script_at(&path.display().to_string(), &e))
866        }
867        ScriptSource::Stdin => {
868            let mut buf = String::new();
869            io::stdin()
870                .lock()
871                .read_to_string(&mut buf)
872                .map_err(|e| errors::read_script_stdin(&e))?;
873            Ok(buf)
874        }
875    }
876}
877
878fn execute_with_shell_runner<F>(
879    opts: Options,
880    workspace_root: GuardedPath,
881    shell_runner: F,
882    require_tty: bool,
883) -> DiagnosticResult<()>
884where
885    F: FnOnce(&GuardedPath, &GuardedPath) -> DiagnosticResult<()>,
886{
887    #[cfg(windows)]
888    maybe_reexec_shell_to_temp(&opts)?;
889
890    // Interpret a tiny Dockerfile-ish script. No tempdir exists yet: the
891    // snapshot materializes lazily on first snapshot-targeted step, so an
892    // empty non-shell run creates nothing at all (issue #131).
893    let script = match &opts.script {
894        ScriptSource::Path(_) => read_script(&opts.script)?,
895        ScriptSource::Stdin => {
896            let stdin = io::stdin();
897            if stdin.is_terminal() {
898                // No piped script provided. If the caller requested `--shell`
899                // allow running with an initially-empty script so we can either
900                // drop into the interactive shell or open the editor later.
901                // Otherwise, require a script on stdin.
902                if opts.shell {
903                    String::new()
904                } else {
905                    return Err(errors::script_stdin_missing());
906                }
907            } else {
908                let mut buf = String::new();
909                stdin
910                    .lock()
911                    .read_to_string(&mut buf)
912                    .map_err(|e| errors::read_script_stdin(&e))?;
913                buf
914            }
915        }
916    };
917
918    // Parse and run steps if we have a non-empty script. Empty scripts are
919    // valid when `--shell` is requested and the caller didn't pipe a script.
920    // Use the caller's workspace as the build context so WORKSPACE LOCAL can
921    // hop back and so COPY can source from the original tree if needed.
922    // Capture the final working directory so shells inherit whatever WORKDIR
923    // the script ended on.
924    let mut final_cwd = workspace_root.clone();
925    let mut snapshot = Arc::new(LazyGuardedTempDir::new());
926    let mut fs: Option<Box<dyn WorkspaceFs>> = None;
927    if !script.trim().is_empty() {
928        let steps = parse_cli_script(&script)?;
929        // Dry-run previews the import closure without binding sockets,
930        // remotes, or execution state.
931        if opts.dry_run {
932            print_dry_run(&steps, &opts.script, &workspace_root)?;
933            return Ok(());
934        }
935        // Bind endpoint sockets before running: conflicts fail fast,
936        // never parse-then-fail-on-bind.
937        #[cfg(feature = "net")]
938        let registry = build_registry(&opts.endpoints)?;
939        #[cfg(not(feature = "net"))]
940        check_no_net_endpoints(&opts.endpoints)?;
941        #[cfg(not(feature = "net"))]
942        check_no_net_remotes(&opts.remotes)?;
943        #[cfg(feature = "net")]
944        report_ephemeral_publishes(&opts.endpoints, &registry);
945        // Validate REMOTE targets against inventory after parsing (targets
946        // live in AST nodes) and before execution: unknown targets fail
947        // here, never mid-run.
948        #[cfg(feature = "net")]
949        let inventory = {
950            let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
951            inventory.log_resolutions();
952            inventory.validate_script(&steps)?;
953            inventory
954        };
955        // If we are running a script from a file, we might have stdin available for the script itself.
956        // If we read the script from stdin, then stdin is consumed.
957        // But if opts.script is ScriptSource::Path, stdin is still available.
958
959        let mut stdin_handle: Option<SharedInput> = None;
960        if let ScriptSource::Path(_) = opts.script {
961            let stdin = io::stdin();
962            if !stdin.is_terminal() {
963                // Wrap stdin in SharedInput (Arc<Mutex<dyn Read + Send>>)
964                // Note: std::io::Stdin is a handle, but we need an owned Read + Send.
965                // std::io::stdin() returns Stdin, which implements Read + Send.
966                // However, we need to be careful about locking.
967                // We can wrap the Stdin struct directly.
968                stdin_handle = Some(Arc::new(Mutex::new(stdin)));
969            }
970        }
971
972        let mut io_cfg = ExecIo::new();
973        io_cfg.set_stdin(stdin_handle);
974        io_cfg.set_script_args(opts.script_args.clone());
975        #[cfg(feature = "net")]
976        register_remote_runners(&mut io_cfg, &inventory);
977        let entry_file = entry_file_of(&opts.script);
978        #[cfg(feature = "net")]
979        let output = run_cli_steps(&workspace_root, &steps, io_cfg, Some(&registry), entry_file)?;
980        #[cfg(not(feature = "net"))]
981        let output = run_cli_steps(&workspace_root, &steps, io_cfg, None, entry_file)?;
982        final_cwd = output.final_cwd;
983        snapshot = output.snapshot;
984        fs = Some(output.fs);
985    }
986
987    // If requested, drop into an interactive shell after running the script.
988    if opts.shell {
989        if require_tty && !has_controlling_tty() {
990            return Err(errors::shell_needs_tty());
991        }
992        // The shell needs a concrete directory: materialize here at shell
993        // entry (not at startup) when the script left the snapshot pending,
994        // then converge the cwd onto the shared concrete root. An empty
995        // script starts the shell in a fresh snapshot directory.
996        match fs.as_ref() {
997            Some(fs) => {
998                if fs.is_snapshot_pending() {
999                    snapshot
1000                        .materialize()
1001                        .map_err(|e| errors::create_shell_temp_dir(&e))?;
1002                }
1003                final_cwd = fs.concretize_cwd(&final_cwd);
1004            }
1005            None => {
1006                snapshot
1007                    .materialize()
1008                    .map_err(|e| errors::create_shell_temp_dir(&e))?;
1009                final_cwd = snapshot
1010                    .get()
1011                    .cloned()
1012                    .expect("shell snapshot materialized above");
1013            }
1014        }
1015        return shell_runner(&final_cwd, &workspace_root);
1016    }
1017
1018    Ok(())
1019}
1020
1021#[cfg(test)]
1022fn execute_for_test<F>(
1023    opts: Options,
1024    workspace_root: GuardedPath,
1025    shell_runner: F,
1026) -> DiagnosticResult<()>
1027where
1028    F: FnOnce(&GuardedPath, &GuardedPath) -> DiagnosticResult<()>,
1029{
1030    execute_with_shell_runner(opts, workspace_root, shell_runner, false)
1031}
1032
1033fn has_controlling_tty() -> bool {
1034    // Prefer checking whether stdin or stderr is a terminal. This avoids
1035    // directly opening device files via `std::fs` while still detecting
1036    // whether an interactive tty is available in the common cases.
1037    #[cfg(unix)]
1038    {
1039        io::stdin().is_terminal() || io::stderr().is_terminal()
1040    }
1041
1042    #[cfg(windows)]
1043    {
1044        io::stdin().is_terminal() || io::stderr().is_terminal()
1045    }
1046
1047    #[cfg(not(any(unix, windows)))]
1048    {
1049        false
1050    }
1051}
1052
1053#[cfg(windows)]
1054fn maybe_reexec_shell_to_temp(opts: &Options) -> DiagnosticResult<()> {
1055    // Only used for interactive shells. Copy the binary to a temp path and run it there so the
1056    // original target exe is free for rebuilding while the shell stays open.
1057    if !opts.shell {
1058        return Ok(());
1059    }
1060    if std::env::var(oxdock_env::oxdock::SHELL_REEXEC)
1061        .ok()
1062        .as_deref()
1063        == Some("1")
1064    {
1065        return Ok(());
1066    }
1067
1068    let self_path = std::env::current_exe().map_err(|e| errors::determine_current_exe(&e))?;
1069    let base_temp = GuardedPath::new_root(std::env::temp_dir().as_path())
1070        .map_err(|e| errors::guard_system_temp_dir(&e))?;
1071    let ts = std::time::SystemTime::now()
1072        .duration_since(std::time::UNIX_EPOCH)
1073        .unwrap_or_default()
1074        .as_millis();
1075    let temp_file = base_temp
1076        .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
1077        .map_err(|e| errors::construct_temp_shell_path(&e))?;
1078
1079    // Copy the current executable into the temporary location via a
1080    // resolver whose root is the temp directory. The source may live
1081    // outside the temp dir, so use `copy_file_from_external`.
1082    let temp_root_guard = temp_file
1083        .parent()
1084        .ok_or_else(errors::shell_temp_missing_parent)?;
1085    let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
1086    let dest = temp_file;
1087    #[allow(clippy::disallowed_types)]
1088    let source = oxdock_fs::UnguardedPath::external(self_path);
1089    resolver_temp
1090        .copy_file_from_unguarded(&source, &dest)
1091        .map_err(|e| errors::copy_shell_runner(&dest.display().to_string(), &e))?;
1092
1093    let mut cmd = CommandBuilder::new(dest.as_path());
1094    cmd.args(std::env::args_os().skip(1));
1095    cmd.env(oxdock_env::oxdock::SHELL_REEXEC, "1");
1096    cmd.spawn()
1097        .map_err(|e| errors::spawn_shell_from(&dest.display().to_string(), &e))?;
1098
1099    // Exit immediately so the original binary can be rebuilt while the shell child stays running.
1100    std::process::exit(0);
1101}
1102
1103pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> DiagnosticResult<()> {
1104    run_steps_with_context(workspace_root, workspace_root, steps)
1105}
1106
1107fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
1108    #[cfg(windows)]
1109    let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
1110    #[cfg(windows)]
1111    let workspace_disp = oxdock_fs::command_path(workspace_root)
1112        .as_ref()
1113        .display()
1114        .to_string();
1115
1116    #[cfg(not(windows))]
1117    let cwd_disp = cwd.display().to_string();
1118    #[cfg(not(windows))]
1119    let workspace_disp = workspace_root.display().to_string();
1120
1121    let pkg = env::var(oxdock_env::cargo::PKG_NAME)
1122        .unwrap_or_else(|_| oxdock_env::oxdock::FALLBACK_APP_NAME.to_string());
1123    indoc::formatdoc! {"
1124        {pkg} shell workspace
1125          cwd: {cwd_disp}
1126          source: workspace root at {workspace_disp}
1127          lifetime: temporary directory created for this shell session; it disappears when you exit
1128          creation: temp workspace starts empty unless your script copies files into it
1129
1130          WARNING: This shell still runs on your host filesystem and is **not** isolated!
1131    "}
1132}
1133
1134fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> DiagnosticResult<()> {
1135    oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
1136}
1137
1138// `command_path` now lives in `oxdock-fs` to centralize Path usage.
1139
1140#[cfg(test)]
1141mod tests {
1142    use super::*;
1143    use anyhow::Result;
1144    use indoc::indoc;
1145    use oxdock_fs::PathResolver;
1146    use std::cell::{Cell, RefCell};
1147
1148    #[cfg_attr(
1149        miri,
1150        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1151    )]
1152    #[test]
1153    fn shell_runner_receives_final_workdir() -> Result<()> {
1154        let workspace = GuardedPath::tempdir()?;
1155        let workspace_root = workspace.as_guarded_path().clone();
1156        let script_path = workspace_root.join("script.ox")?;
1157        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1158        let script = indoc! {"
1159            WRITE temp.txt 123
1160            WORKDIR sub
1161        "};
1162        resolver.write_file(&script_path, script.as_bytes())?;
1163
1164        let opts = Options {
1165            script: ScriptSource::Path(script_path),
1166            shell: true,
1167            dry_run: false,
1168            endpoints: EndpointFlags::default(),
1169            remote_serve: false,
1170            mcp: false,
1171            remotes: Vec::new(),
1172            script_args: Vec::new(),
1173        };
1174
1175        let observed = Cell::new(false);
1176        execute_for_test(opts, workspace_root.clone(), |cwd, _| {
1177            assert!(
1178                cwd.as_path().ends_with("sub"),
1179                "final cwd should end in WORKDIR target, got {}",
1180                cwd.display()
1181            );
1182
1183            let temp_root = GuardedPath::new_root(cwd.root())?;
1184            let sub_dir = temp_root.join("sub")?;
1185            assert_eq!(
1186                cwd.as_path(),
1187                sub_dir.as_path(),
1188                "shell runner cwd should match guarded sub dir"
1189            );
1190            let temp_file = temp_root.join("temp.txt")?;
1191            let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
1192            let contents = temp_resolver.read_to_string(&temp_file)?;
1193            assert!(
1194                contents.contains("123"),
1195                "expected WRITE command to materialize temp file"
1196            );
1197            observed.set(true);
1198            Ok(())
1199        })?;
1200
1201        assert!(
1202            observed.into_inner(),
1203            "shell runner closure should have been invoked"
1204        );
1205        Ok(())
1206    }
1207
1208    #[cfg_attr(
1209        miri,
1210        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1211    )]
1212    #[test]
1213    fn options_parse_requires_script_path_value() {
1214        let workspace = GuardedPath::tempdir().expect("tempdir");
1215        let mut args = vec!["--script".to_string()].into_iter();
1216        let err = Options::parse(&mut args, workspace.as_guarded_path())
1217            .expect_err("expected missing path error");
1218        assert!(err.to_string().contains("--script requires a path"));
1219    }
1220
1221    #[cfg_attr(
1222        miri,
1223        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1224    )]
1225    #[test]
1226    fn options_parse_script_flag_takes_dash_leading_path() {
1227        // #226: dash-named files ride `--script` (bare dash-leading
1228        // positionals are stdin args, never files).
1229        let workspace = GuardedPath::tempdir().expect("tempdir");
1230        let workspace_root = workspace.as_guarded_path().clone();
1231        let mut args = vec!["--script".to_string(), "--weird.ox".to_string()].into_iter();
1232        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1233        match opts.script {
1234            ScriptSource::Path(path) => assert_eq!(
1235                path,
1236                workspace_root.join("--weird.ox").expect("script path")
1237            ),
1238            ScriptSource::Stdin => panic!("expected path script"),
1239        }
1240        assert!(opts.script_args.is_empty());
1241    }
1242
1243    #[cfg_attr(
1244        miri,
1245        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1246    )]
1247    #[test]
1248    fn options_parse_script_path_and_shell() {
1249        let workspace = GuardedPath::tempdir().expect("tempdir");
1250        let workspace_root = workspace.as_guarded_path().clone();
1251        let script_path = workspace_root.join("script.txt").expect("script path");
1252        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1253            .expect("resolver");
1254        resolver
1255            .write_file(&script_path, b"WRITE out.txt hi")
1256            .expect("write script");
1257        // #226: interpreter flags come before the script; anything
1258        // after is verbatim script args.
1259        let mut args = vec![
1260            "--shell".to_string(),
1261            "--script".to_string(),
1262            "script.txt".to_string(),
1263        ]
1264        .into_iter();
1265        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1266        assert!(opts.shell);
1267        match opts.script {
1268            ScriptSource::Path(path) => assert_eq!(path, script_path),
1269            ScriptSource::Stdin => panic!("expected path script"),
1270        }
1271        assert!(opts.script_args.is_empty());
1272
1273        let mut args = vec![
1274            "--script".to_string(),
1275            "script.txt".to_string(),
1276            "--shell".to_string(),
1277        ]
1278        .into_iter();
1279        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1280        assert!(
1281            !opts.shell,
1282            "--shell after the script is data, not the interpreter flag"
1283        );
1284        assert_eq!(opts.script_args, vec!["--shell"]);
1285    }
1286
1287    #[cfg_attr(
1288        miri,
1289        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1290    )]
1291    #[test]
1292    fn options_parse_mcp_flag() {
1293        let workspace = GuardedPath::tempdir().expect("tempdir");
1294        let workspace_root = workspace.as_guarded_path().clone();
1295        let mut args = vec!["--mcp".to_string(), "tools.oxdock".to_string()].into_iter();
1296        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1297        assert!(opts.mcp);
1298        match opts.script {
1299            ScriptSource::Path(path) => assert_eq!(
1300                path,
1301                workspace_root.join("tools.oxdock").expect("script path")
1302            ),
1303            ScriptSource::Stdin => panic!("expected path script"),
1304        }
1305    }
1306
1307    #[cfg_attr(
1308        miri,
1309        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1310    )]
1311    #[test]
1312    fn options_parse_mcp_defaults_off() {
1313        let workspace = GuardedPath::tempdir().expect("tempdir");
1314        let workspace_root = workspace.as_guarded_path().clone();
1315        let mut args = vec!["script.txt".to_string()].into_iter();
1316        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1317        assert!(!opts.mcp);
1318    }
1319
1320    #[cfg_attr(
1321        miri,
1322        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1323    )]
1324    #[test]
1325    fn options_parse_positional_script_path() {
1326        let workspace = GuardedPath::tempdir().expect("tempdir");
1327        let workspace_root = workspace.as_guarded_path().clone();
1328        let mut args = vec!["script.txt".to_string()].into_iter();
1329        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1330        assert!(!opts.shell);
1331        match opts.script {
1332            ScriptSource::Path(path) => assert_eq!(
1333                path,
1334                workspace_root.join("script.txt").expect("script path")
1335            ),
1336            ScriptSource::Stdin => panic!("expected path script"),
1337        }
1338    }
1339
1340    #[cfg_attr(
1341        miri,
1342        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1343    )]
1344    #[test]
1345    fn options_parse_positional_dash_reads_stdin() {
1346        let workspace = GuardedPath::tempdir().expect("tempdir");
1347        let mut args = vec!["-".to_string()].into_iter();
1348        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1349        assert!(matches!(opts.script, ScriptSource::Stdin));
1350    }
1351
1352    #[cfg_attr(
1353        miri,
1354        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1355    )]
1356    #[test]
1357    fn options_parse_second_positional_is_script_arg() {
1358        // #226: after the script, option parsing stops entirely, so a
1359        // second positional (or `--script` there) is verbatim script
1360        // args, never a duplicate-script error.
1361        let workspace = GuardedPath::tempdir().expect("tempdir");
1362        let workspace_root = workspace.as_guarded_path().clone();
1363        let mut args = vec![
1364            "a.ox".to_string(),
1365            "--script".to_string(),
1366            "b.ox".to_string(),
1367        ]
1368        .into_iter();
1369        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1370        match &opts.script {
1371            ScriptSource::Path(path) => assert_eq!(
1372                path,
1373                &workspace_root.join("a.ox").expect("script path"),
1374                "first positional fixes the script"
1375            ),
1376            ScriptSource::Stdin => panic!("expected path script"),
1377        }
1378        assert_eq!(opts.script_args, vec!["--script", "b.ox"]);
1379
1380        let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1381        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1382        assert_eq!(opts.script_args, vec!["b.ox"]);
1383    }
1384
1385    #[cfg_attr(
1386        miri,
1387        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1388    )]
1389    #[test]
1390    fn options_parse_absolute_script_outside_execution_workspace_loads() {
1391        // Stdin parity: an explicit absolute location loads wherever
1392        // it lives; only relative paths resolve under the workspace.
1393        let workspace = GuardedPath::tempdir().expect("tempdir");
1394        let outside = GuardedPath::tempdir().expect("outside");
1395        let target = outside
1396            .as_guarded_path()
1397            .as_path()
1398            .join("step.ox")
1399            .to_string_lossy()
1400            .into_owned();
1401        let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1402        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1403        match opts.script {
1404            ScriptSource::Path(path) => {
1405                assert_eq!(path.as_path().to_string_lossy(), target);
1406                assert_eq!(path.root(), outside.as_guarded_path().as_path());
1407            }
1408            ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1409        }
1410    }
1411
1412    #[cfg_attr(
1413        miri,
1414        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1415    )]
1416    #[test]
1417    fn options_parse_relative_escape_stays_rejected() {
1418        let workspace = GuardedPath::tempdir().expect("tempdir");
1419        let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1420        let err =
1421            Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1422        assert!(err.to_string().contains("guard script path"), "{err:?}");
1423    }
1424
1425    #[cfg_attr(
1426        miri,
1427        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1428    )]
1429    #[test]
1430    fn options_parse_rejects_unknown_flags() {
1431        let workspace = GuardedPath::tempdir().expect("tempdir");
1432        let mut args = vec!["--frobnicate".to_string()].into_iter();
1433        let err = Options::parse(&mut args, workspace.as_guarded_path())
1434            .expect_err("expected unknown flag error");
1435        assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1436    }
1437
1438    #[test]
1439    fn usage_describes_positional_script_and_help() {
1440        let text = usage();
1441        assert!(text.contains("Usage: oxdock"), "{text}");
1442        assert!(text.contains("SCRIPT"), "{text}");
1443        assert!(text.contains("--script"), "{text}");
1444        assert!(text.contains("--help"), "{text}");
1445        assert!(text.contains("--offline"), "{text}");
1446        #[cfg(feature = "net")]
1447        {
1448            assert!(text.contains("--listen"), "{text}");
1449            assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1450        }
1451        #[cfg(not(feature = "net"))]
1452        {
1453            assert!(!text.contains("--listen <addr>"), "{text}");
1454            assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1455            assert!(text.contains("require the `net` feature"), "{text}");
1456        }
1457        // Tagline is single-sourced from the package manifest, not hardcoded.
1458        assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1459    }
1460
1461    #[cfg(feature = "net")]
1462    #[cfg_attr(
1463        miri,
1464        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1465    )]
1466    #[test]
1467    fn options_parse_endpoint_flags() {
1468        // Pure flag parsing: no sockets open, but tempdir keeps the
1469        // ignore uniform with the neighboring parse tests.
1470        let workspace = GuardedPath::tempdir().expect("tempdir");
1471        let mut args = vec![
1472            "--listen".to_string(),
1473            "0.0.0.0:2251".to_string(),
1474            "-p".to_string(),
1475            "2222:demo-proxy".to_string(),
1476            "-p".to_string(),
1477            "0:2252".to_string(),
1478            "-".to_string(),
1479        ]
1480        .into_iter();
1481        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1482        assert_eq!(opts.endpoints.listens.len(), 1);
1483        assert_eq!(opts.endpoints.publishes.len(), 2);
1484        assert!(!opts.endpoints.offline);
1485        assert!(matches!(opts.script, ScriptSource::Stdin));
1486    }
1487
1488    #[cfg_attr(
1489        miri,
1490        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1491    )]
1492    #[test]
1493    fn options_parse_offline_flag() {
1494        let workspace = GuardedPath::tempdir().expect("tempdir");
1495        let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1496        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1497        assert!(opts.endpoints.offline);
1498    }
1499
1500    #[cfg(feature = "net")]
1501    #[cfg_attr(
1502        miri,
1503        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1504    )]
1505    #[test]
1506    fn options_parse_rejects_bad_endpoint_flags() {
1507        let workspace = GuardedPath::tempdir().expect("tempdir");
1508        for args in [
1509            vec!["--listen"],
1510            vec!["--listen", "0.0.0.0:0"],
1511            vec!["-p"],
1512            vec!["-p", "2222"],
1513            vec!["-p", "2222:0"],
1514        ] {
1515            let mut args = args.into_iter().map(str::to_string);
1516            Options::parse(&mut args, workspace.as_guarded_path())
1517                .expect_err("bad endpoint flag must fail");
1518        }
1519    }
1520
1521    #[cfg_attr(
1522        miri,
1523        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1524    )]
1525    #[test]
1526    fn options_parse_empty_values_hold_token_boundaries() {
1527        // Regression: explicit empty values must not shift the stream.
1528        // `--script ""` bails instead of consuming the next token, and a
1529        // bare empty positional is skipped like before.
1530        let workspace = GuardedPath::tempdir().expect("tempdir");
1531        let mut args = vec![
1532            "--script".to_string(),
1533            "".to_string(),
1534            "--shell".to_string(),
1535        ]
1536        .into_iter();
1537        let err = Options::parse(&mut args, workspace.as_guarded_path())
1538            .expect_err("empty script path must fail");
1539        assert!(
1540            err.to_string().contains("--script requires a path"),
1541            "{err:?}"
1542        );
1543        let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1544        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1545        assert!(matches!(opts.script, ScriptSource::Stdin));
1546    }
1547
1548    #[cfg(feature = "net")]
1549    #[cfg_attr(
1550        miri,
1551        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1552    )]
1553    #[test]
1554    fn options_parse_accepts_equals_and_attached_forms() {
1555        // lexopt-native spellings: `--flag=value`, attached short values,
1556        // and `--` separating positionals.
1557        let workspace = GuardedPath::tempdir().expect("tempdir");
1558        let workspace_root = workspace.as_guarded_path().clone();
1559        let mut args = vec![
1560            "--listen=0.0.0.0:2251".to_string(),
1561            "-p2222:demo-proxy".to_string(),
1562            "--".to_string(),
1563            "script.ox".to_string(),
1564        ]
1565        .into_iter();
1566        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1567        assert_eq!(opts.endpoints.listens.len(), 1);
1568        assert_eq!(opts.endpoints.publishes.len(), 1);
1569        match opts.script {
1570            ScriptSource::Path(path) => {
1571                assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1572            }
1573            ScriptSource::Stdin => panic!("expected path script after --"),
1574        }
1575        assert!(opts.script_args.is_empty());
1576    }
1577
1578    #[cfg_attr(
1579        miri,
1580        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1581    )]
1582    #[test]
1583    fn options_parse_routes_verbatim_tail_to_script_args() {
1584        // #226: after the script, option parsing stops. Dash-leading
1585        // tails survive without `--`, and one leading `--` strips.
1586        let workspace = GuardedPath::tempdir().expect("tempdir");
1587        let workspace_root = workspace.as_guarded_path().clone();
1588        let mut args = vec![
1589            "my.ox".to_string(),
1590            "--dry-run".to_string(),
1591            "--listen".to_string(),
1592            "0.0.0.0:2251".to_string(),
1593        ]
1594        .into_iter();
1595        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1596        assert_eq!(
1597            opts.script_args,
1598            vec!["--dry-run", "--listen", "0.0.0.0:2251"]
1599        );
1600
1601        let mut args = vec![
1602            "my.ox".to_string(),
1603            "--".to_string(),
1604            "--dry-run".to_string(),
1605        ]
1606        .into_iter();
1607        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1608        assert_eq!(opts.script_args, vec!["--dry-run"]);
1609
1610        let mut args = vec![
1611            "--script".to_string(),
1612            "my.ox".to_string(),
1613            "--".to_string(),
1614            "a".to_string(),
1615            "--".to_string(),
1616            "b".to_string(),
1617        ]
1618        .into_iter();
1619        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1620        assert_eq!(opts.script_args, vec!["a", "--", "b"]);
1621    }
1622
1623    #[cfg_attr(
1624        miri,
1625        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1626    )]
1627    #[test]
1628    fn options_parse_help_after_script_is_data() {
1629        // `--help`/`--version` stay interpreter-only before the script.
1630        let workspace = GuardedPath::tempdir().expect("tempdir");
1631        let workspace_root = workspace.as_guarded_path().clone();
1632        let mut args = vec!["my.ox".to_string(), "--help".to_string()].into_iter();
1633        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1634        assert_eq!(opts.script_args, vec!["--help"]);
1635        let mut args = vec!["my.ox".to_string(), "--version".to_string()].into_iter();
1636        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1637        assert_eq!(opts.script_args, vec!["--version"]);
1638    }
1639
1640    #[cfg_attr(
1641        miri,
1642        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1643    )]
1644    #[test]
1645    fn options_parse_dash_leading_after_separator_is_stdin_args() {
1646        // `oxdock -- --foo` is stdin plus args, not a file named `--foo`
1647        // (pass those via `--script`). Plain names after `--` stay files.
1648        let workspace = GuardedPath::tempdir().expect("tempdir");
1649        let workspace_root = workspace.as_guarded_path().clone();
1650        let mut args = vec!["--".to_string(), "--foo".to_string()].into_iter();
1651        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1652        assert!(matches!(opts.script, ScriptSource::Stdin));
1653        assert_eq!(opts.script_args, vec!["--foo"]);
1654
1655        let mut args = vec!["--".to_string(), "script.ox".to_string()].into_iter();
1656        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1657        match opts.script {
1658            ScriptSource::Path(path) => {
1659                assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1660            }
1661            ScriptSource::Stdin => panic!("expected path script"),
1662        }
1663        assert!(opts.script_args.is_empty());
1664
1665        let mut args = vec!["--".to_string(), "--".to_string(), "a".to_string()].into_iter();
1666        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1667        assert!(matches!(opts.script, ScriptSource::Stdin));
1668        assert_eq!(opts.script_args, vec!["a"]);
1669    }
1670
1671    #[cfg_attr(
1672        miri,
1673        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1674    )]
1675    #[test]
1676    fn options_parse_preserves_inner_separators_in_tail() {
1677        // Only one leading `--` is stripped. Inner separators stay data.
1678        let workspace = GuardedPath::tempdir().expect("tempdir");
1679        let workspace_root = workspace.as_guarded_path().clone();
1680        let mut args = vec![
1681            "--".to_string(),
1682            "--foo".to_string(),
1683            "--".to_string(),
1684            "--bar".to_string(),
1685        ]
1686        .into_iter();
1687        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1688        assert!(matches!(opts.script, ScriptSource::Stdin));
1689        assert_eq!(opts.script_args, vec!["--foo", "--", "--bar"]);
1690
1691        let mut args = vec![
1692            "my.ox".to_string(),
1693            "a".to_string(),
1694            "--".to_string(),
1695            "b".to_string(),
1696        ]
1697        .into_iter();
1698        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1699        assert_eq!(opts.script_args, vec!["a", "--", "b"]);
1700    }
1701
1702    #[cfg_attr(
1703        miri,
1704        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1705    )]
1706    #[test]
1707    fn options_parse_version_returns_version_without_exiting() {
1708        // Same contract as --help: version surfaces as the parse error
1709        // (parse must not exit the process itself: it is public library
1710        // API). Print it and succeed so the binary exits 0.
1711        let workspace = GuardedPath::tempdir().expect("tempdir");
1712        for flag in ["--version", "-V", "-v"] {
1713            let mut args = vec![flag.to_string()].into_iter();
1714            let err = Options::parse(&mut args, workspace.as_guarded_path())
1715                .expect_err("version flag must not parse as options");
1716            assert_eq!(err.key(), "cli.version_requested");
1717            assert_eq!(err.to_string(), version());
1718        }
1719    }
1720
1721    #[cfg_attr(
1722        miri,
1723        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1724    )]
1725    #[test]
1726    fn options_parse_help_returns_usage_error_without_exiting() {
1727        // Regression: parse is public library API and must return instead of
1728        // terminating the process; `run()` turns this error into a clean exit 0.
1729        let workspace = GuardedPath::tempdir().expect("tempdir");
1730        for flag in ["--help", "-h"] {
1731            let mut args = vec![flag.to_string()].into_iter();
1732            let err = Options::parse(&mut args, workspace.as_guarded_path())
1733                .expect_err("help flag must not parse as options");
1734            assert_eq!(err.key(), "cli.help_requested");
1735            assert_eq!(err.to_string(), usage());
1736        }
1737    }
1738
1739    #[cfg_attr(
1740        miri,
1741        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1742    )]
1743    #[test]
1744    fn options_parse_rejects_remote_script_with_input_intact() {
1745        let workspace = GuardedPath::tempdir().expect("tempdir");
1746        for args in [
1747            vec!["https://example.com/process.oxfile".to_string()],
1748            vec![
1749                "--script".to_string(),
1750                "https://example.com/process.oxfile".to_string(),
1751            ],
1752        ] {
1753            let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1754                .expect_err("remote script must not parse as a path");
1755            let rendered = format!("{err:#}");
1756            assert!(
1757                rendered.contains("not a local path")
1758                    && rendered.contains("https://example.com/process.oxfile"),
1759                "rejection names the intact input: {rendered}"
1760            );
1761            assert!(
1762                !rendered.contains("https:/example.com"),
1763                "scheme must never come out mangled: {rendered}"
1764            );
1765        }
1766    }
1767
1768    #[test]
1769    fn execute_with_result_runs_script() {
1770        let workspace = GuardedPath::tempdir().expect("tempdir");
1771        let workspace_root = workspace.as_guarded_path().clone();
1772        let script_path = workspace_root.join("script.txt").expect("script path");
1773        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1774            .expect("resolver");
1775        resolver
1776            .write_file(&script_path, b"WRITE out.txt hi")
1777            .expect("write script");
1778        let opts = Options {
1779            script: ScriptSource::Path(script_path),
1780            shell: false,
1781            dry_run: false,
1782            endpoints: EndpointFlags::default(),
1783            remote_serve: false,
1784            mcp: false,
1785            remotes: Vec::new(),
1786            script_args: Vec::new(),
1787        };
1788        let result = execute_with_result(opts, workspace_root).expect("execute");
1789        let snapshot = result
1790            .snapshot_path()
1791            .expect("default WRITE materializes the snapshot");
1792        assert_eq!(snapshot, &result.final_cwd);
1793        let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1794        let out = snapshot.join("out.txt").expect("out path");
1795        let contents = temp_resolver.read_to_string(&out).expect("read out");
1796        assert_eq!(contents.trim(), "hi");
1797    }
1798
1799    #[cfg_attr(
1800        miri,
1801        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1802    )]
1803    #[test]
1804    fn execute_with_result_routes_script_args_to_argv() {
1805        // #226: verbatim tail lands in `STD::ARGV()`, never merged
1806        // with interpreter opts.
1807        let workspace = GuardedPath::tempdir().expect("tempdir");
1808        let workspace_root = workspace.as_guarded_path().clone();
1809        let script_path = workspace_root.join("script.txt").expect("script path");
1810        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1811            .expect("resolver");
1812        let script = indoc! {r#"
1813            IMPORT [STD]
1814            LET $args: LIST<STRING> = ARGV()
1815            LET $n: INT = LEN($args)
1816            ASSERT_EQ $n 2
1817            ASSERT_EQ $args.0 "--dry-run"
1818            ASSERT_EQ $args.1 "serve"
1819            WRITE out.txt "ok"
1820        "#};
1821        resolver
1822            .write_file(&script_path, script.as_bytes())
1823            .expect("write script");
1824        // Parse through the real CLI boundary so the routing (strip
1825        // one `--`, keep `--dry-run` as data) is covered too.
1826        let mut args = vec![
1827            "script.txt".to_string(),
1828            "--".to_string(),
1829            "--dry-run".to_string(),
1830            "serve".to_string(),
1831        ]
1832        .into_iter();
1833        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1834        assert_eq!(opts.script_args, vec!["--dry-run", "serve"]);
1835        let result = execute_with_result(opts, workspace_root).expect("execute");
1836        let snapshot = result
1837            .snapshot_path()
1838            .expect("WRITE materializes the snapshot");
1839        let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1840        let out = snapshot.join("out.txt").expect("out path");
1841        assert_eq!(
1842            temp_resolver.read_to_string(&out).expect("read").trim(),
1843            "ok"
1844        );
1845    }
1846
1847    #[cfg_attr(
1848        miri,
1849        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1850    )]
1851    #[test]
1852    fn execute_with_result_local_only_creates_no_snapshot() {
1853        let workspace = GuardedPath::tempdir().expect("tempdir");
1854        let workspace_root = workspace.as_guarded_path().clone();
1855        let script_path = workspace_root.join("script.txt").expect("script path");
1856        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1857            .expect("resolver");
1858        resolver
1859            .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1860            .expect("write script");
1861        let opts = Options {
1862            script: ScriptSource::Path(script_path),
1863            shell: false,
1864            dry_run: false,
1865            endpoints: EndpointFlags::default(),
1866            remote_serve: false,
1867            mcp: false,
1868            remotes: Vec::new(),
1869            script_args: Vec::new(),
1870        };
1871        let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1872        assert!(
1873            !result.has_snapshot(),
1874            "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1875        );
1876        assert!(result.snapshot_path().is_none());
1877        // The write landed in the live workspace tree instead.
1878        let out = workspace_root.join("out.txt").expect("out path");
1879        let contents = resolver.read_to_string(&out).expect("read out");
1880        assert_eq!(contents.trim(), "hi");
1881        // The reported cwd stays under the workspace root.
1882        assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1883    }
1884
1885    #[cfg_attr(
1886        miri,
1887        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1888    )]
1889    #[test]
1890    fn execute_with_result_empty_script_creates_no_snapshot() {
1891        let workspace = GuardedPath::tempdir().expect("tempdir");
1892        let workspace_root = workspace.as_guarded_path().clone();
1893        let script_path = workspace_root.join("empty.txt").expect("script path");
1894        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1895            .expect("resolver");
1896        resolver
1897            .write_file(&script_path, b"")
1898            .expect("write script");
1899        let opts = Options {
1900            script: ScriptSource::Path(script_path),
1901            shell: false,
1902            dry_run: false,
1903            endpoints: EndpointFlags::default(),
1904            remote_serve: false,
1905            mcp: false,
1906            remotes: Vec::new(),
1907            script_args: Vec::new(),
1908        };
1909        let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1910        assert!(
1911            !result.has_snapshot(),
1912            "empty script must not create a snapshot tempdir"
1913        );
1914        assert_eq!(result.final_cwd, workspace_root);
1915    }
1916
1917    #[cfg_attr(
1918        miri,
1919        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1920    )]
1921    #[test]
1922    fn execute_for_test_invokes_shell_runner() -> Result<()> {
1923        let workspace = GuardedPath::tempdir()?;
1924        let workspace_root = workspace.as_guarded_path().clone();
1925        let script_path = workspace_root.join("empty.txt")?;
1926        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1927        resolver.write_file(&script_path, b"")?;
1928        let opts = Options {
1929            script: ScriptSource::Path(script_path),
1930            shell: true,
1931            dry_run: false,
1932            endpoints: EndpointFlags::default(),
1933            remote_serve: false,
1934            mcp: false,
1935            remotes: Vec::new(),
1936            script_args: Vec::new(),
1937        };
1938        let called = RefCell::new(None::<(String, String)>);
1939        execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1940            called.replace(Some((cwd.display(), workspace.display())));
1941            // Shell entry converges onto a concrete, existing directory even
1942            // when the script never touched the snapshot (issue #131).
1943            assert!(
1944                cwd.exists(),
1945                "shell cwd must exist on disk, got {}",
1946                cwd.display()
1947            );
1948            Ok(())
1949        })?;
1950        let seen = called.borrow().clone().expect("shell runner called");
1951        assert_eq!(seen.1, workspace_root.display());
1952        Ok(())
1953    }
1954
1955    /// The `ssh` feature wires the SSH host module into the real CLI
1956    /// runner: serve an ephemeral server and close it through
1957    /// `execute_with_result`, no client needed.
1958    #[cfg(feature = "ssh")]
1959    #[cfg_attr(
1960        miri,
1961        ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1962    )]
1963    #[test]
1964    fn ssh_feature_serves_and_closes() -> Result<()> {
1965        let workspace = GuardedPath::tempdir()?;
1966        let workspace_root = workspace.as_guarded_path().clone();
1967        let script_path = workspace_root.join("ssh-serve.ox")?;
1968        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1969        let script = indoc! {"
1970            IMPORT [STD, SSH]
1971            LET $m: SSH_SERVE_INFO = SSH_SERVE(\"cli-ssh-svc\", {username: \"test\", password: \"test123\"})
1972            SSH_CLOSE($m.server)
1973        "};
1974        resolver.write_file(&script_path, script.as_bytes())?;
1975        let opts = Options {
1976            script: ScriptSource::Path(script_path),
1977            shell: false,
1978            dry_run: false,
1979            endpoints: EndpointFlags {
1980                publishes: vec![(
1981                    std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1982                    "cli-ssh-svc".to_string(),
1983                )],
1984                ..EndpointFlags::default()
1985            },
1986            remote_serve: false,
1987            mcp: false,
1988            remotes: Vec::new(),
1989            script_args: Vec::new(),
1990        };
1991        execute_with_result(opts, workspace_root)?;
1992        Ok(())
1993    }
1994
1995    /// The NET module ships with the `net` feature: bind an ephemeral
1996    /// loopback port and close it through `execute_with_result`, no
1997    /// client needed.
1998    #[cfg(feature = "net")]
1999    #[cfg_attr(
2000        miri,
2001        ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
2002    )]
2003    #[test]
2004    fn net_module_listens_and_closes() -> Result<()> {
2005        let workspace = GuardedPath::tempdir()?;
2006        let workspace_root = workspace.as_guarded_path().clone();
2007        let script_path = workspace_root.join("net-listen.ox")?;
2008        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2009        let script = indoc! {"
2010            IMPORT [STD, NET]
2011            LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
2012            NET_CLOSE($l.listener)
2013        "};
2014        resolver.write_file(&script_path, script.as_bytes())?;
2015        let opts = Options {
2016            script: ScriptSource::Path(script_path),
2017            shell: false,
2018            dry_run: false,
2019            // The port key is only a registry name here: the outer bind
2020            // is ephemeral, so no fixed host port is ever touched.
2021            endpoints: EndpointFlags {
2022                publishes: vec![(
2023                    std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
2024                    "23501".to_string(),
2025                )],
2026                ..EndpointFlags::default()
2027            },
2028            remote_serve: false,
2029            mcp: false,
2030            remotes: Vec::new(),
2031            script_args: Vec::new(),
2032        };
2033        execute_with_result(opts, workspace_root)?;
2034        Ok(())
2035    }
2036
2037    /// A `-p`-mapped outer port is observable in-script: route an
2038    /// ephemeral `-p 0:<name>` resolution through `NET_PORT`/`NET_ADDR`
2039    /// into files an inner `RUN` could equally consume via `ENV`.
2040    #[cfg(feature = "net")]
2041    #[cfg_attr(
2042        miri,
2043        ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
2044    )]
2045    #[test]
2046    fn net_port_addr_observe_publish_mapping() -> Result<()> {
2047        let workspace = GuardedPath::tempdir()?;
2048        let workspace_root = workspace.as_guarded_path().clone();
2049        let script_path = workspace_root.join("net-port.ox")?;
2050        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2051        let script = indoc! {"
2052            IMPORT [STD, NET]
2053            LET $port: INT = NET_PORT(\"routed-svc\")
2054            WRITE port.txt \"{{ $port }}\"
2055            LET $addr: STRING = NET_ADDR(\"routed-svc\")
2056            WRITE addr.txt \"{{ $addr }}\"
2057        "};
2058        resolver.write_file(&script_path, script.as_bytes())?;
2059        let opts = Options {
2060            script: ScriptSource::Path(script_path),
2061            shell: false,
2062            dry_run: false,
2063            endpoints: EndpointFlags {
2064                publishes: vec![(
2065                    std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
2066                    "routed-svc".to_string(),
2067                )],
2068                ..EndpointFlags::default()
2069            },
2070            remote_serve: false,
2071            mcp: false,
2072            remotes: Vec::new(),
2073            script_args: Vec::new(),
2074        };
2075        let result = execute_with_result(opts, workspace_root)?;
2076        let snapshot = result
2077            .snapshot_path()
2078            .expect("WRITE materializes the snapshot");
2079        let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
2080        let port_path = snapshot.join("port.txt")?;
2081        let port_text = snapshot_resolver.read_to_string(&port_path)?;
2082        let port: u16 = port_text
2083            .trim()
2084            .parse()
2085            .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
2086        assert_ne!(port, 0, "ephemeral outer port must resolve");
2087        let addr_path = snapshot.join("addr.txt")?;
2088        let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
2089        assert!(
2090            addr_text.trim().ends_with(&format!(":{port}")),
2091            "dial string must carry the resolved port, got {addr_text:?}"
2092        );
2093        Ok(())
2094    }
2095
2096    /// Without the `ssh` feature the same script must fail to parse:
2097    /// SSH names stay unknown instead of silently changing meaning.
2098    #[cfg(not(feature = "ssh"))]
2099    #[cfg_attr(
2100        miri,
2101        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2102    )]
2103    #[test]
2104    fn ssh_scripts_rejected_without_feature() -> Result<()> {
2105        let workspace = GuardedPath::tempdir()?;
2106        let workspace_root = workspace.as_guarded_path().clone();
2107        let script_path = workspace_root.join("ssh-serve.ox")?;
2108        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2109        let script = indoc! {"
2110            IMPORT [STD, SSH]
2111            LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
2112            SSH_CLOSE($m.server)
2113        "};
2114        resolver.write_file(&script_path, script.as_bytes())?;
2115        let opts = Options {
2116            script: ScriptSource::Path(script_path),
2117            shell: false,
2118            dry_run: false,
2119            endpoints: EndpointFlags::default(),
2120            remote_serve: false,
2121            mcp: false,
2122            remotes: Vec::new(),
2123            script_args: Vec::new(),
2124        };
2125        let err = match execute_with_result(opts, workspace_root) {
2126            Ok(_) => panic!("SSH names must be unknown without the feature"),
2127            Err(err) => err,
2128        };
2129        assert!(err.to_string().contains("SSH"), "{err}");
2130        assert_eq!(err.key(), "cli.module_unlinked", "{err}");
2131        Ok(())
2132    }
2133
2134    /// Without the `net` feature `--listen`/`-p` are rejected with the
2135    /// feature message, while `--offline` stays accepted as trivially
2136    /// satisfied.
2137    #[cfg(not(feature = "net"))]
2138    #[cfg_attr(
2139        miri,
2140        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2141    )]
2142    #[test]
2143    fn net_flags_rejected_without_feature() {
2144        let workspace = GuardedPath::tempdir().expect("tempdir");
2145        for args in [
2146            vec!["--listen", "0.0.0.0:2251", "-"],
2147            vec!["-p", "2222:2251", "-"],
2148            vec!["--listen=0.0.0.0:2251", "-"],
2149        ] {
2150            let mut args = args.into_iter().map(str::to_string);
2151            let err = Options::parse(&mut args, workspace.as_guarded_path())
2152                .expect_err("endpoint flag must fail without net");
2153            assert!(err.to_string().contains("`net` feature"), "{err:?}");
2154            // Typed path: stable key survives rewording.
2155            assert_eq!(err.key(), "cli.feature_required");
2156        }
2157        let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
2158        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
2159        assert!(opts.endpoints.offline);
2160    }
2161
2162    /// Without the `net` feature the same script must fail to parse:
2163    /// NET names stay unknown instead of silently changing meaning.
2164    #[cfg(not(feature = "net"))]
2165    #[cfg_attr(
2166        miri,
2167        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2168    )]
2169    #[test]
2170    fn net_scripts_rejected_without_feature() -> Result<()> {
2171        let workspace = GuardedPath::tempdir()?;
2172        let workspace_root = workspace.as_guarded_path().clone();
2173        let script_path = workspace_root.join("net-listen.ox")?;
2174        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2175        let script = indoc! {"
2176            IMPORT [STD, NET]
2177            LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
2178            LET $body: STRING = NET_FETCH(\"https://example.com/x\")
2179            NET_CLOSE($l.listener)
2180        "};
2181        resolver.write_file(&script_path, script.as_bytes())?;
2182        let opts = Options {
2183            script: ScriptSource::Path(script_path),
2184            shell: false,
2185            dry_run: false,
2186            endpoints: EndpointFlags::default(),
2187            remote_serve: false,
2188            mcp: false,
2189            remotes: Vec::new(),
2190            script_args: Vec::new(),
2191        };
2192        let err = match execute_with_result(opts, workspace_root) {
2193            Ok(_) => panic!("NET names must be unknown without the feature"),
2194            Err(err) => err,
2195        };
2196        assert!(err.to_string().contains("NET"), "{err}");
2197        // Known-but-unlinked: the failure names the module and the key.
2198        assert_eq!(err.key(), "cli.module_unlinked", "{err}");
2199        Ok(())
2200    }
2201
2202    /// Token matching never fires on comments or strings: `// IMPORT
2203    /// [NET]` and `ECHO "IMPORT [NET]"` name no module, and neither do
2204    /// other brackets (`WITH_IO` bindings) or quoted file paths.
2205    #[test]
2206    fn imports_module_ignores_comments_strings_and_other_brackets() {
2207        use oxdock_parser::lex_str;
2208        let toks = lex_str("IMPORT [STD, NET]\n").expect("lex");
2209        assert!(super::imports_module(&toks, "NET"));
2210        assert!(!super::imports_module(&toks, "SSH"));
2211        let toks = lex_str("IF true {\nIMPORT [SSH]\n}\n").expect("lex");
2212        assert!(super::imports_module(&toks, "SSH"));
2213        let toks = lex_str("IMPORT [\"./a.oxdock\" AS LIB]\n").expect("lex");
2214        assert!(!super::imports_module(&toks, "NET"));
2215        // A module name inside the quoted path never counts either.
2216        let toks = lex_str("IMPORT [\"./NET.oxdock\" AS LIB]\n").expect("lex");
2217        assert!(!super::imports_module(&toks, "NET"));
2218        let toks = lex_str("// IMPORT [NET]\nECHO hi\n").expect("lex");
2219        assert!(!super::imports_module(&toks, "NET"));
2220        let toks = lex_str("ECHO \"IMPORT [NET]\"\n").expect("lex");
2221        assert!(!super::imports_module(&toks, "NET"));
2222        let toks = lex_str("WITH_IO [stdout=$p] ECHO hi\n").expect("lex");
2223        assert!(!super::imports_module(&toks, "NET"));
2224    }
2225
2226    /// Lean builds map a genuine `IMPORT [NET]` failure to the typed
2227    /// unlinked-module error, but comment/string lookalikes keep `None`
2228    /// so the real parse error rides through.
2229    #[cfg(not(feature = "net"))]
2230    #[test]
2231    fn unlinked_module_error_needs_a_real_import() {
2232        let err =
2233            super::unlinked_module_error("IMPORT [STD, NET]\n").expect("real import must map");
2234        assert_eq!(err.key(), "cli.module_unlinked");
2235        assert!(super::unlinked_module_error("// IMPORT [NET]\nECHO hi\n").is_none());
2236        assert!(super::unlinked_module_error("ECHO \"IMPORT [NET]\"\n").is_none());
2237        assert!(super::unlinked_module_error("ECHO hi\n").is_none());
2238    }
2239
2240    #[test]
2241    fn process_exit_code_relays_exit_requests() {
2242        use std::sync::Arc as StdArc;
2243        let exit = oxdock_diagnostics::Diagnostic::new(
2244            "t.exit",
2245            "exit 3".to_string(),
2246            oxdock_diagnostics::Diagnostic::make_fields(&[]),
2247        )
2248        .with_source(StdArc::new(ExitRequest::new(3)));
2249        assert_eq!(process_exit_code(&exit), 3);
2250        let relayed = oxdock_diagnostics::Diagnostic::new(
2251            "t.exit",
2252            "exit 3".to_string(),
2253            oxdock_diagnostics::Diagnostic::make_fields(&[]),
2254        )
2255        .with_source(StdArc::new(ExitRequest::new(3)))
2256        .with_contexts(vec!["REMOTE 'prod' exited with code 3".to_string()]);
2257        assert_eq!(process_exit_code(&relayed), 3);
2258        let keyed = oxdock_core::exec::diagnostics::eval_exit_requested(3);
2259        assert_eq!(process_exit_code(&keyed), 3);
2260        let keyed_wrapped = oxdock_core::exec::diagnostics::eval_exit_requested(3)
2261            .with_contexts(vec!["step 1".to_string()]);
2262        assert_eq!(process_exit_code(&keyed_wrapped), 3);
2263        assert_eq!(process_exit_code(&errors::shell_needs_tty()), 1);
2264        assert_eq!(
2265            process_exit_code(
2266                &oxdock_diagnostics::Diagnostic::new(
2267                    "t.exit",
2268                    "exit 300".to_string(),
2269                    oxdock_diagnostics::Diagnostic::make_fields(&[]),
2270                )
2271                .with_source(StdArc::new(ExitRequest::new(300)))
2272            ),
2273            255,
2274            "codes clamp to the portable range"
2275        );
2276        assert_eq!(
2277            process_exit_code(
2278                &oxdock_diagnostics::Diagnostic::new(
2279                    "t.exit",
2280                    "exit -1".to_string(),
2281                    oxdock_diagnostics::Diagnostic::make_fields(&[]),
2282                )
2283                .with_source(StdArc::new(ExitRequest::new(-1)))
2284            ),
2285            0,
2286            "negative codes clamp to zero"
2287        );
2288    }
2289}
2290
2291#[cfg(all(test, windows))]
2292mod windows_shell_tests {
2293    use super::*;
2294
2295    #[test]
2296    fn command_path_strips_verbatim_prefix() -> DiagnosticResult<()> {
2297        let temp = GuardedPath::tempdir()?;
2298        let converted = oxdock_fs::command_path(temp.as_guarded_path());
2299        let as_str = converted.as_ref().display().to_string();
2300        assert!(
2301            !as_str.starts_with(r"\\?\"),
2302            "expected non-verbatim path, got {as_str}"
2303        );
2304        Ok(())
2305    }
2306}