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
//! The captured outcome of a finished process run.

use std::time::Duration;

use crate::error::Error;

/// How a run ended — the explicit form of the `code()`/`timed_out()` pair.
///
/// Non-exhaustive: a future disposition (e.g. a richer platform-specific
/// termination) can be added without a breaking change — so prefer the
/// accessors [`code`](Self::code) / [`signal`](Self::signal) /
/// [`timed_out`](Self::timed_out) over a `match` with a wildcard when you hold a
/// bare `Outcome` (e.g. from [`RunningProcess::wait`](crate::RunningProcess::wait)).
///
/// There is deliberately **no** `Outcome::is_success`: success depends on the
/// accepted exit codes ([`Command::ok_codes`](crate::Command::ok_codes)), which a
/// bare `Outcome` does not carry — use
/// [`ProcessResult::is_success`](crate::ProcessResult::is_success) (which honors
/// `ok_codes`) rather than assuming `Exited(0)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Outcome {
    /// The process exited on its own with this code.
    ///
    /// On **Windows** this also covers a *killed* process: the OS has no signal
    /// abstraction, so termination yields an exit code, not a
    /// [`Signalled`](Self::Signalled). A `TerminateProcess`/
    /// `TerminateJobObject(_, 1)` is reported as `Exited(1)` — indistinguishable
    /// from a voluntary `exit(1)` — and `Ctrl-C` surfaces as
    /// `Exited(-1073741510)` (`STATUS_CONTROL_C_EXIT` as a signed `i32`). This is
    /// the platform truth; the crate does not fabricate a `Signalled` from an
    /// NTSTATUS code (the mapping would be a lossy guess). Use a
    /// [`ProcessGroup`](crate::ProcessGroup) deadline / cancellation token when
    /// you need to *know* you killed it.
    Exited(i32),
    /// Terminated by a signal **(Unix only)** — no exit code exists. The inner
    /// value is the signal number when the platform reports one (`None` when the
    /// kernel does not expose it). **Never produced on Windows**, where a killed
    /// process reports [`Exited`](Self::Exited) with a platform code instead.
    /// A [`ScriptedRunner`](crate::testing::ScriptedRunner) reports
    /// `Signalled(None)` for a killed scripted run, matching Unix.
    Signalled(Option<i32>),
    /// Killed because it exceeded its configured timeout.
    TimedOut,
}

impl Outcome {
    /// The exit code if the process [`Exited`](Self::Exited), else `None`
    /// (a signal kill or timeout has no exit code — never a `-1` sentinel).
    ///
    /// The accessor for a bare `Outcome` (e.g. from
    /// [`RunningProcess::wait`](crate::RunningProcess::wait) or
    /// [`Finished::outcome`](crate::Finished)); mirrors
    /// [`ProcessResult::code`](crate::ProcessResult::code). Because `Outcome` is
    /// `#[non_exhaustive]`, prefer these accessors over a `match` with a wildcard.
    pub fn code(&self) -> Option<i32> {
        match self {
            Outcome::Exited(code) => Some(*code),
            _ => None,
        }
    }

    /// The signal number if the process was [`Signalled`](Self::Signalled) with a
    /// known number, else `None` (a clean exit, a timeout, or a signal the kernel
    /// did not expose). **Unix only** — a killed process reports
    /// [`Exited`](Self::Exited) on Windows.
    pub fn signal(&self) -> Option<i32> {
        match self {
            Outcome::Signalled(signal) => *signal,
            _ => None,
        }
    }

    /// Whether the run was killed because it exceeded its timeout. Mirrors
    /// [`ProcessResult::timed_out`](crate::ProcessResult::timed_out).
    pub fn timed_out(&self) -> bool {
        matches!(self, Outcome::TimedOut)
    }
}

