processkit 1.0.1

Async child-process management for tokio: whole-tree kill-on-drop (no orphans), plus streaming, pipelines, timeouts, and supervision
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
//! The crate's error type.

use std::fmt;
use std::time::Duration;

/// Errors produced when launching or running a child process.
///
/// Spawn failures, a non-zero exit ([`Exit`](Error::Exit)), timeouts, and IO
/// errors fold into one structured enum, so callers can pattern-match on the
/// failure mode instead of parsing strings.
///
/// `Debug` is **manual, not derived**: the [`Exit`](Error::Exit) variant
/// carries both captured streams in full, and a derived `Debug` would dump them
/// — potentially multi-MiB — into a `{e:?}` log line or an `.unwrap()` panic
/// message. The manual impl bounds each stream to a 200-byte preview (mirroring
/// the [`Display`](std::fmt::Display) tail cap) and redacts
/// [`NotFound`](Error::NotFound)'s
/// `searched` (the `PATH` env value) to a directory count, honoring the crate's
/// "never log environment values" rule. The exact streams remain reachable via
/// the public fields.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The child process could not be started (binary not found, permission
    /// denied, …).
    #[error("could not start `{program}`: {source}")]
    Spawn {
        /// The program we tried to launch.
        program: String,
        /// The underlying OS error.
        #[source]
        source: std::io::Error,
    },

    /// The program could not be located, so no child was ever started — it is
    /// not installed, not on `PATH`, or the given path does not resolve to an
    /// executable. The **single** representation of "program not found": the
    /// launch path routes every such failure here regardless of how the program
    /// was named (bare name vs path) or platform, so a caller matches one
    /// variant and [`is_not_found`](Error::is_not_found) classifies it.
    ///
    /// Distinct from [`Spawn`](Error::Spawn), which covers OS-level failures
    /// once the program *is* located (permission denied, busy, a bad working
    /// directory, a `.cmd`/`.bat` on Windows that needs `cmd.exe`, etc.) —
    /// those are **not** `is_not_found`.
    ///
    /// The `searched` cause is structured: `Some(dirs)` when a bare name was
    /// looked up against `PATH` (the directories searched), `None` when the
    /// program was given as a path or `PATH` was customized (no `PATH` search
    /// applied, so there are no directories to name).
    ///
    /// The `Display` message intentionally omits `searched` — `PATH` is an
    /// environment value and must never appear in logs per the crate's
    /// security policy. Access `searched` directly for a diagnostic. The message
    /// says "on PATH" only when a `PATH` search actually happened (`searched` is
    /// `Some`); a path-form or customized-PATH program reads simply "not found".
    #[error("{}", display_not_found(program, searched))]
    NotFound {
        /// The program name that was looked up.
        program: String,
        /// The `PATH` directories searched, joined by the platform separator
        /// (`:` on Unix, `;` on Windows) — `Some` for a bare-name PATH lookup
        /// (empty string when `PATH` is unset), `None` when no PATH search
        /// applied (a path-form program, or a customized PATH). Not included in
        /// `Display`; use it directly when building a user-facing diagnostic.
        searched: Option<String>,
    },

    /// A cassette replay found **no recording** matching the invocation — a
    /// stale or incomplete cassette, not a missing program. Kept distinct
    /// from [`Spawn`](Error::Spawn) / [`NotFound`](Error::NotFound) so a wrapper
    /// that treats "tool not installed" as an *optional* dependency does not
    /// silently swallow a stale cassette as an absent tool.
    ///
    /// [`is_not_found`](Error::is_not_found) returns `false` for this variant.
    #[error(
        "`{program}`: no cassette entry matches this invocation (stale or incomplete cassette)"
    )]
    CassetteMiss {
        /// The program whose invocation found no recording.
        program: String,
    },

    /// The process ran to completion but exited with a non-zero status.
    ///
    /// Produced by the `ensure_success` helpers; the raw exit code is otherwise
    /// reported without erroring (a non-zero exit is not inherently a failure).
    ///
    /// Both captured streams are carried **in full**: `git`/`jj` write decisive
    /// diagnostics to **stdout** on failure (`CONFLICT (content): …`, `nothing to
    /// commit, working tree clean`), so a caller building a user-facing message
    /// wants stdout as a fallback when stderr is empty — see
    /// [`diagnostic`](Self::diagnostic). Consumers also classify on these fields
    /// (grep for a marker, parse a sub-code), so they are never truncated before
    /// the caller sees them; only the `Display` message below is bounded.
    ///
    /// The one-line `Display` message appends the **last non-empty line** of
    /// [`diagnostic`](Self::diagnostic), capped at 200 bytes — `` `git` exited
    /// with code 2: fatal: boom `` — actionable in a log line without dumping
    /// multi-KiB streams into it.
    #[error("{}", display_exit(program, *code, stdout, stderr))]
    Exit {
        /// The program that exited non-zero.
        program: String,
        /// The raw process exit code.
        code: i32,
        /// Captured standard output, in full. Not shown in the `Display`
        /// message; kept for callers that need a stdout-borne failure message.
        /// For the raw-bytes helper (`output_bytes`) this is a lossy UTF-8 decode
        /// of stdout — the exact bytes remain on the originating `ProcessResult`.
        stdout: String,
        /// Captured standard error, in full. Only its **last non-empty
        /// line** (bounded) appears in the `Display` message — the complete
        /// captured text lives here, never poisoning a log line.
        stderr: String,
    },

    /// The process exceeded its configured timeout and was killed.
    ///
    /// Carries whatever the run captured **before** the deadline killed it:
    /// a hung tool's partial stderr is frequently the explanation
    /// (`waiting for lock held by pid 4123`, `connecting to db…`), so it is
    /// reachable via [`diagnostic`](Self::diagnostic) and the public fields
    /// rather than lost. Empty when the producing path captured nothing (a
    /// streaming probe such as `first_line`, which never buffers).
    ///
    /// The one-line `Display` message appends the **last non-empty line** of
    /// [`diagnostic`](Self::diagnostic), capped at 200 bytes — just like
    /// [`Exit`](Error::Exit) — so a log line stays actionable without dumping
    /// the captured streams.
    #[error("{}", display_timeout(program, *timeout, stdout, stderr))]
    Timeout {
        /// The program that timed out.
        program: String,
        /// The deadline that elapsed.
        timeout: Duration,
        /// Standard output captured before the kill, in full. Not shown in the
        /// `Display` message (only its bounded diagnostic tail is). Empty when
        /// the path captured nothing. For the raw-bytes helper this is a lossy
        /// UTF-8 decode; the exact bytes remain on the originating
        /// `ProcessResult`.
        stdout: String,
        /// Standard error captured before the kill, in full — often the
        /// explanation of *why* the tool hung. Only its last non-empty line
        /// (bounded) reaches the `Display` message.
        stderr: String,
    },

    /// The captured output exceeded the
    /// [`OverflowMode::Error`](crate::OverflowMode::Error) fail-loud ceiling —
    /// a line cap ([`max_lines`](crate::OutputBufferPolicy::max_lines)), a byte
    /// cap ([`max_bytes`](crate::OutputBufferPolicy::max_bytes)), or both. The
    /// run itself may have succeeded; this error is raised by the consuming
    /// path after the run completes.
    ///
    /// The pipe is still fully drained (the child never blocks); output past
    /// the ceiling is counted (in the totals) but not retained.
    #[error(
        "`{program}` output exceeded its capture ceiling ({total_lines} lines, {total_bytes} bytes total)"
    )]
    OutputTooLarge {
        /// The program whose output exceeded the ceiling.
        program: String,
        /// The configured line ceiling, if any
        /// (`OutputBufferPolicy::max_lines`).
        line_limit: Option<usize>,
        /// The configured byte ceiling, if any
        /// (`OutputBufferPolicy::max_bytes`).
        byte_limit: Option<usize>,
        /// Total lines that arrived (retained + dropped).
        total_lines: usize,
        /// Total bytes of decoded line text seen (retained + dropped) — the
        /// same unit [`max_bytes`](crate::OutputBufferPolicy::max_bytes) caps:
        /// the sum of line lengths with the trailing newline (and one `\r`)
        /// stripped, not the raw stream size.
        total_bytes: usize,
    },

    /// A readiness probe ([`RunningProcess::wait_for_line`],
    /// [`wait_for_port`](crate::RunningProcess::wait_for_port),
    /// [`wait_for`](crate::RunningProcess::wait_for)) did not pass within its
    /// deadline — the line never appeared, the port never accepted, the check
    /// never returned `true`, or the child exited before becoming ready.
    ///
    /// Distinct from [`Timeout`](Error::Timeout): a probe deadline is separate
    /// from the run's own [`Command::timeout`](crate::Command::timeout), and a
    /// failed probe does **not** kill the child — the caller decides what
    /// happens next.
    ///
    /// [`RunningProcess::wait_for_line`]: crate::RunningProcess::wait_for_line
    #[error("`{program}` was not ready after {timeout:?}")]
    NotReady {
        /// The program that did not become ready.
        program: String,
        /// The probe deadline that elapsed (or would have — an early child
        /// exit fails the probe immediately).
        timeout: Duration,
    },

    /// The process succeeded but its output could not be parsed into the
    /// expected shape (e.g. malformed `--json`). Produced by the fallible-parse
    /// helpers `try_parse` on [`Command`](crate::Command),
    /// [`ProcessRunnerExt`](crate::ProcessRunnerExt),
    /// [`CliClient`](crate::CliClient), and [`Pipeline`](crate::Pipeline) (or any
    /// parser the caller maps into this variant).
    ///
    /// `message` is caller-built and routinely embeds the unparsed output in
    /// full, so — like the [`Exit`](Error::Exit) streams — both `Display` and
    /// `Debug` bound it to a 200-byte preview; the complete text stays
    /// reachable via the public field.
    #[error("{}", display_parse(program, message))]
    Parse {
        /// The program whose output failed to parse.
        program: String,
        /// What went wrong. Carried in full; only `Display`/`Debug` are bounded.
        message: String,
    },

    /// A requested resource limit could not be enforced.
    ///
    /// Produced by [`ProcessGroup::with_options`](crate::ProcessGroup::with_options)
    /// when a [`ResourceLimits`](crate::ResourceLimits) cap was set but the active
    /// mechanism can't honor it — either the platform has no whole-tree container
    /// (macOS/BSD, the Linux process-group fallback), or
    /// the OS rejected the request (on Linux, the cgroup controllers can't be
    /// enabled — see [`ResourceLimits`](crate::ResourceLimits) for the cgroup-v2
    /// "real root only" requirement). An unenforced limit is no protection, so this
    /// is raised rather than leaving the tree silently unbounded.
    #[cfg(feature = "limits")]
    #[error("could not enforce resource limits: {message}")]
    ResourceLimit {
        /// Human-readable detail of which limit could not be enforced and why.
        message: String,
    },

    /// An operation is not supported by the active containment mechanism on
    /// this platform.
    ///
    /// Raised by `ProcessGroup::signal` for any signal other than
    /// `Signal::Kill` on Windows (Job Objects have no POSIX signals).
    #[error("operation `{operation}` is not supported on this platform")]
    Unsupported {
        /// A short description of the operation, e.g. `"signal(Hup)"` or
        /// `"suspend"`.
        operation: String,
    },

    /// The run was cancelled via its `CancellationToken`
    /// ([`Command::cancel_on`](crate::Command::cancel_on)) and its process
    /// tree was killed.
    ///
    /// Asymmetric with [`Timeout`](Error::Timeout) by design: a timeout is
    /// *captured* (`ProcessResult::timed_out`) on the non-checking paths,
    /// whereas a cancellation is **always** raised on every consuming path.
    /// When a run both times out and is cancelled, cancellation wins (it is
    /// checked first).
    ///
    /// Unlike [`Timeout`](Error::Timeout) / [`Signalled`](Error::Signalled),
    /// this carries **no captured streams**: cancellation is a deliberate
    /// caller action that stops the run *immediately*. On the pre-spawn path (the
    /// token was already cancelled) nothing was captured at all; on the consuming
    /// verbs, any output captured before the kill is **intentionally discarded** —
    /// the caller initiated the stop and knows why, so a partial diagnostic would
    /// be noise. [`diagnostic`](Self::diagnostic) returns `None`.
    #[error("`{program}` was cancelled")]
    Cancelled {
        /// The program that was cancelled.
        program: String,
    },

    /// The process was terminated by a signal (Unix) without producing an exit
    /// code. `signal` carries the signal number when the platform reports one
    /// (`None` on Windows or when the kernel does not expose it).
    ///
    /// Distinct from [`Exit`](Error::Exit): a signal-terminated run has no exit
    /// code to check — it is always a failure. Produced by
    /// [`ensure_success`](crate::ProcessResult::ensure_success) and the
    /// `require_code` path when the outcome is
    /// [`Outcome::Signalled`](crate::Outcome::Signalled).
    ///
    /// Carries whatever the run captured before the signal killed it — a
    /// crashing tool's partial stderr is often the diagnostic — reachable via
    /// [`diagnostic`](Self::diagnostic) and the public fields. The one-line
    /// `Display` appends the bounded diagnostic tail, like [`Exit`](Error::Exit).
    #[error("{}", display_signalled(program, *signal, stdout, stderr))]
    Signalled {
        /// The program that was killed by a signal.
        program: String,
        /// The signal number, when reported by the platform.
        signal: Option<i32>,
        /// Standard output captured before the kill, in full. Not shown in the
        /// `Display` message (only its bounded diagnostic tail is). For the
        /// raw-bytes helper this is a lossy UTF-8 decode of stdout.
        stdout: String,
        /// Standard error captured before the kill, in full. Only its last
        /// non-empty line (bounded) reaches the `Display` message.
        stderr: String,
    },

    /// The child ran but feeding its standard input failed for a reason other
    /// than the routine broken pipe.
    ///
    /// This is raised by the consuming paths **only when the
    /// run otherwise succeeded** — a non-zero [`Exit`](Error::Exit), a
    /// [`Signalled`](Error::Signalled), or a [`Timeout`](Error::Timeout) is the
    /// "realer" failure and wins (the stdin error is then dropped). A broken
    /// pipe (`EPIPE` / `ERROR_BROKEN_PIPE` — the child closing stdin before
    /// reading all of it) is routine and **never** surfaces. Diagnoses a
    /// silently-truncated input the otherwise-successful child may have acted on.
    /// The stdin source ([`Command::stdin`](crate::Command::stdin))
    /// is written on a background task; this carries that task's failure.
    ///
    /// The io-level classifiers ([`is_transient`](Error::is_transient),
    /// [`is_not_found`](Error::is_not_found),
    /// [`is_permission_denied`](Error::is_permission_denied)) deliberately return
    /// `false` here: they classify spawn/launch conditions, and the run already
    /// *succeeded* — a blanket retry would re-run a command that worked. Inspect
    /// `source` directly if a stdin-specific retry is wanted.
    #[error("failed to write to `{program}` stdin: {source}")]
    Stdin {
        /// The program whose standard-input write failed.
        program: String,
        /// The underlying IO error (never a broken pipe).
        #[source]
        source: std::io::Error,
    },

    /// A low-level IO error from the crate's own machinery — driving a child
    /// (waiting for exit, issuing a kill), controlling a process group
    /// (signalling, reaping, sampling stats), or reading/writing a cassette
    /// file. It is **not** a spawn/launch condition (those are
    /// [`Spawn`](Error::Spawn) / [`NotFound`](Error::NotFound)).
    ///
    /// There is **deliberately no blanket `From<std::io::Error>`**: the
    /// crate never lets an arbitrary foreign `io::Error` fall into this variant
    /// via `?`. Every `Io` is constructed explicitly at a known site, so the
    /// io-level classifiers ([`is_transient`](Error::is_transient),
    /// [`is_permission_denied`](Error::is_permission_denied)) only ever see an
    /// IO error the crate itself produced — never an unrelated one a caller's
    /// `?` happened to route through here.
    #[error(transparent)]
    Io(std::io::Error),
}

