Skip to main content

magi/
verify_evidence.rs

1//! Pure terminal-failure extraction, comparison, and formatting for verification commands.
2//!
3//! When `graph::run_e2e_with_retry` runs a failed `verify.e2e` command a second time on
4//! the same commit and both attempts exit non-zero, exiting non-zero twice proves only
5//! that verification stays red — not that the same test failed twice. This module parses
6//! raw command output (before `run::summarize_verify` reduces it) to extract confirmed,
7//! count-reconciled terminal test failures, separates intermediate `TRY` failures,
8//! `FLAKY` passes, and cancellations from terminal verdicts, compares both attempts
9//! conservatively (`Matching`, `Distinct`, or `Unknown`), and formats the saved record
10//! consistently across events, CLI/web reports, fixer prompts, recovery evidence, stop
11//! reasons, and automatic task chat reports.
12
13use std::collections::BTreeSet;
14use std::fmt::Write as _;
15
16use serde::{Deserialize, Serialize};
17
18use crate::run::{CommandOutcome, E2eStatus, RunState, summarize_verify};
19
20/// Maximum number of terminal failures captured in a confirmed set. Exceeding this
21/// yields [`FailureExtraction::Unknown`] so truncated sets are never compared as complete.
22pub const MAX_TERMINAL_FAILURES: usize = 32;
23
24/// Maximum number of test names retained per intermediate category (`TRY`, `FLAKY`, etc.).
25pub const MAX_INTERMEDIATE_NAMES: usize = 8;
26
27/// Maximum byte length of the bounded excerpt stored per attempt inside [`RerunComparison`].
28pub const ATTEMPT_EXCERPT_MAX: usize = 4_000;
29
30/// Maximum number of failure names listed inline in one-line summaries before `+N more`.
31pub const DISPLAY_FAILURE_LIMIT: usize = 6;
32
33/// Legacy prefix previously injected into `output_tail` on double failures.
34/// Older `run.json` records carrying this prefix have no structured attempt comparison
35/// and must be treated as an unknown comparison rather than proof of a reproduced failure.
36pub const LEGACY_FAILED_TWICE_PREFIX: &str =
37    "[this command failed twice on the same commit; the output below is the second attempt's]";
38
39/// One confirmed terminal test failure (optional test binary/suite + test name).
40#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
41pub struct TerminalFailure {
42    /// Test binary or target identifier when known (e.g. `magi-cli::isolated_build_cache`).
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub suite: Option<String>,
45    /// Test name within the suite.
46    pub test: String,
47}
48
49impl TerminalFailure {
50    /// Human-readable display label (`<suite> <test>` or `<test>`).
51    pub fn display_name(&self) -> String {
52        match &self.suite {
53            Some(suite) if !suite.is_empty() => format!("{suite} {}", self.test),
54            _ => self.test.clone(),
55        }
56    }
57}
58
59/// Intermediate / non-terminal test activity observed in raw output, kept strictly
60/// separate from terminal failures.
61#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
62pub struct IntermediateNotes {
63    /// Number of intermediate retry failure lines (`TRY N FAIL` / `TRY N TIMEOUT` / ...).
64    #[serde(default)]
65    pub try_failure_count: usize,
66    /// Bounded sample of test identifiers seen in `TRY N` failure lines.
67    #[serde(default, skip_serializing_if = "Vec::is_empty")]
68    pub try_failures: Vec<String>,
69    /// Number of tests that passed on retry (`FLAKY`).
70    #[serde(default)]
71    pub flaky_count: usize,
72    /// Bounded sample of test identifiers marked `FLAKY`.
73    #[serde(default, skip_serializing_if = "Vec::is_empty")]
74    pub flaky: Vec<String>,
75    /// Whether the test runner reported cancellations or partial execution (`M/N tests run`).
76    #[serde(default)]
77    pub cancelled: bool,
78    /// Number of tests not run due to cancellation, when reported in the summary.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub not_run_count: Option<usize>,
81    /// Bounded sample of long-running test notices (`has been running for over ...`).
82    #[serde(default, skip_serializing_if = "Vec::is_empty")]
83    pub long_running: Vec<String>,
84}
85
86impl IntermediateNotes {
87    /// True when no intermediate retries, flaky passes, cancellations, or hangs were observed.
88    pub fn is_empty(&self) -> bool {
89        self.try_failure_count == 0
90            && self.try_failures.is_empty()
91            && self.flaky_count == 0
92            && self.flaky.is_empty()
93            && !self.cancelled
94            && self.not_run_count.is_none()
95            && self.long_running.is_empty()
96    }
97
98    fn record_try(&mut self, label: String) {
99        self.try_failure_count += 1;
100        push_bounded_unique(&mut self.try_failures, label, MAX_INTERMEDIATE_NAMES);
101    }
102
103    fn record_flaky(&mut self, label: String) {
104        if !self.flaky.contains(&label) {
105            self.flaky_count += 1;
106            push_bounded_unique(&mut self.flaky, label, MAX_INTERMEDIATE_NAMES);
107        }
108    }
109
110    fn record_long_running(&mut self, label: String) {
111        push_bounded_unique(&mut self.long_running, label, MAX_INTERMEDIATE_NAMES);
112    }
113
114    /// Compact human-readable summary of separated non-terminal activity, or `None` when empty.
115    pub fn summary(&self) -> Option<String> {
116        let mut parts = Vec::new();
117        if self.try_failure_count > 0 {
118            if self.try_failures.is_empty() {
119                parts.push(format!(
120                    "{} intermediate TRY failure(s)",
121                    self.try_failure_count
122                ));
123            } else {
124                parts.push(format!(
125                    "{} intermediate TRY failure(s) ({})",
126                    self.try_failure_count,
127                    join_bounded(&self.try_failures, 3)
128                ));
129            }
130        }
131        if self.flaky_count > 0 {
132            if self.flaky.is_empty() {
133                parts.push(format!("{} FLAKY pass(es)", self.flaky_count));
134            } else {
135                parts.push(format!(
136                    "{} FLAKY pass(es) ({})",
137                    self.flaky_count,
138                    join_bounded(&self.flaky, 3)
139                ));
140            }
141        }
142        if self.cancelled {
143            match self.not_run_count {
144                Some(n) if n > 0 => parts.push(format!("cancelled ({n} test(s) not run)")),
145                _ => parts.push("cancelled".to_owned()),
146            }
147        }
148        if !self.long_running.is_empty() {
149            parts.push(format!(
150                "long-running test(s): {}",
151                join_bounded(&self.long_running, 3)
152            ));
153        }
154        (!parts.is_empty()).then(|| parts.join("; "))
155    }
156}
157
158/// Result of extracting terminal test failures from one attempt's raw output.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160#[serde(tag = "kind", rename_all = "snake_case")]
161pub enum FailureExtraction {
162    /// Complete, count-reconciled, non-empty set of terminal failing tests.
163    Confirmed {
164        /// Sorted, deduplicated terminal failing tests.
165        failures: Vec<TerminalFailure>,
166    },
167    /// Terminal failing tests could not be confirmed completely.
168    Unknown {
169        /// Why completeness could not be confirmed.
170        reason: String,
171    },
172}
173
174/// Extracted terminal failure set paired with separated intermediate activity for one attempt.
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176pub struct FailureEvidence {
177    /// Confirmed terminal failures or why they are unknown.
178    pub extraction: FailureExtraction,
179    /// Intermediate retries (`TRY`), `FLAKY` passes, and cancellations, kept separate.
180    #[serde(default)]
181    pub intermediate: IntermediateNotes,
182}
183
184/// Bounded evidence preserved for one verification attempt in a two-attempt rerun pair.
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct AttemptEvidence {
187    /// 1-based attempt number (`1` = first failure, `2` = rerun).
188    pub attempt: u8,
189    /// Process exit code, or `None` on timeout/signal/spawn error.
190    pub code: Option<i32>,
191    /// Wall-clock duration in milliseconds.
192    #[serde(default)]
193    pub duration_ms: u64,
194    /// Run-relative artifact path (e.g. `artifacts/e2e-3.out`), when saved.
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub artifact: Option<String>,
197    /// Bounded output excerpt (within [`ATTEMPT_EXCERPT_MAX`]).
198    #[serde(default)]
199    pub excerpt: String,
200    /// Terminal failure extraction from raw output.
201    pub extraction: FailureExtraction,
202    /// Intermediate retries, flaky passes, and cancellations, kept separate.
203    #[serde(default)]
204    pub intermediate: IntermediateNotes,
205}
206
207impl AttemptEvidence {
208    /// Build bounded attempt evidence from a finished [`CommandOutcome`].
209    pub fn from_outcome(attempt: u8, outcome: &CommandOutcome) -> Self {
210        let (extraction, intermediate) = match &outcome.failure_evidence {
211            Some(ev) => (ev.extraction.clone(), ev.intermediate.clone()),
212            None => (
213                FailureExtraction::Unknown {
214                    reason: "no raw failure extraction recorded".to_owned(),
215                },
216                IntermediateNotes::default(),
217            ),
218        };
219        Self {
220            attempt,
221            code: outcome.code,
222            duration_ms: outcome.duration_ms,
223            artifact: outcome.artifact.clone(),
224            excerpt: summarize_verify(&outcome.output_tail, ATTEMPT_EXCERPT_MAX),
225            extraction,
226            intermediate,
227        }
228    }
229
230    /// Return a copy with `excerpt` scrubbed through `scrub`.
231    pub fn scrubbed(&self, scrub: impl Fn(&str) -> String) -> Self {
232        let mut copy = self.clone();
233        copy.excerpt = scrub(&copy.excerpt);
234        copy
235    }
236}
237
238/// Conservative comparison verdict between two consecutive failing attempts on one commit.
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(tag = "kind", rename_all = "snake_case")]
241pub enum ComparisonVerdict {
242    /// Both attempts had confirmed, non-empty, identical terminal test failure sets.
243    Matching {
244        /// Confirmed terminal failures present in both attempts.
245        failures: Vec<TerminalFailure>,
246    },
247    /// Both attempts had confirmed, non-empty, differing terminal test failure sets.
248    Distinct {
249        /// Terminal failures present in both attempts.
250        #[serde(default, skip_serializing_if = "Vec::is_empty")]
251        common: Vec<TerminalFailure>,
252        /// Terminal failures present only in the first attempt.
253        #[serde(default, skip_serializing_if = "Vec::is_empty")]
254        first_only: Vec<TerminalFailure>,
255        /// Terminal failures present only in the second attempt.
256        #[serde(default, skip_serializing_if = "Vec::is_empty")]
257        second_only: Vec<TerminalFailure>,
258    },
259    /// At least one attempt's terminal test failures could not be confirmed.
260    Unknown {
261        /// Why the two attempts could not be compared conclusively.
262        reason: String,
263    },
264}
265
266/// Structured record persisted on a [`CommandOutcome`] that failed twice on one commit.
267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268pub struct RerunComparison {
269    /// Commit SHA both attempts ran against.
270    pub head: String,
271    /// First failing attempt's bounded evidence.
272    pub first: AttemptEvidence,
273    /// Second failing attempt's bounded evidence.
274    pub second: AttemptEvidence,
275    /// Conservative comparison verdict (`Matching`, `Distinct`, or `Unknown`).
276    pub verdict: ComparisonVerdict,
277}
278
279impl RerunComparison {
280    /// Return a copy with attempt excerpts scrubbed through `scrub`.
281    pub fn scrubbed(&self, scrub: impl Fn(&str) -> String) -> Self {
282        Self {
283            head: self.head.clone(),
284            first: self.first.scrubbed(&scrub),
285            second: self.second.scrubbed(&scrub),
286            verdict: self.verdict.clone(),
287        }
288    }
289}
290
291/// True when `output_tail` begins with the legacy double-failure prefix that predates
292/// structured [`RerunComparison`].
293pub fn legacy_failed_twice(output_tail: &str) -> bool {
294    output_tail
295        .trim_start()
296        .starts_with(LEGACY_FAILED_TWICE_PREFIX)
297}
298
299/// Strip ANSI CSI/OSC escape sequences and trailing `\r` from one line.
300pub fn strip_ansi(line: &str) -> String {
301    let line = line.strip_suffix('\r').unwrap_or(line);
302    let mut out = String::with_capacity(line.len());
303    let mut chars = line.chars().peekable();
304    while let Some(c) = chars.next() {
305        if c == '\x1b' {
306            match chars.peek().copied() {
307                Some('[') => {
308                    chars.next();
309                    for ch in chars.by_ref() {
310                        if ('@'..='~').contains(&ch) {
311                            break;
312                        }
313                    }
314                }
315                Some(']') => {
316                    chars.next();
317                    while let Some(ch) = chars.next() {
318                        if ch == '\x07' {
319                            break;
320                        }
321                        if ch == '\x1b' && chars.peek() == Some(&'\\') {
322                            chars.next();
323                            break;
324                        }
325                    }
326                }
327                _ => {}
328            }
329        } else {
330            out.push(c);
331        }
332    }
333    out
334}
335
336/// Extract terminal test failures and intermediate notes from separate raw `stdout` and
337/// `stderr` streams. Neither stream's order is assumed to imply wall-clock execution order.
338pub fn extract_streams(
339    code: Option<i32>,
340    build_failed: bool,
341    stdout: &str,
342    stderr: &str,
343) -> FailureEvidence {
344    let out_lines: Vec<String> = stdout.lines().map(strip_ansi).collect();
345    let err_lines: Vec<String> = stderr.lines().map(strip_ansi).collect();
346    extract_line_streams(code, build_failed, &[&out_lines, &err_lines])
347}
348
349/// Extract terminal test failures and intermediate notes from a single combined raw output.
350pub fn extract_combined(code: Option<i32>, build_failed: bool, body: &str) -> FailureEvidence {
351    let lines: Vec<String> = body.lines().map(strip_ansi).collect();
352    extract_line_streams(code, build_failed, &[&lines])
353}
354
355fn extract_line_streams(
356    code: Option<i32>,
357    build_failed: bool,
358    streams: &[&[String]],
359) -> FailureEvidence {
360    let mut intermediate = IntermediateNotes::default();
361    let mut libtest_total = LibtestSummary::default();
362    let mut nextest_total = NextestSummary::default();
363
364    for lines in streams {
365        let (lib, captured_ranges) = parse_libtest_stream(lines, &mut intermediate);
366        libtest_total.merge(lib);
367        let nx = parse_nextest_stream(lines, &captured_ranges, &mut intermediate);
368        nextest_total.merge(nx);
369    }
370
371    // Cargo writes binary announcements and libtest verdicts to different pipes.
372    // Without interleaving information, only a single announcement and a single
373    // libtest run can be associated unambiguously.
374    if libtest_total.runs == 1 && libtest_total.suites == 1 {
375        for failure in &mut libtest_total.failures {
376            if failure.suite.is_none() {
377                failure.suite.clone_from(&libtest_total.only_suite);
378            }
379        }
380    }
381
382    let extraction = if code.is_none() {
383        FailureExtraction::Unknown {
384            reason: "command timed out or terminated without an exit code".to_owned(),
385        }
386    } else if code == Some(0) {
387        FailureExtraction::Unknown {
388            reason: "command exited 0".to_owned(),
389        }
390    } else if build_failed {
391        FailureExtraction::Unknown {
392            reason: "command failed to build or link".to_owned(),
393        }
394    } else if libtest_total.incomplete || nextest_total.incomplete {
395        FailureExtraction::Unknown {
396            reason: "test run did not finish with a final summary".to_owned(),
397        }
398    } else if libtest_total.overflow || nextest_total.overflow {
399        FailureExtraction::Unknown {
400            reason: format!(
401                "more than {MAX_TERMINAL_FAILURES} terminal test failures reported; complete comparison unavailable"
402            ),
403        }
404    } else if libtest_total.inconsistent || nextest_total.inconsistent {
405        FailureExtraction::Unknown {
406            reason: "reported failure count did not match listed terminal failures".to_owned(),
407        }
408    } else if libtest_total.failed_runs > 0 && nextest_total.failed_runs > 0 {
409        FailureExtraction::Unknown {
410            reason: "multiple test runners reported failures in one command; completeness cannot be confirmed"
411                .to_owned(),
412        }
413    } else if nextest_total.failed_runs > 0 {
414        finalize_confirmed(nextest_total.expected_failures, nextest_total.failures)
415    } else if libtest_total.failed_runs > 0 {
416        finalize_confirmed(libtest_total.expected_failures, libtest_total.failures)
417    } else {
418        FailureExtraction::Unknown {
419            reason: "command exited non-zero without a complete failing test summary".to_owned(),
420        }
421    };
422
423    FailureEvidence {
424        extraction,
425        intermediate,
426    }
427}
428
429fn finalize_confirmed(expected: usize, raw: Vec<TerminalFailure>) -> FailureExtraction {
430    if expected == 0 || raw.is_empty() {
431        return FailureExtraction::Unknown {
432            reason: "no terminal test failures were listed in the final summary".to_owned(),
433        };
434    }
435    if expected > MAX_TERMINAL_FAILURES || raw.len() > MAX_TERMINAL_FAILURES {
436        return FailureExtraction::Unknown {
437            reason: format!(
438                "more than {MAX_TERMINAL_FAILURES} terminal test failures reported; complete comparison unavailable"
439            ),
440        };
441    }
442    let set: BTreeSet<TerminalFailure> = raw.into_iter().collect();
443    if set.len() != expected {
444        return FailureExtraction::Unknown {
445            reason: format!(
446                "reported failure count ({expected}) did not match distinct terminal failures ({})",
447                set.len()
448            ),
449        };
450    }
451    FailureExtraction::Confirmed {
452        failures: set.into_iter().collect(),
453    }
454}
455
456/// Compare two consecutive failing attempts of the same command on commit `head`.
457pub fn compare_attempts(
458    head: &str,
459    first: &CommandOutcome,
460    second: &CommandOutcome,
461) -> RerunComparison {
462    let first_ev = AttemptEvidence::from_outcome(1, first);
463    let second_ev = AttemptEvidence::from_outcome(2, second);
464    let verdict = match (&first_ev.extraction, &second_ev.extraction) {
465        (
466            FailureExtraction::Confirmed { failures: f1 },
467            FailureExtraction::Confirmed { failures: f2 },
468        ) if !f1.is_empty() && !f2.is_empty() => {
469            if f1.iter().chain(f2).any(|f| f.suite.is_none()) {
470                ComparisonVerdict::Unknown {
471                    reason: "terminal failure has no confirmed test binary".to_owned(),
472                }
473            } else if f1 == f2 {
474                ComparisonVerdict::Matching {
475                    failures: f1.clone(),
476                }
477            } else {
478                let s1: BTreeSet<&TerminalFailure> = f1.iter().collect();
479                let s2: BTreeSet<&TerminalFailure> = f2.iter().collect();
480                let common = s1.intersection(&s2).map(|f| (*f).clone()).collect();
481                let first_only = s1.difference(&s2).map(|f| (*f).clone()).collect();
482                let second_only = s2.difference(&s1).map(|f| (*f).clone()).collect();
483                ComparisonVerdict::Distinct {
484                    common,
485                    first_only,
486                    second_only,
487                }
488            }
489        }
490        (FailureExtraction::Unknown { reason: r1 }, FailureExtraction::Unknown { reason: r2 }) => {
491            ComparisonVerdict::Unknown {
492                reason: if r1 == r2 {
493                    format!("both attempts: {r1}")
494                } else {
495                    format!("attempt 1: {r1}; attempt 2: {r2}")
496                },
497            }
498        }
499        (FailureExtraction::Unknown { reason }, _) => ComparisonVerdict::Unknown {
500            reason: format!("attempt 1: {reason}"),
501        },
502        (_, FailureExtraction::Unknown { reason }) => ComparisonVerdict::Unknown {
503            reason: format!("attempt 2: {reason}"),
504        },
505        _ => ComparisonVerdict::Unknown {
506            reason: "empty confirmed terminal failure set".to_owned(),
507        },
508    };
509    RerunComparison {
510        head: head.to_owned(),
511        first: first_ev,
512        second: second_ev,
513        verdict,
514    }
515}
516
517// ---------------------------------------------------------------------------
518// Libtest parser
519// ---------------------------------------------------------------------------
520
521#[derive(Default)]
522struct LibtestSummary {
523    runs: usize,
524    suites: usize,
525    only_suite: Option<String>,
526    failed_runs: usize,
527    expected_failures: usize,
528    failures: Vec<TerminalFailure>,
529    incomplete: bool,
530    inconsistent: bool,
531    overflow: bool,
532}
533
534impl LibtestSummary {
535    fn merge(&mut self, other: Self) {
536        self.runs += other.runs;
537        self.suites += other.suites;
538        if other.only_suite.is_some() {
539            self.only_suite = other.only_suite;
540        }
541        self.failed_runs += other.failed_runs;
542        self.expected_failures += other.expected_failures;
543        self.failures.extend(other.failures);
544        self.incomplete |= other.incomplete;
545        self.inconsistent |= other.inconsistent;
546        self.overflow |= other.overflow;
547    }
548}
549
550struct ActiveLibtest {
551    expected_total: usize,
552    suite: Option<String>,
553    live_failed: BTreeSet<String>,
554    in_failures_section: bool,
555    captured_start: Option<usize>,
556    collecting_list: bool,
557    current_list: Vec<String>,
558    last_valid_closing: Option<(usize, usize, Vec<String>)>,
559    saw_overflow: bool,
560}
561
562struct LibtestResultLine {
563    ok: bool,
564    passed: usize,
565    failed: usize,
566    ignored: usize,
567    measured: usize,
568}
569
570impl LibtestResultLine {
571    fn total(&self) -> usize {
572        self.passed + self.failed + self.ignored + self.measured
573    }
574}
575
576fn parse_libtest_stream(
577    lines: &[String],
578    intermediate: &mut IntermediateNotes,
579) -> (LibtestSummary, Vec<(usize, usize)>) {
580    let mut summary = LibtestSummary::default();
581    let mut captured_ranges: Vec<(usize, usize)> = Vec::new();
582    let mut pending_suite: Option<String> = None;
583    let mut active: Option<ActiveLibtest> = None;
584    let mut standalone_collecting = false;
585    let mut standalone_list: Vec<String> = Vec::new();
586    let mut nextest_captured = false;
587
588    let commit_active = |run: ActiveLibtest,
589                         summary: &mut LibtestSummary,
590                         captured_ranges: &mut Vec<(usize, usize)>| {
591        if run.saw_overflow {
592            summary.overflow = true;
593        } else if let Some((end_line, expected_f, list)) = run.last_valid_closing {
594            if let Some(start) = run.captured_start {
595                captured_ranges.push((start, end_line));
596            }
597            summary.failed_runs += 1;
598            summary.expected_failures += expected_f;
599            for test in list {
600                summary.failures.push(TerminalFailure {
601                    suite: run.suite.clone(),
602                    test,
603                });
604            }
605        } else {
606            summary.incomplete = true;
607        }
608    };
609
610    for (idx, line) in lines.iter().enumerate() {
611        let trimmed = line.trim();
612
613        // If an active libtest run already found a valid closing summary and a new
614        // top-level runner boundary begins, close the previous run first.
615        if let Some(run) = active.as_ref()
616            && run.in_failures_section
617            && run.last_valid_closing.is_some()
618            && (parse_libtest_running_header(trimmed).is_some()
619                || parse_cargo_running_suite(trimmed).is_some()
620                || parse_nextest_summary_header(trimmed).is_some()
621                || trimmed == "------------")
622            && let Some(finished) = active.take()
623        {
624            commit_active(finished, &mut summary, &mut captured_ranges);
625        }
626
627        if active.is_none() {
628            if is_nextest_captured_header(trimmed) {
629                nextest_captured = true;
630                continue;
631            }
632            if nextest_captured {
633                if trimmed == "------------" {
634                    nextest_captured = false;
635                } else {
636                    continue;
637                }
638            }
639        }
640
641        if let Some(run) = active.as_mut() {
642            if !run.in_failures_section {
643                if trimmed == "failures:" && !line.starts_with(' ') {
644                    run.in_failures_section = true;
645                    run.captured_start = Some(idx);
646                    run.collecting_list = true;
647                    run.current_list.clear();
648                } else if let Some(name) = parse_libtest_live_failed(trimmed) {
649                    run.live_failed.insert(name);
650                } else if let Some(name) = parse_libtest_long_running(trimmed) {
651                    intermediate.record_long_running(name);
652                } else if let Some(res) = parse_libtest_result(trimmed) {
653                    if res.ok
654                        && res.failed == 0
655                        && res.total() == run.expected_total
656                        && run.live_failed.is_empty()
657                    {
658                        active = None;
659                    } else {
660                        summary.inconsistent = true;
661                        active = None;
662                    }
663                } else if parse_libtest_running_header(trimmed).is_some()
664                    || parse_nextest_summary_header(trimmed).is_some()
665                {
666                    if let Some(unfinished) = active.take() {
667                        commit_active(unfinished, &mut summary, &mut captured_ranges);
668                    }
669                    if let Some(total) = parse_libtest_running_header(trimmed) {
670                        summary.runs += 1;
671                        active = Some(new_active_libtest(total, pending_suite.take()));
672                    }
673                }
674            } else {
675                // Inside failures: section (captured output + final failures list).
676                if trimmed == "failures:" && !line.starts_with(' ') {
677                    run.collecting_list = true;
678                    run.current_list.clear();
679                } else if run.collecting_list {
680                    if line.starts_with("    ")
681                        && !trimmed.is_empty()
682                        && !trimmed.starts_with("---- ")
683                    {
684                        if run.current_list.len() <= MAX_TERMINAL_FAILURES {
685                            run.current_list.push(trimmed.to_owned());
686                        }
687                    } else if trimmed.is_empty() {
688                        run.collecting_list = false;
689                    } else if let Some(res) = parse_libtest_result(trimmed) {
690                        run.collecting_list = false;
691                        try_close_libtest(run, idx, &res);
692                    } else {
693                        run.collecting_list = false;
694                        run.current_list.clear();
695                    }
696                } else if let Some(res) = parse_libtest_result(trimmed) {
697                    try_close_libtest(run, idx, &res);
698                }
699            }
700            continue;
701        }
702
703        // Idle state (outside an active `running N tests` block).
704        if let Some(suite) = parse_cargo_running_suite(trimmed) {
705            summary.suites += 1;
706            summary.only_suite = Some(suite.clone());
707            pending_suite = Some(suite);
708            standalone_collecting = false;
709            standalone_list.clear();
710        } else if let Some(total) = parse_libtest_running_header(trimmed) {
711            summary.runs += 1;
712            standalone_collecting = false;
713            standalone_list.clear();
714            active = Some(new_active_libtest(total, pending_suite.take()));
715        } else if trimmed == "failures:" && !line.starts_with(' ') {
716            standalone_collecting = true;
717            standalone_list.clear();
718        } else if standalone_collecting {
719            if line.starts_with("    ") && !trimmed.is_empty() && !trimmed.starts_with("---- ") {
720                if standalone_list.len() <= MAX_TERMINAL_FAILURES {
721                    standalone_list.push(trimmed.to_owned());
722                }
723            } else if trimmed.is_empty() {
724                standalone_collecting = false;
725            } else if let Some(res) = parse_libtest_result(trimmed) {
726                standalone_collecting = false;
727                record_standalone_libtest(&res, &standalone_list, &mut summary);
728                standalone_list.clear();
729            } else {
730                standalone_collecting = false;
731                standalone_list.clear();
732            }
733        } else if let Some(res) = parse_libtest_result(trimmed) {
734            record_standalone_libtest(&res, &standalone_list, &mut summary);
735            standalone_list.clear();
736            pending_suite = None;
737        } else if let Some(name) = parse_libtest_long_running(trimmed) {
738            intermediate.record_long_running(name);
739        }
740    }
741
742    if let Some(run) = active.take() {
743        commit_active(run, &mut summary, &mut captured_ranges);
744    }
745
746    (summary, captured_ranges)
747}
748
749fn new_active_libtest(expected_total: usize, suite: Option<String>) -> ActiveLibtest {
750    ActiveLibtest {
751        expected_total,
752        suite,
753        live_failed: BTreeSet::new(),
754        in_failures_section: false,
755        captured_start: None,
756        collecting_list: false,
757        current_list: Vec::new(),
758        last_valid_closing: None,
759        saw_overflow: false,
760    }
761}
762
763fn try_close_libtest(run: &mut ActiveLibtest, idx: usize, res: &LibtestResultLine) {
764    if res.ok || res.failed == 0 || res.total() != run.expected_total {
765        return;
766    }
767    if res.failed > MAX_TERMINAL_FAILURES || run.current_list.len() > MAX_TERMINAL_FAILURES {
768        run.saw_overflow = true;
769        return;
770    }
771    if run.current_list.len() != res.failed {
772        return;
773    }
774    if !run.live_failed.is_empty()
775        && (run.live_failed.len() != res.failed
776            || !run.current_list.iter().all(|n| run.live_failed.contains(n)))
777    {
778        return;
779    }
780    run.last_valid_closing = Some((idx, res.failed, run.current_list.clone()));
781}
782
783fn record_standalone_libtest(
784    res: &LibtestResultLine,
785    list: &[String],
786    summary: &mut LibtestSummary,
787) {
788    summary.runs += 1;
789    if res.ok && res.failed == 0 {
790        return;
791    }
792    if res.failed > MAX_TERMINAL_FAILURES || list.len() > MAX_TERMINAL_FAILURES {
793        summary.overflow = true;
794        return;
795    }
796    if res.failed == 0 || list.len() != res.failed {
797        summary.inconsistent = true;
798        return;
799    }
800    summary.failed_runs += 1;
801    summary.expected_failures += res.failed;
802    for test in list {
803        summary.failures.push(TerminalFailure {
804            suite: None,
805            test: test.clone(),
806        });
807    }
808}
809
810fn parse_cargo_running_suite(trimmed: &str) -> Option<String> {
811    if let Some(rest) = trimmed.strip_prefix("Running ")
812        && let Some((label, binary)) = rest.split_once(" (")
813        && let Some(binary) = binary.strip_suffix(')')
814        && let Some(name) = binary.rsplit(['/', '\\']).next()
815        && !label.is_empty()
816        && !name.is_empty()
817    {
818        return Some(format!("{label} ({name})"));
819    }
820    if let Some(rest) = trimmed.strip_prefix("Doc-tests ") {
821        let label = rest.trim();
822        if !label.is_empty() {
823            return Some(format!("doc-tests {label}"));
824        }
825    }
826    None
827}
828
829fn parse_libtest_running_header(trimmed: &str) -> Option<usize> {
830    let rest = trimmed.strip_prefix("running ")?;
831    let num = rest
832        .strip_suffix(" tests")
833        .or_else(|| rest.strip_suffix(" test"))?;
834    num.parse::<usize>().ok()
835}
836
837fn parse_libtest_live_failed(trimmed: &str) -> Option<String> {
838    let rest = trimmed.strip_prefix("test ")?;
839    let name = rest.strip_suffix(" ... FAILED")?;
840    let name = name.strip_suffix(" - should panic").unwrap_or(name).trim();
841    (!name.is_empty()).then(|| name.to_owned())
842}
843
844fn parse_libtest_long_running(trimmed: &str) -> Option<String> {
845    let rest = trimmed.strip_prefix("test ")?;
846    let (name, _) = rest.split_once(" has been running for over ")?;
847    let name = name.trim();
848    (!name.is_empty()).then(|| name.to_owned())
849}
850
851fn parse_libtest_result(trimmed: &str) -> Option<LibtestResultLine> {
852    let (ok, rest) = if let Some(r) = trimmed.strip_prefix("test result: ok.") {
853        (true, r)
854    } else {
855        (false, trimmed.strip_prefix("test result: FAILED.")?)
856    };
857    let mut passed = None;
858    let mut failed = None;
859    let mut ignored = 0usize;
860    let mut measured = 0usize;
861    for part in rest.split(';') {
862        let p = part.trim();
863        if let Some(n) = p.strip_suffix(" passed").and_then(|s| s.parse().ok()) {
864            passed = Some(n);
865        } else if let Some(n) = p.strip_suffix(" failed").and_then(|s| s.parse().ok()) {
866            failed = Some(n);
867        } else if let Some(n) = p.strip_suffix(" ignored").and_then(|s| s.parse().ok()) {
868            ignored = n;
869        } else if let Some(n) = p.strip_suffix(" measured").and_then(|s| s.parse().ok()) {
870            measured = n;
871        }
872    }
873    Some(LibtestResultLine {
874        ok,
875        passed: passed?,
876        failed: failed?,
877        ignored,
878        measured,
879    })
880}
881
882/// A bounded command-output tail can confirm a contradiction, but cannot
883/// establish that an unrecognized test runner actually ran tests.
884pub(crate) fn contradicts_passing_test(output: &str) -> bool {
885    let mut saw_result = false;
886    let mut saw_pass = false;
887    let mut saw_empty_run = false;
888    for line in output.lines().map(str::trim) {
889        if let Some(result) = parse_libtest_result(line) {
890            if !result.ok || result.failed != 0 {
891                return true;
892            }
893            saw_result = true;
894            saw_pass |= result.passed != 0;
895        } else if line == "running 0 tests" {
896            saw_empty_run = true;
897        }
898    }
899    !saw_pass && (saw_result || saw_empty_run)
900}
901
902// ---------------------------------------------------------------------------
903// Nextest parser
904// ---------------------------------------------------------------------------
905
906#[derive(Default)]
907struct NextestSummary {
908    failed_runs: usize,
909    expected_failures: usize,
910    failures: Vec<TerminalFailure>,
911    incomplete: bool,
912    inconsistent: bool,
913    overflow: bool,
914}
915
916impl NextestSummary {
917    fn merge(&mut self, other: Self) {
918        self.failed_runs += other.failed_runs;
919        self.expected_failures += other.expected_failures;
920        self.failures.extend(other.failures);
921        self.incomplete |= other.incomplete;
922        self.inconsistent |= other.inconsistent;
923        self.overflow |= other.overflow;
924    }
925}
926
927struct NextestHeader {
928    expected_failures: usize,
929    flaky_count: usize,
930    cancelled: bool,
931    not_run: Option<usize>,
932    unrecognized_failure_token: bool,
933}
934
935enum NextestStatusKind {
936    TerminalFailure,
937    Try,
938    Flaky,
939    Cancel,
940    NonFailure,
941}
942
943struct NextestStatusLine {
944    kind: NextestStatusKind,
945    failure: TerminalFailure,
946}
947
948fn in_ranges(idx: usize, ranges: &[(usize, usize)]) -> bool {
949    ranges.iter().any(|&(a, b)| idx >= a && idx <= b)
950}
951
952fn parse_nextest_stream(
953    lines: &[String],
954    libtest_captured: &[(usize, usize)],
955    intermediate: &mut IntermediateNotes,
956) -> NextestSummary {
957    let mut summary = NextestSummary::default();
958    let mut in_captured = false;
959    let mut started_open = false;
960    let mut saw_summary_flaky = 0usize;
961    let mut i = 0usize;
962
963    while i < lines.len() {
964        if in_ranges(i, libtest_captured) {
965            i += 1;
966            continue;
967        }
968        let trimmed = lines[i].trim();
969
970        if is_nextest_captured_header(trimmed) {
971            in_captured = true;
972            i += 1;
973            continue;
974        }
975        if trimmed == "------------" {
976            in_captured = false;
977            i += 1;
978            continue;
979        }
980        if in_captured {
981            // A genuine nextest cancellation banner or new start ends captured output.
982            if trimmed.starts_with("Cancelling due to ")
983                || trimmed == "test run cancelled"
984                || is_nextest_starting_line(trimmed)
985            {
986                in_captured = false;
987            } else {
988                i += 1;
989                continue;
990            }
991        }
992
993        if is_nextest_starting_line(trimmed) {
994            started_open = true;
995            i += 1;
996            continue;
997        }
998
999        if trimmed.starts_with("Cancelling due to ") || trimmed == "test run cancelled" {
1000            intermediate.cancelled = true;
1001            i += 1;
1002            continue;
1003        }
1004
1005        if let Some(header) = parse_nextest_summary_header(trimmed) {
1006            started_open = false;
1007            if header.cancelled {
1008                intermediate.cancelled = true;
1009            }
1010            if let Some(not_run) = header.not_run {
1011                intermediate.not_run_count =
1012                    Some(intermediate.not_run_count.unwrap_or(0) + not_run);
1013            }
1014            saw_summary_flaky += header.flaky_count;
1015            if header.unrecognized_failure_token {
1016                summary.inconsistent = true;
1017            }
1018
1019            let mut block_failures = Vec::new();
1020            let mut j = i + 1;
1021            while j < lines.len() && !in_ranges(j, libtest_captured) {
1022                let next_trimmed = lines[j].trim();
1023                if next_trimmed.is_empty()
1024                    || next_trimmed == "------------"
1025                    || next_trimmed.starts_with("error:")
1026                    || next_trimmed.starts_with("[cargo-make]")
1027                    || parse_nextest_summary_header(next_trimmed).is_some()
1028                {
1029                    break;
1030                }
1031                let Some(parsed) = parse_nextest_status_line(next_trimmed) else {
1032                    break;
1033                };
1034                match parsed.kind {
1035                    NextestStatusKind::TerminalFailure => {
1036                        if block_failures.len() <= MAX_TERMINAL_FAILURES {
1037                            block_failures.push(parsed.failure);
1038                        }
1039                    }
1040                    NextestStatusKind::Try => {
1041                        // Intermediate retry failures inside Summary are strictly separated
1042                        // from terminal failures.
1043                        intermediate.record_try(parsed.failure.display_name());
1044                    }
1045                    NextestStatusKind::Flaky => {
1046                        intermediate.record_flaky(parsed.failure.display_name());
1047                    }
1048                    NextestStatusKind::Cancel => {
1049                        intermediate.cancelled = true;
1050                    }
1051                    NextestStatusKind::NonFailure => {}
1052                }
1053                j += 1;
1054            }
1055
1056            if header.expected_failures > MAX_TERMINAL_FAILURES
1057                || block_failures.len() > MAX_TERMINAL_FAILURES
1058            {
1059                summary.overflow = true;
1060            } else if header.expected_failures == 0 {
1061                if !block_failures.is_empty() {
1062                    summary.inconsistent = true;
1063                }
1064            } else if block_failures.len() != header.expected_failures {
1065                summary.inconsistent = true;
1066            } else {
1067                summary.failed_runs += 1;
1068                summary.expected_failures += header.expected_failures;
1069                summary.failures.extend(block_failures);
1070            }
1071            i = j;
1072            continue;
1073        }
1074
1075        // Non-summary status lines during execution: record intermediate TRY / FLAKY / CANCEL
1076        // only, never terminal failures (only final Summary decides terminal failures).
1077        if let Some(parsed) = parse_nextest_status_line(trimmed) {
1078            match parsed.kind {
1079                NextestStatusKind::Try => intermediate.record_try(parsed.failure.display_name()),
1080                NextestStatusKind::Flaky => {
1081                    intermediate.record_flaky(parsed.failure.display_name())
1082                }
1083                NextestStatusKind::Cancel => intermediate.cancelled = true,
1084                NextestStatusKind::TerminalFailure | NextestStatusKind::NonFailure => {}
1085            }
1086        }
1087        i += 1;
1088    }
1089
1090    if saw_summary_flaky > intermediate.flaky_count {
1091        intermediate.flaky_count = saw_summary_flaky;
1092    }
1093    if started_open {
1094        summary.incomplete = true;
1095    }
1096    summary
1097}
1098
1099fn is_nextest_captured_header(trimmed: &str) -> bool {
1100    (trimmed.starts_with("--- STDOUT:") || trimmed.starts_with("--- STDERR:"))
1101        && trimmed.ends_with("---")
1102}
1103
1104fn is_nextest_starting_line(trimmed: &str) -> bool {
1105    let Some(rest) = trimmed.strip_prefix("Starting ") else {
1106        return false;
1107    };
1108    let mut parts = rest.split_whitespace();
1109    let Some(count) = parts.next().and_then(|n| n.parse::<usize>().ok()) else {
1110        return false;
1111    };
1112    count > 0 && matches!(parts.next(), Some("test" | "tests"))
1113}
1114
1115fn parse_nextest_summary_header(trimmed: &str) -> Option<NextestHeader> {
1116    let rest = trimmed.strip_prefix("Summary [")?;
1117    let (dur, after) = rest.split_once(']')?;
1118    if !is_duration_token(dur.trim()) {
1119        return None;
1120    }
1121    let (counts_part, details) = after.trim().split_once(':')?;
1122    let run_spec = counts_part
1123        .trim()
1124        .strip_suffix(" tests run")
1125        .or_else(|| counts_part.trim().strip_suffix(" test run"))?;
1126
1127    let mut cancelled = false;
1128    let mut not_run = None;
1129    if let Some((ran, total)) = run_spec.split_once('/') {
1130        let ran: usize = ran.trim().parse().ok()?;
1131        let total: usize = total.trim().parse().ok()?;
1132        if ran < total {
1133            cancelled = true;
1134            not_run = Some(total - ran);
1135        }
1136    } else {
1137        run_spec.trim().parse::<usize>().ok()?;
1138    }
1139
1140    let mut expected_failures = 0usize;
1141    let mut flaky_count = 0usize;
1142    let mut unrecognized_failure_token = false;
1143
1144    for segment in split_top_level_commas(details) {
1145        let seg = segment.trim();
1146        if seg.is_empty() {
1147            continue;
1148        }
1149        let (main, paren) = match seg.split_once('(') {
1150            Some((m, p)) => (m.trim(), Some(p.trim_end_matches(')').trim())),
1151            None => (seg, None),
1152        };
1153        if let Some(p) = paren {
1154            for sub in p.split(',') {
1155                let sub = sub.trim();
1156                if let Some(n) = sub
1157                    .strip_suffix(" flaky")
1158                    .and_then(|s| s.parse::<usize>().ok())
1159                {
1160                    flaky_count += n;
1161                }
1162                if sub.contains("cancel") {
1163                    cancelled = true;
1164                }
1165            }
1166        }
1167        let mut words = main.splitn(2, char::is_whitespace);
1168        let Some(n) = words.next().and_then(|s| s.parse::<usize>().ok()) else {
1169            if main.contains("cancel") {
1170                cancelled = true;
1171            }
1172            continue;
1173        };
1174        let label = words.next().unwrap_or("").trim();
1175        match label {
1176            "passed" | "skipped" => {}
1177            "failed" | "timed out" | "exec failed" => expected_failures += n,
1178            "not run" => {
1179                if n > 0 {
1180                    cancelled = true;
1181                    not_run = Some(not_run.unwrap_or(0).max(n));
1182                }
1183            }
1184            other => {
1185                let lower = other.to_lowercase();
1186                if lower.contains("fail") || lower.contains("abort") || lower.contains("timeout") {
1187                    unrecognized_failure_token = true;
1188                }
1189            }
1190        }
1191    }
1192
1193    Some(NextestHeader {
1194        expected_failures,
1195        flaky_count,
1196        cancelled,
1197        not_run,
1198        unrecognized_failure_token,
1199    })
1200}
1201
1202fn split_top_level_commas(input: &str) -> Vec<&str> {
1203    let mut parts = Vec::new();
1204    let mut depth = 0usize;
1205    let mut start = 0usize;
1206    for (idx, ch) in input.char_indices() {
1207        match ch {
1208            '(' => depth += 1,
1209            ')' => depth = depth.saturating_sub(1),
1210            ',' if depth == 0 => {
1211                parts.push(&input[start..idx]);
1212                start = idx + 1;
1213            }
1214            _ => {}
1215        }
1216    }
1217    parts.push(&input[start..]);
1218    parts
1219}
1220
1221fn is_duration_token(tok: &str) -> bool {
1222    let Some(num) = tok.strip_suffix('s') else {
1223        return false;
1224    };
1225    !num.is_empty() && num.bytes().all(|b| b.is_ascii_digit() || b == b'.')
1226}
1227
1228fn parse_nextest_status_line(trimmed: &str) -> Option<NextestStatusLine> {
1229    let (raw_prefix, after_open) = trimmed.split_once('[')?;
1230    let (dur, rest) = after_open.split_once(']')?;
1231    if !is_duration_token(dur.trim()) {
1232        return None;
1233    }
1234    let prefix = raw_prefix.trim();
1235    let kind = if prefix.starts_with("TRY ") {
1236        NextestStatusKind::Try
1237    } else if prefix == "FLAKY" || prefix.starts_with("FLAKY ") {
1238        NextestStatusKind::Flaky
1239    } else if matches!(prefix, "CANCEL" | "CANCELLED" | "TERMINATING") {
1240        NextestStatusKind::Cancel
1241    } else if matches!(prefix, "PASS" | "SKIP" | "LEAK" | "SLOW" | "START") {
1242        NextestStatusKind::NonFailure
1243    } else if matches!(
1244        prefix,
1245        "FAIL" | "TIMEOUT" | "ABORT" | "EXECFAIL" | "LEAK-FAIL" | "FAIL+LEAK"
1246    ) || (prefix.starts_with("SIG")
1247        && prefix.len() >= 5
1248        && prefix
1249            .bytes()
1250            .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()))
1251    {
1252        NextestStatusKind::TerminalFailure
1253    } else {
1254        return None;
1255    };
1256
1257    let mut rest = rest.trim();
1258    // Skip optional nextest progress token such as `(1/10)`.
1259    if let Some(after_paren) = rest.strip_prefix('(')
1260        && let Some((counter, tail)) = after_paren.split_once(')')
1261        && let Some((a, b)) = counter.split_once('/')
1262        && a.bytes().all(|c| c.is_ascii_digit())
1263        && b.bytes().all(|c| c.is_ascii_digit())
1264    {
1265        rest = tail.trim();
1266    }
1267
1268    let mut parts = rest.split_whitespace();
1269    let suite = parts.next()?;
1270    let test = rest[suite.len()..].trim();
1271    if suite.is_empty() || test.is_empty() {
1272        return None;
1273    }
1274    Some(NextestStatusLine {
1275        kind,
1276        failure: TerminalFailure {
1277            suite: Some(suite.to_owned()),
1278            test: test.to_owned(),
1279        },
1280    })
1281}
1282
1283// ---------------------------------------------------------------------------
1284// Shared formatting helpers
1285// ---------------------------------------------------------------------------
1286
1287fn push_bounded_unique(list: &mut Vec<String>, item: String, max: usize) {
1288    if list.len() < max && !list.contains(&item) {
1289        list.push(item);
1290    }
1291}
1292
1293fn join_bounded(items: &[String], max: usize) -> String {
1294    if items.len() <= max {
1295        return items.join(", ");
1296    }
1297    let shown = items[..max].join(", ");
1298    format!("{shown} (+{} more)", items.len() - max)
1299}
1300
1301fn format_failure_list(failures: &[TerminalFailure], max: usize) -> String {
1302    let names: Vec<String> = failures.iter().map(TerminalFailure::display_name).collect();
1303    join_bounded(&names, max)
1304}
1305
1306fn format_artifact_pair(c: &RerunComparison) -> Option<String> {
1307    match (&c.first.artifact, &c.second.artifact) {
1308        (Some(a), Some(b)) => Some(format!("attempt 1: {a}, attempt 2: {b}")),
1309        (Some(a), None) => Some(format!("attempt 1: {a}")),
1310        (None, Some(b)) => Some(format!("attempt 2: {b}")),
1311        (None, None) => None,
1312    }
1313}
1314
1315fn short_sha(sha: &str) -> &str {
1316    sha.get(..8).unwrap_or(sha)
1317}
1318
1319/// Compact one-line summary of a [`RerunComparison`], shared across events, CLI/web
1320/// reports, stop reasons, and automatic task chat reports.
1321pub fn comparison_headline(c: &RerunComparison) -> String {
1322    let head = short_sha(&c.head);
1323    let artifacts = format_artifact_pair(c)
1324        .map(|a| format!(" ({a})"))
1325        .unwrap_or_default();
1326    match &c.verdict {
1327        ComparisonVerdict::Matching { failures } => format!(
1328            "failed twice on {head} with matching terminal failure(s): {}{artifacts}",
1329            format_failure_list(failures, DISPLAY_FAILURE_LIMIT),
1330        ),
1331        ComparisonVerdict::Distinct {
1332            common,
1333            first_only,
1334            second_only,
1335        } => {
1336            let mut parts = Vec::new();
1337            if !first_only.is_empty() {
1338                parts.push(format!(
1339                    "attempt 1 only: {}",
1340                    format_failure_list(first_only, DISPLAY_FAILURE_LIMIT)
1341                ));
1342            }
1343            if !second_only.is_empty() {
1344                parts.push(format!(
1345                    "attempt 2 only: {}",
1346                    format_failure_list(second_only, DISPLAY_FAILURE_LIMIT)
1347                ));
1348            }
1349            if !common.is_empty() {
1350                parts.push(format!(
1351                    "common: {}",
1352                    format_failure_list(common, DISPLAY_FAILURE_LIMIT)
1353                ));
1354            }
1355            format!(
1356                "failed twice on {head} with distinct terminal failure(s) ({}){artifacts}",
1357                parts.join("; "),
1358            )
1359        }
1360        ComparisonVerdict::Unknown { reason } => {
1361            let mut known_sides = Vec::new();
1362            if let FailureExtraction::Confirmed { failures } = &c.first.extraction {
1363                known_sides.push(format!(
1364                    "attempt 1 terminal failure(s): {}",
1365                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1366                ));
1367            }
1368            if let FailureExtraction::Confirmed { failures } = &c.second.extraction {
1369                known_sides.push(format!(
1370                    "attempt 2 terminal failure(s): {}",
1371                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1372                ));
1373            }
1374            let detail = if known_sides.is_empty() {
1375                reason.clone()
1376            } else {
1377                format!("{reason}; {}", known_sides.join("; "))
1378            };
1379            format!(
1380                "exited non-zero twice on {head}; terminal failure comparison unknown ({detail}){artifacts}"
1381            )
1382        }
1383    }
1384}
1385
1386/// Concise comparison or single-attempt summary line for one failing [`CommandOutcome`],
1387/// if structured evidence or a legacy double-failure marker is present.
1388pub fn outcome_comparison_summary(o: &CommandOutcome) -> Option<String> {
1389    if let Some(c) = &o.rerun_comparison {
1390        return Some(comparison_headline(c));
1391    }
1392    if legacy_failed_twice(&o.output_tail) {
1393        return Some(
1394            "legacy record: command exited non-zero twice without structured attempt comparison (comparison unknown)"
1395                .to_owned(),
1396        );
1397    }
1398    if let Some(ev) = &o.failure_evidence {
1399        match &ev.extraction {
1400            FailureExtraction::Confirmed { failures } if !failures.is_empty() => {
1401                let mut line = format!(
1402                    "terminal failure(s): {}",
1403                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1404                );
1405                if let Some(inter) = ev.intermediate.summary() {
1406                    line.push_str(&format!("; non-terminal: {inter}"));
1407                }
1408                if let Some(art) = &o.artifact {
1409                    line.push_str(&format!(" ({art})"));
1410                }
1411                return Some(line);
1412            }
1413            _ => {}
1414        }
1415    }
1416    None
1417}
1418
1419/// Format a `verify` event line for one command that failed twice on the same commit.
1420pub fn rerun_event_message(context: &str, command: &str, c: &RerunComparison) -> String {
1421    let headline = comparison_headline(c);
1422    let suffix = match &c.verdict {
1423        ComparisonVerdict::Matching { .. } => "the failure reproduced — it stands",
1424        ComparisonVerdict::Distinct { .. } => {
1425            "failures did not match across attempts — verification stays red"
1426        }
1427        ComparisonVerdict::Unknown { .. } => {
1428            "cannot conclude the same failure reproduced — verification stays red"
1429        }
1430    };
1431    format!("{context}: `{command}` {headline}; {suffix}")
1432}
1433
1434/// Format one failed [`CommandOutcome`] for fixer/reviewer/recovery prompts.
1435pub fn format_command_prompt_section(o: &CommandOutcome, max_output: usize) -> String {
1436    if let Some(c) = &o.rerun_comparison {
1437        let mut s = format!("$ {}\n", o.command);
1438        let _ = writeln!(s, "Rerun comparison: {}", comparison_headline(c));
1439        match &c.verdict {
1440            ComparisonVerdict::Matching { .. } => {
1441                s.push_str(
1442                    "Both attempts ended with the same confirmed terminal test failure(s).\n",
1443                );
1444            }
1445            ComparisonVerdict::Distinct { .. } => {
1446                s.push_str(
1447                    "The two attempts ended with DIFFERENT terminal test failures; do not assume one root cause covers both.\n",
1448                );
1449            }
1450            ComparisonVerdict::Unknown { .. } => {
1451                s.push_str(
1452                    "The command exited non-zero twice, but terminal test failures could not be confirmed for both attempts; do not assume the same failure reproduced.\n",
1453                );
1454            }
1455        }
1456        format_attempt_prompt(&mut s, &c.first, ATTEMPT_EXCERPT_MAX);
1457        format_attempt_prompt(&mut s, &c.second, max_output);
1458        return s;
1459    }
1460    if legacy_failed_twice(&o.output_tail) {
1461        let stripped = o
1462            .output_tail
1463            .trim_start()
1464            .strip_prefix(LEGACY_FAILED_TWICE_PREFIX)
1465            .unwrap_or(&o.output_tail)
1466            .trim_start();
1467        return format!(
1468            "$ {}\n[legacy record: command exited non-zero twice without structured attempt comparison; comparison unknown — do not assume the same test failed twice]\n{}\n",
1469            o.command,
1470            summarize_verify(stripped, max_output),
1471        );
1472    }
1473    let mut header = String::new();
1474    if let Some(art) = &o.artifact
1475        && !o.output_tail.contains(art)
1476    {
1477        let _ = writeln!(header, "[full output: {art}]");
1478    }
1479    if let Some(ev) = &o.failure_evidence {
1480        if let FailureExtraction::Confirmed { failures } = &ev.extraction {
1481            let _ = writeln!(
1482                header,
1483                "[terminal failure(s): {}]",
1484                format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1485            );
1486        }
1487        if let Some(inter) = ev.intermediate.summary() {
1488            let _ = writeln!(header, "[non-terminal activity: {inter}]");
1489        }
1490    }
1491    format!(
1492        "$ {}\n{}{}\n",
1493        o.command,
1494        header,
1495        summarize_verify(&o.output_tail, max_output),
1496    )
1497}
1498
1499fn format_attempt_prompt(s: &mut String, a: &AttemptEvidence, max_excerpt: usize) {
1500    let code = a.code.map_or_else(|| "none".to_owned(), |c| c.to_string());
1501    let art = a
1502        .artifact
1503        .as_deref()
1504        .map(|p| format!(", artifact {p}"))
1505        .unwrap_or_default();
1506    let _ = writeln!(
1507        s,
1508        "\n--- Attempt {} (exit {code}, {}ms{art}) ---",
1509        a.attempt, a.duration_ms
1510    );
1511    match &a.extraction {
1512        FailureExtraction::Confirmed { failures } => {
1513            let _ = writeln!(
1514                s,
1515                "Terminal failure(s): {}",
1516                format_failure_list(failures, MAX_TERMINAL_FAILURES)
1517            );
1518        }
1519        FailureExtraction::Unknown { reason } => {
1520            let _ = writeln!(s, "Terminal failure(s): unknown ({reason})");
1521        }
1522    }
1523    if let Some(inter) = a.intermediate.summary() {
1524        let _ = writeln!(s, "Non-terminal activity (separate from verdict): {inter}");
1525    }
1526    let excerpt = summarize_verify(&a.excerpt, max_excerpt);
1527    if !excerpt.trim().is_empty() {
1528        let _ = writeln!(s, "{excerpt}");
1529    }
1530}
1531
1532/// Format structured details for a failed command in CLI (`magi show`) output.
1533pub fn format_outcome_cli_lines(o: &CommandOutcome) -> Vec<String> {
1534    let mut lines = Vec::new();
1535    if let Some(c) = &o.rerun_comparison {
1536        lines.push(format!("comparison: {}", comparison_headline(c)));
1537        for a in [&c.first, &c.second] {
1538            let code = a.code.map_or_else(|| "none".to_owned(), |c| c.to_string());
1539            let art = a
1540                .artifact
1541                .as_deref()
1542                .map(|p| format!("  {p}"))
1543                .unwrap_or_default();
1544            let verdict = match &a.extraction {
1545                FailureExtraction::Confirmed { failures } => format!(
1546                    "terminal: {}",
1547                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1548                ),
1549                FailureExtraction::Unknown { reason } => format!("terminal: unknown ({reason})"),
1550            };
1551            let inter = a
1552                .intermediate
1553                .summary()
1554                .map(|m| format!("  [non-terminal: {m}]"))
1555                .unwrap_or_default();
1556            lines.push(format!(
1557                "attempt {} (exit {code}, {}ms{art}): {verdict}{inter}",
1558                a.attempt, a.duration_ms
1559            ));
1560        }
1561    } else {
1562        if legacy_failed_twice(&o.output_tail) {
1563            lines.push(
1564                "comparison: unknown (legacy record exited non-zero twice without structured attempt comparison)"
1565                    .to_owned(),
1566            );
1567        }
1568        if let Some(art) = &o.artifact {
1569            lines.push(format!("artifact: {art}"));
1570        }
1571        if let Some(ev) = &o.failure_evidence {
1572            match &ev.extraction {
1573                FailureExtraction::Confirmed { failures } => lines.push(format!(
1574                    "terminal failure(s): {}",
1575                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1576                )),
1577                FailureExtraction::Unknown { reason } => {
1578                    lines.push(format!("terminal failure(s): unknown ({reason})"))
1579                }
1580            }
1581            if let Some(inter) = ev.intermediate.summary() {
1582                lines.push(format!("non-terminal: {inter}"));
1583            }
1584        }
1585    }
1586    lines
1587}
1588
1589/// Concise summary of the *current* unresolved e2e failure in `state`, if any.
1590///
1591/// Respects resolution order: never resurfaces an earlier review round's e2e failure
1592/// when `head_e2e` or `gate_repair_e2e` subsequently passed, and inspects `head_e2e`,
1593/// `gate_repair_e2e`, and the latest `ReviewRound` in precedence order.
1594pub fn current_e2e_failure_summary(state: &RunState) -> Option<String> {
1595    if let Some(e) = &state.head_e2e {
1596        if !e.passed {
1597            if let Some(line) = summarize_failed_outcomes(&e.outcomes) {
1598                return Some(format!("current head e2e @ {}: {line}", short_sha(&e.head)));
1599            }
1600        } else {
1601            return None;
1602        }
1603    }
1604    if let Some(e) = &state.gate_repair_e2e {
1605        if !e.passed {
1606            if let Some(line) = summarize_failed_outcomes(&e.outcomes) {
1607                return Some(format!("gate repair e2e @ {}: {line}", short_sha(&e.head)));
1608            }
1609        } else {
1610            return None;
1611        }
1612    }
1613    if let Some(r) = state.reviews.last()
1614        && r.e2e_status() == E2eStatus::Failed
1615        && let Some(line) = summarize_failed_outcomes(&r.e2e)
1616    {
1617        let head = r.verified_head.as_deref().unwrap_or(&r.head);
1618        return Some(format!(
1619            "round {} e2e @ {}: {line}",
1620            r.round,
1621            short_sha(head)
1622        ));
1623    }
1624    None
1625}
1626
1627/// Summarize the first failing non-resource-blocked outcome in `outcomes`, preferring
1628/// structured rerun comparisons when present.
1629pub fn summarize_failed_outcomes(outcomes: &[CommandOutcome]) -> Option<String> {
1630    let failing: Vec<&CommandOutcome> = outcomes
1631        .iter()
1632        .filter(|o| !o.ok() && !o.resource_blocked)
1633        .collect();
1634    if failing.is_empty() {
1635        return None;
1636    }
1637    let parts: Vec<String> = failing
1638        .iter()
1639        .take(2)
1640        .map(|o| match outcome_comparison_summary(o) {
1641            Some(detail) => format!("`{}` {detail}", o.command),
1642            None => format!(
1643                "`{}` failed (exit {})",
1644                o.command,
1645                o.code.map_or_else(|| "none".to_owned(), |c| c.to_string())
1646            ),
1647        })
1648        .collect();
1649    Some(parts.join("; "))
1650}
1651
1652#[cfg(test)]
1653mod tests {
1654    use super::*;
1655
1656    fn outcome(code: Option<i32>, raw: &str, artifact: Option<&str>) -> CommandOutcome {
1657        let build_failed = code != Some(0) && raw.contains("error: could not compile");
1658        let evidence = extract_combined(code, build_failed, raw);
1659        CommandOutcome {
1660            command: "cargo make test".to_owned(),
1661            code,
1662            output_tail: summarize_verify(raw, crate::run::VERIFY_SUMMARY),
1663            duration_ms: 1200,
1664            resource_blocked: false,
1665            artifact: artifact.map(str::to_owned),
1666            failure_evidence: Some(evidence),
1667            rerun_comparison: None,
1668        }
1669    }
1670
1671    #[test]
1672    fn nextest_separates_terminal_failures_from_try_flaky_and_cancellations() {
1673        let raw = "\
1674Starting 12 tests across 3 binaries
1675\x1b[33m  TRY 1 FAIL\x1b[0m [   0.500s] magi-cli::chat_notify test_flaky_one
1676\x1b[33m   FLAKY 2/3\x1b[0m [   0.400s] magi-cli::chat_notify test_flaky_one
1677  TRY 1 FAIL [   1.000s] magi-cli::isolated_build_cache test_cache
1678  TRY 2 FAIL [   1.000s] magi-cli::isolated_build_cache test_cache
1679\x1b[31m        FAIL\x1b[0m [   1.200s] magi-cli::isolated_build_cache test_cache
1680Cancelling due to test failure: 2 tests still running
1681      CANCEL [   0.000s] magi-cli::web_render test_other
1682------------
1683     Summary [  10.500s] 5/12 tests run: 4 passed (1 flaky), 1 failed, 0 skipped
1684        FAIL [   1.200s] magi-cli::isolated_build_cache test_cache
1685  TRY 1 FAIL [   1.000s] magi-cli::isolated_build_cache test_cache
1686   FLAKY 2/3 [   0.400s] magi-cli::chat_notify test_flaky_one
1687error: test run failed
1688";
1689        let ev = extract_combined(Some(100), false, raw);
1690        assert_eq!(
1691            ev.extraction,
1692            FailureExtraction::Confirmed {
1693                failures: vec![TerminalFailure {
1694                    suite: Some("magi-cli::isolated_build_cache".to_owned()),
1695                    test: "test_cache".to_owned(),
1696                }]
1697            }
1698        );
1699        assert!(ev.intermediate.try_failure_count >= 2);
1700        assert_eq!(ev.intermediate.flaky_count, 1);
1701        assert!(ev.intermediate.cancelled);
1702        assert_eq!(ev.intermediate.not_run_count, Some(7));
1703    }
1704
1705    #[test]
1706    fn typography_0b11_scenario_distinguishes_unit_failure_from_nextest_failure() {
1707        // Attempt 1: chat unit test failed in cargo test --lib (nextest never ran).
1708        let attempt1_out = "\
1709running 2 tests
1710test ok_test ... ok
1711test talk::tests::chat_timeout ... FAILED
1712
1713failures:
1714
1715---- talk::tests::chat_timeout stdout ----
1716thread 'talk::tests::chat_timeout' panicked at src/talk.rs:42:9:
1717timed out waiting for turn
1718
1719failures:
1720    talk::tests::chat_timeout
1721
1722test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.01s
1723";
1724        let attempt1_err =
1725            "Running unittests src/lib.rs (target/debug/deps/magi-abc)\nerror: test failed\n";
1726        let ev1 = extract_streams(Some(101), false, attempt1_out, attempt1_err);
1727
1728        // Attempt 2: libtest passed on stdout; nextest failed on stderr naming isolated_build_cache.
1729        let attempt2_out = "\
1730running 2 tests
1731test ok_test ... ok
1732test talk::tests::chat_timeout ... ok
1733
1734test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12s
1735";
1736        let attempt2_err = "\
1737Running unittests src/lib.rs (target/debug/deps/magi-abc)
1738Starting 10 tests across 2 binaries
1739  TRY 1 FAIL [   0.300s] magi-cli::other test_transient
1740   FLAKY 2/3 [   0.200s] magi-cli::other test_transient
1741Cancelling due to test failure: 1 test still running
1742------------
1743     Summary [  12.000s] 6/10 tests run: 5 passed (1 flaky), 1 failed, 0 skipped
1744        FAIL [   2.500s] magi-cli::isolated_build_cache test_isolation
1745error: test run failed
1746";
1747        let ev2 = extract_streams(Some(100), false, attempt2_out, attempt2_err);
1748
1749        let o1 = CommandOutcome {
1750            command: "cargo make test".to_owned(),
1751            code: Some(101),
1752            output_tail: attempt1_out.to_owned(),
1753            duration_ms: 5000,
1754            resource_blocked: false,
1755            artifact: Some("artifacts/e2e-3.out".to_owned()),
1756            failure_evidence: Some(ev1),
1757            rerun_comparison: None,
1758        };
1759        let o2 = CommandOutcome {
1760            command: "cargo make test".to_owned(),
1761            code: Some(100),
1762            output_tail: attempt2_err.to_owned(),
1763            duration_ms: 12000,
1764            resource_blocked: false,
1765            artifact: Some("artifacts/e2e-4.out".to_owned()),
1766            failure_evidence: Some(ev2),
1767            rerun_comparison: None,
1768        };
1769        let cmp = compare_attempts("0b11aaaa1234", &o1, &o2);
1770        assert_eq!(
1771            cmp.verdict,
1772            ComparisonVerdict::Distinct {
1773                common: vec![],
1774                first_only: vec![TerminalFailure {
1775                    suite: Some("unittests src/lib.rs (magi-abc)".to_owned()),
1776                    test: "talk::tests::chat_timeout".to_owned(),
1777                }],
1778                second_only: vec![TerminalFailure {
1779                    suite: Some("magi-cli::isolated_build_cache".to_owned()),
1780                    test: "test_isolation".to_owned(),
1781                }],
1782            }
1783        );
1784        let headline = comparison_headline(&cmp);
1785        assert!(
1786            headline.contains("distinct terminal failure(s)"),
1787            "{headline}"
1788        );
1789        assert!(headline.contains("talk::tests::chat_timeout"), "{headline}");
1790        assert!(headline.contains("isolated_build_cache"), "{headline}");
1791        assert!(headline.contains("artifacts/e2e-3.out"), "{headline}");
1792        assert!(headline.contains("artifacts/e2e-4.out"), "{headline}");
1793        let event = rerun_event_message("round 1", "cargo make test", &cmp);
1794        assert!(!event.contains("reproduced"), "{event}");
1795    }
1796
1797    #[test]
1798    fn hang_without_final_summary_is_unknown_not_matching() {
1799        let attempt1_out = "\
1800running 2 tests
1801test ok_test ... ok
1802test talk::tests::chat_timeout has been running for over 60 seconds
1803";
1804        let ev1 = extract_streams(Some(1), false, attempt1_out, "");
1805        assert!(matches!(ev1.extraction, FailureExtraction::Unknown { .. }));
1806        assert_eq!(
1807            ev1.intermediate.long_running,
1808            vec!["talk::tests::chat_timeout"]
1809        );
1810
1811        let attempt2_err = "\
1812------------
1813     Summary [   5.000s] 3 tests run: 2 passed, 1 failed, 0 skipped
1814        FAIL [   1.000s] magi-cli::isolated_build_cache test_isolation
1815";
1816        let ev2 = extract_streams(Some(100), false, "", attempt2_err);
1817        assert!(matches!(
1818            ev2.extraction,
1819            FailureExtraction::Confirmed { .. }
1820        ));
1821
1822        let o1 = CommandOutcome {
1823            command: "cargo make test".to_owned(),
1824            code: Some(1),
1825            output_tail: attempt1_out.to_owned(),
1826            duration_ms: 60_000,
1827            resource_blocked: false,
1828            artifact: Some("artifacts/e2e-3.out".to_owned()),
1829            failure_evidence: Some(ev1),
1830            rerun_comparison: None,
1831        };
1832        let o2 = CommandOutcome {
1833            command: "cargo make test".to_owned(),
1834            code: Some(100),
1835            output_tail: attempt2_err.to_owned(),
1836            duration_ms: 5_000,
1837            resource_blocked: false,
1838            artifact: Some("artifacts/e2e-4.out".to_owned()),
1839            failure_evidence: Some(ev2),
1840            rerun_comparison: None,
1841        };
1842        let cmp = compare_attempts("deadbeef", &o1, &o2);
1843        assert!(matches!(cmp.verdict, ComparisonVerdict::Unknown { .. }));
1844        let headline = comparison_headline(&cmp);
1845        assert!(headline.contains("comparison unknown"), "{headline}");
1846        assert!(headline.contains("isolated_build_cache"), "{headline}");
1847        assert!(headline.contains("artifacts/e2e-3.out"), "{headline}");
1848        assert!(headline.contains("artifacts/e2e-4.out"), "{headline}");
1849    }
1850
1851    #[test]
1852    fn captured_stdout_cannot_spoof_libtest_or_nextest_verdict() {
1853        let raw = "\
1854running 2 tests
1855test ok_test ... ok
1856test real_test ... FAILED
1857
1858failures:
1859
1860---- real_test stdout ----
1861failures:
1862    fake_test
1863
1864test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
1865------------
1866     Summary [   0.100s] 1 tests run: 0 passed, 1 failed, 0 skipped
1867        FAIL [   0.100s] fake::bin fake_nextest
1868
1869failures:
1870    real_test
1871
1872test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s
1873";
1874        let ev = extract_combined(Some(101), false, raw);
1875        assert_eq!(
1876            ev.extraction,
1877            FailureExtraction::Confirmed {
1878                failures: vec![TerminalFailure {
1879                    suite: None,
1880                    test: "real_test".to_owned(),
1881                }]
1882            }
1883        );
1884    }
1885
1886    #[test]
1887    fn count_mismatch_and_cap_overflow_yield_unknown() {
1888        let mismatch = "\
1889------------
1890     Summary [   1.000s] 2 tests run: 0 passed, 2 failed, 0 skipped
1891        FAIL [   0.500s] pkg::bin only_one
1892";
1893        assert!(matches!(
1894            extract_combined(Some(100), false, mismatch).extraction,
1895            FailureExtraction::Unknown { .. }
1896        ));
1897
1898        let mut many =
1899            "------------\n     Summary [   1.000s] 40 tests run: 0 passed, 40 failed, 0 skipped\n"
1900                .to_owned();
1901        for i in 0..40 {
1902            let _ = writeln!(many, "        FAIL [   0.010s] pkg::bin test_{i}");
1903        }
1904        assert!(matches!(
1905            extract_combined(Some(100), false, &many).extraction,
1906            FailureExtraction::Unknown { .. }
1907        ));
1908    }
1909
1910    #[test]
1911    fn matching_a_to_a_and_multi_binary_libtest() {
1912        let raw = "\
1913Running tests/alpha.rs (target/debug/deps/alpha-1234)
1914running 2 tests
1915test a_ok ... ok
1916test a_fail ... FAILED
1917
1918failures:
1919    a_fail
1920
1921test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
1922
1923Running tests/beta.rs (target/debug/deps/beta-5678)
1924running 1 test
1925test b_fail ... FAILED
1926
1927failures:
1928    b_fail
1929
1930test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
1931";
1932        let o1 = outcome(Some(101), raw, Some("artifacts/e2e-1.out"));
1933        let o2 = outcome(Some(101), raw, Some("artifacts/e2e-2.out"));
1934        let cmp = compare_attempts("abcdef12", &o1, &o2);
1935        assert_eq!(
1936            cmp.verdict,
1937            ComparisonVerdict::Matching {
1938                failures: vec![
1939                    TerminalFailure {
1940                        suite: Some("tests/alpha.rs (alpha-1234)".to_owned()),
1941                        test: "a_fail".to_owned(),
1942                    },
1943                    TerminalFailure {
1944                        suite: Some("tests/beta.rs (beta-5678)".to_owned()),
1945                        test: "b_fail".to_owned(),
1946                    },
1947                ]
1948            }
1949        );
1950        let event = rerun_event_message("round 1", "cargo test", &cmp);
1951        assert!(event.contains("the failure reproduced"), "{event}");
1952    }
1953
1954    #[test]
1955    fn split_cargo_streams_require_unambiguous_binary_identity() {
1956        let raw = "\
1957running 1 test
1958test test_layout ... FAILED
1959
1960failures:
1961    test_layout
1962
1963test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
1964";
1965        let alpha = "Running tests/alpha.rs (target/debug/deps/alpha-1234)\n";
1966        let beta = "Running tests/beta.rs (target/debug/deps/beta-5678)\n";
1967        let make = |stderr: &str| {
1968            let mut o = outcome(Some(101), raw, None);
1969            o.failure_evidence = Some(extract_streams(Some(101), false, raw, stderr));
1970            o
1971        };
1972        let a = make(alpha);
1973        assert!(matches!(
1974            compare_attempts("head", &a, &make(alpha)).verdict,
1975            ComparisonVerdict::Matching { .. }
1976        ));
1977        assert!(matches!(
1978            compare_attempts("head", &a, &make(beta)).verdict,
1979            ComparisonVerdict::Distinct { .. }
1980        ));
1981        let same_label = "Running tests/alpha.rs (target/debug/deps/alpha-9999)\n";
1982        assert!(matches!(
1983            compare_attempts("head", &a, &make(same_label)).verdict,
1984            ComparisonVerdict::Distinct { .. }
1985        ));
1986        let ambiguous = make(&format!("{alpha}{beta}"));
1987        for unknown in [make(""), ambiguous] {
1988            assert!(matches!(
1989                compare_attempts("head", &unknown, &unknown).verdict,
1990                ComparisonVerdict::Unknown { .. }
1991            ));
1992        }
1993    }
1994
1995    #[test]
1996    fn nextest_captured_libtest_failure_is_not_an_independent_run() {
1997        let raw = "\
1998Starting 1 test across 1 binary
1999        FAIL [   0.100s] pkg::bin outer
2000--- STDOUT: pkg::bin outer ---
2001running 1 test
2002test inner ... FAILED
2003
2004failures:
2005    inner
2006
2007test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
2008------------
2009     Summary [   0.100s] 1 tests run: 0 passed, 1 failed, 0 skipped
2010        FAIL [   0.100s] pkg::bin outer
2011error: test run failed
2012";
2013        assert_eq!(
2014            extract_streams(Some(100), false, "", raw).extraction,
2015            FailureExtraction::Confirmed {
2016                failures: vec![TerminalFailure {
2017                    suite: Some("pkg::bin".to_owned()),
2018                    test: "outer".to_owned(),
2019                }],
2020            }
2021        );
2022    }
2023
2024    #[test]
2025    fn legacy_failed_twice_is_treated_as_unknown() {
2026        let o = CommandOutcome {
2027            command: "cargo make test".to_owned(),
2028            code: Some(1),
2029            output_tail: format!("{LEGACY_FAILED_TWICE_PREFIX}\nsome output"),
2030            duration_ms: 100,
2031            resource_blocked: false,
2032            artifact: None,
2033            failure_evidence: None,
2034            rerun_comparison: None,
2035        };
2036        let summary = outcome_comparison_summary(&o).unwrap();
2037        assert!(summary.contains("comparison unknown"), "{summary}");
2038        assert!(!summary.contains("reproduced"), "{summary}");
2039    }
2040}