Skip to main content

codex_wrapper/
error.rs

1//! Error types for `codex-wrapper`.
2
3use std::path::PathBuf;
4
5/// Which of a child's captured streams an [`Error::OutputLimitExceeded`]
6/// refers to.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum OutputStream {
9    /// The child's standard output.
10    Stdout,
11    /// The child's standard error.
12    Stderr,
13}
14
15impl std::fmt::Display for OutputStream {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        f.write_str(match self {
18            Self::Stdout => "stdout",
19            Self::Stderr => "stderr",
20        })
21    }
22}
23
24/// Errors returned by `codex-wrapper` operations.
25///
26/// This enum is `#[non_exhaustive]`: match arms must include a `_` catch-all so
27/// new variants can be added without a breaking change. This mirrors
28/// `claude-wrapper`'s `Error` for cross-crate consistency.
29#[derive(Debug, thiserror::Error)]
30#[non_exhaustive]
31pub enum Error {
32    /// The `codex` binary was not found in PATH.
33    #[error("codex binary not found in PATH")]
34    NotFound,
35
36    /// A captured stream passed the ceiling set by
37    /// [`CodexBuilder::output_limit`](crate::CodexBuilder::output_limit).
38    ///
39    /// The run is stopped the same way [`Error::Cancelled`] and
40    /// [`Error::Timeout`] stop it, so the child does not keep writing into a
41    /// buffer nothing will read. No captured bytes are carried here: output
42    /// seen before the ceiling tripped is logged at warn instead, because
43    /// returning a prefix as if it were the result is the truncated success
44    /// this exists to prevent.
45    ///
46    /// The ceiling is off by default and this error cannot occur while it is
47    /// unset.
48    #[error("codex {stream} exceeded the {limit_bytes}-byte capture limit")]
49    OutputLimitExceeded {
50        /// Which captured stream exceeded the ceiling.
51        stream: OutputStream,
52        /// The configured ceiling, in bytes, that was exceeded.
53        limit_bytes: usize,
54    },
55
56    /// The CLI could not authenticate.
57    ///
58    /// Classified from stderr by [`Error::from_command_failure`]; see
59    /// [`FailureKind`] for what that costs. Not retried: the CLI has already
60    /// retried internally by the time this surfaces, and the credentials will
61    /// not have changed.
62    #[error("codex authentication failed: {}", first_line(message))]
63    Auth {
64        /// The CLI's stderr, trimmed. Retained whole rather than reduced to
65        /// the matched line, so nothing is lost to classification.
66        message: String,
67        command: String,
68        exit_code: i32,
69        working_dir: Option<PathBuf>,
70    },
71
72    /// The CLI rejected the configuration before running.
73    ///
74    /// An unknown key under `--strict-config`, or a malformed override.
75    #[error("codex rejected the configuration: {}", first_line(message))]
76    Config {
77        /// The CLI's stderr, trimmed.
78        message: String,
79        command: String,
80        exit_code: i32,
81        working_dir: Option<PathBuf>,
82    },
83
84    /// The working directory is not a trusted directory or git repo, and
85    /// `--skip-git-repo-check` was not set.
86    #[error("codex refused an untrusted directory: {}", first_line(message))]
87    NotTrustedDirectory {
88        /// The CLI's stderr, trimmed.
89        message: String,
90        command: String,
91        exit_code: i32,
92        working_dir: Option<PathBuf>,
93    },
94
95    /// The session or thread being resumed does not exist.
96    #[error("codex session not found: {}", first_line(message))]
97    SessionNotFound {
98        /// The CLI's stderr, trimmed.
99        message: String,
100        command: String,
101        exit_code: i32,
102        working_dir: Option<PathBuf>,
103    },
104
105    /// A codex command failed with a non-zero exit code.
106    #[error("codex command failed: {command} (exit code {exit_code}){}{}{}", working_dir.as_ref().map(|d| format!(" (in {})", d.display())).unwrap_or_default(), if stdout.is_empty() { String::new() } else { format!("\nstdout: {stdout}") }, if stderr.is_empty() { String::new() } else { format!("\nstderr: {stderr}") })]
107    CommandFailed {
108        command: String,
109        exit_code: i32,
110        stdout: String,
111        stderr: String,
112        working_dir: Option<PathBuf>,
113    },
114
115    /// An I/O error occurred while spawning or communicating with the process.
116    #[error("io error: {message}{}", working_dir.as_ref().map(|d| format!(" (in {})", d.display())).unwrap_or_default())]
117    Io {
118        message: String,
119        #[source]
120        source: std::io::Error,
121        working_dir: Option<PathBuf>,
122    },
123
124    /// The command timed out.
125    #[error("codex command timed out after {timeout_seconds}s")]
126    Timeout { timeout_seconds: u64 },
127
128    /// A session's token budget was reached.
129    ///
130    /// Denominated in tokens rather than money because the CLI reports token
131    /// counts and no cost; see [`crate::budget`].
132    #[error("token budget exceeded: {total_tokens} of {max_tokens} tokens")]
133    TokenBudgetExceeded {
134        /// Tokens recorded when the ceiling was hit. May exceed `max_tokens`,
135        /// since a turn's usage is only known once it has been spent.
136        total_tokens: u64,
137        /// The configured ceiling.
138        max_tokens: u64,
139    },
140
141    /// A native rollout-budget configuration was invalid before launch.
142    #[error("invalid Codex rollout budget: {message}")]
143    InvalidRolloutBudget {
144        /// The failed invariant.
145        message: String,
146    },
147
148    /// A file on disk could not be parsed.
149    ///
150    /// Distinct from [`Error::Config`], which is the CLI rejecting a
151    /// configuration it was given. This one never ran a command, so it
152    /// carries no exit code and is not a [`FailureKind`].
153    #[cfg(feature = "config")]
154    #[error("failed to parse {}: {message}", path.display())]
155    ConfigParse {
156        /// The file that could not be parsed.
157        path: PathBuf,
158        /// The parser's message.
159        message: String,
160    },
161
162    /// A bypass of codex's safety controls was requested without permission.
163    ///
164    /// See [`crate::dangerous`]. Never a command failure: nothing ran.
165    #[error("bypassing codex safety controls requires {variable} to be set")]
166    DangerousNotAllowed {
167        /// The environment variable that would have permitted it.
168        variable: &'static str,
169    },
170
171    /// The run was cancelled by the caller.
172    ///
173    /// The process group was asked to stop, given `grace_seconds`, then
174    /// killed. Distinct from [`Error::Timeout`], which is the client's own
175    /// deadline rather than the caller's decision.
176    #[error("codex run cancelled (after a {grace_seconds}s grace period)")]
177    Cancelled {
178        /// How long the group was given to exit before being killed.
179        grace_seconds: u64,
180    },
181
182    /// JSON parsing failed.
183    #[cfg(feature = "json")]
184    #[error("json parse error: {message}")]
185    Json {
186        message: String,
187        #[source]
188        source: serde_json::Error,
189    },
190
191    /// The installed CLI version does not meet the minimum requirement.
192    #[error("CLI version {found} does not meet minimum requirement {minimum}")]
193    VersionMismatch {
194        found: crate::version::CliVersion,
195        minimum: crate::version::CliVersion,
196    },
197
198    /// The installed CLI is outside the wrapper's tested-against range.
199    ///
200    /// Only returned by
201    /// [`Codex::ensure_tested_cli_version`](crate::Codex::ensure_tested_cli_version).
202    /// The default path reports drift as a
203    /// [`CliVersionStatus`](crate::CliVersionStatus) rather than an error.
204    #[error("CLI version {found} is outside the tested range {tested_min}..={tested_max}")]
205    UntestedCliVersion {
206        found: crate::version::CliVersion,
207        tested_min: crate::version::CliVersion,
208        tested_max: crate::version::CliVersion,
209    },
210
211    // Add new variants at the end of the enum, below the last one. The enum has no
212    // `#[repr]`, so inserting a variant earlier shifts the implicit
213    // discriminant of every variant after it, which `cargo-semver-checks`
214    // reports as a breaking change (`enum_no_repr_variant_discriminant_changed`)
215    // and which makes release-plz propose a major version. `Error` carries
216    // data, so no caller can read those values with `as`; the lint is stricter
217    // than it needs to be, and it still decides the version.
218    /// `codex app-server` answered a request with a JSON-RPC error.
219    ///
220    /// `code` and `message` are the server's own. `method` is the request that
221    /// failed, for example `turn/steer`.
222    #[cfg(feature = "app-server")]
223    #[error("codex app-server rejected `{method}`: {message} (code {code})")]
224    AppServerRpc {
225        /// The request method that was rejected.
226        method: String,
227        /// The JSON-RPC error code.
228        code: i64,
229        /// The server's error message.
230        message: String,
231        /// Additional error data, when the server sent any.
232        data: Option<serde_json::Value>,
233    },
234
235    /// The connection to `codex app-server` failed, or the server sent
236    /// something that is not valid JSON-RPC.
237    ///
238    /// Covers the server exiting or being stopped while a request was waiting,
239    /// a session that has already ended, and a stream that could not be read or
240    /// written. When the server wrote to stderr, the last lines are included.
241    #[cfg(feature = "app-server")]
242    #[error("codex app-server protocol error: {message}")]
243    AppServerProtocol {
244        /// What went wrong.
245        message: String,
246    },
247
248    /// A run was being stopped, and stopping or reaping its process failed.
249    ///
250    /// Cancellation, a timeout, an exceeded output limit, a parse error, or an
251    /// I/O error on the child's pipes each end a run by terminating the owned
252    /// process group and waiting on the direct child. When that cleanup
253    /// succeeds the original error is returned unchanged. When it fails, this
254    /// is returned instead, so a caller is never told [`Error::Cancelled`] or
255    /// [`Error::Timeout`] about a child that may not have been reaped and could
256    /// still be running.
257    ///
258    /// Match on `reason` for why the run was stopped. `cleanup` is the
259    /// [`source`](std::error::Error::source) of this error, so a reporter
260    /// walking the chain reaches the underlying I/O failure.
261    ///
262    /// Not retried by [`RetryPolicy`](crate::RetryPolicy), even when `reason`
263    /// is a timeout: the previous attempt's process is not known to be gone.
264    #[error("{reason}; cleanup of the codex process then failed, so it may not have been reaped")]
265    CleanupFailed {
266        /// The error the run would have returned had cleanup succeeded.
267        reason: Box<Error>,
268        /// The failure from stopping or waiting on the child.
269        #[source]
270        cleanup: Box<Error>,
271    },
272
273    /// An opt-in `codex app-server` transport limit was exceeded.
274    ///
275    /// Set with the `max_*` methods on
276    /// [`AppServerBuilder`](crate::app_server::AppServerBuilder). The
277    /// connection is ended rather than a message dropped: every waiting
278    /// request fails with this error, later sends fail at once, and the
279    /// process the client owns is killed. Distinct from
280    /// [`Error::OutputLimitExceeded`], which is the lifetime total of
281    /// [`CodexBuilder::output_limit`](crate::CodexBuilder::output_limit).
282    #[cfg(feature = "app-server")]
283    #[error("codex app-server {limit} limit of {max} exceeded")]
284    AppServerLimitExceeded {
285        /// Which limit was exceeded.
286        limit: crate::app_server::AppServerLimit,
287        /// The configured maximum.
288        max: usize,
289    },
290
291    /// An [`AppServerBuilder`](crate::app_server::AppServerBuilder) setting is
292    /// invalid. Reported by `start` before anything is spawned.
293    #[cfg(feature = "app-server")]
294    #[error("invalid codex app-server configuration: {message}")]
295    AppServerConfig {
296        /// What is wrong with the configuration.
297        message: String,
298    },
299}
300
301impl From<std::io::Error> for Error {
302    fn from(e: std::io::Error) -> Self {
303        Self::Io {
304            message: e.to_string(),
305            source: e,
306            working_dir: None,
307        }
308    }
309}
310
311/// Result type alias for codex-wrapper operations.
312pub type Result<T> = std::result::Result<T, Error>;
313
314/// The first non-empty line of a message, for a one-line `Display`.
315fn first_line(message: &str) -> &str {
316    message
317        .lines()
318        .map(str::trim)
319        .find(|line| !line.is_empty())
320        .unwrap_or(message)
321}
322
323/// The class of a failed command, for matching without destructuring.
324///
325/// Returned by [`Error::failure_kind`].
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327#[non_exhaustive]
328pub enum FailureKind {
329    /// The CLI could not authenticate.
330    Auth,
331    /// The CLI rejected the configuration before running.
332    Config,
333    /// The working directory was not trusted.
334    NotTrustedDirectory,
335    /// The session or thread being resumed does not exist.
336    SessionNotFound,
337    /// A non-zero exit that matched no known signature.
338    Unclassified,
339}
340
341/// Signatures observed on `codex-cli` 0.145.0, each from a captured failing
342/// run. Matched against stderr, since every one of them exits 1: the exit code
343/// carries no information here.
344///
345/// Deliberately matched on the stable part of each message. The auth line, for
346/// instance, also carries a request id and a `cf-ray` header that differ every
347/// time.
348const SIGNATURES: &[(&str, FailureKind)] = &[
349    ("401 Unauthorized", FailureKind::Auth),
350    ("Missing bearer or basic authentication", FailureKind::Auth),
351    (
352        "Not inside a trusted directory",
353        FailureKind::NotTrustedDirectory,
354    ),
355    ("Error loading config.toml", FailureKind::Config),
356    ("unknown configuration field", FailureKind::Config),
357    (
358        "no rollout found for thread id",
359        FailureKind::SessionNotFound,
360    ),
361];
362
363impl Error {
364    /// The error to return for a run stopped with `reason`, given how cleanup
365    /// of its process went.
366    ///
367    /// Every path that stops a child before returning goes through here, so
368    /// a failed cleanup cannot be reported as the bare stop reason.
369    pub(crate) fn after_cleanup(reason: Error, cleanup: Result<()>) -> Self {
370        match cleanup {
371            Ok(()) => reason,
372            Err(cleanup) => Error::CleanupFailed {
373                reason: Box::new(reason),
374                cleanup: Box::new(cleanup),
375            },
376        }
377    }
378
379    /// Build an error from a failed command, classifying it by stderr.
380    ///
381    /// Every non-zero exit in this crate goes through here, so a caller can
382    /// branch on the class rather than substring-matching stderr themselves.
383    /// An unrecognized failure stays [`Error::CommandFailed`] with its output
384    /// intact, so classification never loses information.
385    ///
386    /// Classification is by message, because it has to be: every failure
387    /// observed on 0.145.0 exits 1. That makes it sensitive to the CLI
388    /// rewording a message, which is the cost of doing it here instead of in
389    /// every caller. `tests/contract.rs` is where a reworded message should be
390    /// caught.
391    #[must_use]
392    pub fn from_command_failure(
393        command: String,
394        exit_code: i32,
395        stdout: String,
396        stderr: String,
397        working_dir: Option<PathBuf>,
398    ) -> Self {
399        let message = stderr.trim().to_string();
400
401        let kind = SIGNATURES
402            .iter()
403            .find(|(needle, _)| message.contains(needle))
404            .map(|(_, kind)| *kind);
405
406        match kind {
407            Some(FailureKind::Auth) => Error::Auth {
408                message,
409                command,
410                exit_code,
411                working_dir,
412            },
413            Some(FailureKind::Config) => Error::Config {
414                message,
415                command,
416                exit_code,
417                working_dir,
418            },
419            Some(FailureKind::NotTrustedDirectory) => Error::NotTrustedDirectory {
420                message,
421                command,
422                exit_code,
423                working_dir,
424            },
425            Some(FailureKind::SessionNotFound) => Error::SessionNotFound {
426                message,
427                command,
428                exit_code,
429                working_dir,
430            },
431            _ => Error::CommandFailed {
432                command,
433                exit_code,
434                stdout,
435                stderr,
436                working_dir,
437            },
438        }
439    }
440
441    /// The class of this failure, or `None` if it is not a command failure.
442    #[must_use]
443    pub fn failure_kind(&self) -> Option<FailureKind> {
444        match self {
445            Error::Auth { .. } => Some(FailureKind::Auth),
446            Error::Config { .. } => Some(FailureKind::Config),
447            Error::NotTrustedDirectory { .. } => Some(FailureKind::NotTrustedDirectory),
448            Error::SessionNotFound { .. } => Some(FailureKind::SessionNotFound),
449            Error::CommandFailed { .. } => Some(FailureKind::Unclassified),
450            _ => None,
451        }
452    }
453
454    /// The process exit code, for any variant that came from one.
455    ///
456    /// Classification moved some failures off [`Error::CommandFailed`], so
457    /// anything reading an exit code should read it here rather than matching
458    /// that one variant.
459    #[must_use]
460    pub fn exit_code(&self) -> Option<i32> {
461        match self {
462            Error::CommandFailed { exit_code, .. }
463            | Error::Auth { exit_code, .. }
464            | Error::Config { exit_code, .. }
465            | Error::NotTrustedDirectory { exit_code, .. }
466            | Error::SessionNotFound { exit_code, .. } => Some(*exit_code),
467            _ => None,
468        }
469    }
470
471    /// Whether re-running the identical command could plausibly succeed.
472    ///
473    /// False for the classified failures: each is a deterministic rejection,
474    /// and the CLI has already retried the auth case internally before it
475    /// surfaces here.
476    #[must_use]
477    pub fn is_deterministic_failure(&self) -> bool {
478        matches!(
479            self,
480            Error::Auth { .. }
481                | Error::Config { .. }
482                | Error::NotTrustedDirectory { .. }
483                | Error::SessionNotFound { .. }
484        )
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    #[test]
493    fn display_not_found() {
494        let err = Error::NotFound;
495        assert_eq!(err.to_string(), "codex binary not found in PATH");
496    }
497
498    #[test]
499    fn display_command_failed_minimal() {
500        let err = Error::CommandFailed {
501            command: "exec".to_string(),
502            exit_code: 1,
503            stdout: String::new(),
504            stderr: String::new(),
505            working_dir: None,
506        };
507        assert_eq!(err.to_string(), "codex command failed: exec (exit code 1)");
508    }
509
510    #[test]
511    fn display_command_failed_with_all_fields() {
512        let err = Error::CommandFailed {
513            command: "exec".to_string(),
514            exit_code: 2,
515            stdout: "out".to_string(),
516            stderr: "err".to_string(),
517            working_dir: Some(PathBuf::from("/tmp")),
518        };
519        assert_eq!(
520            err.to_string(),
521            "codex command failed: exec (exit code 2) (in /tmp)\nstdout: out\nstderr: err"
522        );
523    }
524
525    #[test]
526    fn display_io_without_working_dir() {
527        let source = std::io::Error::other("disk full");
528        let err = Error::Io {
529            message: source.to_string(),
530            source,
531            working_dir: None,
532        };
533        assert_eq!(err.to_string(), "io error: disk full");
534    }
535
536    #[test]
537    fn display_io_with_working_dir() {
538        let source = std::io::Error::other("disk full");
539        let err = Error::Io {
540            message: source.to_string(),
541            source,
542            working_dir: Some(PathBuf::from("/home/user")),
543        };
544        assert_eq!(err.to_string(), "io error: disk full (in /home/user)");
545    }
546
547    #[test]
548    fn display_timeout() {
549        let err = Error::Timeout {
550            timeout_seconds: 30,
551        };
552        assert_eq!(err.to_string(), "codex command timed out after 30s");
553    }
554
555    #[cfg(feature = "json")]
556    #[test]
557    fn display_json() {
558        let source: serde_json::Error =
559            serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
560        let err = Error::Json {
561            message: source.to_string(),
562            source,
563        };
564        assert!(err.to_string().starts_with("json parse error:"));
565    }
566
567    #[test]
568    fn display_version_mismatch() {
569        let err = Error::VersionMismatch {
570            found: crate::version::CliVersion::new(0, 100, 0),
571            minimum: crate::version::CliVersion::new(0, 145, 0),
572        };
573        assert_eq!(
574            err.to_string(),
575            "CLI version 0.100.0 does not meet minimum requirement 0.145.0"
576        );
577    }
578
579    // ---------------------------------------------------------------
580    // Classification (#85)
581    // ---------------------------------------------------------------
582
583    fn classify(stderr: &str) -> Error {
584        Error::from_command_failure(
585            "codex exec hi".into(),
586            1,
587            String::new(),
588            stderr.into(),
589            None,
590        )
591    }
592
593    /// Each string is transcribed from a captured codex-cli 0.145.0 failure,
594    /// varying parts and all.
595    #[test]
596    fn classifies_every_captured_signature() {
597        let cases: &[(&str, FailureKind)] = &[
598            (
599                "ERROR: unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: a272310168bcba62-SJC, request id: req_ef11",
600                FailureKind::Auth,
601            ),
602            (
603                "Not inside a trusted directory and --skip-git-repo-check was not specified.",
604                FailureKind::NotTrustedDirectory,
605            ),
606            (
607                "Error loading config.toml: unknown configuration field `bogus` in -c/--config override",
608                FailureKind::Config,
609            ),
610            (
611                "Error: thread/resume: thread/resume failed: no rollout found for thread id 00000000-0000-0000-0000-000000000000 (code -32600)",
612                FailureKind::SessionNotFound,
613            ),
614        ];
615
616        for (stderr, expected) in cases {
617            let err = classify(stderr);
618            assert_eq!(
619                err.failure_kind(),
620                Some(*expected),
621                "misclassified: {stderr}"
622            );
623            assert_eq!(err.exit_code(), Some(1));
624            assert!(err.is_deterministic_failure(), "{stderr}");
625        }
626    }
627
628    /// An unrecognized failure must keep its output rather than being forced
629    /// into a class. Classification is allowed to not know.
630    #[test]
631    fn an_unknown_failure_stays_command_failed_with_its_output() {
632        let err = Error::from_command_failure(
633            "codex exec hi".into(),
634            2,
635            "partial stdout".into(),
636            "something new the CLI started saying".into(),
637            None,
638        );
639
640        assert_eq!(err.failure_kind(), Some(FailureKind::Unclassified));
641        assert!(!err.is_deterministic_failure());
642        match err {
643            Error::CommandFailed {
644                stdout,
645                stderr,
646                exit_code,
647                ..
648            } => {
649                assert_eq!(stdout, "partial stdout");
650                assert_eq!(stderr, "something new the CLI started saying");
651                assert_eq!(exit_code, 2);
652            }
653            other => panic!("expected CommandFailed, got {other:?}"),
654        }
655    }
656
657    /// The whole of stderr is kept, not just the matched line, so nothing is
658    /// lost to classification.
659    #[test]
660    fn a_classified_failure_keeps_the_full_message() {
661        let err = classify(
662            "ERROR: Reconnecting... 5/5\nERROR: unexpected status 401 Unauthorized: Missing bearer",
663        );
664        match &err {
665            Error::Auth { message, .. } => {
666                assert!(message.contains("Reconnecting... 5/5"), "{message}");
667                assert!(message.contains("401 Unauthorized"), "{message}");
668            }
669            other => panic!("expected Auth, got {other:?}"),
670        }
671        // Display stays one line, leading with the first thing stderr said.
672        assert_eq!(
673            err.to_string(),
674            "codex authentication failed: ERROR: Reconnecting... 5/5"
675        );
676    }
677
678    #[test]
679    fn successful_cleanup_returns_the_stop_reason_unchanged() {
680        let err = Error::after_cleanup(Error::Timeout { timeout_seconds: 7 }, Ok(()));
681        assert!(
682            matches!(err, Error::Timeout { timeout_seconds: 7 }),
683            "{err:?}"
684        );
685    }
686
687    /// The reason stays matchable and readable, and the cleanup failure is
688    /// the source, so walking the chain reaches the I/O error beneath it.
689    #[test]
690    fn failed_cleanup_carries_the_reason_and_chains_to_the_cleanup_error() {
691        let cleanup = Error::from(std::io::Error::other("wait failed"));
692        let err = Error::after_cleanup(Error::Cancelled { grace_seconds: 2 }, Err(cleanup));
693
694        assert_eq!(
695            err.to_string(),
696            "codex run cancelled (after a 2s grace period); cleanup of the codex process \
697             then failed, so it may not have been reaped"
698        );
699        let Error::CleanupFailed { reason, .. } = &err else {
700            panic!("expected CleanupFailed, got {err:?}");
701        };
702        assert!(
703            matches!(**reason, Error::Cancelled { grace_seconds: 2 }),
704            "{reason:?}"
705        );
706
707        let source = std::error::Error::source(&err).expect("cleanup is the source");
708        assert_eq!(source.to_string(), "io error: wait failed");
709        let io = source.source().expect("the I/O error is reachable");
710        assert_eq!(io.to_string(), "wait failed");
711
712        // The child did not exit on its own terms, so no exit code is
713        // reported even if the wrapped reason were to carry one.
714        assert_eq!(err.failure_kind(), None);
715        assert_eq!(err.exit_code(), None);
716    }
717
718    #[test]
719    fn non_command_errors_have_no_failure_kind() {
720        assert_eq!(Error::NotFound.failure_kind(), None);
721        assert_eq!(Error::Timeout { timeout_seconds: 5 }.failure_kind(), None);
722        assert_eq!(Error::NotFound.exit_code(), None);
723    }
724}