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, flatten_chain};
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: &Diagnostic) -> Diagnostic {
386    let cmd_text = format!("{cmd:?}");
387    let reason_text = flatten_chain(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; the flattened chain lives here so the call site stays
440/// `format!`-free. Third-party-feeling OS errors ride the lift below
441/// and never attach a source.
442pub fn job_assign_failed(reason: &Diagnostic) -> Diagnostic {
443    let reason_text = flatten_chain(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/// Windows job-object assignment failed at the OS call. Takes the
452/// operation name (`CreateJobObjectW`,
453/// `AssignProcessToJobObject`) and the underlying I/O failure; the
454/// io text rides verbatim in both message and reason field. Native
455/// `?` propagation plus `with_contexts` keeps the chain flattened
456/// byte-identical to the retired shape. Sourceless: the chain text
457/// is the message.
458pub fn job_assign_io_failed(op: &str, err: &std::io::Error) -> Diagnostic {
459    let err_text = err.to_string();
460    let message = format!("{op} failed: {err_text}");
461    Diagnostic::new(
462        "proc.run.job_assign_failed",
463        message.clone(),
464        Diagnostic::make_fields(&[(FIELD_REASON, message.as_str())]),
465    )
466}
467
468/// Spawned piped child missing a stdio half. Takes the command (any
469/// `Debug`: `std::process::Command`) and the stream name (`stdin`,
470/// `stdout`, or `stderr`); rendering lives here. Shared by the
471/// piped and piped-with-stderr paths: one key, one mode.
472pub fn spawn_pipe_half_missing(cmd: &impl std::fmt::Debug, stream: &str) -> Diagnostic {
473    let cmd_text = format!("{cmd:?}");
474    let message = format!("spawned process has no piped {stream}: {cmd_text}");
475    Diagnostic::new(
476        "proc.run.spawn_pipe_half_missing",
477        message,
478        Diagnostic::make_fields(&[(FIELD_COMMAND, cmd_text.as_str()), (FIELD_STREAM, stream)]),
479    )
480}
481
482/// Interactive shell window launch failed. Takes the underlying
483/// failure; the flattened chain lives here so the call site stays
484/// `format!`-free. The chained spawn diagnostic rides inline;
485/// no source is attached.
486pub fn spawn_interactive_window_failed(reason: &Diagnostic) -> Diagnostic {
487    let reason_text = flatten_chain(reason);
488    let message = format!("failed to start interactive shell window: {reason_text}");
489    Diagnostic::new(
490        "proc.run.interactive_spawn_failed",
491        message,
492        Diagnostic::make_fields(&[(FIELD_REASON, reason_text.as_str())]),
493    )
494}
495
496/// Shell exiting non-zero. Takes the wait status; rendering lives
497/// here.
498pub fn shell_exited_with_status(status: &std::process::ExitStatus) -> Diagnostic {
499    let status_text = status.to_string();
500    let message = format!("shell exited with status {status_text}");
501    Diagnostic::new(
502        "proc.run.shell_exited_with_status",
503        message,
504        Diagnostic::make_fields(&[(FIELD_STATUS, status_text.as_str())]),
505    )
506}
507
508/// Interactive shell on a platform without one. Parameterless: the
509/// wording is fixed.
510pub fn run_interactive_unsupported() -> Diagnostic {
511    Diagnostic::new(
512        "proc.run.interactive_unsupported",
513        "interactive shell unsupported on this platform".to_string(),
514        Diagnostic::make_fields(&[]),
515    )
516}
517
518/// Stdout capture for a background command. Parameterless: the
519/// wording is fixed.
520pub fn run_bg_capture_unsupported() -> Diagnostic {
521    Diagnostic::new(
522        "proc.run.bg_capture_unsupported",
523        "cannot capture stdout for background command".to_string(),
524        Diagnostic::make_fields(&[]),
525    )
526}
527
528/// Stdout capture for a background command under Miri isolation.
529/// Parameterless: the wording is fixed.
530pub fn run_bg_capture_unsupported_miri() -> Diagnostic {
531    Diagnostic::new(
532        "proc.run.bg_capture_unsupported_miri",
533        "cannot capture stdout for background command under Miri".to_string(),
534        Diagnostic::make_fields(&[]),
535    )
536}
537
538/// Stdout streaming for a background command under Miri isolation.
539/// Parameterless: the wording is fixed.
540pub fn run_bg_stdout_stream_unsupported_miri() -> Diagnostic {
541    Diagnostic::new(
542        "proc.run.bg_stdout_stream_unsupported_miri",
543        "stdout streaming not supported for background command under Miri".to_string(),
544        Diagnostic::make_fields(&[]),
545    )
546}
547
548/// Stderr streaming for a background command under Miri isolation.
549/// Parameterless: the wording is fixed.
550pub fn run_bg_stderr_stream_unsupported_miri() -> Diagnostic {
551    Diagnostic::new(
552        "proc.run.bg_stderr_stream_unsupported_miri",
553        "stderr streaming not supported for background command under Miri".to_string(),
554        Diagnostic::make_fields(&[]),
555    )
556}
557
558/// Native spawn under the Miri synthetic backend. Parameterless: the
559/// wording is fixed.
560pub fn run_spawn_unsupported_miri() -> Diagnostic {
561    Diagnostic::new(
562        "proc.run.spawn_unsupported_miri",
563        "spawn is not supported under Miri synthetic process backend".to_string(),
564        Diagnostic::make_fields(&[]),
565    )
566}
567
568/// Unguarded write under Miri isolation. Parameterless: the wording
569/// is fixed.
570pub fn run_unguarded_writes_unsupported_miri() -> Diagnostic {
571    Diagnostic::new(
572        "proc.run.unguarded_writes_unsupported_miri",
573        "unguarded writes not supported in Miri".to_string(),
574        Diagnostic::make_fields(&[]),
575    )
576}
577
578/// Default `run_argv` with no override. Takes the argv; `Debug`
579/// rendering lives here.
580pub fn run_argv_unimplemented(argv: &[String]) -> Diagnostic {
581    let argv_text = format!("{argv:?}");
582    let message = format!("run_argv not implemented for argv {argv_text}");
583    Diagnostic::new(
584        "proc.run.argv_unimplemented",
585        message,
586        Diagnostic::make_fields(&[(FIELD_ARGV, argv_text.as_str())]),
587    )
588}
589
590/// Spawn without `PATH` in the script environment. Takes the program;
591/// the `PATH` spelling and the `INHERIT_ENV` fix derive from the
592/// declared env contract, never literals.
593pub fn spawn_requires_path(program: &str) -> Diagnostic {
594    let message = format!(
595        "cannot resolve '{program}' without {} in the script environment; declare {KEYWORD_INHERIT_ENV} [{}]",
596        oxdock_env::os::PATH,
597        oxdock_env::os::PATH,
598    );
599    Diagnostic::new(
600        "proc.run.spawn_requires_path",
601        message,
602        Diagnostic::make_fields(&[(FIELD_PROGRAM, program)]),
603    )
604}
605
606/// Windows spawn without `SystemRoot` in the script environment. The
607/// name spelling and the `INHERIT_ENV` fix derive from the declared
608/// env contract, never literals.
609pub fn spawn_requires_system_root() -> Diagnostic {
610    let message = format!(
611        "Windows process execution requires {} in the script environment; declare {KEYWORD_INHERIT_ENV} [{}]",
612        oxdock_env::os::windows::SYSTEM_ROOT,
613        oxdock_env::os::windows::SYSTEM_ROOT,
614    );
615    Diagnostic::new(
616        "proc.run.spawn_requires_system_root",
617        message,
618        Diagnostic::make_fields(&[]),
619    )
620}
621
622/// Mock stdin snapshot losing the lock race. Parameterless: the
623/// wording is fixed.
624pub fn run_stdin_lock_failed() -> Diagnostic {
625    Diagnostic::new(
626        "proc.run.stdin_lock_failed",
627        "failed to lock stdin".to_string(),
628        Diagnostic::make_fields(&[]),
629    )
630}
631
632/// Mock stdin snapshot read failed. Takes the I/O failure;
633/// rendering lives here. The typed I/O error rides as the chained
634/// source so `Error::source` and `{err:#}` chains keep it. Distinct
635/// key from `run_stdin_lock_failed`: that names a poisoned stream
636/// lock, while this names a failed read on the live stream.
637pub fn run_stdin_read_failed(err: &std::io::Error) -> Diagnostic {
638    let err_text = err.to_string();
639    let message = format!("failed to read mock stdin: {err_text}");
640    Diagnostic::new(
641        "proc.run.stdin_read_failed",
642        message,
643        Diagnostic::make_fields(&[(FIELD_ERR, err_text.as_str())]),
644    )
645    .with_source(std::sync::Arc::new(std::io::Error::new(
646        err.kind(),
647        err_text,
648    )))
649}
650
651/// Capture buffer losing the lock race. Parameterless: the wording
652/// is fixed.
653pub fn run_capture_lock_poisoned() -> Diagnostic {
654    Diagnostic::new(
655        "proc.run.capture_lock_poisoned",
656        "capture stdout poisoned".to_string(),
657        Diagnostic::make_fields(&[]),
658    )
659}
660
661#[cfg(test)]
662pub(crate) fn reason_sample(msg: &str) -> Diagnostic {
663    Diagnostic::new(
664        "test.reason.sample",
665        msg.to_string(),
666        Diagnostic::make_fields(&[]),
667    )
668}
669
670#[cfg(test)]
671mod tests {
672    use super::*;
673    use oxdock_sys_test_utils::exit_status_from_code as exit_status;
674
675    #[test]
676    fn each_failure_has_a_distinct_key() {
677        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "x");
678        let reason = reason_sample("boom");
679        let keys = [
680            undefined_env_var("FOO", false).key(),
681            undefined_script_var("x", None).key(),
682            missing_step_override("n", None).key(),
683            invalid_placeholder_format("k").key(),
684            call_without_registry("M", "F").key(),
685            call_arg_too_deep(8).key(),
686            call_arg_empty_var().key(),
687            call_arg_invalid("s").key(),
688            call_arg_nested_calls().key(),
689            map_entry_invalid("e").key(),
690            map_duplicate_key("k").key(),
691            key_path_missing_property("r", "s").key(),
692            key_path_bad_index("r", "s").key(),
693            key_path_index_out_of_bounds("r", 5, 2).key(),
694            key_path_on_primitive("r", "s").key(),
695            render_pipe().key(),
696            render_semaphore().key(),
697            render_permit().key(),
698            run_interpreter_unsupported_miri().key(),
699            run_exec_requires_argv().key(),
700            run_exec_requires_program().key(),
701            shell_exited_with_status(&exit_status(1)).key(),
702            run_interactive_unsupported().key(),
703            run_bg_capture_unsupported().key(),
704            run_bg_capture_unsupported_miri().key(),
705            run_bg_stdout_stream_unsupported_miri().key(),
706            run_bg_stderr_stream_unsupported_miri().key(),
707            run_spawn_unsupported_miri().key(),
708            run_unguarded_writes_unsupported_miri().key(),
709            run_argv_unimplemented(&["RUN".to_string()]).key(),
710            spawn_requires_path("prog").key(),
711            spawn_requires_system_root().key(),
712            run_stdin_lock_failed().key(),
713            run_stdin_read_failed(&io_err).key(),
714            run_capture_lock_poisoned().key(),
715            run_current_exe_failed(&io_err).key(),
716            run_failed(&"echo hi", &io_err).key(),
717            run_wait_failed(&"echo hi", &reason).key(),
718            spawn_failed(&"echo hi", &io_err).key(),
719            wait_failed(&io_err).key(),
720            job_assign_failed(&reason).key(),
721            spawn_pipe_half_missing(&"echo hi", "stdin").key(),
722            spawn_interactive_window_failed(&reason).key(),
723        ];
724        let mut seen = std::collections::HashSet::new();
725        for k in keys {
726            assert!(seen.insert(k), "duplicate key {k}");
727        }
728
729        // `run_command_failed` renders any `Debug` command description;
730        // one key for every description shape.
731        assert_eq!(
732            run_command_failed(&"echo hi", &exit_status(1)).key(),
733            run_command_failed(&vec!["echo".to_string()], &exit_status(1)).key()
734        );
735    }
736
737    #[test]
738    fn hinted_and_bare_share_one_key() {
739        assert_eq!(
740            undefined_env_var("FOO", false).key(),
741            undefined_env_var("FOO", true).key()
742        );
743        assert_eq!(
744            undefined_script_var("x", None).key(),
745            undefined_script_var("x", Some(ScriptSuggest::Env)).key()
746        );
747        assert_eq!(
748            missing_step_override("n", None).key(),
749            missing_step_override("n", Some(OverrideSuggest::EnvVar)).key()
750        );
751    }
752
753    #[test]
754    fn messages_match_canonical_wording() {
755        assert_eq!(
756            undefined_env_var("FOO", false).message(),
757            "undefined environment variable: 'FOO'"
758        );
759        assert_eq!(
760            undefined_env_var("FOO", true).message(),
761            "undefined environment variable: 'FOO'; did you mean '$FOO' (script variable)?"
762        );
763        assert_eq!(
764            undefined_env_var("", false).message(),
765            "undefined environment variable: ''"
766        );
767        assert_eq!(
768            undefined_script_var("WHO", Some(ScriptSuggest::Env)).message(),
769            "undefined script variable: '$WHO'; did you mean 'env:WHO' (environment variable)?"
770        );
771        assert_eq!(
772            missing_step_override("PORT", Some(OverrideSuggest::ScriptVar)).message(),
773            "missing required step override argument: 'PORT'; did you mean '$PORT' (script variable)?"
774        );
775        assert_eq!(
776            missing_step_override("PORT", Some(OverrideSuggest::EnvVar)).message(),
777            "missing required step override argument: 'PORT'; did you mean 'env:PORT' (environment variable)?"
778        );
779        assert_eq!(
780            key_path_index_out_of_bounds("r", 5, 2).message(),
781            "index 5 out of bounds for list '$r' (len: 2)"
782        );
783        assert_eq!(
784            call_arg_too_deep(8).message(),
785            "placeholder call argument nests too deep (limit 8)"
786        );
787        // `ExitStatus` Display is platform-specific (`exit status: N`
788        // on Unix, `exit code: N` on Windows): interpolate the value
789        // itself so the template wording is pinned without assuming
790        // either rendering.
791        let failed_status = exit_status(3);
792        assert_eq!(
793            run_command_failed(&"echo hi", &failed_status).message(),
794            format!("command \"echo hi\" failed with status {failed_status}")
795        );
796        let exited_status = exit_status(1);
797        assert_eq!(
798            shell_exited_with_status(&exited_status).message(),
799            format!("shell exited with status {exited_status}")
800        );
801        assert_eq!(
802            run_argv_unimplemented(&["RUN".to_string()]).message(),
803            "run_argv not implemented for argv [\"RUN\"]"
804        );
805        assert_eq!(
806            spawn_requires_path("prog").message(),
807            "cannot resolve 'prog' without PATH in the script environment; declare INHERIT_ENV [PATH]"
808        );
809        assert_eq!(
810            spawn_requires_system_root().message(),
811            "Windows process execution requires SystemRoot in the script environment; declare INHERIT_ENV [SystemRoot]"
812        );
813        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
814        assert_eq!(
815            run_current_exe_failed(&io_err).message(),
816            "cannot determine current executable: nope"
817        );
818        assert_eq!(
819            run_failed(&"echo hi", &io_err).message(),
820            "failed to run \"echo hi\": nope"
821        );
822        assert_eq!(
823            run_stdin_read_failed(&io_err).message(),
824            "failed to read mock stdin: nope"
825        );
826        assert_eq!(
827            run_wait_failed(&"echo hi", &reason_sample("boom")).message(),
828            "failed to run \"echo hi\": boom"
829        );
830        assert_eq!(
831            spawn_failed(&"echo hi", &io_err).message(),
832            "failed to spawn \"echo hi\": nope"
833        );
834        assert_eq!(
835            wait_failed(&io_err).message(),
836            "failed to wait for child process: nope"
837        );
838        assert_eq!(job_assign_failed(&reason_sample("boom")).message(), "boom");
839        assert_eq!(
840            job_assign_io_failed("CreateJobObjectW", &io_err).message(),
841            "CreateJobObjectW failed: nope"
842        );
843        assert_eq!(
844            job_assign_io_failed("CreateJobObjectW", &io_err).key(),
845            "proc.run.job_assign_failed"
846        );
847        assert_eq!(
848            spawn_interactive_window_failed(&reason_sample("boom")).message(),
849            "failed to start interactive shell window: boom"
850        );
851        assert_eq!(
852            spawn_pipe_half_missing(&"echo hi", "stdin").message(),
853            "spawned process has no piped stdin: \"echo hi\""
854        );
855        assert_eq!(
856            spawn_interactive_window_failed(&reason_sample("boom")).message(),
857            "failed to start interactive shell window: boom"
858        );
859    }
860
861    #[test]
862    fn io_leaf_ctors_match_retired_anyhow_round_trip() {
863        // The Windows call sites built their inner diagnostic via the
864        // retired anyhow bridge plus `with_contexts`, then flattened
865        // through the passthrough owner. The typed leaves must
866        // reproduce that chain byte for byte: key, message, and
867        // rendered text. The retired bridge (including its
868        // `proc.run.synthetic_failed` fallback) is deleted, so the
869        // shape is pinned directly here.
870        for op in ["CreateJobObjectW", "AssignProcessToJobObject"] {
871            let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
872            let io_text = io_err.to_string();
873            let direct = job_assign_io_failed(op, &io_err);
874            assert_eq!(direct.key(), "proc.run.job_assign_failed");
875            assert_eq!(direct.to_string(), format!("{op} failed: {io_text}"));
876        }
877    }
878
879    #[test]
880    fn io_ctors_preserve_typed_source_chain() {
881        use std::error::Error as _;
882        let err = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
883        for diag in [
884            run_current_exe_failed(&err),
885            run_failed(&"echo hi", &err),
886            spawn_failed(&"echo hi", &err),
887            wait_failed(&err),
888        ] {
889            let source = diag.source().expect("io ctor keeps a source");
890            let io_source = source
891                .downcast_ref::<std::io::Error>()
892                .expect("source is the typed io error");
893            assert_eq!(io_source.kind(), std::io::ErrorKind::NotFound);
894            assert_eq!(io_source.to_string(), "nope");
895        }
896    }
897}