/// The captured result of running a process to completion.
///
/// `T` is the standard-output payload: [`String`] for the text helpers
/// (`output_string`) or [`Vec<u8>`] for the raw-bytes helper (`output_bytes`).
/// Standard error is always captured as text. A non-zero exit code is **not**
/// treated as an error on its own — inspect [`code`](Self::code) or call
/// [`ensure_success`](Self::ensure_success).
///
/// `#[must_use]`: the result *is* the exit status — dropping it unread discards
/// the only signal that the command failed. Call
/// [`is_success`](Self::is_success) / [`code`](Self::code) /
/// [`ensure_success`](Self::ensure_success). If you only need the side effect,
/// prefer a verb that never produces a result to discard —
/// [`run_unit`](crate::Command::run_unit) (error-or-`()`) or
/// [`exit_code`](crate::Command::exit_code) — rather than capturing and binding
/// to `let _`.
#[must_use = "a ProcessResult carries the exit status; inspect is_success()/code()/ensure_success() or it is silently discarded"]
#[derive(Debug, Clone)]
pub struct ProcessResult<T> {
    program: String,
    stdout: T,
    stderr: String,
    outcome: Outcome,
    /// Carried so the success-checking helpers can build a faithful [`Error::Timeout`].
    timeout: Option<Duration>,
    /// `Duration::ZERO` for synthetic results that didn't time a real process.
    duration: Duration,
    /// Whether a bounded [`OutputBufferPolicy`](crate::OutputBufferPolicy)
    /// dropped captured output lines.
    truncated: bool,
    /// Retained + dropped, so a checking verb can build a faithful
    /// [`Error::OutputTooLarge`]; meaningful only when `truncated`.
    total_lines: usize,
    total_bytes: usize,
    /// Exit codes treated as success by [`is_success`](Self::is_success) /
    /// [`ensure_success`](Self::ensure_success). Default `[0]`; widened via
    /// [`Command::ok_codes`](crate::Command::ok_codes).
    ok_codes: Vec<i32>,
}

// Equality is over the *logical* outcome: `duration` and `truncated` are excluded
// so a recorded result compares equal to its replay (which rebuilds duration as
// `Duration::ZERO`), keeping the cassette round-trip contract intact.
impl<T: PartialEq> PartialEq for ProcessResult<T> {
    fn eq(&self, other: &Self) -> bool {
        self.program == other.program
            && self.stdout == other.stdout
            && self.stderr == other.stderr
            && self.outcome == other.outcome
            && self.timeout == other.timeout
            && self.ok_codes == other.ok_codes
    }
}

impl<T: Eq> Eq for ProcessResult<T> {}

impl<T> ProcessResult<T> {
    /// Build a result from the [`Outcome`] every producing path has in hand.
    pub(crate) fn new(
        program: String,
        stdout: T,
        stderr: String,
        outcome: Outcome,
        timeout: Option<Duration>,
    ) -> Self {
        Self {
            program,
            stdout,
            stderr,
            outcome,
            timeout,
            // Producer-only setters fill these on real runs; defaults keep
            // synthetic results correct.
            duration: Duration::ZERO,
            truncated: false,
            total_lines: 0,
            total_bytes: 0,
            ok_codes: vec![0],
        }
    }

    /// The program this result is attributed to (lossy UTF-8 of the program
    /// name) — the same value the error variants carry. For a
    /// [`Pipeline`](crate::Pipeline) outcome this is the pipefail-attributed
    /// stage: the first stage that didn't exit cleanly, or the last stage
    /// when every stage succeeded.
    pub fn program(&self) -> &str {
        &self.program
    }

    /// The captured standard output (text or bytes depending on `T`).
    pub fn stdout(&self) -> &T {
        &self.stdout
    }

    /// Consume the result and return just the captured standard output.
    pub fn into_stdout(self) -> T {
        self.stdout
    }

    /// The captured standard error.
    pub fn stderr(&self) -> &str {
        &self.stderr
    }

    /// How the run ended, as the explicit three-way [`Outcome`].
    pub fn outcome(&self) -> Outcome {
        self.outcome
    }

    /// The process exit code, or `None` when the run yielded no code — killed by
    /// its timeout ([`timed_out`](Self::timed_out) is then `true`) or terminated
    /// by a signal on Unix (`timed_out` is `false`). There is no synthetic
    /// sentinel: a missing code is `None`, never `-1`. Derived from
    /// [`outcome`](Self::outcome).
    pub fn code(&self) -> Option<i32> {
        self.outcome.code()
    }

    /// Whether the run was killed because it exceeded its timeout. Derived
    /// from [`outcome`](Self::outcome).
    pub fn timed_out(&self) -> bool {
        self.outcome.timed_out()
    }

    /// The signal number if the process was terminated by a signal with a known
    /// number (**Unix only**; `None` otherwise — a clean exit, a timeout, or a
    /// signal the kernel did not expose). Derived from [`outcome`](Self::outcome);
    /// the `Outcome`-level twin is [`Outcome::signal`].
    pub fn signal(&self) -> Option<i32> {
        self.outcome.signal()
    }