impl Error {
    /// The best human-facing message for a failed run, trimmed of surrounding
    /// whitespace: captured standard error if it carries text, otherwise the
    /// captured standard output (where `git` puts `CONFLICT …` and `git commit`
    /// puts `nothing to commit`). Covers the variants that capture streams — a
    /// non-zero [`Exit`](Error::Exit), a [`Timeout`](Error::Timeout) (the partial
    /// output of a hung-then-killed tool), and a [`Signalled`](Error::Signalled)
    /// crash. Returns `None` when there is no captured output to show — a silent
    /// run (both streams blank) or a variant that carries none
    /// ([`Spawn`](Error::Spawn), [`Cancelled`](Error::Cancelled),
    /// [`Parse`](Error::Parse), [`Io`](Error::Io)) — so a caller can fall back to
    /// the [`Display`](std::fmt::Display) message. For the raw, untrimmed stream
    /// match on the variant's fields directly.
    pub fn diagnostic(&self) -> Option<&str> {
        // Exhaustive on purpose: a future stream-carrying variant must add itself
        // here rather than fall through a `_ => None` and be invisible to
        // `diagnostic()`. `#[non_exhaustive]` only constrains downstream matches.
        match self {
            Error::Exit { stdout, stderr, .. }
            | Error::Timeout { stdout, stderr, .. }
            | Error::Signalled { stdout, stderr, .. } => exit_diagnostic(stdout, stderr),
            Error::Spawn { .. }
            | Error::NotFound { .. }
            | Error::CassetteMiss { .. }
            | Error::OutputTooLarge { .. }
            | Error::NotReady { .. }
            | Error::Parse { .. }
            | Error::Unsupported { .. }
            | Error::Cancelled { .. }
            | Error::Stdin { .. }
            | Error::Io(_) => None,
            #[cfg(feature = "limits")]
            Error::ResourceLimit { .. } => None,
        }
    }

