Skip to main content

oxdock_cli/
errors.rs

1//! CLI user-facing errors behind single constructors with stable keys.
2//!
3//! This module owns every CLI template and key (`cli.*`). It builds on
4//! the generic [`oxdock_diagnostics::Diagnostic`] transport but owns its
5//! wording: changing CLI text happens here, never in the leaf crate.
6//! DSL diagnostics stay owned by the DSL crates.
7
8pub use oxdock_diagnostics::Diagnostic;
9use oxdock_macros::oxdock_embed;
10
11// CLI usage bodies, one file per Cargo feature variant: statically
12// compiled assets cannot branch on Cargo features, so the script
13// renders both variants (version line included, through inherited
14// Cargo metadata) and Rust `#[cfg]` picks the live one.
15oxdock_embed! {
16    name: UsageAssets,
17    script: {
18        INHERIT_ENV [CARGO_PKG_VERSION, CARGO_PKG_DESCRIPTION]
19        FUNC EMIT_BODY($is_net: BOOL): VOID {
20            LET $net_flags: STRING = """
21              --offline          open no sockets (endpoint flags require the `net` feature)
22            """
23
24            LET $tail: STRING = """
25            Endpoint flags (--listen/-p) require the `net` feature (rebuild with --features net).
26            """
27
28            IF $is_net {
29                $net_flags = """
30                  --listen <addr>    expose a logical service port ([host:]port, repeatable)
31                  -p <[host:]outer:inner>  map outer port to an inner service port or name (repeatable; outer 0 is ephemeral; bare outer binds loopback, prefix 0.0.0.0: for all interfaces)
32                  --offline          open no sockets (conflicts with --listen/-p)
33                  --remote TARGET=CMD    bind a REMOTE target to a stdio transport command (repeatable)
34                """
35                $tail = "Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces."
36            }
37
38            ECHO """
39            oxdock {{ env:CARGO_PKG_VERSION }} — {{ env:CARGO_PKG_DESCRIPTION }}
40
41            Usage: oxdock [OPTIONS] [--] [SCRIPT] [-- script-args...]
42              SCRIPT             script file path (same as `--script <file>`); `-` reads stdin
43              --script <file|->  script file (relative resolves under the OxDock workspace root), or `-` for stdin
44              --shell            run the script, then drop into an interactive shell (requires a TTY)
45              --dry-run          print the transitive import closure (file:line CMD) instead of running
46              --mcp              serve EXPORTed FUNCs as MCP tools over stdio (requires the `mcp` feature)
47            {{ $net_flags }}
48              --help, -h         print this help and exit
49              --version, -V, -v   print the version and exit
50
51            With no script given, reads the script from stdin (must be piped unless `--shell`).
52            Everything after SCRIPT is a verbatim script arg (read via `STD::ARGV()`); one leading `--` there is a separator and dropped, so `--dry-run` after the script stays data.
53            {{ $tail }}
54            """
55        }
56
57        LET $p: PIPE
58        WITH_IO [stdout=$p] {
59            EMIT_BODY(true)
60        }
61        WITH_IO [stdin=$p] WRITE dist/usage-net.txt
62        WITH_IO [stdout=$p] {
63            EMIT_BODY(false)
64        }
65        WITH_IO [stdin=$p] WRITE dist/usage-lean.txt
66    },
67    out_dir: "usage-prebuilt",
68}
69
70/// Human-readable CLI usage, printed for `--help`/`-h`. The full
71/// text, version line included, is rendered once at compile time by
72/// the `UsageAssets` script above. Feature selection stays in Rust
73/// `#[cfg]`: the DSL has no feature namespace, so each variant lives
74/// in its own asset file.
75pub fn usage() -> String {
76    #[cfg(feature = "net")]
77    let asset = "dist/usage-net.txt";
78    #[cfg(not(feature = "net"))]
79    let asset = "dist/usage-lean.txt";
80    let file = UsageAssets::get(asset).expect("usage must be embedded");
81    str::from_utf8(file.data.as_ref())
82        .expect("usage is UTF-8")
83        .to_string()
84}
85
86/// A flag needing a Cargo feature this build lacks. Takes the flag and
87/// the feature that would provide it; both ride as structured fields.
88pub fn feature_required(flag: &str, feature: &str) -> anyhow::Error {
89    let message =
90        format!("{flag} requires the `{feature}` feature (rebuild with --features {feature})");
91    let diag = Diagnostic::new(
92        "cli.feature_required",
93        message,
94        Diagnostic::make_fields(&[("flag", flag), ("feature", feature)]),
95    );
96    anyhow::Error::new(diag)
97}
98
99/// `--offline` combined with socket flags.
100pub fn offline_conflict() -> anyhow::Error {
101    let diag = Diagnostic::new(
102        "cli.offline_conflict",
103        "--offline conflicts with --listen/-p (offline runs open no sockets)".to_string(),
104        Diagnostic::make_fields(&[]),
105    );
106    anyhow::Error::new(diag)
107}
108
109/// Same virtual endpoint mapped twice.
110pub fn endpoint_duplicate_inner(endpoint: &str) -> anyhow::Error {
111    let message = format!("virtual endpoint '{endpoint}' is mapped twice");
112    let diag = Diagnostic::new(
113        "cli.endpoint_duplicate_inner",
114        message,
115        Diagnostic::make_fields(&[("endpoint", endpoint)]),
116    );
117    anyhow::Error::new(diag)
118}
119
120/// Same outer socket address mapped twice.
121pub fn endpoint_duplicate_outer(addr: &str) -> anyhow::Error {
122    let message = format!("outer socket address {addr} is mapped twice");
123    let diag = Diagnostic::new(
124        "cli.endpoint_duplicate_outer",
125        message,
126        Diagnostic::make_fields(&[("address", addr)]),
127    );
128    anyhow::Error::new(diag)
129}
130
131/// `--listen` without a value: an address is required.
132pub fn listen_requires_address() -> anyhow::Error {
133    let diag = Diagnostic::new(
134        "cli.listen_requires_address",
135        "--listen requires an address ([host:]port)".to_string(),
136        Diagnostic::make_fields(&[("flag", "--listen")]),
137    );
138    anyhow::Error::new(diag)
139}
140
141/// `--listen` with a non-numeric bare port.
142pub fn listen_port_numeric(raw: &str) -> anyhow::Error {
143    let message = format!("--listen port must be numeric 1-65535, got {raw:?}");
144    let diag = Diagnostic::new(
145        "cli.listen_port_numeric",
146        message,
147        Diagnostic::make_fields(&[("flag", "--listen"), ("got", raw)]),
148    );
149    anyhow::Error::new(diag)
150}
151
152/// `--listen` port `0`: an exposed ephemeral port has no stable
153/// service key (that shape belongs to `-p 0:<endpoint>`).
154pub fn listen_port_zero() -> anyhow::Error {
155    let diag = Diagnostic::new(
156        "cli.listen_port_zero",
157        "--listen port 0 has no stable service key (use -p 0:<endpoint> for an ephemeral outer port)"
158            .to_string(),
159        Diagnostic::make_fields(&[("flag", "--listen")]),
160    );
161    anyhow::Error::new(diag)
162}
163
164/// `--listen` with an unparsable socket address.
165pub fn listen_address_invalid(raw: &str) -> anyhow::Error {
166    let message = format!("--listen address must be [host:]port (try 0.0.0.0:2251), got {raw:?}");
167    let diag = Diagnostic::new(
168        "cli.listen_address_invalid",
169        message,
170        Diagnostic::make_fields(&[("flag", "--listen"), ("got", raw)]),
171    );
172    anyhow::Error::new(diag)
173}
174
175/// `-p` without the `outer:inner` shape, or with an empty inner.
176pub fn publish_requires_shape(raw: &str) -> anyhow::Error {
177    let message = format!(
178        "-p requires [host:]outer:inner (try -p 2222:2251 or -p 127.0.0.1:1234:ssh-server), got {raw:?}"
179    );
180    let diag = Diagnostic::new(
181        "cli.publish_requires_shape",
182        message,
183        Diagnostic::make_fields(&[("flag", "-p"), ("got", raw)]),
184    );
185    anyhow::Error::new(diag)
186}
187
188/// `-p` with an unparsable outer address.
189pub fn publish_outer_invalid(raw: &str) -> anyhow::Error {
190    let message = format!(
191        "-p outer address invalid in {raw:?} (expected a port 0-65535 or a [host:]port address)"
192    );
193    let diag = Diagnostic::new(
194        "cli.publish_outer_invalid",
195        message,
196        Diagnostic::make_fields(&[("flag", "-p"), ("got", raw)]),
197    );
198    anyhow::Error::new(diag)
199}
200
201/// `-p` inner endpoint rejected by the endpoint grammar. Takes the
202/// underlying `Diagnostic` by value; `{reason:#}` (full chain)
203/// formatting lives here so call sites stay `format!`-free. The inner
204/// is a leaf parse-surface failure (sourceless inline), so rendering
205/// the bare `Diagnostic` matches the retired anyhow-chain bytes
206/// exactly. Net-only: lean builds store the raw inner text and reject
207/// later with the feature error.
208#[cfg(feature = "net")]
209pub fn publish_inner_invalid(raw: &str, reason: Diagnostic) -> anyhow::Error {
210    let reason_text = format!("{reason:#}");
211    let message = format!("-p inner endpoint invalid in {raw:?}: {reason_text}");
212    let diag = Diagnostic::new(
213        "cli.publish_inner_invalid",
214        message,
215        Diagnostic::make_fields(&[("flag", "-p"), ("got", raw), ("reason", &reason_text)]),
216    );
217    anyhow::Error::new(diag)
218}
219
220/// Script imports a module the CLI knows but this build did not link.
221/// Takes the module name and the Cargo feature that would link it.
222pub fn module_unlinked(module: &str, feature: &str) -> anyhow::Error {
223    let message =
224        format!("module `{module}` is known but not linked (rebuild with --features {feature})");
225    let diag = Diagnostic::new(
226        "cli.module_unlinked",
227        message,
228        Diagnostic::make_fields(&[("module", module), ("feature", feature)]),
229    );
230    anyhow::Error::new(diag)
231}
232
233/// Unknown `--long` / `-s` flag. Takes the bare name plus whether it
234/// was long (`--name`) or short (`-n`); the template owns the dashes.
235pub fn unexpected_flag(name: &str, long: bool) -> anyhow::Error {
236    let prefix = if long { "--" } else { "-" };
237    let message = format!("unexpected flag: {prefix}{name}");
238    let diag = Diagnostic::new(
239        "cli.unexpected_flag",
240        message,
241        Diagnostic::make_fields(&[("flag", name)]),
242    );
243    anyhow::Error::new(diag)
244}
245
246/// `--script` without a value.
247pub fn script_flag_needs_path() -> anyhow::Error {
248    let diag = Diagnostic::new(
249        "cli.script_flag_needs_path",
250        "--script requires a path".to_string(),
251        Diagnostic::make_fields(&[("flag", "--script")]),
252    );
253    anyhow::Error::new(diag)
254}
255
256/// SCRIPT positional that is a URL, not a workspace path.
257pub fn script_not_local(text: &str) -> anyhow::Error {
258    let message = format!("not a local path: {text:?} (pass a workspace path or `-` for stdin)");
259    let diag = Diagnostic::new(
260        "cli.script_not_local",
261        message,
262        Diagnostic::make_fields(&[("got", text)]),
263    );
264    anyhow::Error::new(diag)
265}
266
267/// OS argument that is not valid UTF-8.
268pub fn arg_not_utf8() -> anyhow::Error {
269    let diag = Diagnostic::new(
270        "cli.arg_not_utf8",
271        "argument must be UTF-8".to_string(),
272        Diagnostic::make_fields(&[]),
273    );
274    anyhow::Error::new(diag)
275}
276
277/// lexopt plumbing failure. Takes the underlying failure;
278/// `{reason:#}` formatting lives here so call sites stay
279/// `format!`-free.
280pub fn arg_lex_error(reason: &lexopt::Error) -> anyhow::Error {
281    let reason_text = format!("{reason:#}");
282    let diag = Diagnostic::new(
283        "cli.arg_lex_error",
284        reason_text.clone(),
285        Diagnostic::make_fields(&[("reason", &reason_text)]),
286    );
287    anyhow::Error::new(diag)
288}
289
290/// `--remote` without a value.
291pub fn remote_requires_value() -> anyhow::Error {
292    let diag = Diagnostic::new(
293        "cli.remote_requires_value",
294        "--remote requires <target>=\"<command>\"".to_string(),
295        Diagnostic::make_fields(&[("flag", "--remote")]),
296    );
297    anyhow::Error::new(diag)
298}
299
300/// `--remote` without the `<target>="<command>"` shape (lean pure
301/// validator, kept live so the flag stays diagnosed without `net`).
302#[cfg(not(feature = "net"))]
303pub fn remote_requires_shape(raw: &str) -> anyhow::Error {
304    let message = format!("invalid --remote {raw:?}: expected <target>=\"<command>\"");
305    let diag = Diagnostic::new(
306        "cli.remote_requires_shape",
307        message,
308        Diagnostic::make_fields(&[("flag", "--remote"), ("got", raw)]),
309    );
310    anyhow::Error::new(diag)
311}
312
313/// No piped script on stdin and no `--shell` to justify emptiness.
314pub fn script_stdin_missing() -> anyhow::Error {
315    let diag = Diagnostic::new(
316        "cli.script_stdin_missing",
317        "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
318            .to_string(),
319        Diagnostic::make_fields(&[]),
320    );
321    anyhow::Error::new(diag)
322}
323
324/// Workspace root discovery failed. Takes the underlying failure;
325/// the outer text matches the retired bare context byte for byte.
326pub fn guard_workspace_root(reason: &anyhow::Error) -> anyhow::Error {
327    let reason_text = format!("{reason:#}");
328    let message = format!("guard workspace root: {reason_text}");
329    let diag = Diagnostic::new(
330        "cli.guard_workspace_root",
331        message,
332        Diagnostic::make_fields(&[("reason", &reason_text)]),
333    );
334    anyhow::Error::new(diag)
335}
336
337/// Script path rejected by the workspace guard. Takes the path and
338/// the underlying failure; shared by both parse sites (one key).
339pub fn guard_script_path(path: &str, reason: &anyhow::Error) -> anyhow::Error {
340    let reason_text = format!("{reason:#}");
341    let message = format!("guard script path {path}: {reason_text}");
342    let diag = Diagnostic::new(
343        "cli.guard_script_path",
344        message,
345        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
346    );
347    anyhow::Error::new(diag)
348}
349
350/// Script file unreadable. Takes the display path and the underlying
351/// failure; the outer text matches the retired bare context byte
352/// for byte.
353pub fn read_script_at(path: &str, reason: &anyhow::Error) -> anyhow::Error {
354    let reason_text = format!("{reason:#}");
355    let message = format!("failed to read script at {path}: {reason_text}");
356    let diag = Diagnostic::new(
357        "cli.read_script_at",
358        message,
359        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
360    );
361    anyhow::Error::new(diag)
362}
363
364/// Piped script unreadable from stdin. Takes the underlying failure;
365/// shared by both read sites (one key).
366pub fn read_script_stdin(reason: &anyhow::Error) -> anyhow::Error {
367    let reason_text = format!("{reason:#}");
368    let message = format!("failed to read script from stdin: {reason_text}");
369    let diag = Diagnostic::new(
370        "cli.read_script_stdin",
371        message,
372        Diagnostic::make_fields(&[("reason", &reason_text)]),
373    );
374    anyhow::Error::new(diag)
375}
376
377/// Shell snapshot directory failed to materialize. Takes the
378/// underlying failure; shared by both snapshot arms (one key).
379pub fn create_shell_temp_dir(reason: &anyhow::Error) -> anyhow::Error {
380    let reason_text = format!("{reason:#}");
381    let message = format!("failed to create shell temp dir: {reason_text}");
382    let diag = Diagnostic::new(
383        "cli.create_shell_temp_dir",
384        message,
385        Diagnostic::make_fields(&[("reason", &reason_text)]),
386    );
387    anyhow::Error::new(diag)
388}
389
390/// `--shell` without a controlling terminal.
391pub fn shell_needs_tty() -> anyhow::Error {
392    let diag = Diagnostic::new(
393        "cli.shell_needs_tty",
394        "--shell requires a tty (no controlling tty available)".to_string(),
395        Diagnostic::make_fields(&[("flag", "--shell")]),
396    );
397    anyhow::Error::new(diag)
398}
399
400/// `--shell` through `execute_with_result`, which never supports it
401/// (embedder API misuse, not user input).
402pub fn shell_unsupported_in_result() -> anyhow::Error {
403    let diag = Diagnostic::new(
404        "cli.shell_unsupported_in_result",
405        "execute_with_result does not support --shell".to_string(),
406        Diagnostic::make_fields(&[]),
407    );
408    anyhow::Error::new(diag)
409}
410
411/// Windows shell re-exec staging hit a temp path without a parent
412/// (internal invariant, not user input).
413#[cfg(windows)]
414pub fn shell_temp_missing_parent() -> anyhow::Error {
415    let diag = Diagnostic::new(
416        "cli.shell_temp_missing_parent",
417        "temp path unexpectedly missing parent".to_string(),
418        Diagnostic::make_fields(&[]),
419    );
420    anyhow::Error::new(diag)
421}
422
423/// Windows shell re-exec could not locate the running executable.
424/// Takes the underlying failure.
425#[cfg(windows)]
426pub fn determine_current_exe(reason: &anyhow::Error) -> anyhow::Error {
427    let reason_text = format!("{reason:#}");
428    let message = format!("determine current executable: {reason_text}");
429    let diag = Diagnostic::new(
430        "cli.determine_current_exe",
431        message,
432        Diagnostic::make_fields(&[("reason", &reason_text)]),
433    );
434    anyhow::Error::new(diag)
435}
436
437/// Windows shell re-exec could not guard the system temp dir.
438/// Takes the underlying failure.
439#[cfg(windows)]
440pub fn guard_system_temp_dir(reason: &anyhow::Error) -> anyhow::Error {
441    let reason_text = format!("{reason:#}");
442    let message = format!("guard system temp dir: {reason_text}");
443    let diag = Diagnostic::new(
444        "cli.guard_system_temp_dir",
445        message,
446        Diagnostic::make_fields(&[("reason", &reason_text)]),
447    );
448    anyhow::Error::new(diag)
449}
450
451/// Windows shell re-exec could not build the temp shell path.
452/// Takes the underlying failure.
453#[cfg(windows)]
454pub fn construct_temp_shell_path(reason: &anyhow::Error) -> anyhow::Error {
455    let reason_text = format!("{reason:#}");
456    let message = format!("construct temp shell path: {reason_text}");
457    let diag = Diagnostic::new(
458        "cli.construct_temp_shell_path",
459        message,
460        Diagnostic::make_fields(&[("reason", &reason_text)]),
461    );
462    anyhow::Error::new(diag)
463}
464
465/// Windows shell re-exec could not copy the runner binary. Takes
466/// the destination display path and the underlying failure.
467#[cfg(windows)]
468pub fn copy_shell_runner(dest: &str, reason: &anyhow::Error) -> anyhow::Error {
469    let reason_text = format!("{reason:#}");
470    let message = format!("failed to copy shell runner to {dest}: {reason_text}");
471    let diag = Diagnostic::new(
472        "cli.copy_shell_runner",
473        message,
474        Diagnostic::make_fields(&[("dest", dest), ("reason", &reason_text)]),
475    );
476    anyhow::Error::new(diag)
477}
478
479/// Windows shell re-exec could not spawn the staged runner. Takes
480/// the destination display path and the spawn failure, which rides
481/// `anyhow` (not by value): the `spawn_failed` diagnostic carries
482/// its own chained source, and only the `{:#}` chain walk renders
483/// those bytes.
484#[cfg(windows)]
485pub fn spawn_shell_from(dest: &str, reason: &anyhow::Error) -> anyhow::Error {
486    let reason_text = format!("{reason:#}");
487    let message = format!("failed to spawn shell from {dest}: {reason_text}");
488    let diag = Diagnostic::new(
489        "cli.spawn_shell_from",
490        message,
491        Diagnostic::make_fields(&[("dest", dest), ("reason", &reason_text)]),
492    );
493    anyhow::Error::new(diag)
494}
495
496/// `--remote-serve` combined with script/shell/remote inputs.
497#[cfg(feature = "net")]
498pub fn remote_serve_runs_alone() -> anyhow::Error {
499    let diag = Diagnostic::new(
500        "cli.remote_serve_runs_alone",
501        "--remote-serve runs alone (no --script, --shell, --remote, or script args)".to_string(),
502        Diagnostic::make_fields(&[("flag", "--remote-serve")]),
503    );
504    anyhow::Error::new(diag)
505}
506
507/// `--remote-serve` without piped stdio.
508#[cfg(feature = "net")]
509pub fn remote_serve_needs_stdio() -> anyhow::Error {
510    let diag = Diagnostic::new(
511        "cli.remote_serve_needs_stdio",
512        "--remote-serve requires piped stdio (no TTY)".to_string(),
513        Diagnostic::make_fields(&[("flag", "--remote-serve")]),
514    );
515    anyhow::Error::new(diag)
516}
517
518/// Fetch tar arrived with no staging section (guest protocol
519/// invariant, not user input).
520#[cfg(feature = "net")]
521pub fn fetch_tar_no_stage() -> anyhow::Error {
522    let diag = Diagnostic::new(
523        "cli.serve_fetch_tar_no_stage",
524        "serve fetch tar arrived with no stage".to_string(),
525        Diagnostic::make_fields(&[]),
526    );
527    anyhow::Error::new(diag)
528}
529
530/// Fetch tar dir member escapes staging. Takes the member path and the
531/// underlying failure; `{reason:#}` formatting lives here so call
532/// sites stay `format!`-free.
533#[cfg(feature = "net")]
534pub fn fetch_dir_escapes(path: &str, reason: &anyhow::Error) -> anyhow::Error {
535    let reason_text = format!("{reason:#}");
536    let message = format!("fetch dir {path:?} escapes staging: {reason_text}");
537    let diag = Diagnostic::new(
538        "cli.serve_fetch_dir_escapes",
539        message,
540        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
541    );
542    anyhow::Error::new(diag)
543}
544
545/// Fetch tar file member escapes staging.
546#[cfg(feature = "net")]
547pub fn fetch_file_escapes(path: &str, reason: &anyhow::Error) -> anyhow::Error {
548    let reason_text = format!("{reason:#}");
549    let message = format!("fetch file {path:?} escapes staging: {reason_text}");
550    let diag = Diagnostic::new(
551        "cli.serve_fetch_file_escapes",
552        message,
553        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
554    );
555    anyhow::Error::new(diag)
556}
557
558/// Fetch tar parent directory escapes staging.
559#[cfg(feature = "net")]
560pub fn fetch_parent_escapes(path: &str, reason: &anyhow::Error) -> anyhow::Error {
561    let reason_text = format!("{reason:#}");
562    let message = format!("fetch parent {path:?} escapes staging: {reason_text}");
563    let diag = Diagnostic::new(
564        "cli.serve_fetch_parent_escapes",
565        message,
566        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
567    );
568    anyhow::Error::new(diag)
569}
570
571/// Fetch tar symlink member refused (content arrives resolved
572/// host-side; symlinks are never served).
573#[cfg(feature = "net")]
574pub fn fetch_symlink_refused(path: &str, target: &str) -> anyhow::Error {
575    let message = format!("fetch symlink {path:?} -> {target:?} refused: fetch entries are files");
576    let diag = Diagnostic::new(
577        "cli.serve_fetch_symlink_refused",
578        message,
579        Diagnostic::make_fields(&[("path", path), ("target", target)]),
580    );
581    anyhow::Error::new(diag)
582}
583
584/// Serve engine worker thread panicked (internal invariant).
585#[cfg(feature = "net")]
586pub fn serve_engine_panicked() -> anyhow::Error {
587    let diag = Diagnostic::new(
588        "cli.serve_engine_panicked",
589        "serve engine thread panicked".to_string(),
590        Diagnostic::make_fields(&[]),
591    );
592    anyhow::Error::new(diag)
593}
594
595/// Transfer staging tempdir failed. Takes the wrapped failure;
596/// `{reason:#}` formatting lives here.
597#[cfg(feature = "net")]
598pub fn serve_transfer_tempdir_failed(reason: &anyhow::Error) -> anyhow::Error {
599    let reason_text = format!("{reason:#}");
600    let message = format!("serve transfer tempdir failed: {reason_text}");
601    let diag = Diagnostic::new(
602        "cli.serve_transfer_tempdir_failed",
603        message,
604        Diagnostic::make_fields(&[("reason", &reason_text)]),
605    );
606    anyhow::Error::new(diag)
607}
608
609/// Fetch descriptor decode failed. Takes the concrete serialization
610/// failure; rendering lives here.
611#[cfg(feature = "net")]
612pub fn serve_fetch_descriptor_decode_failed(reason: &serde_json::Error) -> anyhow::Error {
613    let reason_text = reason.to_string();
614    let message = format!("serve fetch descriptor decode failed: {reason_text}");
615    let diag = Diagnostic::new(
616        "cli.serve_fetch_descriptor_decode_failed",
617        message,
618        Diagnostic::make_fields(&[("reason", &reason_text)]),
619    );
620    anyhow::Error::new(diag)
621}
622
623/// Unpack staging tempdir failed. Takes the wrapped failure;
624/// `{reason:#}` formatting lives here.
625#[cfg(feature = "net")]
626pub fn serve_staging_tempdir_failed(reason: &anyhow::Error) -> anyhow::Error {
627    let reason_text = format!("{reason:#}");
628    let message = format!("serve staging tempdir failed: {reason_text}");
629    let diag = Diagnostic::new(
630        "cli.serve_staging_tempdir_failed",
631        message,
632        Diagnostic::make_fields(&[("reason", &reason_text)]),
633    );
634    anyhow::Error::new(diag)
635}
636
637/// Push staging tempdir failed. Takes the wrapped failure;
638/// `{reason:#}` formatting lives here.
639#[cfg(feature = "net")]
640pub fn serve_push_tempdir_failed(reason: &anyhow::Error) -> anyhow::Error {
641    let reason_text = format!("{reason:#}");
642    let message = format!("serve push tempdir failed: {reason_text}");
643    let diag = Diagnostic::new(
644        "cli.serve_push_tempdir_failed",
645        message,
646        Diagnostic::make_fields(&[("reason", &reason_text)]),
647    );
648    anyhow::Error::new(diag)
649}
650
651/// Guest push source escapes staging. Takes the underlying failure;
652/// `{reason:#}` formatting lives here.
653#[cfg(feature = "net")]
654pub fn push_source_escapes(guest_src: &str, reason: &anyhow::Error) -> anyhow::Error {
655    let reason_text = format!("{reason:#}");
656    let message = format!("guest push source {guest_src:?} escapes staging: {reason_text}");
657    let diag = Diagnostic::new(
658        "cli.serve_push_source_escapes",
659        message,
660        Diagnostic::make_fields(&[("source", guest_src), ("reason", &reason_text)]),
661    );
662    anyhow::Error::new(diag)
663}
664
665/// Guest push source unreadable. Takes the underlying failure;
666/// `{reason:#}` formatting lives here.
667#[cfg(feature = "net")]
668pub fn push_source_unreadable(path: &str, reason: &anyhow::Error) -> anyhow::Error {
669    let reason_text = format!("{reason:#}");
670    let message = format!("guest push source {path:?} unreadable: {reason_text}");
671    let diag = Diagnostic::new(
672        "cli.serve_push_source_unreadable",
673        message,
674        Diagnostic::make_fields(&[("source", path), ("reason", &reason_text)]),
675    );
676    anyhow::Error::new(diag)
677}
678
679/// Guest push source missing from staging.
680#[cfg(feature = "net")]
681pub fn push_source_missing(guest_src: &str, reason: &anyhow::Error) -> anyhow::Error {
682    let reason_text = format!("{reason:#}");
683    let message = format!("guest push source {guest_src:?} missing: {reason_text}");
684    let diag = Diagnostic::new(
685        "cli.serve_push_source_missing",
686        message,
687        Diagnostic::make_fields(&[("source", guest_src), ("reason", &reason_text)]),
688    );
689    anyhow::Error::new(diag)
690}
691
692/// `--mcp` without piped stdio.
693#[cfg(feature = "mcp")]
694pub fn mcp_needs_stdio() -> anyhow::Error {
695    let diag = Diagnostic::new(
696        "cli.mcp_needs_stdio",
697        "--mcp requires piped stdio transport".to_string(),
698        Diagnostic::make_fields(&[("flag", "--mcp")]),
699    );
700    anyhow::Error::new(diag)
701}
702
703/// `--mcp` reading the script from stdin (stdin carries JSON-RPC).
704#[cfg(feature = "mcp")]
705pub fn mcp_needs_script_file() -> anyhow::Error {
706    let diag = Diagnostic::new(
707        "cli.mcp_needs_script_file",
708        "--mcp requires a script file (stdin carries the JSON-RPC stream)".to_string(),
709        Diagnostic::make_fields(&[("flag", "--mcp")]),
710    );
711    anyhow::Error::new(diag)
712}
713
714/// `--mcp` combined with other run inputs. Takes the conflicting
715/// inputs as structured items; joining lives here.
716#[cfg(feature = "mcp")]
717pub fn mcp_runs_alone(conflicts: &[&str]) -> anyhow::Error {
718    let joined = conflicts.join(", ");
719    let message = format!("--mcp runs alone (no {joined})");
720    let diag = Diagnostic::new(
721        "cli.mcp_runs_alone",
722        message,
723        Diagnostic::make_fields(&[("flag", "--mcp"), ("conflicts", &joined)]),
724    );
725    anyhow::Error::new(diag)
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731
732    #[cfg(feature = "net")]
733    fn serde_err() -> serde_json::Error {
734        serde_json::from_slice::<serde_json::Value>(b"{bad}").unwrap_err()
735    }
736
737    #[test]
738    fn feature_message_shared_across_sites() {
739        for (flag, feature) in [
740            ("--listen", "net"),
741            ("-p", "net"),
742            ("script module", "net"),
743            ("--remote-serve", "net"),
744            ("--mcp", "mcp"),
745        ] {
746            let err = feature_required(flag, feature);
747            let diag = err
748                .downcast_ref::<Diagnostic>()
749                .expect("CLI errors stay typed");
750            assert_eq!(diag.key(), "cli.feature_required");
751            assert!(diag.message().contains(flag), "{diag}");
752            assert!(diag.message().contains(feature), "{diag}");
753        }
754    }
755
756    #[test]
757    fn mcp_feature_gate_names_mcp_not_net() {
758        let err = feature_required("--mcp", "mcp");
759        let diag = err
760            .downcast_ref::<Diagnostic>()
761            .expect("CLI errors stay typed");
762        let text = diag.message();
763        assert!(text.contains("`mcp`"), "{diag}");
764        assert!(text.contains("--features mcp"), "{diag}");
765        assert!(!text.contains("net"), "{diag}");
766    }
767
768    #[test]
769    fn endpoint_duplicates_name_the_key() {
770        let inner = endpoint_duplicate_inner("2251");
771        let diag = inner.downcast_ref::<Diagnostic>().expect("typed CLI error");
772        assert_eq!(diag.key(), "cli.endpoint_duplicate_inner");
773
774        let outer = endpoint_duplicate_outer("127.0.0.1:2222");
775        let diag = outer.downcast_ref::<Diagnostic>().expect("typed CLI error");
776        assert_eq!(diag.key(), "cli.endpoint_duplicate_outer");
777    }
778
779    #[test]
780    fn untrusted_input_cannot_crash_cli_errors() {
781        let evil = "bad\u{1f}flag".to_string();
782        let err = feature_required(&evil, "net");
783        let diag = err.downcast_ref::<Diagnostic>().expect("typed");
784        assert!(!diag.message().contains('\u{1f}'));
785    }
786
787    #[test]
788    fn net_shape_errors_carry_stable_keys() {
789        let cases: &[(&str, anyhow::Error)] = &[
790            ("cli.listen_requires_address", listen_requires_address()),
791            ("cli.listen_port_numeric", listen_port_numeric("abc")),
792            ("cli.listen_port_zero", listen_port_zero()),
793            (
794                "cli.listen_address_invalid",
795                listen_address_invalid("0.0.0.0:99999"),
796            ),
797            ("cli.publish_requires_shape", publish_requires_shape("2251")),
798            (
799                "cli.publish_outer_invalid",
800                publish_outer_invalid("abc:2251"),
801            ),
802            // Net-only: lean builds store the raw inner and reject with
803            // the feature error instead.
804            #[cfg(feature = "net")]
805            (
806                "cli.publish_inner_invalid",
807                publish_inner_invalid(
808                    "2222:0",
809                    Diagnostic::new(
810                        "t.reason",
811                        "bad endpoint".to_string(),
812                        Diagnostic::make_fields(&[]),
813                    ),
814                ),
815            ),
816            ("cli.module_unlinked", module_unlinked("NET", "net")),
817            ("cli.unexpected_flag", unexpected_flag("frobnicate", true)),
818            ("cli.script_flag_needs_path", script_flag_needs_path()),
819            ("cli.script_not_local", script_not_local("https://x")),
820            ("cli.arg_not_utf8", arg_not_utf8()),
821            (
822                "cli.arg_lex_error",
823                arg_lex_error(&lexopt::Error::UnexpectedOption("--nope".to_string())),
824            ),
825            ("cli.remote_requires_value", remote_requires_value()),
826            #[cfg(not(feature = "net"))]
827            ("cli.remote_requires_shape", remote_requires_shape("prod")),
828            ("cli.script_stdin_missing", script_stdin_missing()),
829            ("cli.shell_needs_tty", shell_needs_tty()),
830            (
831                "cli.shell_unsupported_in_result",
832                shell_unsupported_in_result(),
833            ),
834            #[cfg(windows)]
835            ("cli.shell_temp_missing_parent", shell_temp_missing_parent()),
836            #[cfg(feature = "net")]
837            ("cli.remote_serve_runs_alone", remote_serve_runs_alone()),
838            #[cfg(feature = "net")]
839            ("cli.remote_serve_needs_stdio", remote_serve_needs_stdio()),
840            #[cfg(feature = "net")]
841            ("cli.serve_fetch_tar_no_stage", fetch_tar_no_stage()),
842            #[cfg(feature = "net")]
843            (
844                "cli.serve_fetch_dir_escapes",
845                fetch_dir_escapes("a", &anyhow::anyhow!("root")),
846            ),
847            #[cfg(feature = "net")]
848            (
849                "cli.serve_fetch_file_escapes",
850                fetch_file_escapes("a", &anyhow::anyhow!("root")),
851            ),
852            #[cfg(feature = "net")]
853            (
854                "cli.serve_fetch_parent_escapes",
855                fetch_parent_escapes("a", &anyhow::anyhow!("root")),
856            ),
857            #[cfg(feature = "net")]
858            (
859                "cli.serve_fetch_symlink_refused",
860                fetch_symlink_refused("a", "b"),
861            ),
862            #[cfg(feature = "net")]
863            ("cli.serve_engine_panicked", serve_engine_panicked()),
864            #[cfg(feature = "net")]
865            (
866                "cli.serve_transfer_tempdir_failed",
867                serve_transfer_tempdir_failed(&anyhow::anyhow!("boom")),
868            ),
869            #[cfg(feature = "net")]
870            (
871                "cli.serve_fetch_descriptor_decode_failed",
872                serve_fetch_descriptor_decode_failed(&serde_err()),
873            ),
874            #[cfg(feature = "net")]
875            (
876                "cli.serve_staging_tempdir_failed",
877                serve_staging_tempdir_failed(&anyhow::anyhow!("boom")),
878            ),
879            #[cfg(feature = "net")]
880            (
881                "cli.serve_push_tempdir_failed",
882                serve_push_tempdir_failed(&anyhow::anyhow!("boom")),
883            ),
884            #[cfg(feature = "net")]
885            (
886                "cli.serve_push_source_escapes",
887                push_source_escapes("a", &anyhow::anyhow!("root")),
888            ),
889            #[cfg(feature = "net")]
890            (
891                "cli.serve_push_source_unreadable",
892                push_source_unreadable("a", &anyhow::anyhow!("root")),
893            ),
894            #[cfg(feature = "net")]
895            (
896                "cli.serve_push_source_missing",
897                push_source_missing("a", &anyhow::anyhow!("root")),
898            ),
899            #[cfg(feature = "mcp")]
900            ("cli.mcp_needs_stdio", mcp_needs_stdio()),
901            #[cfg(feature = "mcp")]
902            ("cli.mcp_needs_script_file", mcp_needs_script_file()),
903            #[cfg(feature = "mcp")]
904            ("cli.mcp_runs_alone", mcp_runs_alone(&["--shell"])),
905            (
906                "cli.guard_workspace_root",
907                guard_workspace_root(&anyhow::anyhow!("boom")),
908            ),
909            (
910                "cli.guard_script_path",
911                guard_script_path("s.ox", &anyhow::anyhow!("boom")),
912            ),
913            (
914                "cli.read_script_at",
915                read_script_at("s.ox", &anyhow::anyhow!("boom")),
916            ),
917            (
918                "cli.read_script_stdin",
919                read_script_stdin(&anyhow::anyhow!("boom")),
920            ),
921            (
922                "cli.create_shell_temp_dir",
923                create_shell_temp_dir(&anyhow::anyhow!("boom")),
924            ),
925            #[cfg(windows)]
926            (
927                "cli.determine_current_exe",
928                determine_current_exe(&anyhow::anyhow!("boom")),
929            ),
930            #[cfg(windows)]
931            (
932                "cli.guard_system_temp_dir",
933                guard_system_temp_dir(&anyhow::anyhow!("boom")),
934            ),
935            #[cfg(windows)]
936            (
937                "cli.construct_temp_shell_path",
938                construct_temp_shell_path(&anyhow::anyhow!("boom")),
939            ),
940            #[cfg(windows)]
941            (
942                "cli.copy_shell_runner",
943                copy_shell_runner("d.exe", &anyhow::anyhow!("boom")),
944            ),
945            #[cfg(windows)]
946            (
947                "cli.spawn_shell_from",
948                spawn_shell_from("d.exe", &anyhow::anyhow!("boom")),
949            ),
950        ];
951        let mut seen = std::collections::HashSet::new();
952        for (key, err) in cases {
953            let diag = err
954                .downcast_ref::<Diagnostic>()
955                .expect("CLI errors stay typed");
956            assert_eq!(&diag.key(), key, "{diag}");
957            assert!(seen.insert(*key), "duplicate key {key}");
958        }
959    }
960
961    #[test]
962    fn flag_shape_messages_name_the_flag() {
963        assert_eq!(
964            unexpected_flag("frobnicate", true)
965                .downcast_ref::<Diagnostic>()
966                .expect("typed")
967                .message(),
968            "unexpected flag: --frobnicate"
969        );
970        assert_eq!(
971            unexpected_flag("z", false)
972                .downcast_ref::<Diagnostic>()
973                .expect("typed")
974                .message(),
975            "unexpected flag: -z"
976        );
977        assert_eq!(
978            script_flag_needs_path()
979                .downcast_ref::<Diagnostic>()
980                .expect("typed")
981                .message(),
982            "--script requires a path"
983        );
984        assert!(
985            script_not_local("https://x/y")
986                .to_string()
987                .contains("\"https://x/y\"")
988        );
989        assert!(
990            arg_lex_error(&lexopt::Error::UnexpectedOption("--nope".to_string()))
991                .to_string()
992                .contains("--nope")
993        );
994        assert_eq!(
995            remote_requires_value()
996                .downcast_ref::<Diagnostic>()
997                .expect("typed")
998                .message(),
999            "--remote requires <target>=\"<command>\""
1000        );
1001        #[cfg(feature = "mcp")]
1002        assert_eq!(
1003            mcp_runs_alone(&["--shell", "--remote"])
1004                .downcast_ref::<Diagnostic>()
1005                .expect("typed")
1006                .message(),
1007            "--mcp runs alone (no --shell, --remote)"
1008        );
1009    }
1010
1011    #[test]
1012    fn startup_context_messages_carry_outer_text() {
1013        let msg = |err: anyhow::Error| {
1014            err.downcast_ref::<Diagnostic>()
1015                .expect("typed")
1016                .message()
1017                .to_string()
1018        };
1019        assert_eq!(
1020            msg(guard_workspace_root(&anyhow::anyhow!("boom"))),
1021            "guard workspace root: boom"
1022        );
1023        assert_eq!(
1024            msg(guard_script_path("s.ox", &anyhow::anyhow!("boom"))),
1025            "guard script path s.ox: boom"
1026        );
1027        assert_eq!(
1028            msg(read_script_at("s.ox", &anyhow::anyhow!("denied"))),
1029            "failed to read script at s.ox: denied"
1030        );
1031        assert_eq!(
1032            msg(read_script_stdin(&anyhow::anyhow!("boom"))),
1033            "failed to read script from stdin: boom"
1034        );
1035        assert_eq!(
1036            msg(create_shell_temp_dir(&anyhow::anyhow!("boom"))),
1037            "failed to create shell temp dir: boom"
1038        );
1039    }
1040
1041    #[cfg(windows)]
1042    #[test]
1043    fn windows_reexec_messages_carry_outer_text() {
1044        let msg = |err: anyhow::Error| {
1045            err.downcast_ref::<Diagnostic>()
1046                .expect("typed")
1047                .message()
1048                .to_string()
1049        };
1050        assert_eq!(
1051            msg(determine_current_exe(&anyhow::anyhow!("boom"))),
1052            "determine current executable: boom"
1053        );
1054        assert_eq!(
1055            msg(guard_system_temp_dir(&anyhow::anyhow!("boom"))),
1056            "guard system temp dir: boom"
1057        );
1058        assert_eq!(
1059            msg(construct_temp_shell_path(&anyhow::anyhow!("boom"))),
1060            "construct temp shell path: boom"
1061        );
1062        assert_eq!(
1063            msg(copy_shell_runner("d.exe", &anyhow::anyhow!("boom"))),
1064            "failed to copy shell runner to d.exe: boom"
1065        );
1066        assert_eq!(
1067            msg(spawn_shell_from("d.exe", &anyhow::anyhow!("boom"))),
1068            "failed to spawn shell from d.exe: boom"
1069        );
1070    }
1071
1072    #[cfg(feature = "mcp")]
1073    #[test]
1074    fn mcp_gate_messages() {
1075        assert_eq!(
1076            mcp_needs_stdio()
1077                .downcast_ref::<Diagnostic>()
1078                .expect("typed")
1079                .message(),
1080            "--mcp requires piped stdio transport"
1081        );
1082        assert_eq!(
1083            mcp_needs_script_file()
1084                .downcast_ref::<Diagnostic>()
1085                .expect("typed")
1086                .message(),
1087            "--mcp requires a script file (stdin carries the JSON-RPC stream)"
1088        );
1089    }
1090
1091    #[cfg(feature = "net")]
1092    #[test]
1093    fn serve_staging_messages_name_the_member() {
1094        let err = fetch_dir_escapes("a", &anyhow::anyhow!("root"));
1095        assert!(err.to_string().contains("\"a\""), "{err}");
1096        assert!(err.to_string().contains("root"), "{err}");
1097        let err = fetch_symlink_refused("a", "b");
1098        assert_eq!(
1099            err.downcast_ref::<Diagnostic>().expect("typed").message(),
1100            "fetch symlink \"a\" -> \"b\" refused: fetch entries are files"
1101        );
1102        let err = push_source_unreadable("a", &anyhow::anyhow!("denied"));
1103        assert!(err.to_string().contains("denied"), "{err}");
1104        assert_eq!(
1105            serve_transfer_tempdir_failed(&anyhow::anyhow!("boom"))
1106                .downcast_ref::<Diagnostic>()
1107                .expect("typed")
1108                .message(),
1109            "serve transfer tempdir failed: boom"
1110        );
1111        assert_eq!(
1112            serve_fetch_descriptor_decode_failed(&serde_err())
1113                .downcast_ref::<Diagnostic>()
1114                .expect("typed")
1115                .message(),
1116            "serve fetch descriptor decode failed: key must be a string at line 1 column 2"
1117        );
1118        assert_eq!(
1119            serve_staging_tempdir_failed(&anyhow::anyhow!("boom"))
1120                .downcast_ref::<Diagnostic>()
1121                .expect("typed")
1122                .message(),
1123            "serve staging tempdir failed: boom"
1124        );
1125        assert_eq!(
1126            serve_push_tempdir_failed(&anyhow::anyhow!("boom"))
1127                .downcast_ref::<Diagnostic>()
1128                .expect("typed")
1129                .message(),
1130            "serve push tempdir failed: boom"
1131        );
1132    }
1133
1134    #[test]
1135    fn net_shape_messages_name_the_flag_and_value() {
1136        assert_eq!(
1137            listen_requires_address()
1138                .downcast_ref::<Diagnostic>()
1139                .expect("typed")
1140                .message(),
1141            "--listen requires an address ([host:]port)"
1142        );
1143        assert!(
1144            publish_requires_shape("2251")
1145                .to_string()
1146                .contains("\"2251\"")
1147        );
1148        #[cfg(feature = "net")]
1149        {
1150            let err = publish_inner_invalid(
1151                "2222:0",
1152                Diagnostic::new(
1153                    "t.reason",
1154                    "bad endpoint".to_string(),
1155                    Diagnostic::make_fields(&[]),
1156                ),
1157            );
1158            let text = err.to_string();
1159            assert!(text.contains("\"2222:0\""), "{text}");
1160            assert!(text.contains("bad endpoint"), "{text}");
1161        }
1162        assert_eq!(
1163            module_unlinked("NET", "net")
1164                .downcast_ref::<Diagnostic>()
1165                .expect("typed")
1166                .message(),
1167            "module `NET` is known but not linked (rebuild with --features net)"
1168        );
1169    }
1170}