Skip to main content

oxdock_process/
diagnostics.rs

1//! Template-expansion errors behind single constructors with stable keys.
2//!
3//! This module owns every expansion template and key (`proc.expand.*`).
4//! It builds on the generic [`oxdock_diagnostics::Diagnostic`] transport
5//! but owns its wording: changing expansion text happens here, never at
6//! the call sites. Call sites pass structured data only, never
7//! `format!` strings. Suggestion hints render inline in the message
8//! (never via `with_hint`, avoiding double-print in `Display`); the
9//! `did you mean` shape lives here, call sites pass only the scope.
10
11use oxdock_diagnostics::Diagnostic;
12use oxdock_fs::env as oxdock_env;
13use oxdock_parser::{
14    KEYWORD_INHERIT_ENV, KEYWORD_LET, KEYWORD_RUN, PERMIT_TYPE_NAME, PIPE_TYPE_NAME,
15    SEMAPHORE_TYPE_NAME, STRING_TYPE_NAME,
16};
17
18/// Structured field keys. Single spelling for the whole module:
19/// constructors reference these, never literals, so a key rename is
20/// one edit.
21const FIELD_KEY: &str = "key";
22const FIELD_NAME: &str = "name";
23const FIELD_MODULE: &str = "module";
24const FIELD_FUNC: &str = "func";
25const FIELD_ARG: &str = "arg";
26const FIELD_ENTRY: &str = "entry";
27const FIELD_ROOT: &str = "root";
28const FIELD_SEGMENT: &str = "segment";
29const FIELD_INDEX: &str = "index";
30const FIELD_LEN: &str = "len";
31const FIELD_LIMIT: &str = "limit";
32const FIELD_COMMAND: &str = "command";
33const FIELD_STATUS: &str = "status";
34const FIELD_ARGV: &str = "argv";
35const FIELD_PROGRAM: &str = "program";
36const FIELD_ERR: &str = "err";
37const FIELD_REASON: &str = "reason";
38const FIELD_STREAM: &str = "stream";
39
40/// Suggestion scope for an undefined `$var` miss: the name also lives
41/// in the step environment or the override table.
42pub enum ScriptSuggest {
43    /// `env:{name}` holds a value.
44    Env,
45    /// A step override named `{name}` exists.
46    StepOverride,
47}
48
49/// Suggestion scope for a missing step-override miss: the name also
50/// lives in the script variables or the environment.
51pub enum OverrideSuggest {
52    /// `${name}` holds a value.
53    ScriptVar,
54    /// `env:{name}` holds a value.
55    EnvVar,
56}
57
58/// Render one `did you mean` hint. Single owner for the shape; callers
59/// pass the already-derived spelling and scope label.
60fn did_you_mean(spelling: &str, scope: &str) -> String {
61    format!("; did you mean '{spelling}' ({scope})?")
62}
63
64/// Undefined `env:KEY`. Takes the key plus whether a same-named script
65/// variable exists; the hint shape lives here.
66pub fn undefined_env_var(key: &str, suggest_script_var: bool) -> Diagnostic {
67    let hint = if suggest_script_var {
68        did_you_mean(&format!("${key}"), "script variable")
69    } else {
70        String::new()
71    };
72    let message = format!("undefined environment variable: '{key}'{hint}");
73    Diagnostic::new(
74        "proc.expand.undefined_env_var",
75        message,
76        Diagnostic::make_fields(&[(FIELD_KEY, key)]),
77    )
78}
79
80/// Undefined `$var`. Takes the name plus an optional suggestion scope;
81/// hinted and bare share one key and one mode.
82pub fn undefined_script_var(rest: &str, suggest: Option<ScriptSuggest>) -> Diagnostic {
83    let hint = match suggest {
84        Some(ScriptSuggest::Env) => did_you_mean(&format!("env:{rest}"), "environment variable"),
85        Some(ScriptSuggest::StepOverride) => did_you_mean(rest, "step override"),
86        None => String::new(),
87    };
88    let message = format!("undefined script variable: '${rest}'{hint}");
89    Diagnostic::new(
90        "proc.expand.undefined_script_var",
91        message,
92        Diagnostic::make_fields(&[(FIELD_NAME, rest)]),
93    )
94}
95
96/// Missing step-override argument. Takes the name plus an optional
97/// suggestion scope; hinted and bare share one key and one mode.
98pub fn missing_step_override(name: &str, suggest: Option<OverrideSuggest>) -> Diagnostic {
99    let hint = match suggest {
100        Some(OverrideSuggest::ScriptVar) => did_you_mean(&format!("${name}"), "script variable"),
101        Some(OverrideSuggest::EnvVar) => {
102            did_you_mean(&format!("env:{name}"), "environment variable")
103        }
104        None => String::new(),
105    };
106    let message = format!("missing required step override argument: '{name}'{hint}");
107    Diagnostic::new(
108        "proc.expand.missing_step_override",
109        message,
110        Diagnostic::make_fields(&[(FIELD_NAME, name)]),
111    )
112}
113
114/// Placeholder in no resolvable shape. Takes the raw key; quoting
115/// lives here.
116pub fn invalid_placeholder_format(key: &str) -> Diagnostic {
117    let message = format!(
118        "invalid placeholder format '{key}': script variables must start with '$' and environment variables with 'env:'"
119    );
120    Diagnostic::new(
121        "proc.expand.invalid_placeholder_format",
122        message,
123        Diagnostic::make_fields(&[(FIELD_KEY, key)]),
124    )
125}
126
127/// Placeholder call with no registered resolver. Takes the module and
128/// function names; quoting lives here.
129pub fn call_without_registry(module: &str, name: &str) -> Diagnostic {
130    let message = format!(
131        "placeholder call '{module}::{name}' has no function registry; register one with with_call_resolver"
132    );
133    Diagnostic::new(
134        "proc.expand.call_without_registry",
135        message,
136        Diagnostic::make_fields(&[(FIELD_MODULE, module), (FIELD_FUNC, name)]),
137    )
138}
139
140/// Placeholder call argument nesting past the literal depth cap. Takes
141/// the cap; rendering lives here.
142pub fn call_arg_too_deep(limit: usize) -> Diagnostic {
143    let message = format!("placeholder call argument nests too deep (limit {limit})");
144    Diagnostic::new(
145        "proc.expand.call_arg_too_deep",
146        message,
147        Diagnostic::make_fields(&[(FIELD_LIMIT, &limit.to_string())]),
148    )
149}
150
151/// Empty `$` variable reference in a call argument. Parameterless: the
152/// wording is fixed.
153pub fn call_arg_empty_var() -> Diagnostic {
154    Diagnostic::new(
155        "proc.expand.call_arg_empty_var",
156        "invalid placeholder call argument: empty variable reference".to_string(),
157        Diagnostic::make_fields(&[]),
158    )
159}
160
161/// Unresolvable placeholder call argument. Takes the raw source;
162/// quoting lives here.
163pub fn call_arg_invalid(src: &str) -> Diagnostic {
164    let message = format!(
165        "invalid placeholder call argument '{src}': use $var.path, a string, int, float, or bool literal, or a {{key: value}} or [item] literal"
166    );
167    Diagnostic::new(
168        "proc.expand.call_arg_invalid",
169        message,
170        Diagnostic::make_fields(&[(FIELD_ARG, src)]),
171    )
172}
173
174/// Nested calls inside placeholder arguments. Parameterless: the
175/// wording is fixed.
176pub fn call_arg_nested_calls() -> Diagnostic {
177    Diagnostic::new(
178        "proc.expand.call_arg_nested_calls",
179        "nested calls are not supported in placeholder arguments".to_string(),
180        Diagnostic::make_fields(&[]),
181    )
182}
183
184/// Map literal entry without exactly one top-level `:`. Takes the raw
185/// entry; quoting lives here.
186pub fn map_entry_invalid(entry: &str) -> Diagnostic {
187    let message = format!("invalid map literal entry '{entry}': use key: value");
188    Diagnostic::new(
189        "proc.expand.map_entry_invalid",
190        message,
191        Diagnostic::make_fields(&[(FIELD_ENTRY, entry)]),
192    )
193}
194
195/// Duplicate key in a map literal. Takes the key; quoting lives here.
196pub fn map_duplicate_key(key: &str) -> Diagnostic {
197    let message = format!("duplicate key '{key}' in map literal");
198    Diagnostic::new(
199        "proc.expand.map_duplicate_key",
200        message,
201        Diagnostic::make_fields(&[(FIELD_KEY, key)]),
202    )
203}
204
205/// Missing property on a map during key-path traversal. Takes the root
206/// variable and the segment; quoting lives here.
207pub fn key_path_missing_property(root: &str, segment: &str) -> Diagnostic {
208    let message = format!("property '{segment}' not found on object '${root}'");
209    Diagnostic::new(
210        "proc.expand.key_path_missing_property",
211        message,
212        Diagnostic::make_fields(&[(FIELD_ROOT, root), (FIELD_SEGMENT, segment)]),
213    )
214}
215
216/// Non-numeric list index during key-path traversal. Takes the root
217/// variable and the segment; quoting lives here.
218pub fn key_path_bad_index(root: &str, segment: &str) -> Diagnostic {
219    let message = format!("invalid array index '{segment}' on list '${root}'");
220    Diagnostic::new(
221        "proc.expand.key_path_bad_index",
222        message,
223        Diagnostic::make_fields(&[(FIELD_ROOT, root), (FIELD_SEGMENT, segment)]),
224    )
225}
226
227/// Out-of-bounds list index during key-path traversal. Takes the root
228/// variable, the index, and the list length; rendering lives here.
229pub fn key_path_index_out_of_bounds(root: &str, idx: usize, len: usize) -> Diagnostic {
230    let message = format!("index {idx} out of bounds for list '${root}' (len: {len})");
231    Diagnostic::new(
232        "proc.expand.key_path_index_out_of_bounds",
233        message,
234        Diagnostic::make_fields(&[
235            (FIELD_ROOT, root),
236            (FIELD_INDEX, &idx.to_string()),
237            (FIELD_LEN, &len.to_string()),
238        ]),
239    )
240}
241
242/// Property access on a primitive during key-path traversal. Takes the
243/// root variable and the segment; quoting lives here.
244pub fn key_path_on_primitive(root: &str, segment: &str) -> Diagnostic {
245    let message = format!("cannot access property '{segment}' on primitive value of '${root}'");
246    Diagnostic::new(
247        "proc.expand.key_path_on_primitive",
248        message,
249        Diagnostic::make_fields(&[(FIELD_ROOT, root), (FIELD_SEGMENT, segment)]),
250    )
251}
252
253/// `PIPE` value interpolated as text. Parameterless: the wording and
254/// the `LET` capture guidance live here.
255pub fn render_pipe() -> Diagnostic {
256    Diagnostic::new(
257        "proc.expand.render_pipe",
258        format!(
259            "cannot render {PIPE_TYPE_NAME} as {STRING_TYPE_NAME}: pipes carry streams between steps, not text. Capture the producing step's output with {KEYWORD_LET} $var: {STRING_TYPE_NAME} = ... instead."
260        ),
261        Diagnostic::make_fields(&[]),
262    )
263}
264
265/// `SEMAPHORE` value interpolated as text. Parameterless: the wording
266/// lives here.
267pub fn render_semaphore() -> Diagnostic {
268    Diagnostic::new(
269        "proc.expand.render_semaphore",
270        format!(
271            "cannot render {SEMAPHORE_TYPE_NAME} as {STRING_TYPE_NAME}: semaphores coordinate task access between steps, not text."
272        ),
273        Diagnostic::make_fields(&[]),
274    )
275}
276
277/// `PERMIT` value interpolated as text. Parameterless: the wording
278/// lives here.
279pub fn render_permit() -> Diagnostic {
280    Diagnostic::new(
281        "proc.expand.render_permit",
282        format!(
283            "cannot render {PERMIT_TYPE_NAME} as {STRING_TYPE_NAME}: permits grant scoped task access, not text."
284        ),
285        Diagnostic::make_fields(&[]),
286    )
287}
288
289/// `INTERPRETER` lookup under Miri isolation. Parameterless: the
290/// wording is fixed.
291pub fn run_interpreter_unsupported_miri() -> Diagnostic {
292    Diagnostic::new(
293        "proc.run.interpreter_unsupported_miri",
294        "INTERPRETER is unsupported under Miri isolation".to_string(),
295        Diagnostic::make_fields(&[]),
296    )
297}
298
299/// Empty `RUN` exec argv. Parameterless: the wording is fixed.
300pub fn run_exec_requires_argv() -> Diagnostic {
301    Diagnostic::new(
302        "proc.run.exec_requires_argv",
303        format!("{KEYWORD_RUN} exec form requires at least one argument"),
304        Diagnostic::make_fields(&[]),
305    )
306}
307
308/// `RUN` exec form with an empty program. Parameterless: the wording
309/// is fixed.
310pub fn run_exec_requires_program() -> Diagnostic {
311    Diagnostic::new(
312        "proc.run.exec_requires_program",
313        format!("{KEYWORD_RUN} exec form requires a non-empty executable"),
314        Diagnostic::make_fields(&[]),
315    )
316}
317
318/// Spawned command exiting non-zero. Takes the command (any
319/// `Debug`: `std::process::Command`, argv slice, or script text) and
320/// the wait status; both renderings live here.
321pub fn run_command_failed(
322    desc: &impl std::fmt::Debug,
323    status: &std::process::ExitStatus,
324) -> Diagnostic {
325    let desc_text = format!("{desc:?}");
326    let status_text = status.to_string();
327    let message = format!("command {desc_text} failed with status {status_text}");
328    Diagnostic::new(
329        "proc.run.command_failed",
330        message,
331        Diagnostic::make_fields(&[
332            (FIELD_COMMAND, desc_text.as_str()),
333            (FIELD_STATUS, status_text.as_str()),
334        ]),
335    )
336}
337
338/// Current-executable lookup failed. Takes the I/O failure;
339/// rendering lives here. The typed I/O error rides as the chained
340/// source so `Error::source` and `{err:#}` chains keep it.
341pub fn run_current_exe_failed(err: &std::io::Error) -> Diagnostic {
342    let err_text = err.to_string();
343    let message = format!("cannot determine current executable: {err_text}");
344    Diagnostic::new(
345        "proc.run.current_exe_failed",
346        message,
347        Diagnostic::make_fields(&[(FIELD_ERR, err_text.as_str())]),
348    )
349    .with_source(std::sync::Arc::new(std::io::Error::new(
350        err.kind(),
351        err_text,
352    )))
353}
354
355/// Spawning or waiting on a shell command failed. Takes the command
356/// (any `Debug`: `std::process::Command`) and the I/O failure;
357/// rendering lives here. Shared by the status-wait and piped-output
358/// paths: one key, one mode. The typed I/O error rides as the
359/// chained source.
360pub fn run_failed(cmd: &impl std::fmt::Debug, err: &std::io::Error) -> Diagnostic {
361    let cmd_text = format!("{cmd:?}");
362    let err_text = err.to_string();
363    let message = format!("failed to run {cmd_text}: {err_text}");
364    Diagnostic::new(
365        "proc.run.run_failed",
366        message,
367        Diagnostic::make_fields(&[
368            (FIELD_COMMAND, cmd_text.as_str()),
369            (FIELD_ERR, err_text.as_str()),
370        ]),
371    )
372    .with_source(std::sync::Arc::new(std::io::Error::new(
373        err.kind(),
374        err_text,
375    )))
376}
377
378/// Waiting on a managed shell child failed. Takes the command (any
379/// `Debug`: `std::process::Command`) plus the wrapped wait failure;
380/// the chain renders inline. Distinct key from `run_failed`: that
381/// wraps a direct `std::io::Error` from `std` spawn/wait calls,
382/// while this wraps the managed-handle wait chain (already keyed
383/// `wait_failed` inside); the retired wordings match
384/// byte-identically through `{reason:#}`.
385pub fn run_wait_failed(cmd: &impl std::fmt::Debug, reason: &anyhow::Error) -> Diagnostic {
386    let cmd_text = format!("{cmd:?}");
387    let reason_text = format!("{reason:#}");
388    let message = format!("failed to run {cmd_text}: {reason_text}");
389    Diagnostic::new(
390        "proc.run.run_wait_failed",
391        message,
392        Diagnostic::make_fields(&[
393            (FIELD_COMMAND, cmd_text.as_str()),
394            (FIELD_REASON, reason_text.as_str()),
395        ]),
396    )
397}
398
399/// Spawning a shell command failed. Takes the command (any `Debug`:
400/// `std::process::Command`) and the I/O failure; rendering lives
401/// here. The typed I/O error rides as the chained source.
402pub fn spawn_failed(cmd: &impl std::fmt::Debug, err: &std::io::Error) -> Diagnostic {
403    let cmd_text = format!("{cmd:?}");
404    let err_text = err.to_string();
405    let message = format!("failed to spawn {cmd_text}: {err_text}");
406    Diagnostic::new(
407        "proc.run.spawn_failed",
408        message,
409        Diagnostic::make_fields(&[
410            (FIELD_COMMAND, cmd_text.as_str()),
411            (FIELD_ERR, err_text.as_str()),
412        ]),
413    )
414    .with_source(std::sync::Arc::new(std::io::Error::new(
415        err.kind(),
416        err_text,
417    )))
418}
419
420/// Waiting on a spawned child failed. Takes the I/O failure;
421/// rendering lives here. Shared by the `try_wait` poll and the
422/// blocking `wait`: one key, one mode. The typed I/O error rides
423/// as the chained source.
424pub fn wait_failed(err: &std::io::Error) -> Diagnostic {
425    let err_text = err.to_string();
426    let message = format!("failed to wait for child process: {err_text}");
427    Diagnostic::new(
428        "proc.run.wait_failed",
429        message,
430        Diagnostic::make_fields(&[(FIELD_ERR, err_text.as_str())]),
431    )
432    .with_source(std::sync::Arc::new(std::io::Error::new(
433        err.kind(),
434        err_text,
435    )))
436}
437
438/// Windows job-object assignment failed. Takes the underlying
439/// failure; `{reason:#}` formatting lives here so the call site
440/// stays `format!`-free. Third-party-feeling OS errors ride the
441/// anyhow passthrough and never attach a source.
442pub fn job_assign_failed(reason: &anyhow::Error) -> Diagnostic {
443    let reason_text = format!("{reason:#}");
444    Diagnostic::new(
445        "proc.run.job_assign_failed",
446        reason_text.clone(),
447        Diagnostic::make_fields(&[(FIELD_REASON, reason_text.as_str())]),
448    )
449}
450
451/// Synthetic Miri-backend failure. Takes the underlying failure;
452/// `{reason:#}` formatting lives here so the call site stays
453/// `format!`-free. Already-keyed payloads are reclaimed by
454/// [`from_anyhow`], so this only names genuinely unkeyed fallout.
455pub fn synthetic_failed(reason: &anyhow::Error) -> Diagnostic {
456    let reason_text = format!("{reason:#}");
457    Diagnostic::new(
458        "proc.run.synthetic_failed",
459        reason_text.clone(),
460        Diagnostic::make_fields(&[(FIELD_REASON, reason_text.as_str())]),
461    )
462}
463
464/// Reclaim an already-keyed diagnostic from an `anyhow` failure,
465/// wrapping anything else as a synthetic-backend failure. Single
466/// owner for the Miri-arm mapping so both arms preserve keys
467/// instead of restating the downcast.
468pub fn from_anyhow(err: anyhow::Error) -> Diagnostic {
469    match err.downcast::<Diagnostic>() {
470        Ok(diag) => diag,
471        Err(err) => synthetic_failed(&err),
472    }
473}
474
475/// Spawned piped child missing a stdio half. Takes the command (any
476/// `Debug`: `std::process::Command`) and the stream name (`stdin`,
477/// `stdout`, or `stderr`); rendering lives here. Shared by the
478/// piped and piped-with-stderr paths: one key, one mode.
479pub fn spawn_pipe_half_missing(cmd: &impl std::fmt::Debug, stream: &str) -> Diagnostic {
480    let cmd_text = format!("{cmd:?}");
481    let message = format!("spawned process has no piped {stream}: {cmd_text}");
482    Diagnostic::new(
483        "proc.run.spawn_pipe_half_missing",
484        message,
485        Diagnostic::make_fields(&[(FIELD_COMMAND, cmd_text.as_str()), (FIELD_STREAM, stream)]),
486    )
487}
488
489/// Interactive shell window launch failed. Takes the underlying
490/// failure; `{reason:#}` formatting lives here so the call site
491/// stays `format!`-free. The chained spawn diagnostic rides inline;
492/// no source is attached.
493pub fn spawn_interactive_window_failed(reason: &anyhow::Error) -> Diagnostic {
494    let reason_text = format!("{reason:#}");
495    let message = format!("failed to start interactive shell window: {reason_text}");
496    Diagnostic::new(
497        "proc.run.interactive_spawn_failed",
498        message,
499        Diagnostic::make_fields(&[(FIELD_REASON, reason_text.as_str())]),
500    )
501}
502
503/// Shell exiting non-zero. Takes the wait status; rendering lives
504/// here.
505pub fn shell_exited_with_status(status: &std::process::ExitStatus) -> Diagnostic {
506    let status_text = status.to_string();
507    let message = format!("shell exited with status {status_text}");
508    Diagnostic::new(
509        "proc.run.shell_exited_with_status",
510        message,
511        Diagnostic::make_fields(&[(FIELD_STATUS, status_text.as_str())]),
512    )
513}
514
515/// Interactive shell on a platform without one. Parameterless: the
516/// wording is fixed.
517pub fn run_interactive_unsupported() -> Diagnostic {
518    Diagnostic::new(
519        "proc.run.interactive_unsupported",
520        "interactive shell unsupported on this platform".to_string(),
521        Diagnostic::make_fields(&[]),
522    )
523}
524
525/// Stdout capture for a background command. Parameterless: the
526/// wording is fixed.
527pub fn run_bg_capture_unsupported() -> Diagnostic {
528    Diagnostic::new(
529        "proc.run.bg_capture_unsupported",
530        "cannot capture stdout for background command".to_string(),
531        Diagnostic::make_fields(&[]),
532    )
533}
534
535/// Stdout capture for a background command under Miri isolation.
536/// Parameterless: the wording is fixed.
537pub fn run_bg_capture_unsupported_miri() -> Diagnostic {
538    Diagnostic::new(
539        "proc.run.bg_capture_unsupported_miri",
540        "cannot capture stdout for background command under Miri".to_string(),
541        Diagnostic::make_fields(&[]),
542    )
543}
544
545/// Stdout streaming for a background command under Miri isolation.
546/// Parameterless: the wording is fixed.
547pub fn run_bg_stdout_stream_unsupported_miri() -> Diagnostic {
548    Diagnostic::new(
549        "proc.run.bg_stdout_stream_unsupported_miri",
550        "stdout streaming not supported for background command under Miri".to_string(),
551        Diagnostic::make_fields(&[]),
552    )
553}
554
555/// Stderr streaming for a background command under Miri isolation.
556/// Parameterless: the wording is fixed.
557pub fn run_bg_stderr_stream_unsupported_miri() -> Diagnostic {
558    Diagnostic::new(
559        "proc.run.bg_stderr_stream_unsupported_miri",
560        "stderr streaming not supported for background command under Miri".to_string(),
561        Diagnostic::make_fields(&[]),
562    )
563}
564
565/// Native spawn under the Miri synthetic backend. Parameterless: the
566/// wording is fixed.
567pub fn run_spawn_unsupported_miri() -> Diagnostic {
568    Diagnostic::new(
569        "proc.run.spawn_unsupported_miri",
570        "spawn is not supported under Miri synthetic process backend".to_string(),
571        Diagnostic::make_fields(&[]),
572    )
573}
574
575/// Unguarded write under Miri isolation. Parameterless: the wording
576/// is fixed.
577pub fn run_unguarded_writes_unsupported_miri() -> Diagnostic {
578    Diagnostic::new(
579        "proc.run.unguarded_writes_unsupported_miri",
580        "unguarded writes not supported in Miri".to_string(),
581        Diagnostic::make_fields(&[]),
582    )
583}
584
585/// Default `run_argv` with no override. Takes the argv; `Debug`
586/// rendering lives here.
587pub fn run_argv_unimplemented(argv: &[String]) -> Diagnostic {
588    let argv_text = format!("{argv:?}");
589    let message = format!("run_argv not implemented for argv {argv_text}");
590    Diagnostic::new(
591        "proc.run.argv_unimplemented",
592        message,
593        Diagnostic::make_fields(&[(FIELD_ARGV, argv_text.as_str())]),
594    )
595}
596
597/// Spawn without `PATH` in the script environment. Takes the program;
598/// the `PATH` spelling and the `INHERIT_ENV` fix derive from the
599/// declared env contract, never literals.
600pub fn spawn_requires_path(program: &str) -> Diagnostic {
601    let message = format!(
602        "cannot resolve '{program}' without {} in the script environment; declare {KEYWORD_INHERIT_ENV} [{}]",
603        oxdock_env::os::PATH,
604        oxdock_env::os::PATH,
605    );
606    Diagnostic::new(
607        "proc.run.spawn_requires_path",
608        message,
609        Diagnostic::make_fields(&[(FIELD_PROGRAM, program)]),
610    )
611}
612
613/// Windows spawn without `SystemRoot` in the script environment. The
614/// name spelling and the `INHERIT_ENV` fix derive from the declared
615/// env contract, never literals.
616pub fn spawn_requires_system_root() -> Diagnostic {
617    let message = format!(
618        "Windows process execution requires {} in the script environment; declare {KEYWORD_INHERIT_ENV} [{}]",
619        oxdock_env::os::windows::SYSTEM_ROOT,
620        oxdock_env::os::windows::SYSTEM_ROOT,
621    );
622    Diagnostic::new(
623        "proc.run.spawn_requires_system_root",
624        message,
625        Diagnostic::make_fields(&[]),
626    )
627}
628
629/// Mock stdin snapshot losing the lock race. Parameterless: the
630/// wording is fixed.
631pub fn run_stdin_lock_failed() -> Diagnostic {
632    Diagnostic::new(
633        "proc.run.stdin_lock_failed",
634        "failed to lock stdin".to_string(),
635        Diagnostic::make_fields(&[]),
636    )
637}
638
639/// Capture buffer losing the lock race. Parameterless: the wording
640/// is fixed.
641pub fn run_capture_lock_poisoned() -> Diagnostic {
642    Diagnostic::new(
643        "proc.run.capture_lock_poisoned",
644        "capture stdout poisoned".to_string(),
645        Diagnostic::make_fields(&[]),
646    )
647}
648
649#[cfg(test)]
650mod tests {
651    use super::*;
652    use oxdock_sys_test_utils::exit_status_from_code as exit_status;
653
654    #[test]
655    fn each_failure_has_a_distinct_key() {
656        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "x");
657        let keys = [
658            undefined_env_var("FOO", false).key(),
659            undefined_script_var("x", None).key(),
660            missing_step_override("n", None).key(),
661            invalid_placeholder_format("k").key(),
662            call_without_registry("M", "F").key(),
663            call_arg_too_deep(8).key(),
664            call_arg_empty_var().key(),
665            call_arg_invalid("s").key(),
666            call_arg_nested_calls().key(),
667            map_entry_invalid("e").key(),
668            map_duplicate_key("k").key(),
669            key_path_missing_property("r", "s").key(),
670            key_path_bad_index("r", "s").key(),
671            key_path_index_out_of_bounds("r", 5, 2).key(),
672            key_path_on_primitive("r", "s").key(),
673            render_pipe().key(),
674            render_semaphore().key(),
675            render_permit().key(),
676            run_interpreter_unsupported_miri().key(),
677            run_exec_requires_argv().key(),
678            run_exec_requires_program().key(),
679            shell_exited_with_status(&exit_status(1)).key(),
680            run_interactive_unsupported().key(),
681            run_bg_capture_unsupported().key(),
682            run_bg_capture_unsupported_miri().key(),
683            run_bg_stdout_stream_unsupported_miri().key(),
684            run_bg_stderr_stream_unsupported_miri().key(),
685            run_spawn_unsupported_miri().key(),
686            run_unguarded_writes_unsupported_miri().key(),
687            run_argv_unimplemented(&["RUN".to_string()]).key(),
688            spawn_requires_path("prog").key(),
689            spawn_requires_system_root().key(),
690            run_stdin_lock_failed().key(),
691            run_capture_lock_poisoned().key(),
692            run_current_exe_failed(&io_err).key(),
693            run_failed(&"echo hi", &io_err).key(),
694            run_wait_failed(&"echo hi", &anyhow::anyhow!("boom")).key(),
695            spawn_failed(&"echo hi", &io_err).key(),
696            wait_failed(&io_err).key(),
697            job_assign_failed(&anyhow::anyhow!("boom")).key(),
698            synthetic_failed(&anyhow::anyhow!("boom")).key(),
699            spawn_pipe_half_missing(&"echo hi", "stdin").key(),
700            spawn_interactive_window_failed(&anyhow::anyhow!("boom")).key(),
701        ];
702        let mut seen = std::collections::HashSet::new();
703        for k in keys {
704            assert!(seen.insert(k), "duplicate key {k}");
705        }
706
707        // `run_command_failed` renders any `Debug` command description;
708        // one key for every description shape.
709        assert_eq!(
710            run_command_failed(&"echo hi", &exit_status(1)).key(),
711            run_command_failed(&vec!["echo".to_string()], &exit_status(1)).key()
712        );
713    }
714
715    #[test]
716    fn hinted_and_bare_share_one_key() {
717        assert_eq!(
718            undefined_env_var("FOO", false).key(),
719            undefined_env_var("FOO", true).key()
720        );
721        assert_eq!(
722            undefined_script_var("x", None).key(),
723            undefined_script_var("x", Some(ScriptSuggest::Env)).key()
724        );
725        assert_eq!(
726            missing_step_override("n", None).key(),
727            missing_step_override("n", Some(OverrideSuggest::EnvVar)).key()
728        );
729    }
730
731    #[test]
732    fn messages_match_canonical_wording() {
733        assert_eq!(
734            undefined_env_var("FOO", false).message(),
735            "undefined environment variable: 'FOO'"
736        );
737        assert_eq!(
738            undefined_env_var("FOO", true).message(),
739            "undefined environment variable: 'FOO'; did you mean '$FOO' (script variable)?"
740        );
741        assert_eq!(
742            undefined_env_var("", false).message(),
743            "undefined environment variable: ''"
744        );
745        assert_eq!(
746            undefined_script_var("WHO", Some(ScriptSuggest::Env)).message(),
747            "undefined script variable: '$WHO'; did you mean 'env:WHO' (environment variable)?"
748        );
749        assert_eq!(
750            missing_step_override("PORT", Some(OverrideSuggest::ScriptVar)).message(),
751            "missing required step override argument: 'PORT'; did you mean '$PORT' (script variable)?"
752        );
753        assert_eq!(
754            missing_step_override("PORT", Some(OverrideSuggest::EnvVar)).message(),
755            "missing required step override argument: 'PORT'; did you mean 'env:PORT' (environment variable)?"
756        );
757        assert_eq!(
758            key_path_index_out_of_bounds("r", 5, 2).message(),
759            "index 5 out of bounds for list '$r' (len: 2)"
760        );
761        assert_eq!(
762            call_arg_too_deep(8).message(),
763            "placeholder call argument nests too deep (limit 8)"
764        );
765        // `ExitStatus` Display is platform-specific (`exit status: N`
766        // on Unix, `exit code: N` on Windows): interpolate the value
767        // itself so the template wording is pinned without assuming
768        // either rendering.
769        let failed_status = exit_status(3);
770        assert_eq!(
771            run_command_failed(&"echo hi", &failed_status).message(),
772            format!("command \"echo hi\" failed with status {failed_status}")
773        );
774        let exited_status = exit_status(1);
775        assert_eq!(
776            shell_exited_with_status(&exited_status).message(),
777            format!("shell exited with status {exited_status}")
778        );
779        assert_eq!(
780            run_argv_unimplemented(&["RUN".to_string()]).message(),
781            "run_argv not implemented for argv [\"RUN\"]"
782        );
783        assert_eq!(
784            spawn_requires_path("prog").message(),
785            "cannot resolve 'prog' without PATH in the script environment; declare INHERIT_ENV [PATH]"
786        );
787        assert_eq!(
788            spawn_requires_system_root().message(),
789            "Windows process execution requires SystemRoot in the script environment; declare INHERIT_ENV [SystemRoot]"
790        );
791        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
792        assert_eq!(
793            run_current_exe_failed(&io_err).message(),
794            "cannot determine current executable: nope"
795        );
796        assert_eq!(
797            run_failed(&"echo hi", &io_err).message(),
798            "failed to run \"echo hi\": nope"
799        );
800        assert_eq!(
801            run_wait_failed(&"echo hi", &anyhow::anyhow!("boom")).message(),
802            "failed to run \"echo hi\": boom"
803        );
804        assert_eq!(
805            spawn_failed(&"echo hi", &io_err).message(),
806            "failed to spawn \"echo hi\": nope"
807        );
808        assert_eq!(
809            wait_failed(&io_err).message(),
810            "failed to wait for child process: nope"
811        );
812        assert_eq!(
813            job_assign_failed(&anyhow::anyhow!("boom")).message(),
814            "boom"
815        );
816        assert_eq!(synthetic_failed(&anyhow::anyhow!("boom")).message(), "boom");
817        assert_eq!(
818            spawn_pipe_half_missing(&"echo hi", "stdin").message(),
819            "spawned process has no piped stdin: \"echo hi\""
820        );
821        assert_eq!(
822            spawn_interactive_window_failed(&anyhow::anyhow!("boom")).message(),
823            "failed to start interactive shell window: boom"
824        );
825    }
826
827    #[test]
828    fn from_anyhow_reclaims_keyed_payloads() {
829        let keyed = run_exec_requires_argv();
830        let key = keyed.key();
831        let reclaimed = from_anyhow(anyhow::Error::new(keyed));
832        assert_eq!(reclaimed.key(), key);
833        assert_eq!(
834            reclaimed.message(),
835            "RUN exec form requires at least one argument"
836        );
837        let wrapped = from_anyhow(anyhow::anyhow!("boom"));
838        assert_eq!(wrapped.key(), "proc.run.synthetic_failed");
839        assert_eq!(wrapped.message(), "boom");
840    }
841
842    #[test]
843    fn io_ctors_preserve_typed_source_chain() {
844        use std::error::Error as _;
845        let err = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
846        for diag in [
847            run_current_exe_failed(&err),
848            run_failed(&"echo hi", &err),
849            spawn_failed(&"echo hi", &err),
850            wait_failed(&err),
851        ] {
852            let source = diag.source().expect("io ctor keeps a source");
853            let io_source = source
854                .downcast_ref::<std::io::Error>()
855                .expect("source is the typed io error");
856            assert_eq!(io_source.kind(), std::io::ErrorKind::NotFound);
857            assert_eq!(io_source.to_string(), "nope");
858        }
859    }
860}