    /// Whether the process exited with an **accepted** code — `0` by default, or
    /// any code in the set configured via
    /// [`Command::ok_codes`](crate::Command::ok_codes).
    pub fn is_success(&self) -> bool {
        matches!(self.outcome, Outcome::Exited(code) if self.ok_codes.contains(&code))
    }

    /// Return `self` unchanged when the run succeeded, otherwise the matching
    /// error: [`Error::Timeout`] if the run was killed by its deadline (checked
    /// first), [`Error::Signalled`](crate::Error::Signalled) if it was terminated
    /// by a signal (no exit code), else [`Error::Exit`] for an exit code outside
    /// the accepted set (code `0` by default — see
    /// [`Command::ok_codes`](crate::Command::ok_codes)), carrying the code and
    /// both captured streams in full (the [`Display`](std::fmt::Display) impl
    /// bounds what it prints; the fields stay complete for classification).
    pub fn ensure_success(self) -> Result<Self, Error>
    where
        T: StdoutText,
    {
        match self.outcome {
            Outcome::Exited(code) if self.ok_codes.contains(&code) => Ok(self),
            Outcome::TimedOut => Err(Error::Timeout {
                program: self.program.clone(),
                timeout: self.timeout.unwrap_or_default(),
                stdout: self.stdout.as_text(),
                stderr: self.stderr.clone(),
            }),
            Outcome::Signalled(signal) => Err(Error::Signalled {
                program: self.program.clone(),
                signal,
                stdout: self.stdout.as_text(),
                stderr: self.stderr.clone(),
            }),
            Outcome::Exited(code) => Err(Error::Exit {
                program: self.program.clone(),
                code,
                stdout: self.stdout.as_text(),
                stderr: self.stderr.clone(),
            }),
        }
    }

    /// The exit code for the code-returning convenience helpers
    /// (`Command::exit_code`, `ProcessRunnerExt::exit_code`, `CliClient::exit_code`):
    /// a timeout surfaces as [`Error::Timeout`], a signal-kill (no code) as
    /// [`Error::Signalled`], otherwise the code.
    pub(crate) fn require_code(&self) -> Result<i32, Error>
    where
        T: StdoutText,
    {
        match self.outcome {
            Outcome::Exited(code) => Ok(code),
            Outcome::TimedOut => Err(Error::Timeout {
                program: self.program.clone(),
                timeout: self.timeout.unwrap_or_default(),
                stdout: self.stdout.as_text(),
                stderr: self.stderr.clone(),
            }),
            Outcome::Signalled(signal) => Err(Error::Signalled {
                program: self.program.clone(),
                signal,
                stdout: self.stdout.as_text(),
                stderr: self.stderr.clone(),
            }),
        }
    }

    /// The wall-clock duration of the run — spawn to exit (or kill). It is
    /// `Duration::ZERO` for synthetic results that didn't time a real process
    /// (a scripted/replayed bulk `output_string`).
    pub fn duration(&self) -> Duration {
        self.duration
    }

    /// Whether a bounded [`OutputBufferPolicy`](crate::OutputBufferPolicy)
    /// discarded captured output lines (one or more lines were dropped by the
    /// buffer policy). Lines a streaming consumer popped are *not* truncation, so
    /// this stays `false` under the default unbounded policy even after a partial
    /// [`stdout_lines`](crate::RunningProcess::stdout_lines) stream, and for the
    /// raw stdout of [`output_bytes`](crate::Command::output_bytes) (not
    /// line-buffered).
    pub fn truncated(&self) -> bool {
        self.truncated
    }

    /// Stamp the run's wall-clock duration (producer-only).
    pub(crate) fn with_duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    /// Record that a bounded buffer dropped captured lines (producer-only).
    pub(crate) fn with_truncated(mut self, truncated: bool) -> Self {
        self.truncated = truncated;
        self
    }

    /// Record the total lines/bytes the streams produced (retained + dropped),
    /// so a checking verb can build a faithful [`Error::OutputTooLarge`] when it
    /// refuses truncated output. Producer-only.
    pub(crate) fn with_overflow_totals(mut self, total_lines: usize, total_bytes: usize) -> Self {
        self.total_lines = total_lines;
        self.total_bytes = total_bytes;
        self
    }

    /// Total lines seen across the captured streams (retained + dropped) —
    /// companion to [`truncated`](Self::truncated) for re-stamping a folded
    /// result (e.g. the pipeline pipefail fold). Producer-only.
    pub(crate) fn total_lines(&self) -> usize {
        self.total_lines
    }