    /// Whether the **program could not be located** — it is not installed, not
    /// on `PATH`, or the given path does not resolve to an executable. True for
    /// [`NotFound`](Error::NotFound) and **only** that variant: the launch
    /// path funnels every program-not-found failure into `NotFound`, so this is
    /// the one check a caller needs to surface a "command not installed?" hint.
    ///
    /// `false` for every other variant — notably it does **not** fire for a
    /// missing or invalid working directory (a [`Spawn`](Error::Spawn) carrying
    /// [`NotFound`](std::io::ErrorKind::NotFound)/`NotADirectory`): a bad `cwd`
    /// is not a missing program, so the hint would mislead. It is also `false`
    /// for a program that *is* installed but can't be executed directly (e.g. a
    /// Windows `.cmd`/`.bat` that needs `cmd.exe` — surfaced as `Spawn`).
    pub fn is_not_found(&self) -> bool {
        matches!(self, Error::NotFound { .. })
    }

    /// Whether this is a spawn/IO **permission denial** (`EACCES`/`EPERM`): the
    /// binary isn't executable, or the OS refused the launch. True for
    /// [`Spawn`](Error::Spawn) / [`Io`](Error::Io) carrying
    /// [`PermissionDenied`](std::io::ErrorKind::PermissionDenied); `false`
    /// otherwise.
    pub fn is_permission_denied(&self) -> bool {
        self.io_source()
            .is_some_and(|e| e.kind() == std::io::ErrorKind::PermissionDenied)
    }

    /// Whether this is a **transient** spawn/IO condition a bare retry can clear
    /// — interrupted (`EINTR`), would-block (`EAGAIN`), a busy resource, a
    /// text-file-busy executable mid-write (`ETXTBSY`), or a Windows sharing/lock
    /// violation. Classifies the [`Spawn`](Error::Spawn)/[`Io`](Error::Io) IO
    /// error only.
    ///
    /// **Scope: IO/spawn-level, never exit codes.** Whether a tool's non-zero
    /// [`Exit`](Error::Exit) is retryable is domain-specific (a `git` 128 is not
    /// generically transient) — that stays the caller's call. [`Timeout`](Error::Timeout)
    /// is also excluded by design; compose it if wanted:
    /// `e.is_transient() || matches!(e, Error::Timeout { .. })`.
    ///
    /// Pairs with [`Command::retry`](crate::Command::retry):
    /// `cmd.retry(3, backoff, |e| e.is_transient())`.
    pub fn is_transient(&self) -> bool {
        self.io_source().is_some_and(is_transient_io)
    }

    /// The underlying [`std::io::Error`] for the variants that carry one
    /// ([`Spawn`](Error::Spawn), [`Io`](Error::Io)) — the basis for the io-level
    /// classifiers above.
    fn io_source(&self) -> Option<&std::io::Error> {
        // Exhaustive on purpose: a future variant carrying an `io::Error` must
        // add itself here so the io-level classifiers (`is_transient`,
        // `is_permission_denied`) see it, rather than slipping through a wildcard.
        match self {
            Error::Spawn { source, .. } => Some(source),
            Error::Io(source) => Some(source),
            Error::NotFound { .. }
            | Error::CassetteMiss { .. }
            | Error::Exit { .. }
            | Error::Timeout { .. }
            | Error::OutputTooLarge { .. }
            | Error::NotReady { .. }
            | Error::Parse { .. }
            | Error::Unsupported { .. }
            | Error::Cancelled { .. }
            | Error::Signalled { .. }
            | Error::Stdin { .. } => None,
            #[cfg(feature = "limits")]
            Error::ResourceLimit { .. } => None,
        }
    }
}

/// Manual `Debug`: bounds the [`Exit`](Error::Exit) streams and redacts
/// the `PATH` value, so `{e:?}` / `.unwrap()` neither dumps a multi-MiB stream
/// nor logs an environment value. Every other variant mirrors what the derive
/// would print.
impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Spawn { program, source } => f
                .debug_struct("Spawn")
                .field("program", program)
                .field("source", source)
                .finish(),
            Error::NotFound { program, searched } => f
                .debug_struct("NotFound")
                .field("program", program)
                // `searched` is the `PATH` env value — never rendered; summarize
                // as a directory count (`None` renders as `None`).
                .field("searched", &searched.as_deref().map(SearchedRedaction))
                .finish(),
            Error::CassetteMiss { program } => f
                .debug_struct("CassetteMiss")
                .field("program", program)
                .finish(),
            Error::Exit {
                program,
                code,
                stdout,
                stderr,
            } => f
                .debug_struct("Exit")
                .field("program", program)
                .field("code", code)
                .field("stdout", &StreamPreview(stdout))
                .field("stderr", &StreamPreview(stderr))
                .finish(),
            Error::Timeout {
                program,
                timeout,
                stdout,
                stderr,
            } => f
                .debug_struct("Timeout")
                .field("program", program)
                .field("timeout", timeout)
                .field("stdout", &StreamPreview(stdout))
                .field("stderr", &StreamPreview(stderr))
                .finish(),
            Error::OutputTooLarge {
                program,
                line_limit,
                byte_limit,
                total_lines,
                total_bytes,
            } => f
                .debug_struct("OutputTooLarge")
                .field("program", program)
                .field("line_limit", line_limit)
                .field("byte_limit", byte_limit)
                .field("total_lines", total_lines)
                .field("total_bytes", total_bytes)
                .finish(),
            Error::NotReady { program, timeout } => f
                .debug_struct("NotReady")
                .field("program", program)
                .field("timeout", timeout)
                .finish(),
            Error::Parse { program, message } => f
                .debug_struct("Parse")
                .field("program", program)
                // Caller-built, often the full unparsed output — bound it.
                .field("message", &StreamPreview(message))
                .finish(),
            #[cfg(feature = "limits")]
            Error::ResourceLimit { message } => f
                .debug_struct("ResourceLimit")
                // Bounded like every text-bearing variant to keep the "no
                // unbounded text in Debug" invariant uniform, though `message`
                // is short today.
                .field("message", &StreamPreview(message))
                .finish(),
            Error::Unsupported { operation } => f
                .debug_struct("Unsupported")
                .field("operation", operation)
                .finish(),
            Error::Cancelled { program } => f
                .debug_struct("Cancelled")
                .field("program", program)
                .finish(),
            Error::Signalled {
                program,
                signal,
                stdout,
                stderr,
            } => f
                .debug_struct("Signalled")
                .field("program", program)
                .field("signal", signal)
                .field("stdout", &StreamPreview(stdout))
                .field("stderr", &StreamPreview(stderr))
                .finish(),
            Error::Stdin { program, source } => f
                .debug_struct("Stdin")
                .field("program", program)
                .field("source", source)
                .finish(),
            Error::Io(source) => f.debug_tuple("Io").field(source).finish(),
        }
    }
}

/// `Debug` for a captured stream, bounded to a 200-byte char-boundary preview
/// with a `(+N bytes)` note — the [`Exit`](Error::Exit) streams can be multi-MiB
/// and must never flood a `{e:?}` log line or `.unwrap()` panic message. Mirrors
/// the [`Display`](std::fmt::Display) tail cap in [`display_exit`].
struct StreamPreview<'a>(&'a str);

impl fmt::Debug for StreamPreview<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        const CAP: usize = DIAG_CAP;
        let s = self.0;
        if s.len() <= CAP {
            return fmt::Debug::fmt(s, f);
        }
        let mut cut = CAP;
        while !s.is_char_boundary(cut) {
            cut -= 1;
        }
        write!(f, "{:?}… (+{} bytes)", &s[..cut], s.len() - cut)
    }
}

/// `Debug` for [`NotFound`](Error::NotFound)'s `searched`: the `PATH` value is an
/// environment value and must never be logged, so it renders only as a directory
/// count (`<N directories>`) — never the directories themselves.
struct SearchedRedaction<'a>(&'a str);

impl fmt::Debug for SearchedRedaction<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        const SEP: char = if cfg!(windows) { ';' } else { ':' };
        // Count non-empty segments only, so a trailing or doubled separator does
        // not inflate the redacted count.
        let n = self.0.split(SEP).filter(|s| !s.is_empty()).count();
        write!(f, "<{n} directories>")
    }
}