    /// Total bytes seen across the captured streams (retained + dropped).
    pub(crate) fn total_bytes(&self) -> usize {
        self.total_bytes
    }

    /// Refuse silently-truncated output. The checking verbs that hand back
    /// stdout *as if complete* (`run`/`parse`/`try_parse`) call this so a bounded
    /// drop-policy that discarded lines surfaces as [`Error::OutputTooLarge`]
    /// rather than feeding a parser a truncated tail. The lenient capture verbs
    /// (`output_string`/`output_bytes`/`checked`) do **not** call it — they
    /// return the result with [`truncated`](Self::truncated) set so the caller
    /// decides. `line_limit`/`byte_limit` are the command's configured ceilings.
    pub(crate) fn reject_if_truncated(
        &self,
        line_limit: Option<usize>,
        byte_limit: Option<usize>,
    ) -> Result<(), Error> {
        if self.truncated {
            return Err(Error::OutputTooLarge {
                program: self.program.clone(),
                line_limit,
                byte_limit,
                total_lines: self.total_lines,
                total_bytes: self.total_bytes,
            });
        }
        Ok(())
    }

    /// Set the exit codes treated as success (producer-only). An empty set is
    /// ignored — it would make every exit a failure — so the default `[0]` stands.
    pub(crate) fn with_ok_codes(mut self, ok_codes: Vec<i32>) -> Self {
        if !ok_codes.is_empty() {
            self.ok_codes = ok_codes;
        }
        self
    }
}

impl ProcessResult<String> {
    /// Standard output followed by standard error, joined — handy when a tool
    /// interleaves diagnostics across both streams.
    ///
    /// A `\n` separator is inserted between the streams when stdout is
    /// non-empty and does not already end with a newline, preventing the last
    /// stdout line from being glued to the first stderr line.
    pub fn combined(&self) -> String {
        let out = self.stdout();
        let err = self.stderr();
        if !out.is_empty() && !err.is_empty() && !out.ends_with('\n') {
            format!("{out}\n{err}")
        } else {
            format!("{out}{err}")
        }
    }

    /// The best human-facing message from a captured run, trimmed of surrounding
    /// whitespace: standard error if it carries text, otherwise standard output —
    /// `git`/`jj` put `CONFLICT …` and `nothing to commit` on stdout, so a probe
    /// that captured the result (rather than erroring) can build the same friendly
    /// message [`Error::diagnostic`](crate::Error::diagnostic) gives the erroring
    /// path. For the raw, untrimmed streams use [`stdout`](Self::stdout) /
    /// [`stderr`](Self::stderr).
    pub fn diagnostic(&self) -> &str {
        if self.stderr.trim().is_empty() {
            self.stdout.trim()
        } else {
            self.stderr.trim()
        }
    }
}

/// Render captured stdout as text for [`Error::Exit`], whatever the payload type:
/// a [`String`] is taken as-is; raw bytes are decoded lossily.
///
/// An implementation detail of [`ensure_success`](ProcessResult::ensure_success):
/// `pub` only to satisfy the bound's visibility (the `result` module is private,
/// so it is unnameable outside the crate) and `#[doc(hidden)]` so it stays off
/// the public docs.
#[doc(hidden)]
pub trait StdoutText {
    fn as_text(&self) -> String;
}

impl StdoutText for String {
    fn as_text(&self) -> String {
        self.clone()
    }
}