/// `NotFound`'s one-line `Display`. Says "not found on PATH" only when a `PATH`
/// search actually happened (`searched.is_some()` — a bare name looked up against
/// the process `PATH`); a path-form program or a customized `PATH` (`None`) reads
/// `` `{program}` not found ``, since no `PATH` lookup occurred. Never includes
/// the `searched` value itself (the `PATH` env value — the crate's secret rule).
fn display_not_found(program: &str, searched: &Option<String>) -> String {
    match searched {
        Some(_) => format!("`{program}` not found on PATH"),
        None => format!("`{program}` not found"),
    }
}

/// `Parse`'s one-line `Display`: `` failed to parse `{program}` output: {message} ``
/// with the caller-built `message` bounded to a 200-byte char-boundary head
/// — its start carries the actionable detail (`unexpected token at line 3`),
/// unlike a captured stream whose *tail* is quoted — so an embedded multi-KiB
/// unparsed dump can never poison a log line. The full text stays on the field.
///
/// `Parse` messages routinely embed attacker-influenced unparsed output, so each
/// char is passed through [`is_display_unsafe`] and replaced with `U+FFFD` if
/// dangerous — the same control-/bidi-injection defense the captured-stream tails
/// get, which a bare truncation would have skipped.
fn display_parse(program: &str, message: &str) -> String {
    let mut out = format!("failed to parse `{program}` output: ");
    push_sanitized_capped(&mut out, message, DIAG_CAP);
    out
}

/// `Signalled`'s one-line Display: `` `{program}` was terminated by signal {n} ``
/// when a number is known, `` `{program}` was terminated by a signal `` otherwise,
/// plus the bounded diagnostic tail of the captured streams, like
/// [`display_exit`].
fn display_signalled(program: &str, signal: Option<i32>, stdout: &str, stderr: &str) -> String {
    let mut message = match signal {
        Some(n) => format!("`{program}` was terminated by signal {n}"),
        None => format!("`{program}` was terminated by a signal"),
    };
    append_diagnostic_tail(&mut message, stdout, stderr);
    message
}

/// `Timeout`'s one-line Display: `` `{program}` timed out after {timeout:?} `` plus
/// the bounded diagnostic tail of whatever the run captured before the kill
/// — a hung tool's last stderr line is often the explanation. Same tail cap as
/// [`display_exit`].
fn display_timeout(program: &str, timeout: Duration, stdout: &str, stderr: &str) -> String {
    let mut message = format!("`{program}` timed out after {timeout:?}");
    append_diagnostic_tail(&mut message, stdout, stderr);
    message
}

/// io-level "retry as-is" conditions: transient kernel/filesystem states a bare
/// retry can clear, distinct from a permanent failure (not-found, permission).
/// Kept deliberately narrow.
fn is_transient_io(e: &std::io::Error) -> bool {
    use std::io::ErrorKind;
    // `ExecutableFileBusy` (std's `ETXTBSY` mapping) clears once the writer
    // closes the executable.
    if matches!(
        e.kind(),
        ErrorKind::Interrupted
            | ErrorKind::WouldBlock
            | ErrorKind::ResourceBusy
            | ErrorKind::ExecutableFileBusy
    ) {
        return true;
    }
    // std leaves Windows sharing/lock violations `Uncategorized`, so match the
    // raw codes: ERROR_SHARING_VIOLATION (32) / ERROR_LOCK_VIOLATION (33).
    #[cfg(windows)]
    {
        matches!(e.raw_os_error(), Some(32 | 33))
    }
    #[cfg(not(windows))]
    {
        false
    }
}

/// The stream a failed run's message should quote: stderr when it carries
/// text, else stdout (where `git` puts `CONFLICT …`), else nothing.
fn exit_diagnostic<'a>(stdout: &'a str, stderr: &'a str) -> Option<&'a str> {
    [stderr, stdout]
        .into_iter()
        .map(str::trim)
        .find(|text| !text.is_empty())
}

/// `Exit`'s one-line `Display`: program + code, plus a bounded excerpt of the
/// diagnostic — its **last** non-empty line (the actionable one: `git push`
/// ends with `remote: permission denied`, not starts), capped at 200 bytes on
/// a char boundary so a binary-garbage or one-enormous-line stream can never
/// poison a log line.
fn display_exit(program: &str, code: i32, stdout: &str, stderr: &str) -> String {
    let mut message = format!("`{program}` exited with code {code}");
    append_diagnostic_tail(&mut message, stdout, stderr);
    message
}

/// The byte budget every one-line `Display`/`Debug` excerpt of caller- or
/// child-influenced text is capped to, so a multi-KiB stream or unparsed dump can
/// never poison a log line. Shared by [`push_sanitized_capped`], the
/// [`StreamPreview`] `Debug`, and the diagnostic-tail/`Parse` displays.
const DIAG_CAP: usize = 200;

/// Append `text` to `out`, replacing any [display-unsafe](is_display_unsafe) char
/// with `U+FFFD` and stopping at `cap` bytes (an `…` marks truncation). The byte
/// budget counts only `text`, never what `out` already holds. The single
/// sanitize-and-cap loop shared by the `Display` paths that embed
/// attacker-influenced text — the diagnostic tail ([`append_diagnostic_tail`])
/// and the [`Parse`](Error::Parse) message head ([`display_parse`]) — so the
/// control-/bidi-injection defense and the cap can't drift apart.
fn push_sanitized_capped(out: &mut String, text: &str, cap: usize) {
    let mut written = 0usize;
    for ch in text.chars() {
        let ch = if is_display_unsafe(ch) {
            '\u{FFFD}'
        } else {
            ch
        };
        if written + ch.len_utf8() > cap {
            out.push('');
            return;
        }
        out.push(ch);
        written += ch.len_utf8();
    }
}

/// Whether `ch` is unsafe to emit verbatim into a one-line log/terminal from
/// attacker-influenced text: a control character (ANSI `ESC`, `BEL`,
/// `NUL`, `CR`, cursor moves, …), a Unicode **line/paragraph separator** that a
/// terminal or log viewer renders as a newline (breaking the "one actionable
/// line" intent), **or** a Unicode bidirectional-formatting control — the
/// "Trojan Source" class (CVE-2021-42574) that can visually reorder the
/// surrounding text in a terminal or editor.
fn is_display_unsafe(ch: char) -> bool {
    ch.is_control()
        || matches!(ch,
            '\u{2028}' | '\u{2029}'   // LS PS (line/paragraph separators — `is_control` misses these)
            | '\u{202A}'..='\u{202E}' // LRE RLE PDF LRO RLO (embeddings/overrides)
            | '\u{2066}'..='\u{2069}' // LRI RLI FSI PDI (isolates)
            | '\u{200E}' | '\u{200F}' // LRM RLM (implicit marks)
            | '\u{061C}'              // ALM (Arabic letter mark)
        )
}