impl StdoutText for Vec<u8> {
    fn as_text(&self) -> String {
        String::from_utf8_lossy(self).into_owned()
    }
}

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

    #[test]
    fn outcome_accessors_match_each_variant() {
        // The bare-`Outcome` accessors, so callers needn't `match` a
        // non_exhaustive enum with a wildcard.
        assert_eq!(Outcome::Exited(7).code(), Some(7));
        assert_eq!(Outcome::Exited(7).signal(), None);
        assert!(!Outcome::Exited(7).timed_out());

        assert_eq!(Outcome::Signalled(Some(9)).signal(), Some(9));
        assert_eq!(Outcome::Signalled(Some(9)).code(), None);
        assert_eq!(Outcome::Signalled(None).signal(), None);
        assert!(!Outcome::Signalled(None).timed_out());

        assert!(Outcome::TimedOut.timed_out());
        assert_eq!(Outcome::TimedOut.code(), None);
        assert_eq!(Outcome::TimedOut.signal(), None);

        // The accessors agree with the ProcessResult-level ones derived from the
        // same outcome.
        let exited = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Outcome::Exited(2),
            None,
        );
        assert_eq!(exited.outcome().code(), exited.code());
        assert_eq!(exited.outcome().signal(), exited.signal());
        assert_eq!(exited.outcome().timed_out(), exited.timed_out());

        let killed = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Outcome::Signalled(Some(9)),
            None,
        );
        assert_eq!(killed.signal(), Some(9));
        assert_eq!(killed.code(), None);
    }

    #[test]
    fn outcome_reflects_the_three_terminal_states() {
        let exited = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Outcome::Exited(3),
            None,
        );
        assert_eq!(exited.outcome(), Outcome::Exited(3));

        let signalled = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Outcome::Signalled(None),
            None,
        );
        assert_eq!(signalled.outcome(), Outcome::Signalled(None));

        let timed_out = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Outcome::TimedOut,
            None,
        );
        assert_eq!(timed_out.outcome(), Outcome::TimedOut);
    }

    #[test]
    fn signalled_carries_signal_number() {
        let killed = ProcessResult::new(
            "git".into(),
            "out".to_owned(),
            String::new(),
            Outcome::Signalled(Some(9)),
            None,
        );
        assert_eq!(killed.code(), None);
        assert!(!killed.timed_out());
        assert!(!killed.is_success());
        assert_eq!(killed.outcome(), Outcome::Signalled(Some(9)));
        match killed.ensure_success().unwrap_err() {
            // The captured stdout flows into the error.
            Error::Signalled {
                program,
                signal,
                stdout,
                ..
            } => {
                assert_eq!(program, "git");
                assert_eq!(signal, Some(9));
                assert_eq!(stdout, "out");
            }
            other => panic!("expected Signalled, got {other:?}"),
        }
    }

    #[test]
    fn derived_accessors_agree_with_outcome() {
        for outcome in [
            Outcome::Exited(0),
            Outcome::Exited(7),
            Outcome::Signalled(None),
            Outcome::TimedOut,
        ] {
            let r = ProcessResult::new("x".into(), String::new(), String::new(), outcome, None);
            match r.outcome() {
                Outcome::Exited(c) => {
                    assert_eq!(r.code(), Some(c));
                    assert!(!r.timed_out());
                    assert_eq!(r.is_success(), c == 0);
                }
                Outcome::Signalled(_) => {
                    assert_eq!(r.code(), None);
                    assert!(!r.timed_out());
                    assert!(!r.is_success());
                }
                Outcome::TimedOut => {
                    assert_eq!(r.code(), None);
                    assert!(r.timed_out());
                    assert!(!r.is_success());
                }
            }
        }
    }

    #[test]
    fn success_is_code_zero() {
        let ok = ProcessResult::new(
            "git".into(),
            "out".to_owned(),
            String::new(),
            Outcome::Exited(0),
            None,
        );
        assert!(ok.is_success());
        assert_eq!(ok.code(), Some(0));
        assert!(ok.ensure_success().is_ok());
    }

    #[test]
    fn nonzero_exit_carries_both_streams() {
        let bad = ProcessResult::new(
            "git".into(),
            "CONFLICT (content): merge conflict in a.rs".to_owned(),
            "boom".to_owned(),
            Outcome::Exited(2),
            None,
        );
        assert!(!bad.is_success());
        assert_eq!(bad.code(), Some(2));
        let err = bad.ensure_success().unwrap_err();
        match err {
            Error::Exit {
                program,
                code,
                stdout,
                stderr,
            } => {
                assert_eq!(program, "git");
                assert_eq!(code, 2);
                assert_eq!(stdout, "CONFLICT (content): merge conflict in a.rs");
                assert_eq!(stderr, "boom");
            }
            other => panic!("expected Exit, got {other:?}"),
        }
    }

    #[test]
    fn diagnostic_prefers_stderr_then_falls_back_to_stdout() {
        let with_stderr = ProcessResult::new(
            "git".into(),
            "on stdout".into(),
            "  on stderr \n".into(),
            Outcome::Exited(1),
            None,
        );
        assert_eq!(with_stderr.diagnostic(), "on stderr");
        assert_eq!(
            with_stderr.ensure_success().unwrap_err().diagnostic(),
            Some("on stderr")
        );

        // stderr blank → stdout (where `git merge` writes CONFLICT) is the message.
        let conflict = ProcessResult::new(
            "git".into(),
            "CONFLICT (content): merge conflict in a.rs".into(),
            "   \n".into(),
            Outcome::Exited(1),
            None,
        );
        assert_eq!(
            conflict.diagnostic(),
            "CONFLICT (content): merge conflict in a.rs"
        );
        let Error::Exit { .. } = conflict.clone().ensure_success().unwrap_err() else {
            panic!("expected Exit");
        };
        assert_eq!(
            conflict.ensure_success().unwrap_err().diagnostic(),
            Some("CONFLICT (content): merge conflict in a.rs")
        );

        // Both streams blank → no captured message; the caller falls back to the
        // Display text rather than an empty string.
        let silent = ProcessResult::new(
            "git".into(),
            String::new(),
            "  \n".into(),
            Outcome::Exited(1),
            None,
        );
        assert_eq!(silent.ensure_success().unwrap_err().diagnostic(), None);
    }

    #[test]
    fn timed_out_takes_precedence_over_exit_code() {
        // A timed-out run must report as a distinct Timeout, not a non-zero Exit.
        let timed = ProcessResult::new(
            "git".into(),
            "out".to_owned(),
            String::new(),
            Outcome::TimedOut,
            Some(Duration::from_millis(500)),
        );
        assert!(timed.timed_out());
        assert_eq!(timed.code(), None);
        match timed.ensure_success().unwrap_err() {
            Error::Timeout {
                program,
                timeout,
                stdout,
                ..
            } => {
                assert_eq!(program, "git");
                assert_eq!(timeout, Duration::from_millis(500));
                // Partial stdout captured before the kill is carried.
                assert_eq!(stdout, "out");
            }
            other => panic!("expected Timeout, got {other:?}"),
        }
    }

    #[test]
    fn signal_kill_surfaces_as_signalled_error() {
        // A signal-terminated run (no code, not a timeout) must surface
        // `Error::Signalled` from both `require_code` and `ensure_success`,
        // never a synthetic `Error::Exit { code: -1 }` sentinel.
        let killed = ProcessResult::new(
            "git".into(),
            "out".to_owned(),
            String::new(),
            Outcome::Signalled(None),
            None,
        );
        assert_eq!(killed.code(), None);
        assert!(!killed.is_success());
        assert!(matches!(
            killed.require_code().unwrap_err(),
            Error::Signalled { .. }
        ));
        match killed.ensure_success().unwrap_err() {
            Error::Signalled {
                program, signal, ..
            } => {
                assert_eq!(program, "git");
                assert_eq!(signal, None);
            }
            other => panic!("expected Signalled for a signal-kill, got {other:?}"),
        }
    }

    #[test]
    fn combined_concatenates_stdout_then_stderr() {
        let r = ProcessResult::new(
            "p".into(),
            "out".to_owned(),
            "err".to_owned(),
            Outcome::Exited(0),
            None,
        );
        // A newline separator is inserted so the last stdout line is not glued
        // to the first stderr line.
        assert_eq!(r.combined(), "out\nerr");
    }

    #[test]
    fn combined_no_extra_newline_when_stdout_already_ends_with_newline() {
        // When stdout ends with \n, no extra newline is added.
        let r = ProcessResult::new(
            "p".into(),
            "out\n".to_owned(),
            "err".to_owned(),
            Outcome::Exited(0),
            None,
        );
        assert_eq!(r.combined(), "out\nerr");
    }

    #[test]
    fn combined_no_separator_when_one_stream_is_empty() {
        let stdout_only = ProcessResult::new(
            "p".into(),
            "out".to_owned(),
            String::new(),
            Outcome::Exited(0),
            None,
        );
        assert_eq!(stdout_only.combined(), "out");

        let stderr_only = ProcessResult::new(
            "p".into(),
            String::new(),
            "err".to_owned(),
            Outcome::Exited(0),
            None,
        );
        assert_eq!(stderr_only.combined(), "err");
    }

    #[test]
    fn error_exit_carries_full_streams() {
        // The error fields must carry the complete captured streams — consumers
        // classify on them (grep for a marker, parse a code). The `Display` impl
        // bounds what it *prints*; the fields stay whole.
        let big = "x".repeat(10_000);
        let bad = ProcessResult::new(
            "p".into(),
            big.clone().into_bytes(),
            big.clone(),
            Outcome::Exited(1),
            None,
        );
        assert_eq!(bad.stderr().len(), 10_000);
        let Error::Exit { stdout, stderr, .. } = bad.ensure_success().unwrap_err() else {
            panic!("expected Exit");
        };
        assert_eq!(stdout.len(), 10_000, "full stdout carried, untruncated");
        assert_eq!(stderr.len(), 10_000, "full stderr carried, untruncated");
        assert!(stdout.chars().all(|c| c == 'x'));
        assert!(stderr.chars().all(|c| c == 'x'));
    }

    #[test]
    fn ok_codes_widen_success_without_masking_other_failures() {
        let one = ProcessResult::new(
            "grep".into(),
            "out".to_owned(),
            String::new(),
            Outcome::Exited(1),
            None,
        )
        .with_ok_codes(vec![0, 1]);
        assert!(one.is_success(), "exit 1 is success when accepted");
        assert!(one.ensure_success().is_ok());

        let two = ProcessResult::new(
            "grep".into(),
            "out".to_owned(),
            String::new(),
            Outcome::Exited(2),
            None,
        )
        .with_ok_codes(vec![0, 1]);
        assert!(!two.is_success(), "an unaccepted code is still a failure");
        assert!(matches!(
            two.ensure_success().unwrap_err(),
            Error::Exit { code: 2, .. }
        ));
    }

    #[test]
    fn new_defaults_zero_duration_untruncated_and_zero_only_success() {
        let r = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Outcome::Exited(1),
            None,
        );
        assert_eq!(r.duration(), Duration::ZERO);
        assert!(!r.truncated());
        assert!(!r.is_success(), "the default accepts only code 0");

        let stamped = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Outcome::Exited(0),
            None,
        )
        .with_duration(Duration::from_millis(5))
        .with_truncated(true);
        assert_eq!(stamped.duration(), Duration::from_millis(5));
        assert!(stamped.truncated());
        assert!(stamped.is_success());
    }

    #[test]
    fn checking_verbs_reject_truncated_output() {
        // A checking verb that hands back stdout (run/parse/try_parse) must refuse
        // silently-truncated output, surfacing OutputTooLarge with the configured
        // limits and the totals seen — not feed a parser a tail.
        let truncated = ProcessResult::new(
            "p".into(),
            "tail".to_owned(),
            String::new(),
            Outcome::Exited(0),
            None,
        )
        .with_truncated(true)
        .with_overflow_totals(5000, 1_000_000);
        match truncated.reject_if_truncated(Some(100), None) {
            Err(Error::OutputTooLarge {
                program,
                line_limit,
                byte_limit,
                total_lines,
                total_bytes,
            }) => {
                assert_eq!(program, "p");
                assert_eq!(line_limit, Some(100));
                assert_eq!(byte_limit, None);
                assert_eq!(total_lines, 5000);
                assert_eq!(total_bytes, 1_000_000);
            }
            other => panic!("expected OutputTooLarge, got {other:?}"),
        }

        // A complete (untruncated) result passes.
        let complete = ProcessResult::new(
            "p".into(),
            "full".to_owned(),
            String::new(),
            Outcome::Exited(0),
            None,
        );
        assert!(complete.reject_if_truncated(Some(100), None).is_ok());
    }

    #[test]
    fn empty_ok_codes_is_ignored() {
        let r = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Outcome::Exited(0),
            None,
        )
        .with_ok_codes(vec![]);
        assert!(
            r.is_success(),
            "an empty accepted set falls back to the default [0]"
        );
    }

    #[test]
    fn equality_ignores_duration_and_truncation() {
        // The cassette round-trip relies on this: a recorded result (non-zero
        // duration) must compare equal to its replay (Duration::ZERO).
        let base = ProcessResult::new(
            "p".into(),
            "out".to_owned(),
            String::new(),
            Outcome::Exited(0),
            None,
        );
        let measured = base
            .clone()
            .with_duration(Duration::from_secs(5))
            .with_truncated(true);
        assert_eq!(
            base, measured,
            "duration and truncation are not part of identity"
        );

        // …but the logical fields still distinguish results.
        let different = ProcessResult::new(
            "p".into(),
            "DIFF".to_owned(),
            String::new(),
            Outcome::Exited(0),
            None,
        );
        assert_ne!(base, different);
        let widened = base.clone().with_ok_codes(vec![0, 1]);
        assert_ne!(base, widened, "ok_codes is part of identity");
    }
}