/// Append `: <last non-empty diagnostic line>` to a one-line error `Display`,
/// capped at 200 bytes on a char boundary with an ellipsis. Shared by
/// [`display_exit`], [`display_timeout`], and [`display_signalled`] so a
/// captured-stream error stays one actionable line and a binary-garbage or
/// one-enormous-line stream can never poison a log line. A no-op when both
/// streams are blank.
///
/// Each char is passed through [`is_display_unsafe`] and
/// replaced with `U+FFFD` if dangerous, so a hostile child's stderr cannot inject
/// terminal escape sequences (ANSI, `BEL`, `NUL`, cursor moves) or bidi-reordering
/// controls into an operator's log or terminal through a `{err}` format. (The
/// line was already split on `\n`; this also neutralizes any stray embedded
/// `\r`/`ESC`.)
fn append_diagnostic_tail(message: &mut String, stdout: &str, stderr: &str) {
    let tail = exit_diagnostic(stdout, stderr)
        .and_then(|text| text.lines().rev().map(str::trim).find(|l| !l.is_empty()));
    if let Some(tail) = tail {
        message.push_str(": ");
        push_sanitized_capped(message, tail, DIAG_CAP);
    }
}

/// Crate result alias.
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn display_tail_sanitizes_control_chars_against_terminal_injection() {
        // A hostile child's stderr last line carrying ANSI/BEL/NUL must not reach
        // a `{err}` log/terminal verbatim — control bytes become U+FFFD, while
        // printable text survives.
        let err = Error::Exit {
            program: "tool".into(),
            code: 1,
            stdout: String::new(),
            stderr: "boom\x1b[31m\x07\x00danger".into(),
        };
        let msg = err.to_string();
        assert!(!msg.contains('\x1b'), "ESC must be sanitized: {msg:?}");
        assert!(!msg.contains('\x07'), "BEL must be sanitized: {msg:?}");
        assert!(!msg.contains('\x00'), "NUL must be sanitized: {msg:?}");
        assert!(msg.contains("boom"), "printable text is kept: {msg:?}");
        assert!(msg.contains("danger"), "printable text is kept: {msg:?}");
    }

    #[test]
    fn display_tail_strips_bidi_controls_against_trojan_source() {
        // A hostile stderr last line carrying bidi-override controls
        // (CVE-2021-42574) must not reach a `{err}` line and visually reorder it.
        let err = Error::Exit {
            program: "tool".into(),
            code: 1,
            stdout: String::new(),
            stderr: "safe\u{202E}reversed\u{202C}\u{2066}iso".into(),
        };
        let msg = err.to_string();
        assert!(!msg.contains('\u{202E}'), "RLO must be sanitized: {msg:?}");
        assert!(!msg.contains('\u{202C}'), "PDF must be sanitized: {msg:?}");
        assert!(!msg.contains('\u{2066}'), "LRI must be sanitized: {msg:?}");
        assert!(msg.contains("safe"), "printable text is kept: {msg:?}");
    }

    #[test]
    fn display_tail_strips_unicode_line_separators() {
        // U+2028 / U+2029 are NOT `char::is_control()`, yet terminals and log
        // viewers render them as a newline — a hostile last line carrying them
        // must not inject a break into the one-line `{err}` render.
        let err = Error::Exit {
            program: "tool".into(),
            code: 1,
            stdout: String::new(),
            stderr: "before\u{2028}after\u{2029}end".into(),
        };
        let msg = err.to_string();
        assert!(!msg.contains('\u{2028}'), "LS must be sanitized: {msg:?}");
        assert!(!msg.contains('\u{2029}'), "PS must be sanitized: {msg:?}");
        assert!(msg.contains("before"), "printable text is kept: {msg:?}");
        assert!(msg.contains("after"), "printable text is kept: {msg:?}");
    }

    #[test]
    fn parse_display_sanitizes_control_and_bidi_injection() {
        // `Parse` messages routinely embed attacker-influenced unparsed output;
        // the one-line Display must neutralize control AND bidi controls, not
        // just truncate.
        let err = Error::Parse {
            program: "jq".into(),
            message: "bad\x1b[31m\x07token\u{202E}flip\u{2069}sep\u{2028}end".into(),
        };
        let msg = err.to_string();
        assert!(!msg.contains('\x1b'), "ESC must be sanitized: {msg:?}");
        assert!(!msg.contains('\x07'), "BEL must be sanitized: {msg:?}");
        assert!(!msg.contains('\u{202E}'), "RLO must be sanitized: {msg:?}");
        assert!(!msg.contains('\u{2069}'), "PDI must be sanitized: {msg:?}");
        assert!(!msg.contains('\u{2028}'), "LS must be sanitized: {msg:?}");
        assert!(msg.contains("bad"), "printable text is kept: {msg:?}");
        assert!(msg.contains("token"), "printable text is kept: {msg:?}");
    }

    #[test]
    fn debug_bounds_exit_streams_so_unwrap_cannot_dump_them() {
        // A derived Debug would dump both full streams into `{e:?}` /
        // `.unwrap()`. The manual Debug bounds each to a 200-byte preview.
        let huge = "x".repeat(10_000);
        let err = Error::Exit {
            program: "tool".into(),
            code: 1,
            stdout: huge.clone(),
            stderr: huge,
        };
        let dbg = format!("{err:?}");
        assert!(
            dbg.len() < 700,
            "Debug must be bounded (two 200-byte previews + struct), got {} bytes",
            dbg.len()
        );
        assert!(
            !dbg.contains(&"x".repeat(300)),
            "must not dump the full multi-KiB stream"
        );
        // The bounded preview is still present and marked as truncated.
        assert!(dbg.contains("(+9800 bytes)"), "got: {dbg}");
        // A short stream is shown verbatim (no truncation note).
        let small = Error::Exit {
            program: "tool".into(),
            code: 2,
            stdout: "hello".into(),
            stderr: String::new(),
        };
        let dbg = format!("{small:?}");
        assert!(dbg.contains("\"hello\""), "got: {dbg}");
        assert!(
            !dbg.contains("bytes)"),
            "no truncation note for a short stream: {dbg}"
        );
    }

    #[test]
    fn debug_redacts_the_path_value_in_not_found() {
        // `searched` is the PATH env value and must never appear in Debug
        // (which feeds `{e:?}` logs and `.unwrap()` panics).
        let err = Error::NotFound {
            program: "tool".into(),
            searched: Some("/secret/bin:/another/private/dir".into()),
        };
        let dbg = format!("{err:?}");
        assert!(
            !dbg.contains("/secret/bin") && !dbg.contains("/another/private/dir"),
            "PATH value must not appear in Debug: {dbg}"
        );
        assert!(
            dbg.contains("directories"),
            "should summarize as a count: {dbg}"
        );
    }

    #[test]
    fn exit_display_appends_a_bounded_diagnostic_tail() {
        // The Display stays one actionable line — program + code + the LAST
        // non-empty diagnostic line — never the full captured streams.
        let err = Error::Exit {
            program: "git".into(),
            code: 2,
            stdout: "CONFLICT (content): merge conflict in a.rs".into(),
            stderr: "warning: something\nfatal: boom\n".into(),
        };
        assert_eq!(err.to_string(), "`git` exited with code 2: fatal: boom");

        // stderr blank → the stdout-borne message (git's CONFLICT) is used.
        let err = Error::Exit {
            program: "git".into(),
            code: 2,
            stdout: "CONFLICT (content): merge conflict in a.rs".into(),
            stderr: "   ".into(),
        };
        assert_eq!(
            err.to_string(),
            "`git` exited with code 2: CONFLICT (content): merge conflict in a.rs"
        );
    }

    #[test]
    fn exit_display_with_blank_streams_has_no_trailing_colon() {
        let err = Error::Exit {
            program: "git".into(),
            code: 2,
            stdout: String::new(),
            stderr: "  \n ".into(),
        };
        assert_eq!(err.to_string(), "`git` exited with code 2");
    }

    #[test]
    fn exit_display_tail_is_capped_and_never_leaks_the_stream() {
        // A multi-KiB single-line stderr must not poison the log line: the
        // tail is cut at 200 bytes on a char boundary, with an ellipsis.
        let huge = "é".repeat(3000); // 2 bytes/char exercises the boundary
        let err = Error::Exit {
            program: "x".into(),
            code: 1,
            stdout: String::new(),
            stderr: huge,
        };
        let message = err.to_string();
        assert!(message.len() < 250, "capped, got {} bytes", message.len());
        assert!(message.ends_with(''), "got: {message}");
        assert!(message.starts_with("`x` exited with code 1: éé"));
    }

    #[test]
    fn diagnostic_is_none_for_non_exit_variants() {
        // A timeout that captured nothing has no diagnostic (streams-bearing
        // case covered in `timeout_and_signalled_carry_diagnostic_streams`).
        let timeout = Error::Timeout {
            program: "git".into(),
            timeout: Duration::from_secs(1),
            stdout: String::new(),
            stderr: String::new(),
        };
        assert_eq!(timeout.diagnostic(), None);
        let unsupported = Error::Unsupported {
            operation: "suspend".into(),
        };
        assert_eq!(unsupported.diagnostic(), None);
        let not_ready = Error::NotReady {
            program: "server".into(),
            timeout: Duration::from_secs(10),
        };
        assert_eq!(not_ready.diagnostic(), None);
        {
            let cancelled = Error::Cancelled {
                program: "job".into(),
            };
            assert_eq!(cancelled.diagnostic(), None);
        }
        #[cfg(feature = "limits")]
        {
            let limit = Error::ResourceLimit {
                message: "cgroup controller delegation unavailable".into(),
            };
            assert_eq!(limit.diagnostic(), None);
        }
    }

    #[test]
    fn cancelled_display_names_the_program() {
        let err = Error::Cancelled {
            program: "long-job".into(),
        };
        assert_eq!(err.to_string(), "`long-job` was cancelled");
        // A cancellation deliberately carries no streams, so diagnostic is None.
        assert_eq!(err.diagnostic(), None);
    }

    #[test]
    fn timeout_and_signalled_carry_diagnostic_streams() {
        // A hung-then-killed tool's partial stderr is the explanation —
        // reachable via diagnostic(), and its last line tails the Display.
        let timeout = Error::Timeout {
            program: "db-migrate".into(),
            timeout: Duration::from_secs(30),
            stdout: String::new(),
            stderr: "connecting…\nwaiting for lock held by pid 4123\n".into(),
        };
        assert_eq!(
            timeout.diagnostic(),
            Some("connecting…\nwaiting for lock held by pid 4123")
        );
        assert_eq!(
            timeout.to_string(),
            "`db-migrate` timed out after 30s: waiting for lock held by pid 4123"
        );

        // stderr blank → the stdout-borne message is used (mirrors Exit).
        let signalled = Error::Signalled {
            program: "worker".into(),
            signal: Some(11),
            stdout: "processing batch 7\n".into(),
            stderr: String::new(),
        };
        assert_eq!(signalled.diagnostic(), Some("processing batch 7"));
        assert_eq!(
            signalled.to_string(),
            "`worker` was terminated by signal 11: processing batch 7"
        );
    }

    #[test]
    fn timeout_and_signalled_debug_bounds_their_streams() {
        // Captured streams must be bounded in Debug, exactly like Exit — a
        // multi-MiB partial capture must never flood `{e:?}`.
        let huge = "x".repeat(10_000);
        let timeout = Error::Timeout {
            program: "t".into(),
            timeout: Duration::from_secs(1),
            stdout: huge.clone(),
            stderr: huge.clone(),
        };
        let dbg = format!("{timeout:?}");
        assert!(dbg.len() < 800, "Debug must be bounded, got {}", dbg.len());
        assert!(!dbg.contains(&"x".repeat(300)), "must not dump the stream");
        assert!(dbg.contains("(+9800 bytes)"), "got: {dbg}");

        let signalled = Error::Signalled {
            program: "s".into(),
            signal: None,
            stdout: huge.clone(),
            stderr: huge,
        };
        let dbg = format!("{signalled:?}");
        assert!(dbg.len() < 800, "Debug must be bounded, got {}", dbg.len());
        assert!(!dbg.contains(&"x".repeat(300)), "must not dump the stream");
    }

    #[test]
    fn parse_message_is_bounded_in_display_and_debug() {
        // The `Parse` message is caller-built and routinely embeds the full
        // unparsed output — it must be bounded like the `Exit` streams, never
        // dumped whole into a `{e}` log line or a `{e:?}` panic message.
        let huge = "x".repeat(10_000);
        let err = Error::Parse {
            program: "jq".into(),
            message: huge,
        };
        let display = err.to_string();
        assert!(
            display.len() < 300,
            "Display must be bounded, got {} bytes",
            display.len()
        );
        assert!(display.starts_with("failed to parse `jq` output: "));
        assert!(
            display.ends_with(''),
            "truncated Display ends with ellipsis"
        );
        let dbg = format!("{err:?}");
        assert!(
            dbg.len() < 400,
            "Debug must be bounded, got {} bytes",
            dbg.len()
        );
        assert!(
            !dbg.contains(&"x".repeat(300)),
            "must not dump the full message: {dbg}"
        );
        assert!(dbg.contains("bytes)"), "truncation note present: {dbg}");

        // A short message is shown verbatim (no truncation, no ellipsis).
        let small = Error::Parse {
            program: "jq".into(),
            message: "unexpected token at line 3".into(),
        };
        assert_eq!(
            small.to_string(),
            "failed to parse `jq` output: unexpected token at line 3"
        );
        assert!(!format!("{small:?}").contains("bytes)"));
    }

    #[test]
    fn not_ready_display_names_program_and_timeout() {
        let err = Error::NotReady {
            program: "my-server".into(),
            timeout: Duration::from_secs(10),
        };
        assert_eq!(err.to_string(), "`my-server` was not ready after 10s");
    }

    #[test]
    fn unsupported_display_names_the_operation() {
        let err = Error::Unsupported {
            operation: "signal(Hup)".into(),
        };
        assert_eq!(
            err.to_string(),
            "operation `signal(Hup)` is not supported on this platform"
        );
    }

    #[cfg(feature = "limits")]
    #[test]
    fn resource_limit_display_carries_reason() {
        let err = Error::ResourceLimit {
            message: "no cgroup or Job Object available".into(),
        };
        assert_eq!(
            err.to_string(),
            "could not enforce resource limits: no cgroup or Job Object available"
        );
    }

    #[test]
    fn signalled_display_and_diagnostic() {
        let with_signal = Error::Signalled {
            program: "git".into(),
            signal: Some(9),
            stdout: String::new(),
            stderr: String::new(),
        };
        assert_eq!(with_signal.to_string(), "`git` was terminated by signal 9");
        assert_eq!(with_signal.diagnostic(), None);
        assert!(!with_signal.is_not_found());
        assert!(!with_signal.is_permission_denied());
        assert!(!with_signal.is_transient());

        let no_signal = Error::Signalled {
            program: "git".into(),
            signal: None,
            stdout: String::new(),
            stderr: String::new(),
        };
        assert_eq!(no_signal.to_string(), "`git` was terminated by a signal");
    }

    #[test]
    fn not_found_display_and_classifier() {
        let err = Error::NotFound {
            program: "my-tool".into(),
            searched: Some("/usr/bin:/usr/local/bin".into()),
        };
        // Display must NOT include the raw PATH value (env values are never
        // logged); searched is still accessible.
        let display = err.to_string();
        assert_eq!(display, "`my-tool` not found on PATH");
        assert!(
            !display.contains("/usr/bin"),
            "Display must not expose PATH value: {display}"
        );
        assert!(err.is_not_found(), "NotFound must satisfy is_not_found()");
        assert!(!err.is_permission_denied());
        assert!(!err.is_transient());
        assert_eq!(err.diagnostic(), None);
    }

    #[test]
    fn not_found_without_path_search_omits_on_path() {
        // A path-form program (or a customized PATH) is `NotFound` with
        // `searched: None` — no PATH lookup happened, so the message must not
        // claim "on PATH". Still `is_not_found()`.
        let err = Error::NotFound {
            program: "/no/such/tool".into(),
            searched: None,
        };
        assert_eq!(err.to_string(), "`/no/such/tool` not found");
        assert!(err.is_not_found());
        // The bare-name case (a real PATH search) still says "on PATH".
        let bare = Error::NotFound {
            program: "tool".into(),
            searched: Some("/usr/bin".into()),
        };
        assert_eq!(bare.to_string(), "`tool` not found on PATH");
    }

    fn spawn(kind: std::io::ErrorKind) -> Error {
        Error::Spawn {
            program: "x".into(),
            source: std::io::Error::from(kind),
        }
    }

    #[test]
    fn not_found_and_permission_denied_are_classified_on_spawn_and_io() {
        use std::io::ErrorKind::{NotFound, PermissionDenied};
        // `is_not_found()` is true ONLY for the `NotFound` variant — a
        // `Spawn`/`Io` carrying a `NotFound` io kind (e.g. a bad cwd) is not a
        // missing program, so the "not installed?" hint can't misfire.
        assert!(
            Error::NotFound {
                program: "x".into(),
                searched: None,
            }
            .is_not_found()
        );
        assert!(!spawn(NotFound).is_not_found());
        assert!(!Error::Io(std::io::Error::from(NotFound)).is_not_found());
        assert!(!spawn(NotFound).is_permission_denied());

        assert!(spawn(PermissionDenied).is_permission_denied());
        assert!(!spawn(PermissionDenied).is_not_found());
        // Neither permanent failure counts as transient.
        assert!(!spawn(NotFound).is_transient());
        assert!(!spawn(PermissionDenied).is_transient());
    }

    #[test]
    fn transient_kinds_are_classified() {
        // ExecutableFileBusy is built straight from the kind (no raw errno) —
        // the classifier must recognize it by `ErrorKind` alone.
        for kind in [
            std::io::ErrorKind::Interrupted,
            std::io::ErrorKind::WouldBlock,
            std::io::ErrorKind::ResourceBusy,
            std::io::ErrorKind::ExecutableFileBusy,
        ] {
            assert!(spawn(kind).is_transient(), "{kind:?} should be transient");
            assert!(
                Error::Io(std::io::Error::from(kind)).is_transient(),
                "{kind:?} (Io) should be transient"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn etxtbsy_is_transient_on_unix() {
        let err = Error::Spawn {
            program: "busy".into(),
            source: std::io::Error::from_raw_os_error(libc::ETXTBSY),
        };
        assert!(err.is_transient());
        assert!(!err.is_not_found() && !err.is_permission_denied());
    }

    #[cfg(windows)]
    #[test]
    fn sharing_and_lock_violations_are_transient_on_windows() {
        for code in [32, 33] {
            let err = Error::Spawn {
                program: "locked".into(),
                source: std::io::Error::from_raw_os_error(code),
            };
            assert!(
                err.is_transient(),
                "raw os error {code} should be transient"
            );
        }
    }

    #[test]
    fn classifiers_are_false_for_non_io_variants() {
        // A tool's non-zero exit is never an io-level classification (its
        // retryability is the caller's domain), and Timeout is excluded too.
        let exit = Error::Exit {
            program: "git".into(),
            code: 128,
            stdout: String::new(),
            stderr: "could not resolve host".into(),
        };
        assert!(!exit.is_not_found() && !exit.is_permission_denied() && !exit.is_transient());
        let timeout = Error::Timeout {
            program: "x".into(),
            timeout: Duration::from_secs(1),
            stdout: String::new(),
            stderr: String::new(),
        };
        assert!(
            !timeout.is_transient(),
            "Timeout is excluded from is_transient by design"
        );
    }
}