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 (including final-attempt `TRY N <FAIL>`
8//! entries under nextest `Summary`), separates intermediate `TRY` retries,
9//! `FLAKY` passes, and cancellations from terminal verdicts, compares both attempts
10//! conservatively (`Matching`, `Distinct`, or `Unknown`), and formats the saved record
11//! consistently across events, CLI/web reports, fixer prompts, recovery evidence, stop
12//! reasons, and automatic task chat reports.
13
14use std::collections::{BTreeMap, BTreeSet};
15use std::fmt::Write as _;
16
17use serde::{Deserialize, Serialize};
18
19use crate::run::{CommandOutcome, E2eStatus, RunState, summarize_verify};
20
21/// Maximum number of terminal failures captured in a confirmed set. Exceeding this
22/// yields [`FailureExtraction::Unknown`] so truncated sets are never compared as complete.
23pub const MAX_TERMINAL_FAILURES: usize = 32;
24
25/// Maximum number of test names retained per intermediate category (`TRY`, `FLAKY`, etc.).
26pub const MAX_INTERMEDIATE_NAMES: usize = 8;
27
28/// Maximum byte length of the bounded excerpt stored per attempt inside [`RerunComparison`].
29pub const ATTEMPT_EXCERPT_MAX: usize = 4_000;
30
31/// Maximum number of failure names listed inline in one-line summaries before `+N more`.
32pub const DISPLAY_FAILURE_LIMIT: usize = 6;
33
34/// Legacy prefix previously injected into `output_tail` on double failures.
35/// Older `run.json` records carrying this prefix have no structured attempt comparison
36/// and must be treated as an unknown comparison rather than proof of a reproduced failure.
37pub const LEGACY_FAILED_TWICE_PREFIX: &str =
38    "[this command failed twice on the same commit; the output below is the second attempt's]";
39
40/// One confirmed terminal test failure (optional test binary/suite + test name).
41#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42pub struct TerminalFailure {
43    /// Test binary or target identifier when known (e.g. `magi-cli::isolated_build_cache`).
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub suite: Option<String>,
46    /// Test name within the suite.
47    pub test: String,
48}
49
50impl TerminalFailure {
51    /// Human-readable display label (`<suite> <test>` or `<test>`).
52    pub fn display_name(&self) -> String {
53        match &self.suite {
54            Some(suite) if !suite.is_empty() => format!("{suite} {}", self.test),
55            _ => self.test.clone(),
56        }
57    }
58}
59
60/// Intermediate / non-terminal test activity observed in raw output, kept strictly
61/// separate from terminal failures.
62#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
63pub struct IntermediateNotes {
64    /// Number of intermediate retry failure lines (`TRY N FAIL` / `TRY N TIMEOUT` / ...).
65    #[serde(default)]
66    pub try_failure_count: usize,
67    /// Bounded sample of test identifiers seen in `TRY N` failure lines.
68    #[serde(default, skip_serializing_if = "Vec::is_empty")]
69    pub try_failures: Vec<String>,
70    /// Number of tests that passed on retry (`FLAKY`).
71    #[serde(default)]
72    pub flaky_count: usize,
73    /// Bounded sample of test identifiers marked `FLAKY`.
74    #[serde(default, skip_serializing_if = "Vec::is_empty")]
75    pub flaky: Vec<String>,
76    /// Whether the test runner reported cancellations or partial execution (`M/N tests run`).
77    #[serde(default)]
78    pub cancelled: bool,
79    /// Number of tests not run due to cancellation, when reported in the summary.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub not_run_count: Option<usize>,
82    /// Bounded sample of long-running test notices (`has been running for over ...`).
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub long_running: Vec<String>,
85}
86
87impl IntermediateNotes {
88    /// True when no intermediate retries, flaky passes, cancellations, or hangs were observed.
89    pub fn is_empty(&self) -> bool {
90        self.try_failure_count == 0
91            && self.try_failures.is_empty()
92            && self.flaky_count == 0
93            && self.flaky.is_empty()
94            && !self.cancelled
95            && self.not_run_count.is_none()
96            && self.long_running.is_empty()
97    }
98
99    fn record_try(&mut self, label: String) {
100        self.try_failure_count += 1;
101        push_bounded_unique(&mut self.try_failures, label, MAX_INTERMEDIATE_NAMES);
102    }
103
104    fn record_flaky(&mut self, label: String) {
105        if !self.flaky.contains(&label) {
106            self.flaky_count += 1;
107            push_bounded_unique(&mut self.flaky, label, MAX_INTERMEDIATE_NAMES);
108        }
109    }
110
111    fn record_long_running(&mut self, label: String) {
112        push_bounded_unique(&mut self.long_running, label, MAX_INTERMEDIATE_NAMES);
113    }
114
115    /// Compact human-readable summary of separated non-terminal activity, or `None` when empty.
116    pub fn summary(&self) -> Option<String> {
117        let mut parts = Vec::new();
118        if self.try_failure_count > 0 {
119            if self.try_failures.is_empty() {
120                parts.push(format!(
121                    "{} intermediate TRY failure(s)",
122                    self.try_failure_count
123                ));
124            } else {
125                parts.push(format!(
126                    "{} intermediate TRY failure(s) ({})",
127                    self.try_failure_count,
128                    join_bounded(&self.try_failures, 3)
129                ));
130            }
131        }
132        if self.flaky_count > 0 {
133            if self.flaky.is_empty() {
134                parts.push(format!("{} FLAKY pass(es)", self.flaky_count));
135            } else {
136                parts.push(format!(
137                    "{} FLAKY pass(es) ({})",
138                    self.flaky_count,
139                    join_bounded(&self.flaky, 3)
140                ));
141            }
142        }
143        if self.cancelled {
144            match self.not_run_count {
145                Some(n) if n > 0 => parts.push(format!("cancelled ({n} test(s) not run)")),
146                _ => parts.push("cancelled".to_owned()),
147            }
148        }
149        if !self.long_running.is_empty() {
150            parts.push(format!(
151                "long-running test(s): {}",
152                join_bounded(&self.long_running, 3)
153            ));
154        }
155        (!parts.is_empty()).then(|| parts.join("; "))
156    }
157}
158
159/// Result of extracting terminal test failures from one attempt's raw output.
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(tag = "kind", rename_all = "snake_case")]
162pub enum FailureExtraction {
163    /// Complete, count-reconciled, non-empty set of terminal failing tests.
164    Confirmed {
165        /// Sorted, deduplicated terminal failing tests.
166        failures: Vec<TerminalFailure>,
167    },
168    /// Terminal failing tests could not be confirmed completely.
169    Unknown {
170        /// Why completeness could not be confirmed.
171        reason: String,
172    },
173}
174
175/// Extracted terminal failure set paired with separated intermediate activity for one attempt.
176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
177pub struct FailureEvidence {
178    /// Confirmed terminal failures or why they are unknown.
179    pub extraction: FailureExtraction,
180    /// Intermediate retries (`TRY`), `FLAKY` passes, and cancellations, kept separate.
181    #[serde(default)]
182    pub intermediate: IntermediateNotes,
183}
184
185/// Bounded evidence preserved for one verification attempt in a two-attempt rerun pair.
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
187pub struct AttemptEvidence {
188    /// 1-based attempt number (`1` = first failure, `2` = rerun).
189    pub attempt: u8,
190    /// Process exit code, or `None` on timeout/signal/spawn error.
191    pub code: Option<i32>,
192    /// Wall-clock duration in milliseconds.
193    #[serde(default)]
194    pub duration_ms: u64,
195    /// Run-relative artifact path (e.g. `artifacts/e2e-3.out`), when saved.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub artifact: Option<String>,
198    /// Bounded output excerpt (within [`ATTEMPT_EXCERPT_MAX`]).
199    #[serde(default)]
200    pub excerpt: String,
201    /// Terminal failure extraction from raw output.
202    pub extraction: FailureExtraction,
203    /// Intermediate retries, flaky passes, and cancellations, kept separate.
204    #[serde(default)]
205    pub intermediate: IntermediateNotes,
206}
207
208impl AttemptEvidence {
209    /// Build bounded attempt evidence from a finished [`CommandOutcome`].
210    pub fn from_outcome(attempt: u8, outcome: &CommandOutcome) -> Self {
211        let (extraction, intermediate) = match &outcome.failure_evidence {
212            Some(ev) => (ev.extraction.clone(), ev.intermediate.clone()),
213            None => (
214                FailureExtraction::Unknown {
215                    reason: "no raw failure extraction recorded".to_owned(),
216                },
217                IntermediateNotes::default(),
218            ),
219        };
220        Self {
221            attempt,
222            code: outcome.code,
223            duration_ms: outcome.duration_ms,
224            artifact: outcome.artifact.clone(),
225            excerpt: summarize_verify(&outcome.output_tail, ATTEMPT_EXCERPT_MAX),
226            extraction,
227            intermediate,
228        }
229    }
230
231    /// Return a copy with `excerpt` scrubbed through `scrub`.
232    pub fn scrubbed(&self, scrub: impl Fn(&str) -> String) -> Self {
233        let mut copy = self.clone();
234        copy.excerpt = scrub(&copy.excerpt);
235        copy
236    }
237}
238
239/// Conservative comparison verdict between two consecutive failing attempts on one commit.
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241#[serde(tag = "kind", rename_all = "snake_case")]
242pub enum ComparisonVerdict {
243    /// Both attempts had confirmed, non-empty, identical terminal test failure sets.
244    Matching {
245        /// Confirmed terminal failures present in both attempts.
246        failures: Vec<TerminalFailure>,
247    },
248    /// Both attempts had confirmed, non-empty, differing terminal test failure sets.
249    Distinct {
250        /// Terminal failures present in both attempts.
251        #[serde(default, skip_serializing_if = "Vec::is_empty")]
252        common: Vec<TerminalFailure>,
253        /// Terminal failures present only in the first attempt.
254        #[serde(default, skip_serializing_if = "Vec::is_empty")]
255        first_only: Vec<TerminalFailure>,
256        /// Terminal failures present only in the second attempt.
257        #[serde(default, skip_serializing_if = "Vec::is_empty")]
258        second_only: Vec<TerminalFailure>,
259    },
260    /// At least one attempt's terminal test failures could not be confirmed.
261    Unknown {
262        /// Why the two attempts could not be compared conclusively.
263        reason: String,
264    },
265}
266
267/// Structured record persisted on a [`CommandOutcome`] that failed twice on one commit.
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269pub struct RerunComparison {
270    /// Commit SHA both attempts ran against.
271    pub head: String,
272    /// First failing attempt's bounded evidence.
273    pub first: AttemptEvidence,
274    /// Second failing attempt's bounded evidence.
275    pub second: AttemptEvidence,
276    /// Conservative comparison verdict (`Matching`, `Distinct`, or `Unknown`).
277    pub verdict: ComparisonVerdict,
278}
279
280impl RerunComparison {
281    /// Return a copy with attempt excerpts scrubbed through `scrub`.
282    pub fn scrubbed(&self, scrub: impl Fn(&str) -> String) -> Self {
283        Self {
284            head: self.head.clone(),
285            first: self.first.scrubbed(&scrub),
286            second: self.second.scrubbed(&scrub),
287            verdict: self.verdict.clone(),
288        }
289    }
290}
291
292/// True when `output_tail` begins with the legacy double-failure prefix that predates
293/// structured [`RerunComparison`].
294pub fn legacy_failed_twice(output_tail: &str) -> bool {
295    output_tail
296        .trim_start()
297        .starts_with(LEGACY_FAILED_TWICE_PREFIX)
298}
299
300/// Strip ANSI CSI/OSC escape sequences and trailing `\r` from one line.
301pub fn strip_ansi(line: &str) -> String {
302    let line = line.strip_suffix('\r').unwrap_or(line);
303    let mut out = String::with_capacity(line.len());
304    let mut chars = line.chars().peekable();
305    while let Some(c) = chars.next() {
306        if c == '\x1b' {
307            match chars.peek().copied() {
308                Some('[') => {
309                    chars.next();
310                    for ch in chars.by_ref() {
311                        if ('@'..='~').contains(&ch) {
312                            break;
313                        }
314                    }
315                }
316                Some(']') => {
317                    chars.next();
318                    while let Some(ch) = chars.next() {
319                        if ch == '\x07' {
320                            break;
321                        }
322                        if ch == '\x1b' && chars.peek() == Some(&'\\') {
323                            chars.next();
324                            break;
325                        }
326                    }
327                }
328                _ => {}
329            }
330        } else {
331            out.push(c);
332        }
333    }
334    out
335}
336
337/// Extract terminal test failures and intermediate notes from separate raw `stdout` and
338/// `stderr` streams. Neither stream's order is assumed to imply wall-clock execution order.
339pub fn extract_streams(
340    code: Option<i32>,
341    build_failed: bool,
342    stdout: &str,
343    stderr: &str,
344) -> FailureEvidence {
345    let out_lines: Vec<String> = stdout.lines().map(strip_ansi).collect();
346    let err_lines: Vec<String> = stderr.lines().map(strip_ansi).collect();
347    extract_line_streams(code, build_failed, &[&out_lines, &err_lines])
348}
349
350/// Extract terminal test failures and intermediate notes from a single combined raw output.
351pub fn extract_combined(code: Option<i32>, build_failed: bool, body: &str) -> FailureEvidence {
352    let lines: Vec<String> = body.lines().map(strip_ansi).collect();
353    extract_line_streams(code, build_failed, &[&lines])
354}
355
356fn extract_line_streams(
357    code: Option<i32>,
358    build_failed: bool,
359    streams: &[&[String]],
360) -> FailureEvidence {
361    let mut intermediate = IntermediateNotes::default();
362    let mut libtest_total = LibtestSummary::default();
363    let mut nextest_total = NextestSummary::default();
364
365    for lines in streams {
366        let (lib, captured_ranges) = parse_libtest_stream(lines, &mut intermediate);
367        libtest_total.merge(lib);
368        let nx = parse_nextest_stream(lines, &captured_ranges, &mut intermediate);
369        nextest_total.merge(nx);
370    }
371
372    // Cargo writes binary announcements and libtest verdicts to different pipes.
373    // Without interleaving information, only a single announcement and a single
374    // libtest run can be associated unambiguously.
375    if libtest_total.runs == 1 && libtest_total.suites == 1 {
376        for failure in &mut libtest_total.failures {
377            if failure.suite.is_none() {
378                failure.suite.clone_from(&libtest_total.only_suite);
379            }
380        }
381    }
382
383    let extraction = if code.is_none() {
384        FailureExtraction::Unknown {
385            reason: "command timed out or terminated without an exit code".to_owned(),
386        }
387    } else if code == Some(0) {
388        FailureExtraction::Unknown {
389            reason: "command exited 0".to_owned(),
390        }
391    } else if build_failed {
392        FailureExtraction::Unknown {
393            reason: "command failed to build or link".to_owned(),
394        }
395    } else if libtest_total.incomplete || nextest_total.incomplete {
396        FailureExtraction::Unknown {
397            reason: "test run did not finish with a final summary".to_owned(),
398        }
399    } else if libtest_total.overflow || nextest_total.overflow {
400        FailureExtraction::Unknown {
401            reason: format!(
402                "more than {MAX_TERMINAL_FAILURES} terminal test failures reported; complete comparison unavailable"
403            ),
404        }
405    } else if libtest_total.inconsistent || nextest_total.inconsistent {
406        FailureExtraction::Unknown {
407            reason: "reported failure count did not match listed terminal failures".to_owned(),
408        }
409    } else if libtest_total.failed_runs > 0 && nextest_total.failed_runs > 0 {
410        FailureExtraction::Unknown {
411            reason: "multiple test runners reported failures in one command; completeness cannot be confirmed"
412                .to_owned(),
413        }
414    } else if nextest_total.failed_runs > 0 {
415        finalize_confirmed(nextest_total.expected_failures, nextest_total.failures)
416    } else if libtest_total.failed_runs > 0 {
417        finalize_confirmed(libtest_total.expected_failures, libtest_total.failures)
418    } else {
419        FailureExtraction::Unknown {
420            reason: "command exited non-zero without a complete failing test summary".to_owned(),
421        }
422    };
423
424    FailureEvidence {
425        extraction,
426        intermediate,
427    }
428}
429
430fn finalize_confirmed(expected: usize, raw: Vec<TerminalFailure>) -> FailureExtraction {
431    if expected == 0 || raw.is_empty() {
432        return FailureExtraction::Unknown {
433            reason: "no terminal test failures were listed in the final summary".to_owned(),
434        };
435    }
436    if expected > MAX_TERMINAL_FAILURES || raw.len() > MAX_TERMINAL_FAILURES {
437        return FailureExtraction::Unknown {
438            reason: format!(
439                "more than {MAX_TERMINAL_FAILURES} terminal test failures reported; complete comparison unavailable"
440            ),
441        };
442    }
443    let set: BTreeSet<TerminalFailure> = raw.into_iter().collect();
444    if set.len() != expected {
445        return FailureExtraction::Unknown {
446            reason: format!(
447                "reported failure count ({expected}) did not match distinct terminal failures ({})",
448                set.len()
449            ),
450        };
451    }
452    FailureExtraction::Confirmed {
453        failures: set.into_iter().collect(),
454    }
455}
456
457/// Compare two consecutive failing attempts of the same command on commit `head`.
458pub fn compare_attempts(
459    head: &str,
460    first: &CommandOutcome,
461    second: &CommandOutcome,
462) -> RerunComparison {
463    let first_ev = AttemptEvidence::from_outcome(1, first);
464    let second_ev = AttemptEvidence::from_outcome(2, second);
465    let verdict = match (&first_ev.extraction, &second_ev.extraction) {
466        (
467            FailureExtraction::Confirmed { failures: f1 },
468            FailureExtraction::Confirmed { failures: f2 },
469        ) if !f1.is_empty() && !f2.is_empty() => {
470            if f1.iter().chain(f2).any(|f| f.suite.is_none()) {
471                ComparisonVerdict::Unknown {
472                    reason: "terminal failure has no confirmed test binary".to_owned(),
473                }
474            } else if f1 == f2 {
475                ComparisonVerdict::Matching {
476                    failures: f1.clone(),
477                }
478            } else {
479                let s1: BTreeSet<&TerminalFailure> = f1.iter().collect();
480                let s2: BTreeSet<&TerminalFailure> = f2.iter().collect();
481                let common = s1.intersection(&s2).map(|f| (*f).clone()).collect();
482                let first_only = s1.difference(&s2).map(|f| (*f).clone()).collect();
483                let second_only = s2.difference(&s1).map(|f| (*f).clone()).collect();
484                ComparisonVerdict::Distinct {
485                    common,
486                    first_only,
487                    second_only,
488                }
489            }
490        }
491        (FailureExtraction::Unknown { reason: r1 }, FailureExtraction::Unknown { reason: r2 }) => {
492            ComparisonVerdict::Unknown {
493                reason: if r1 == r2 {
494                    format!("both attempts: {r1}")
495                } else {
496                    format!("attempt 1: {r1}; attempt 2: {r2}")
497                },
498            }
499        }
500        (FailureExtraction::Unknown { reason }, _) => ComparisonVerdict::Unknown {
501            reason: format!("attempt 1: {reason}"),
502        },
503        (_, FailureExtraction::Unknown { reason }) => ComparisonVerdict::Unknown {
504            reason: format!("attempt 2: {reason}"),
505        },
506        _ => ComparisonVerdict::Unknown {
507            reason: "empty confirmed terminal failure set".to_owned(),
508        },
509    };
510    RerunComparison {
511        head: head.to_owned(),
512        first: first_ev,
513        second: second_ev,
514        verdict,
515    }
516}
517
518// ---------------------------------------------------------------------------
519// Libtest parser
520// ---------------------------------------------------------------------------
521
522#[derive(Default)]
523struct LibtestSummary {
524    runs: usize,
525    suites: usize,
526    only_suite: Option<String>,
527    failed_runs: usize,
528    expected_failures: usize,
529    failures: Vec<TerminalFailure>,
530    incomplete: bool,
531    inconsistent: bool,
532    overflow: bool,
533}
534
535impl LibtestSummary {
536    fn merge(&mut self, other: Self) {
537        self.runs += other.runs;
538        self.suites += other.suites;
539        if other.only_suite.is_some() {
540            self.only_suite = other.only_suite;
541        }
542        self.failed_runs += other.failed_runs;
543        self.expected_failures += other.expected_failures;
544        self.failures.extend(other.failures);
545        self.incomplete |= other.incomplete;
546        self.inconsistent |= other.inconsistent;
547        self.overflow |= other.overflow;
548    }
549}
550
551struct ActiveLibtest {
552    expected_total: usize,
553    suite: Option<String>,
554    live_failed: BTreeSet<String>,
555    in_failures_section: bool,
556    captured_start: Option<usize>,
557    collecting_list: bool,
558    current_list: Vec<String>,
559    last_valid_closing: Option<(usize, usize, Vec<String>)>,
560    saw_overflow: bool,
561}
562
563struct LibtestResultLine {
564    ok: bool,
565    passed: usize,
566    failed: usize,
567    ignored: usize,
568    measured: usize,
569}
570
571impl LibtestResultLine {
572    fn total(&self) -> usize {
573        self.passed + self.failed + self.ignored + self.measured
574    }
575}
576
577fn parse_libtest_stream(
578    lines: &[String],
579    intermediate: &mut IntermediateNotes,
580) -> (LibtestSummary, Vec<(usize, usize)>) {
581    let mut summary = LibtestSummary::default();
582    let mut captured_ranges: Vec<(usize, usize)> = Vec::new();
583    let mut pending_suite: Option<String> = None;
584    let mut active: Option<ActiveLibtest> = None;
585    let mut standalone_collecting = false;
586    let mut standalone_list: Vec<String> = Vec::new();
587    let mut nextest_captured: Option<NextestCapturedMode> = None;
588
589    let commit_active = |run: ActiveLibtest,
590                         summary: &mut LibtestSummary,
591                         captured_ranges: &mut Vec<(usize, usize)>| {
592        if run.saw_overflow {
593            summary.overflow = true;
594        } else if let Some((end_line, expected_f, list)) = run.last_valid_closing {
595            if let Some(start) = run.captured_start {
596                captured_ranges.push((start, end_line));
597            }
598            summary.failed_runs += 1;
599            summary.expected_failures += expected_f;
600            for test in list {
601                summary.failures.push(TerminalFailure {
602                    suite: run.suite.clone(),
603                    test,
604                });
605            }
606        } else {
607            summary.incomplete = true;
608        }
609    };
610
611    for (idx, line) in lines.iter().enumerate() {
612        let trimmed = line.trim();
613        let top_level = is_top_level(line);
614
615        // If an active libtest run already found a valid closing summary and a new
616        // top-level runner boundary begins, close the previous run first.
617        if let Some(run) = active.as_ref()
618            && run.in_failures_section
619            && run.last_valid_closing.is_some()
620            && ((top_level && parse_libtest_running_header(trimmed).is_some())
621                || parse_cargo_running_suite(trimmed).is_some()
622                || parse_nextest_summary_header(trimmed).is_some()
623                || (top_level && is_nextest_rule(trimmed)))
624            && let Some(finished) = active.take()
625        {
626            commit_active(finished, &mut summary, &mut captured_ranges);
627        }
628
629        if active.is_none() {
630            if let Some(mode) = parse_nextest_captured_header(line) {
631                nextest_captured = Some(mode);
632                continue;
633            }
634            if let Some(mode) = nextest_captured {
635                if top_level && is_nextest_rule(trimmed) {
636                    nextest_captured = None;
637                    continue;
638                }
639                match mode {
640                    NextestCapturedMode::Indented => {
641                        if !trimmed.is_empty() && !line.starts_with("    ") {
642                            nextest_captured = None;
643                        } else {
644                            continue;
645                        }
646                    }
647                    NextestCapturedMode::Unindented => {
648                        if trimmed.starts_with("Cancelling due to ")
649                            || trimmed == "test run cancelled"
650                            || is_nextest_starting_line(trimmed)
651                        {
652                            nextest_captured = None;
653                        } else {
654                            continue;
655                        }
656                    }
657                }
658            }
659        }
660
661        if let Some(run) = active.as_mut() {
662            if !run.in_failures_section {
663                if top_level && trimmed == "failures:" {
664                    run.in_failures_section = true;
665                    run.captured_start = Some(idx);
666                    run.collecting_list = true;
667                    run.current_list.clear();
668                } else if top_level && let Some(name) = parse_libtest_live_failed(trimmed) {
669                    run.live_failed.insert(name);
670                } else if top_level && let Some(name) = parse_libtest_long_running(trimmed) {
671                    intermediate.record_long_running(name);
672                } else if top_level && let Some(res) = parse_libtest_result(trimmed) {
673                    if res.ok
674                        && res.failed == 0
675                        && res.total() == run.expected_total
676                        && run.live_failed.is_empty()
677                    {
678                        active = None;
679                    } else {
680                        summary.inconsistent = true;
681                        active = None;
682                    }
683                } else if (top_level && parse_libtest_running_header(trimmed).is_some())
684                    || parse_nextest_summary_header(trimmed).is_some()
685                {
686                    if let Some(unfinished) = active.take() {
687                        commit_active(unfinished, &mut summary, &mut captured_ranges);
688                    }
689                    if top_level && let Some(total) = parse_libtest_running_header(trimmed) {
690                        summary.runs += 1;
691                        active = Some(new_active_libtest(total, pending_suite.take()));
692                    }
693                }
694            } else {
695                // Inside failures: section (captured output + final failures list).
696                if top_level && trimmed == "failures:" {
697                    run.collecting_list = true;
698                    run.current_list.clear();
699                } else if run.collecting_list {
700                    if line.starts_with("    ")
701                        && !trimmed.is_empty()
702                        && !trimmed.starts_with("---- ")
703                    {
704                        if run.current_list.len() <= MAX_TERMINAL_FAILURES {
705                            run.current_list.push(trimmed.to_owned());
706                        }
707                    } else if trimmed.is_empty() {
708                        run.collecting_list = false;
709                    } else if top_level && let Some(res) = parse_libtest_result(trimmed) {
710                        run.collecting_list = false;
711                        try_close_libtest(run, idx, &res);
712                    } else {
713                        run.collecting_list = false;
714                        run.current_list.clear();
715                    }
716                } else if top_level && let Some(res) = parse_libtest_result(trimmed) {
717                    try_close_libtest(run, idx, &res);
718                }
719            }
720            continue;
721        }
722
723        // Idle state (outside an active `running N tests` block).
724        if let Some(suite) = parse_cargo_running_suite(trimmed) {
725            summary.suites += 1;
726            summary.only_suite = Some(suite.clone());
727            pending_suite = Some(suite);
728            standalone_collecting = false;
729            standalone_list.clear();
730        } else if top_level && let Some(total) = parse_libtest_running_header(trimmed) {
731            summary.runs += 1;
732            standalone_collecting = false;
733            standalone_list.clear();
734            active = Some(new_active_libtest(total, pending_suite.take()));
735        } else if top_level && trimmed == "failures:" {
736            standalone_collecting = true;
737            standalone_list.clear();
738        } else if standalone_collecting {
739            if line.starts_with("    ") && !trimmed.is_empty() && !trimmed.starts_with("---- ") {
740                if standalone_list.len() <= MAX_TERMINAL_FAILURES {
741                    standalone_list.push(trimmed.to_owned());
742                }
743            } else if trimmed.is_empty() {
744                standalone_collecting = false;
745            } else if top_level && let Some(res) = parse_libtest_result(trimmed) {
746                standalone_collecting = false;
747                record_standalone_libtest(&res, &standalone_list, &mut summary);
748                standalone_list.clear();
749            } else {
750                standalone_collecting = false;
751                standalone_list.clear();
752            }
753        } else if top_level && let Some(res) = parse_libtest_result(trimmed) {
754            record_standalone_libtest(&res, &standalone_list, &mut summary);
755            standalone_list.clear();
756            pending_suite = None;
757        } else if top_level && let Some(name) = parse_libtest_long_running(trimmed) {
758            intermediate.record_long_running(name);
759        }
760    }
761
762    if let Some(run) = active.take() {
763        commit_active(run, &mut summary, &mut captured_ranges);
764    }
765
766    (summary, captured_ranges)
767}
768
769fn new_active_libtest(expected_total: usize, suite: Option<String>) -> ActiveLibtest {
770    ActiveLibtest {
771        expected_total,
772        suite,
773        live_failed: BTreeSet::new(),
774        in_failures_section: false,
775        captured_start: None,
776        collecting_list: false,
777        current_list: Vec::new(),
778        last_valid_closing: None,
779        saw_overflow: false,
780    }
781}
782
783fn try_close_libtest(run: &mut ActiveLibtest, idx: usize, res: &LibtestResultLine) {
784    if res.ok || res.failed == 0 || res.total() != run.expected_total {
785        return;
786    }
787    if res.failed > MAX_TERMINAL_FAILURES || run.current_list.len() > MAX_TERMINAL_FAILURES {
788        run.saw_overflow = true;
789        return;
790    }
791    if run.current_list.len() != res.failed {
792        return;
793    }
794    if !run.live_failed.is_empty()
795        && (run.live_failed.len() != res.failed
796            || !run.current_list.iter().all(|n| run.live_failed.contains(n)))
797    {
798        return;
799    }
800    run.last_valid_closing = Some((idx, res.failed, run.current_list.clone()));
801}
802
803fn record_standalone_libtest(
804    res: &LibtestResultLine,
805    list: &[String],
806    summary: &mut LibtestSummary,
807) {
808    summary.runs += 1;
809    if res.ok && res.failed == 0 {
810        return;
811    }
812    if res.failed > MAX_TERMINAL_FAILURES || list.len() > MAX_TERMINAL_FAILURES {
813        summary.overflow = true;
814        return;
815    }
816    if res.failed == 0 || list.len() != res.failed {
817        summary.inconsistent = true;
818        return;
819    }
820    summary.failed_runs += 1;
821    summary.expected_failures += res.failed;
822    for test in list {
823        summary.failures.push(TerminalFailure {
824            suite: None,
825            test: test.clone(),
826        });
827    }
828}
829
830fn parse_cargo_running_suite(trimmed: &str) -> Option<String> {
831    if let Some(rest) = trimmed.strip_prefix("Running ")
832        && let Some((label, binary)) = rest.split_once(" (")
833        && let Some(binary) = binary.strip_suffix(')')
834        && let Some(name) = binary.rsplit(['/', '\\']).next()
835        && !label.is_empty()
836        && !name.is_empty()
837    {
838        return Some(format!("{label} ({name})"));
839    }
840    if let Some(rest) = trimmed.strip_prefix("Doc-tests ") {
841        let label = rest.trim();
842        if !label.is_empty() {
843            return Some(format!("doc-tests {label}"));
844        }
845    }
846    None
847}
848
849fn parse_libtest_running_header(trimmed: &str) -> Option<usize> {
850    let rest = trimmed.strip_prefix("running ")?;
851    let num = rest
852        .strip_suffix(" tests")
853        .or_else(|| rest.strip_suffix(" test"))?;
854    num.parse::<usize>().ok()
855}
856
857fn parse_libtest_live_failed(trimmed: &str) -> Option<String> {
858    let rest = trimmed.strip_prefix("test ")?;
859    let name = rest.strip_suffix(" ... FAILED")?;
860    let name = name.strip_suffix(" - should panic").unwrap_or(name).trim();
861    (!name.is_empty()).then(|| name.to_owned())
862}
863
864fn parse_libtest_long_running(trimmed: &str) -> Option<String> {
865    let rest = trimmed.strip_prefix("test ")?;
866    let (name, _) = rest.split_once(" has been running for over ")?;
867    let name = name.trim();
868    (!name.is_empty()).then(|| name.to_owned())
869}
870
871fn parse_libtest_result(trimmed: &str) -> Option<LibtestResultLine> {
872    let (ok, rest) = if let Some(r) = trimmed.strip_prefix("test result: ok.") {
873        (true, r)
874    } else {
875        (false, trimmed.strip_prefix("test result: FAILED.")?)
876    };
877    let mut passed = None;
878    let mut failed = None;
879    let mut ignored = 0usize;
880    let mut measured = 0usize;
881    for part in rest.split(';') {
882        let p = part.trim();
883        if let Some(n) = p.strip_suffix(" passed").and_then(|s| s.parse().ok()) {
884            passed = Some(n);
885        } else if let Some(n) = p.strip_suffix(" failed").and_then(|s| s.parse().ok()) {
886            failed = Some(n);
887        } else if let Some(n) = p.strip_suffix(" ignored").and_then(|s| s.parse().ok()) {
888            ignored = n;
889        } else if let Some(n) = p.strip_suffix(" measured").and_then(|s| s.parse().ok()) {
890            measured = n;
891        }
892    }
893    Some(LibtestResultLine {
894        ok,
895        passed: passed?,
896        failed: failed?,
897        ignored,
898        measured,
899    })
900}
901
902/// A bounded command-output tail can confirm a contradiction, but cannot
903/// establish that an unrecognized test runner actually ran tests.
904pub(crate) fn contradicts_passing_test(output: &str) -> bool {
905    let mut saw_result = false;
906    let mut saw_pass = false;
907    let mut saw_empty_run = false;
908    for line in output.lines().map(str::trim) {
909        if let Some(result) = parse_libtest_result(line) {
910            if !result.ok || result.failed != 0 {
911                return true;
912            }
913            saw_result = true;
914            saw_pass |= result.passed != 0;
915        } else if line == "running 0 tests" {
916            saw_empty_run = true;
917        }
918    }
919    !saw_pass && (saw_result || saw_empty_run)
920}
921
922// ---------------------------------------------------------------------------
923// Nextest parser
924// ---------------------------------------------------------------------------
925
926#[derive(Default)]
927struct NextestSummary {
928    failed_runs: usize,
929    expected_failures: usize,
930    failures: Vec<TerminalFailure>,
931    incomplete: bool,
932    inconsistent: bool,
933    overflow: bool,
934}
935
936impl NextestSummary {
937    fn merge(&mut self, other: Self) {
938        self.failed_runs += other.failed_runs;
939        self.expected_failures += other.expected_failures;
940        self.failures.extend(other.failures);
941        self.incomplete |= other.incomplete;
942        self.inconsistent |= other.inconsistent;
943        self.overflow |= other.overflow;
944    }
945}
946
947struct NextestHeader {
948    expected_failures: usize,
949    flaky_count: usize,
950    cancelled: bool,
951    not_run: Option<usize>,
952    unrecognized_failure_token: bool,
953}
954
955#[derive(Debug, Clone, Copy, PartialEq, Eq)]
956enum NextestCapturedMode {
957    /// Indented captured output (`  stdout ───`, `  stderr ───`, `  combined ───`,
958    /// or ASCII `---`), where body lines are empty or indented by at least 4 spaces.
959    Indented,
960    /// Unindented captured output (`── stdout ──`, `-- stdout --`, `--- STDOUT: ... ---`,
961    /// `─── STDOUT: ... ───`, including `TRY N STDOUT:` variants).
962    Unindented,
963}
964
965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
966enum NextestProgressToken {
967    /// Completed progress counter such as `(1/2)` or `( 475/3510)`.
968    Completed,
969    /// Retry placeholder indicating an intermediate attempt that will be retried,
970    /// such as `(───)`, `(─────────)`, `(---)`, or `(  ⋯/3510)`.
971    RetryPlaceholder,
972}
973
974#[derive(Debug, Clone, Copy, PartialEq, Eq)]
975enum NextestStatusKind {
976    /// Failure status (`FAIL`, `TIMEOUT`, `ABORT`, `EXECFAIL`, `LEAK-FAIL`,
977    /// `FAIL+LEAK`, `SIG*`), either bare (`attempt == None`) or retried (`attempt == Some(n)`).
978    Failure,
979    /// Successful non-flaky completion (`PASS`, `LEAK`).
980    Pass,
981    /// Passed on retry (`FLAKY`, `FLAKY N/M`).
982    Flaky,
983    /// Cancellation status (`CANCEL`, `CANCELLED`, `TERMINATING`).
984    Cancel,
985    /// Other non-terminal, non-failure status (`SKIP`, `SLOW`, `START`, `RETRY`).
986    Other,
987}
988
989struct NextestStatusLine {
990    kind: NextestStatusKind,
991    attempt: Option<usize>,
992    progress: Option<NextestProgressToken>,
993    failure: TerminalFailure,
994}
995
996#[derive(Default)]
997struct RunTestHistory {
998    max_attempt: usize,
999    passed: bool,
1000    try_failures: Vec<usize>,
1001}
1002
1003#[derive(Default)]
1004struct SummaryTestEntries {
1005    bare_failures: usize,
1006    try_failures: Vec<(usize, bool)>,
1007    saw_pass_or_flaky: bool,
1008    max_attempt: usize,
1009}
1010
1011fn is_top_level(line: &str) -> bool {
1012    !line.starts_with(' ') && !line.starts_with('\t')
1013}
1014
1015fn is_rule_chars(s: &str, min_chars: usize) -> bool {
1016    s.chars().count() >= min_chars && (s.chars().all(|c| c == '-') || s.chars().all(|c| c == '─'))
1017}
1018
1019fn is_nextest_rule(trimmed: &str) -> bool {
1020    is_rule_chars(trimmed, 12)
1021}
1022
1023fn in_ranges(idx: usize, ranges: &[(usize, usize)]) -> bool {
1024    ranges.iter().any(|&(a, b)| idx >= a && idx <= b)
1025}
1026
1027fn flush_run_history(
1028    run_history: &mut BTreeMap<TerminalFailure, RunTestHistory>,
1029    intermediate: &mut IntermediateNotes,
1030) {
1031    for (failure, exec) in std::mem::take(run_history) {
1032        let distinct_attempts: BTreeSet<usize> = exec.try_failures.into_iter().collect();
1033        for _ in distinct_attempts {
1034            intermediate.record_try(failure.display_name());
1035        }
1036    }
1037}
1038
1039fn parse_nextest_stream(
1040    lines: &[String],
1041    libtest_captured: &[(usize, usize)],
1042    intermediate: &mut IntermediateNotes,
1043) -> NextestSummary {
1044    let mut summary = NextestSummary::default();
1045    let mut in_captured: Option<NextestCapturedMode> = None;
1046    let mut started_open = false;
1047    let mut saw_summary_flaky = 0usize;
1048    let mut run_history: BTreeMap<TerminalFailure, RunTestHistory> = BTreeMap::new();
1049    let mut i = 0usize;
1050
1051    while i < lines.len() {
1052        if in_ranges(i, libtest_captured) {
1053            i += 1;
1054            continue;
1055        }
1056        let line = &lines[i];
1057        let trimmed = line.trim();
1058        let top_level = is_top_level(line);
1059
1060        if let Some(mode) = parse_nextest_captured_header(line) {
1061            in_captured = Some(mode);
1062            i += 1;
1063            continue;
1064        }
1065        if top_level && is_nextest_rule(trimmed) {
1066            in_captured = None;
1067            i += 1;
1068            continue;
1069        }
1070        if let Some(mode) = in_captured {
1071            match mode {
1072                NextestCapturedMode::Indented => {
1073                    // Indented captured blocks consist solely of blank lines and 4-space-indented
1074                    // test output; any non-empty line with fewer than 4 leading spaces (such as
1075                    // `  TRY 2 PASS`, `   FLAKY 2/3`, `Cancelling due to ...`, `error:`) ends it.
1076                    if !trimmed.is_empty() && !line.starts_with("    ") {
1077                        in_captured = None;
1078                    } else {
1079                        i += 1;
1080                        continue;
1081                    }
1082                }
1083                NextestCapturedMode::Unindented => {
1084                    // A genuine nextest cancellation banner or new start ends unindented captured output.
1085                    if trimmed.starts_with("Cancelling due to ")
1086                        || trimmed == "test run cancelled"
1087                        || is_nextest_starting_line(trimmed)
1088                    {
1089                        in_captured = None;
1090                    } else {
1091                        i += 1;
1092                        continue;
1093                    }
1094                }
1095            }
1096        }
1097
1098        if is_nextest_starting_line(trimmed) {
1099            if started_open {
1100                summary.incomplete = true;
1101                flush_run_history(&mut run_history, intermediate);
1102            }
1103            started_open = true;
1104            i += 1;
1105            continue;
1106        }
1107
1108        if trimmed.starts_with("Cancelling due to ") || trimmed == "test run cancelled" {
1109            intermediate.cancelled = true;
1110            i += 1;
1111            continue;
1112        }
1113
1114        if let Some(header) = parse_nextest_summary_header(trimmed) {
1115            started_open = false;
1116            if header.cancelled {
1117                intermediate.cancelled = true;
1118            }
1119            if let Some(not_run) = header.not_run {
1120                intermediate.not_run_count =
1121                    Some(intermediate.not_run_count.unwrap_or(0) + not_run);
1122            }
1123            saw_summary_flaky += header.flaky_count;
1124            if header.unrecognized_failure_token {
1125                summary.inconsistent = true;
1126            }
1127
1128            let mut summary_tests: BTreeMap<TerminalFailure, SummaryTestEntries> = BTreeMap::new();
1129            let mut block_inconsistent = false;
1130            let mut j = i + 1;
1131            while j < lines.len() && !in_ranges(j, libtest_captured) {
1132                let next_line = &lines[j];
1133                let next_trimmed = next_line.trim();
1134                if parse_nextest_captured_header(next_line) == Some(NextestCapturedMode::Indented) {
1135                    j += 1;
1136                    while j < lines.len() && !in_ranges(j, libtest_captured) {
1137                        let cap_line = &lines[j];
1138                        let cap_trimmed = cap_line.trim();
1139                        if parse_nextest_captured_header(cap_line)
1140                            == Some(NextestCapturedMode::Indented)
1141                            || cap_trimmed.is_empty()
1142                            || cap_line.starts_with("    ")
1143                        {
1144                            j += 1;
1145                        } else {
1146                            break;
1147                        }
1148                    }
1149                    continue;
1150                }
1151                if next_trimmed.is_empty()
1152                    || (is_top_level(next_line) && is_nextest_rule(next_trimmed))
1153                    || next_trimmed.starts_with("error:")
1154                    || next_trimmed.starts_with("[cargo-make]")
1155                    || parse_nextest_summary_header(next_trimmed).is_some()
1156                {
1157                    break;
1158                }
1159                let Some(parsed) = parse_nextest_status_line(next_trimmed) else {
1160                    break;
1161                };
1162                let entry = summary_tests.entry(parsed.failure.clone()).or_default();
1163                if let Some(attempt) = parsed.attempt {
1164                    entry.max_attempt = entry.max_attempt.max(attempt);
1165                }
1166                match parsed.kind {
1167                    NextestStatusKind::Failure => {
1168                        let is_placeholder =
1169                            parsed.progress == Some(NextestProgressToken::RetryPlaceholder);
1170                        if let Some(attempt) = parsed.attempt {
1171                            entry.try_failures.push((attempt, is_placeholder));
1172                        } else if is_placeholder {
1173                            block_inconsistent = true;
1174                        } else {
1175                            entry.bare_failures += 1;
1176                        }
1177                    }
1178                    NextestStatusKind::Flaky => {
1179                        entry.saw_pass_or_flaky = true;
1180                        intermediate.record_flaky(parsed.failure.display_name());
1181                    }
1182                    NextestStatusKind::Pass => {
1183                        entry.saw_pass_or_flaky = true;
1184                    }
1185                    NextestStatusKind::Cancel => {
1186                        intermediate.cancelled = true;
1187                    }
1188                    NextestStatusKind::Other => {}
1189                }
1190                j += 1;
1191            }
1192
1193            // Resolve terminal failures per `(suite, test)` from the Summary block,
1194            // reinforced by execution history for this run:
1195            // - A bare failure takes precedence over `TRY` lines for the same test.
1196            // - Tests that reached `FLAKY` or `PASS` have no terminal failure.
1197            // - `TRY` lines with a retry placeholder or a higher observed attempt are intermediate.
1198            // - The remaining highest-attempt failure is terminal; earlier attempts (deduplicated
1199            //   across execution and Summary) are recorded as intermediate retries.
1200            let mut block_failures = Vec::new();
1201            for (failure, entry) in summary_tests {
1202                let exec = run_history.remove(&failure).unwrap_or_default();
1203                let combined_max_attempt = entry.max_attempt.max(exec.max_attempt);
1204                let reached_pass = entry.saw_pass_or_flaky || exec.passed;
1205
1206                let mut resolved_terminal_attempt: Option<usize> = None;
1207                let mut is_terminal_failure = false;
1208
1209                if entry.bare_failures > 0 {
1210                    if entry.bare_failures > 1 || reached_pass {
1211                        block_inconsistent = true;
1212                    } else {
1213                        is_terminal_failure = true;
1214                    }
1215                } else if !entry.try_failures.is_empty() && !reached_pass {
1216                    let eligible: Vec<usize> = entry
1217                        .try_failures
1218                        .iter()
1219                        .filter(|&&(attempt, is_placeholder)| {
1220                            !is_placeholder && attempt >= combined_max_attempt
1221                        })
1222                        .map(|&(attempt, _)| attempt)
1223                        .collect();
1224                    if let Some(&max_eligible) = eligible.iter().max() {
1225                        let count_at_max = eligible.iter().filter(|&&a| a == max_eligible).count();
1226                        if count_at_max > 1 {
1227                            block_inconsistent = true;
1228                        } else {
1229                            is_terminal_failure = true;
1230                            resolved_terminal_attempt = Some(max_eligible);
1231                        }
1232                    }
1233                }
1234
1235                if is_terminal_failure {
1236                    block_failures.push(failure.clone());
1237                }
1238
1239                let mut intermediate_attempts: BTreeSet<usize> = BTreeSet::new();
1240                for attempt in exec.try_failures {
1241                    if Some(attempt) != resolved_terminal_attempt {
1242                        intermediate_attempts.insert(attempt);
1243                    }
1244                }
1245                for (attempt, _) in entry.try_failures {
1246                    if Some(attempt) != resolved_terminal_attempt {
1247                        intermediate_attempts.insert(attempt);
1248                    }
1249                }
1250                for _ in intermediate_attempts {
1251                    intermediate.record_try(failure.display_name());
1252                }
1253            }
1254            flush_run_history(&mut run_history, intermediate);
1255
1256            if header.expected_failures > MAX_TERMINAL_FAILURES
1257                || block_failures.len() > MAX_TERMINAL_FAILURES
1258            {
1259                summary.overflow = true;
1260            } else if block_inconsistent {
1261                summary.inconsistent = true;
1262            } else if header.expected_failures == 0 {
1263                if !block_failures.is_empty() {
1264                    summary.inconsistent = true;
1265                }
1266            } else if block_failures.len() != header.expected_failures {
1267                summary.inconsistent = true;
1268            } else {
1269                summary.failed_runs += 1;
1270                summary.expected_failures += header.expected_failures;
1271                summary.failures.extend(block_failures);
1272            }
1273            i = j;
1274            continue;
1275        }
1276
1277        // Non-summary status lines during execution: track per-test retry history, FLAKY,
1278        // and CANCEL only; only final Summary decides terminal failures.
1279        if let Some(parsed) = parse_nextest_status_line(trimmed) {
1280            let hist = run_history.entry(parsed.failure.clone()).or_default();
1281            if let Some(attempt) = parsed.attempt {
1282                hist.max_attempt = hist.max_attempt.max(attempt);
1283            }
1284            match parsed.kind {
1285                NextestStatusKind::Failure => {
1286                    if let Some(attempt) = parsed.attempt {
1287                        hist.try_failures.push(attempt);
1288                    }
1289                }
1290                NextestStatusKind::Pass => {
1291                    hist.passed = true;
1292                }
1293                NextestStatusKind::Flaky => {
1294                    hist.passed = true;
1295                    intermediate.record_flaky(parsed.failure.display_name());
1296                }
1297                NextestStatusKind::Cancel => intermediate.cancelled = true,
1298                NextestStatusKind::Other => {}
1299            }
1300        }
1301        i += 1;
1302    }
1303
1304    flush_run_history(&mut run_history, intermediate);
1305
1306    if saw_summary_flaky > intermediate.flaky_count {
1307        intermediate.flaky_count = saw_summary_flaky;
1308    }
1309    if started_open {
1310        summary.incomplete = true;
1311    }
1312    summary
1313}
1314
1315fn parse_nextest_captured_header(line: &str) -> Option<NextestCapturedMode> {
1316    let trimmed = line.trim();
1317    if line.starts_with("  ") && !line.starts_with("    ") {
1318        // Default nextest 0.9+ indented stream headers: `  stdout ───`, `  stderr ───`,
1319        // `  combined ───`, and ASCII `---` equivalents.
1320        for prefix in ["stdout ", "stderr ", "combined "] {
1321            if let Some(rest) = trimmed.strip_prefix(prefix)
1322                && is_rule_chars(rest.trim(), 2)
1323            {
1324                return Some(NextestCapturedMode::Indented);
1325            }
1326        }
1327        return None;
1328    }
1329    if !is_top_level(line) {
1330        return None;
1331    }
1332    // `--no-output-indent` headers: `── stdout ──`, `-- stderr --`, `── combined ──`.
1333    for delim in ["──", "--"] {
1334        if let Some(inner) = trimmed
1335            .strip_prefix(delim)
1336            .and_then(|s| s.strip_suffix(delim))
1337        {
1338            let inner = inner.trim_matches(['─', '-']).trim();
1339            if matches!(inner, "stdout" | "stderr" | "combined") {
1340                return Some(NextestCapturedMode::Unindented);
1341            }
1342        }
1343    }
1344    // Legacy / verbose nextest headers: `--- STDOUT: ... ---`, `--- TRY 1 STDERR: ... ---`,
1345    // and Unicode `─── ... ───` equivalents.
1346    for delim in ["---", "───"] {
1347        if let Some(inner) = trimmed
1348            .strip_prefix(delim)
1349            .and_then(|s| s.strip_suffix(delim))
1350        {
1351            let inner = inner.trim();
1352            let stream_part = if let Some(after_try) = inner.strip_prefix("TRY ") {
1353                let mut parts = after_try.splitn(2, char::is_whitespace);
1354                let Some(n) = parts.next() else {
1355                    continue;
1356                };
1357                if n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) {
1358                    continue;
1359                }
1360                parts.next().unwrap_or("").trim_start()
1361            } else {
1362                inner
1363            };
1364            if stream_part.starts_with("STDOUT:")
1365                || stream_part.starts_with("STDERR:")
1366                || stream_part.starts_with("COMBINED:")
1367                || stream_part.starts_with("OUTPUT:")
1368            {
1369                return Some(NextestCapturedMode::Unindented);
1370            }
1371        }
1372    }
1373    None
1374}
1375
1376fn is_nextest_starting_line(trimmed: &str) -> bool {
1377    let Some(rest) = trimmed.strip_prefix("Starting ") else {
1378        return false;
1379    };
1380    let mut parts = rest.split_whitespace();
1381    let Some(count) = parts.next().and_then(|n| n.parse::<usize>().ok()) else {
1382        return false;
1383    };
1384    count > 0 && matches!(parts.next(), Some("test" | "tests"))
1385}
1386
1387fn parse_nextest_summary_header(trimmed: &str) -> Option<NextestHeader> {
1388    let rest = trimmed.strip_prefix("Summary [")?;
1389    let (dur, after) = rest.split_once(']')?;
1390    if !is_duration_token(dur.trim()) {
1391        return None;
1392    }
1393    let (counts_part, details) = after.trim().split_once(':')?;
1394    let run_spec = counts_part
1395        .trim()
1396        .strip_suffix(" tests run")
1397        .or_else(|| counts_part.trim().strip_suffix(" test run"))?;
1398
1399    let mut cancelled = false;
1400    let mut not_run = None;
1401    if let Some((ran, total)) = run_spec.split_once('/') {
1402        let ran: usize = ran.trim().parse().ok()?;
1403        let total: usize = total.trim().parse().ok()?;
1404        if ran < total {
1405            cancelled = true;
1406            not_run = Some(total - ran);
1407        }
1408    } else {
1409        run_spec.trim().parse::<usize>().ok()?;
1410    }
1411
1412    let mut expected_failures = 0usize;
1413    let mut flaky_count = 0usize;
1414    let mut unrecognized_failure_token = false;
1415
1416    for segment in split_top_level_commas(details) {
1417        let seg = segment.trim();
1418        if seg.is_empty() {
1419            continue;
1420        }
1421        let (main, paren) = match seg.split_once('(') {
1422            Some((m, p)) => (m.trim(), Some(p.trim_end_matches(')').trim())),
1423            None => (seg, None),
1424        };
1425        if let Some(p) = paren {
1426            for sub in p.split(',') {
1427                let sub = sub.trim();
1428                if let Some(n) = sub
1429                    .strip_suffix(" flaky")
1430                    .and_then(|s| s.parse::<usize>().ok())
1431                {
1432                    flaky_count += n;
1433                }
1434                if sub.contains("cancel") {
1435                    cancelled = true;
1436                }
1437            }
1438        }
1439        let mut words = main.splitn(2, char::is_whitespace);
1440        let Some(n) = words.next().and_then(|s| s.parse::<usize>().ok()) else {
1441            if main.contains("cancel") {
1442                cancelled = true;
1443            }
1444            continue;
1445        };
1446        let label = words.next().unwrap_or("").trim();
1447        match label {
1448            "passed" | "skipped" => {}
1449            "failed" | "timed out" | "exec failed" => expected_failures += n,
1450            "not run" => {
1451                if n > 0 {
1452                    cancelled = true;
1453                    not_run = Some(not_run.unwrap_or(0).max(n));
1454                }
1455            }
1456            other => {
1457                let lower = other.to_lowercase();
1458                if lower.contains("fail") || lower.contains("abort") || lower.contains("timeout") {
1459                    unrecognized_failure_token = true;
1460                }
1461            }
1462        }
1463    }
1464
1465    Some(NextestHeader {
1466        expected_failures,
1467        flaky_count,
1468        cancelled,
1469        not_run,
1470        unrecognized_failure_token,
1471    })
1472}
1473
1474fn split_top_level_commas(input: &str) -> Vec<&str> {
1475    let mut parts = Vec::new();
1476    let mut depth = 0usize;
1477    let mut start = 0usize;
1478    for (idx, ch) in input.char_indices() {
1479        match ch {
1480            '(' => depth += 1,
1481            ')' => depth = depth.saturating_sub(1),
1482            ',' if depth == 0 => {
1483                parts.push(&input[start..idx]);
1484                start = idx + 1;
1485            }
1486            _ => {}
1487        }
1488    }
1489    parts.push(&input[start..]);
1490    parts
1491}
1492
1493fn is_duration_token(tok: &str) -> bool {
1494    let Some(num) = tok.strip_suffix('s') else {
1495        return false;
1496    };
1497    !num.is_empty() && num.bytes().all(|b| b.is_ascii_digit() || b == b'.')
1498}
1499
1500fn is_nextest_failure_status(status: &str) -> bool {
1501    matches!(
1502        status,
1503        "FAIL" | "TIMEOUT" | "ABORT" | "EXECFAIL" | "LEAK-FAIL" | "FAIL+LEAK"
1504    ) || (status.starts_with("SIG")
1505        && status.len() >= 5
1506        && status
1507            .bytes()
1508            .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()))
1509}
1510
1511fn parse_flaky_attempt(prefix: &str) -> Option<usize> {
1512    let rest = prefix.strip_prefix("FLAKY ")?.trim();
1513    let (attempt_str, total_str) = rest.split_once('/')?;
1514    let attempt = attempt_str.trim().parse::<usize>().ok()?;
1515    let total_token = total_str.split_whitespace().next()?;
1516    let _total = total_token.parse::<usize>().ok()?;
1517    (attempt > 0).then_some(attempt)
1518}
1519
1520fn is_retry_placeholder_chars(s: &str) -> bool {
1521    !s.is_empty() && (s.chars().all(|c| matches!(c, '─' | '-' | '⋯' | '…')) || s == "...")
1522}
1523
1524fn strip_nextest_progress_token(rest: &str) -> (Option<NextestProgressToken>, &str) {
1525    let Some(after_open) = rest.strip_prefix('(') else {
1526        return (None, rest);
1527    };
1528    let Some((inner, tail)) = after_open.split_once(')') else {
1529        return (None, rest);
1530    };
1531    let inner_trimmed = inner.trim();
1532    if is_retry_placeholder_chars(inner_trimmed) {
1533        return (
1534            Some(NextestProgressToken::RetryPlaceholder),
1535            tail.trim_start(),
1536        );
1537    }
1538    if let Some((a, b)) = inner.split_once('/') {
1539        let a = a.trim();
1540        let b = b.trim();
1541        if !a.is_empty() && !b.is_empty() && b.bytes().all(|c| c.is_ascii_digit()) {
1542            if a.bytes().all(|c| c.is_ascii_digit()) {
1543                return (Some(NextestProgressToken::Completed), tail.trim_start());
1544            }
1545            if is_retry_placeholder_chars(a) {
1546                return (
1547                    Some(NextestProgressToken::RetryPlaceholder),
1548                    tail.trim_start(),
1549                );
1550            }
1551        }
1552    }
1553    (None, rest)
1554}
1555
1556fn parse_nextest_status_line(trimmed: &str) -> Option<NextestStatusLine> {
1557    let (raw_prefix, after_open) = trimmed.split_once('[')?;
1558    let (dur, rest) = after_open.split_once(']')?;
1559    if !is_duration_token(dur.trim()) {
1560        return None;
1561    }
1562    let prefix = raw_prefix.trim();
1563    let (attempt, kind) = if let Some(after_try) = prefix.strip_prefix("TRY ") {
1564        let mut parts = after_try.split_whitespace();
1565        let attempt_num = parts.next()?.parse::<usize>().ok()?;
1566        let status = parts.next()?;
1567        if attempt_num == 0 || parts.next().is_some() {
1568            return None;
1569        }
1570        let kind = if is_nextest_failure_status(status) {
1571            NextestStatusKind::Failure
1572        } else if matches!(status, "PASS" | "LEAK") {
1573            NextestStatusKind::Pass
1574        } else if matches!(status, "CANCEL" | "CANCELLED" | "TERMINATING") {
1575            NextestStatusKind::Cancel
1576        } else if matches!(status, "SKIP" | "SLOW" | "START") {
1577            NextestStatusKind::Other
1578        } else {
1579            return None;
1580        };
1581        (Some(attempt_num), kind)
1582    } else if prefix == "FLAKY" || prefix.starts_with("FLAKY ") {
1583        (parse_flaky_attempt(prefix), NextestStatusKind::Flaky)
1584    } else if matches!(prefix, "CANCEL" | "CANCELLED" | "TERMINATING") {
1585        (None, NextestStatusKind::Cancel)
1586    } else if matches!(prefix, "PASS" | "LEAK") {
1587        (None, NextestStatusKind::Pass)
1588    } else if matches!(prefix, "SKIP" | "SLOW" | "START")
1589        || prefix == "RETRY"
1590        || prefix.starts_with("RETRY ")
1591    {
1592        (None, NextestStatusKind::Other)
1593    } else if is_nextest_failure_status(prefix) {
1594        (None, NextestStatusKind::Failure)
1595    } else {
1596        return None;
1597    };
1598
1599    let (progress, rest) = strip_nextest_progress_token(rest.trim());
1600    let mut parts = rest.split_whitespace();
1601    let suite = parts.next()?;
1602    let test = rest[suite.len()..].trim();
1603    if suite.is_empty() || test.is_empty() {
1604        return None;
1605    }
1606    Some(NextestStatusLine {
1607        kind,
1608        attempt,
1609        progress,
1610        failure: TerminalFailure {
1611            suite: Some(suite.to_owned()),
1612            test: test.to_owned(),
1613        },
1614    })
1615}
1616
1617// ---------------------------------------------------------------------------
1618// Shared formatting helpers
1619// ---------------------------------------------------------------------------
1620
1621fn push_bounded_unique(list: &mut Vec<String>, item: String, max: usize) {
1622    if list.len() < max && !list.contains(&item) {
1623        list.push(item);
1624    }
1625}
1626
1627fn join_bounded(items: &[String], max: usize) -> String {
1628    if items.len() <= max {
1629        return items.join(", ");
1630    }
1631    let shown = items[..max].join(", ");
1632    format!("{shown} (+{} more)", items.len() - max)
1633}
1634
1635fn format_failure_list(failures: &[TerminalFailure], max: usize) -> String {
1636    let names: Vec<String> = failures.iter().map(TerminalFailure::display_name).collect();
1637    join_bounded(&names, max)
1638}
1639
1640fn format_artifact_pair(c: &RerunComparison) -> Option<String> {
1641    match (&c.first.artifact, &c.second.artifact) {
1642        (Some(a), Some(b)) => Some(format!("attempt 1: {a}, attempt 2: {b}")),
1643        (Some(a), None) => Some(format!("attempt 1: {a}")),
1644        (None, Some(b)) => Some(format!("attempt 2: {b}")),
1645        (None, None) => None,
1646    }
1647}
1648
1649fn short_sha(sha: &str) -> &str {
1650    sha.get(..8).unwrap_or(sha)
1651}
1652
1653/// Compact one-line summary of a [`RerunComparison`], shared across events, CLI/web
1654/// reports, stop reasons, and automatic task chat reports.
1655pub fn comparison_headline(c: &RerunComparison) -> String {
1656    let head = short_sha(&c.head);
1657    let artifacts = format_artifact_pair(c)
1658        .map(|a| format!(" ({a})"))
1659        .unwrap_or_default();
1660    match &c.verdict {
1661        ComparisonVerdict::Matching { failures } => format!(
1662            "failed twice on {head} with matching terminal failure(s): {}{artifacts}",
1663            format_failure_list(failures, DISPLAY_FAILURE_LIMIT),
1664        ),
1665        ComparisonVerdict::Distinct {
1666            common,
1667            first_only,
1668            second_only,
1669        } => {
1670            let mut parts = Vec::new();
1671            if !first_only.is_empty() {
1672                parts.push(format!(
1673                    "attempt 1 only: {}",
1674                    format_failure_list(first_only, DISPLAY_FAILURE_LIMIT)
1675                ));
1676            }
1677            if !second_only.is_empty() {
1678                parts.push(format!(
1679                    "attempt 2 only: {}",
1680                    format_failure_list(second_only, DISPLAY_FAILURE_LIMIT)
1681                ));
1682            }
1683            if !common.is_empty() {
1684                parts.push(format!(
1685                    "common: {}",
1686                    format_failure_list(common, DISPLAY_FAILURE_LIMIT)
1687                ));
1688            }
1689            format!(
1690                "failed twice on {head} with distinct terminal failure(s) ({}){artifacts}",
1691                parts.join("; "),
1692            )
1693        }
1694        ComparisonVerdict::Unknown { reason } => {
1695            let mut known_sides = Vec::new();
1696            if let FailureExtraction::Confirmed { failures } = &c.first.extraction {
1697                known_sides.push(format!(
1698                    "attempt 1 terminal failure(s): {}",
1699                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1700                ));
1701            }
1702            if let FailureExtraction::Confirmed { failures } = &c.second.extraction {
1703                known_sides.push(format!(
1704                    "attempt 2 terminal failure(s): {}",
1705                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1706                ));
1707            }
1708            let detail = if known_sides.is_empty() {
1709                reason.clone()
1710            } else {
1711                format!("{reason}; {}", known_sides.join("; "))
1712            };
1713            format!(
1714                "exited non-zero twice on {head}; terminal failure comparison unknown ({detail}){artifacts}"
1715            )
1716        }
1717    }
1718}
1719
1720/// Concise comparison or single-attempt summary line for one failing [`CommandOutcome`],
1721/// if structured evidence or a legacy double-failure marker is present.
1722pub fn outcome_comparison_summary(o: &CommandOutcome) -> Option<String> {
1723    if let Some(c) = &o.rerun_comparison {
1724        return Some(comparison_headline(c));
1725    }
1726    if legacy_failed_twice(&o.output_tail) {
1727        return Some(
1728            "legacy record: command exited non-zero twice without structured attempt comparison (comparison unknown)"
1729                .to_owned(),
1730        );
1731    }
1732    if let Some(ev) = &o.failure_evidence {
1733        match &ev.extraction {
1734            FailureExtraction::Confirmed { failures } if !failures.is_empty() => {
1735                let mut line = format!(
1736                    "terminal failure(s): {}",
1737                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1738                );
1739                if let Some(inter) = ev.intermediate.summary() {
1740                    line.push_str(&format!("; non-terminal: {inter}"));
1741                }
1742                if let Some(art) = &o.artifact {
1743                    line.push_str(&format!(" ({art})"));
1744                }
1745                return Some(line);
1746            }
1747            _ => {}
1748        }
1749    }
1750    None
1751}
1752
1753/// Format a `verify` event line for one command that failed twice on the same commit.
1754pub fn rerun_event_message(context: &str, command: &str, c: &RerunComparison) -> String {
1755    let headline = comparison_headline(c);
1756    let suffix = match &c.verdict {
1757        ComparisonVerdict::Matching { .. } => "the failure reproduced — it stands",
1758        ComparisonVerdict::Distinct { .. } => {
1759            "failures did not match across attempts — verification stays red"
1760        }
1761        ComparisonVerdict::Unknown { .. } => {
1762            "cannot conclude the same failure reproduced — verification stays red"
1763        }
1764    };
1765    format!("{context}: `{command}` {headline}; {suffix}")
1766}
1767
1768/// Format one failed [`CommandOutcome`] for fixer/reviewer/recovery prompts.
1769pub fn format_command_prompt_section(o: &CommandOutcome, max_output: usize) -> String {
1770    if let Some(c) = &o.rerun_comparison {
1771        let mut s = format!("$ {}\n", o.command);
1772        let _ = writeln!(s, "Rerun comparison: {}", comparison_headline(c));
1773        match &c.verdict {
1774            ComparisonVerdict::Matching { .. } => {
1775                s.push_str(
1776                    "Both attempts ended with the same confirmed terminal test failure(s).\n",
1777                );
1778            }
1779            ComparisonVerdict::Distinct { .. } => {
1780                s.push_str(
1781                    "The two attempts ended with DIFFERENT terminal test failures; do not assume one root cause covers both.\n",
1782                );
1783            }
1784            ComparisonVerdict::Unknown { .. } => {
1785                s.push_str(
1786                    "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",
1787                );
1788            }
1789        }
1790        format_attempt_prompt(&mut s, &c.first, ATTEMPT_EXCERPT_MAX);
1791        format_attempt_prompt(&mut s, &c.second, max_output);
1792        return s;
1793    }
1794    if legacy_failed_twice(&o.output_tail) {
1795        let stripped = o
1796            .output_tail
1797            .trim_start()
1798            .strip_prefix(LEGACY_FAILED_TWICE_PREFIX)
1799            .unwrap_or(&o.output_tail)
1800            .trim_start();
1801        return format!(
1802            "$ {}\n[legacy record: command exited non-zero twice without structured attempt comparison; comparison unknown — do not assume the same test failed twice]\n{}\n",
1803            o.command,
1804            summarize_verify(stripped, max_output),
1805        );
1806    }
1807    let mut header = String::new();
1808    if let Some(art) = &o.artifact
1809        && !o.output_tail.contains(art)
1810    {
1811        let _ = writeln!(header, "[full output: {art}]");
1812    }
1813    if let Some(ev) = &o.failure_evidence {
1814        if let FailureExtraction::Confirmed { failures } = &ev.extraction {
1815            let _ = writeln!(
1816                header,
1817                "[terminal failure(s): {}]",
1818                format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1819            );
1820        }
1821        if let Some(inter) = ev.intermediate.summary() {
1822            let _ = writeln!(header, "[non-terminal activity: {inter}]");
1823        }
1824    }
1825    format!(
1826        "$ {}\n{}{}\n",
1827        o.command,
1828        header,
1829        summarize_verify(&o.output_tail, max_output),
1830    )
1831}
1832
1833fn format_attempt_prompt(s: &mut String, a: &AttemptEvidence, max_excerpt: usize) {
1834    let code = a.code.map_or_else(|| "none".to_owned(), |c| c.to_string());
1835    let art = a
1836        .artifact
1837        .as_deref()
1838        .map(|p| format!(", artifact {p}"))
1839        .unwrap_or_default();
1840    let _ = writeln!(
1841        s,
1842        "\n--- Attempt {} (exit {code}, {}ms{art}) ---",
1843        a.attempt, a.duration_ms
1844    );
1845    match &a.extraction {
1846        FailureExtraction::Confirmed { failures } => {
1847            let _ = writeln!(
1848                s,
1849                "Terminal failure(s): {}",
1850                format_failure_list(failures, MAX_TERMINAL_FAILURES)
1851            );
1852        }
1853        FailureExtraction::Unknown { reason } => {
1854            let _ = writeln!(s, "Terminal failure(s): unknown ({reason})");
1855        }
1856    }
1857    if let Some(inter) = a.intermediate.summary() {
1858        let _ = writeln!(s, "Non-terminal activity (separate from verdict): {inter}");
1859    }
1860    let excerpt = summarize_verify(&a.excerpt, max_excerpt);
1861    if !excerpt.trim().is_empty() {
1862        let _ = writeln!(s, "{excerpt}");
1863    }
1864}
1865
1866/// Format structured details for a failed command in CLI (`magi show`) output.
1867pub fn format_outcome_cli_lines(o: &CommandOutcome) -> Vec<String> {
1868    let mut lines = Vec::new();
1869    if let Some(c) = &o.rerun_comparison {
1870        lines.push(format!("comparison: {}", comparison_headline(c)));
1871        for a in [&c.first, &c.second] {
1872            let code = a.code.map_or_else(|| "none".to_owned(), |c| c.to_string());
1873            let art = a
1874                .artifact
1875                .as_deref()
1876                .map(|p| format!("  {p}"))
1877                .unwrap_or_default();
1878            let verdict = match &a.extraction {
1879                FailureExtraction::Confirmed { failures } => format!(
1880                    "terminal: {}",
1881                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1882                ),
1883                FailureExtraction::Unknown { reason } => format!("terminal: unknown ({reason})"),
1884            };
1885            let inter = a
1886                .intermediate
1887                .summary()
1888                .map(|m| format!("  [non-terminal: {m}]"))
1889                .unwrap_or_default();
1890            lines.push(format!(
1891                "attempt {} (exit {code}, {}ms{art}): {verdict}{inter}",
1892                a.attempt, a.duration_ms
1893            ));
1894        }
1895    } else {
1896        if legacy_failed_twice(&o.output_tail) {
1897            lines.push(
1898                "comparison: unknown (legacy record exited non-zero twice without structured attempt comparison)"
1899                    .to_owned(),
1900            );
1901        }
1902        if let Some(art) = &o.artifact {
1903            lines.push(format!("artifact: {art}"));
1904        }
1905        if let Some(ev) = &o.failure_evidence {
1906            match &ev.extraction {
1907                FailureExtraction::Confirmed { failures } => lines.push(format!(
1908                    "terminal failure(s): {}",
1909                    format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
1910                )),
1911                FailureExtraction::Unknown { reason } => {
1912                    lines.push(format!("terminal failure(s): unknown ({reason})"))
1913                }
1914            }
1915            if let Some(inter) = ev.intermediate.summary() {
1916                lines.push(format!("non-terminal: {inter}"));
1917            }
1918        }
1919    }
1920    lines
1921}
1922
1923/// Concise summary of the *current* unresolved e2e failure in `state`, if any.
1924///
1925/// Respects resolution order: never resurfaces an earlier review round's e2e failure
1926/// when `head_e2e` or `gate_repair_e2e` subsequently passed, and inspects `head_e2e`,
1927/// `gate_repair_e2e`, and the latest `ReviewRound` in precedence order.
1928pub fn current_e2e_failure_summary(state: &RunState) -> Option<String> {
1929    if let Some(e) = &state.head_e2e {
1930        if !e.passed {
1931            if let Some(line) = summarize_failed_outcomes(&e.outcomes) {
1932                return Some(format!("current head e2e @ {}: {line}", short_sha(&e.head)));
1933            }
1934        } else {
1935            return None;
1936        }
1937    }
1938    if let Some(e) = &state.gate_repair_e2e {
1939        if !e.passed {
1940            if let Some(line) = summarize_failed_outcomes(&e.outcomes) {
1941                return Some(format!("gate repair e2e @ {}: {line}", short_sha(&e.head)));
1942            }
1943        } else {
1944            return None;
1945        }
1946    }
1947    if let Some(r) = state.reviews.last()
1948        && r.e2e_status() == E2eStatus::Failed
1949        && let Some(line) = summarize_failed_outcomes(&r.e2e)
1950    {
1951        let head = r.verified_head.as_deref().unwrap_or(&r.head);
1952        return Some(format!(
1953            "round {} e2e @ {}: {line}",
1954            r.round,
1955            short_sha(head)
1956        ));
1957    }
1958    None
1959}
1960
1961/// Summarize the first failing non-resource-blocked outcome in `outcomes`, preferring
1962/// structured rerun comparisons when present.
1963pub fn summarize_failed_outcomes(outcomes: &[CommandOutcome]) -> Option<String> {
1964    let failing: Vec<&CommandOutcome> = outcomes
1965        .iter()
1966        .filter(|o| !o.ok() && !o.resource_blocked)
1967        .collect();
1968    if failing.is_empty() {
1969        return None;
1970    }
1971    let parts: Vec<String> = failing
1972        .iter()
1973        .take(2)
1974        .map(|o| match outcome_comparison_summary(o) {
1975            Some(detail) => format!("`{}` {detail}", o.command),
1976            None => format!(
1977                "`{}` failed (exit {})",
1978                o.command,
1979                o.code.map_or_else(|| "none".to_owned(), |c| c.to_string())
1980            ),
1981        })
1982        .collect();
1983    Some(parts.join("; "))
1984}
1985
1986#[cfg(test)]
1987mod tests {
1988    use super::*;
1989
1990    fn outcome(code: Option<i32>, raw: &str, artifact: Option<&str>) -> CommandOutcome {
1991        let build_failed = code != Some(0) && raw.contains("error: could not compile");
1992        let evidence = extract_combined(code, build_failed, raw);
1993        CommandOutcome {
1994            command: "cargo make test".to_owned(),
1995            code,
1996            output_tail: summarize_verify(raw, crate::run::VERIFY_SUMMARY),
1997            duration_ms: 1200,
1998            resource_blocked: false,
1999            artifact: artifact.map(str::to_owned),
2000            failure_evidence: Some(evidence),
2001            rerun_comparison: None,
2002        }
2003    }
2004
2005    #[test]
2006    fn nextest_separates_terminal_failures_from_try_flaky_and_cancellations() {
2007        let raw = "\
2008Starting 12 tests across 3 binaries
2009\x1b[33m  TRY 1 FAIL\x1b[0m [   0.500s] magi-cli::chat_notify test_flaky_one
2010\x1b[33m   FLAKY 2/3\x1b[0m [   0.400s] magi-cli::chat_notify test_flaky_one
2011  TRY 1 FAIL [   1.000s] magi-cli::isolated_build_cache test_cache
2012  TRY 2 FAIL [   1.000s] magi-cli::isolated_build_cache test_cache
2013\x1b[31m        FAIL\x1b[0m [   1.200s] magi-cli::isolated_build_cache test_cache
2014Cancelling due to test failure: 2 tests still running
2015      CANCEL [   0.000s] magi-cli::web_render test_other
2016------------
2017     Summary [  10.500s] 5/12 tests run: 4 passed (1 flaky), 1 failed, 0 skipped
2018        FAIL [   1.200s] magi-cli::isolated_build_cache test_cache
2019  TRY 1 FAIL [   1.000s] magi-cli::isolated_build_cache test_cache
2020   FLAKY 2/3 [   0.400s] magi-cli::chat_notify test_flaky_one
2021error: test run failed
2022";
2023        let ev = extract_combined(Some(100), false, raw);
2024        assert_eq!(
2025            ev.extraction,
2026            FailureExtraction::Confirmed {
2027                failures: vec![TerminalFailure {
2028                    suite: Some("magi-cli::isolated_build_cache".to_owned()),
2029                    test: "test_cache".to_owned(),
2030                }]
2031            }
2032        );
2033        assert!(ev.intermediate.try_failure_count >= 2);
2034        assert_eq!(ev.intermediate.flaky_count, 1);
2035        assert!(ev.intermediate.cancelled);
2036        assert_eq!(ev.intermediate.not_run_count, Some(7));
2037    }
2038
2039    #[test]
2040    fn typography_0b11_scenario_distinguishes_unit_failure_from_nextest_failure() {
2041        // Attempt 1: chat unit test failed in cargo test --lib (nextest never ran).
2042        let attempt1_out = "\
2043running 2 tests
2044test ok_test ... ok
2045test talk::tests::chat_timeout ... FAILED
2046
2047failures:
2048
2049---- talk::tests::chat_timeout stdout ----
2050thread 'talk::tests::chat_timeout' panicked at src/talk.rs:42:9:
2051timed out waiting for turn
2052
2053failures:
2054    talk::tests::chat_timeout
2055
2056test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.01s
2057";
2058        let attempt1_err =
2059            "Running unittests src/lib.rs (target/debug/deps/magi-abc)\nerror: test failed\n";
2060        let ev1 = extract_streams(Some(101), false, attempt1_out, attempt1_err);
2061
2062        // Attempt 2: libtest passed on stdout; nextest failed on stderr naming isolated_build_cache.
2063        let attempt2_out = "\
2064running 2 tests
2065test ok_test ... ok
2066test talk::tests::chat_timeout ... ok
2067
2068test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12s
2069";
2070        let attempt2_err = "\
2071Running unittests src/lib.rs (target/debug/deps/magi-abc)
2072Starting 10 tests across 2 binaries
2073  TRY 1 FAIL [   0.300s] magi-cli::other test_transient
2074   FLAKY 2/3 [   0.200s] magi-cli::other test_transient
2075Cancelling due to test failure: 1 test still running
2076------------
2077     Summary [  12.000s] 6/10 tests run: 5 passed (1 flaky), 1 failed, 0 skipped
2078        FAIL [   2.500s] magi-cli::isolated_build_cache test_isolation
2079error: test run failed
2080";
2081        let ev2 = extract_streams(Some(100), false, attempt2_out, attempt2_err);
2082
2083        let o1 = CommandOutcome {
2084            command: "cargo make test".to_owned(),
2085            code: Some(101),
2086            output_tail: attempt1_out.to_owned(),
2087            duration_ms: 5000,
2088            resource_blocked: false,
2089            artifact: Some("artifacts/e2e-3.out".to_owned()),
2090            failure_evidence: Some(ev1),
2091            rerun_comparison: None,
2092        };
2093        let o2 = CommandOutcome {
2094            command: "cargo make test".to_owned(),
2095            code: Some(100),
2096            output_tail: attempt2_err.to_owned(),
2097            duration_ms: 12000,
2098            resource_blocked: false,
2099            artifact: Some("artifacts/e2e-4.out".to_owned()),
2100            failure_evidence: Some(ev2),
2101            rerun_comparison: None,
2102        };
2103        let cmp = compare_attempts("0b11aaaa1234", &o1, &o2);
2104        assert_eq!(
2105            cmp.verdict,
2106            ComparisonVerdict::Distinct {
2107                common: vec![],
2108                first_only: vec![TerminalFailure {
2109                    suite: Some("unittests src/lib.rs (magi-abc)".to_owned()),
2110                    test: "talk::tests::chat_timeout".to_owned(),
2111                }],
2112                second_only: vec![TerminalFailure {
2113                    suite: Some("magi-cli::isolated_build_cache".to_owned()),
2114                    test: "test_isolation".to_owned(),
2115                }],
2116            }
2117        );
2118        let headline = comparison_headline(&cmp);
2119        assert!(
2120            headline.contains("distinct terminal failure(s)"),
2121            "{headline}"
2122        );
2123        assert!(headline.contains("talk::tests::chat_timeout"), "{headline}");
2124        assert!(headline.contains("isolated_build_cache"), "{headline}");
2125        assert!(headline.contains("artifacts/e2e-3.out"), "{headline}");
2126        assert!(headline.contains("artifacts/e2e-4.out"), "{headline}");
2127        let event = rerun_event_message("round 1", "cargo make test", &cmp);
2128        assert!(!event.contains("reproduced"), "{event}");
2129    }
2130
2131    #[test]
2132    fn hang_without_final_summary_is_unknown_not_matching() {
2133        let attempt1_out = "\
2134running 2 tests
2135test ok_test ... ok
2136test talk::tests::chat_timeout has been running for over 60 seconds
2137";
2138        let ev1 = extract_streams(Some(1), false, attempt1_out, "");
2139        assert!(matches!(ev1.extraction, FailureExtraction::Unknown { .. }));
2140        assert_eq!(
2141            ev1.intermediate.long_running,
2142            vec!["talk::tests::chat_timeout"]
2143        );
2144
2145        let attempt2_err = "\
2146------------
2147     Summary [   5.000s] 3 tests run: 2 passed, 1 failed, 0 skipped
2148        FAIL [   1.000s] magi-cli::isolated_build_cache test_isolation
2149";
2150        let ev2 = extract_streams(Some(100), false, "", attempt2_err);
2151        assert!(matches!(
2152            ev2.extraction,
2153            FailureExtraction::Confirmed { .. }
2154        ));
2155
2156        let o1 = CommandOutcome {
2157            command: "cargo make test".to_owned(),
2158            code: Some(1),
2159            output_tail: attempt1_out.to_owned(),
2160            duration_ms: 60_000,
2161            resource_blocked: false,
2162            artifact: Some("artifacts/e2e-3.out".to_owned()),
2163            failure_evidence: Some(ev1),
2164            rerun_comparison: None,
2165        };
2166        let o2 = CommandOutcome {
2167            command: "cargo make test".to_owned(),
2168            code: Some(100),
2169            output_tail: attempt2_err.to_owned(),
2170            duration_ms: 5_000,
2171            resource_blocked: false,
2172            artifact: Some("artifacts/e2e-4.out".to_owned()),
2173            failure_evidence: Some(ev2),
2174            rerun_comparison: None,
2175        };
2176        let cmp = compare_attempts("deadbeef", &o1, &o2);
2177        assert!(matches!(cmp.verdict, ComparisonVerdict::Unknown { .. }));
2178        let headline = comparison_headline(&cmp);
2179        assert!(headline.contains("comparison unknown"), "{headline}");
2180        assert!(headline.contains("isolated_build_cache"), "{headline}");
2181        assert!(headline.contains("artifacts/e2e-3.out"), "{headline}");
2182        assert!(headline.contains("artifacts/e2e-4.out"), "{headline}");
2183    }
2184
2185    #[test]
2186    fn captured_stdout_cannot_spoof_libtest_or_nextest_verdict() {
2187        let raw = "\
2188running 2 tests
2189test ok_test ... ok
2190test real_test ... FAILED
2191
2192failures:
2193
2194---- real_test stdout ----
2195failures:
2196    fake_test
2197
2198test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
2199------------
2200     Summary [   0.100s] 1 tests run: 0 passed, 1 failed, 0 skipped
2201        FAIL [   0.100s] fake::bin fake_nextest
2202
2203failures:
2204    real_test
2205
2206test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s
2207";
2208        let ev = extract_combined(Some(101), false, raw);
2209        assert_eq!(
2210            ev.extraction,
2211            FailureExtraction::Confirmed {
2212                failures: vec![TerminalFailure {
2213                    suite: None,
2214                    test: "real_test".to_owned(),
2215                }]
2216            }
2217        );
2218    }
2219
2220    #[test]
2221    fn count_mismatch_and_cap_overflow_yield_unknown() {
2222        let mismatch = "\
2223------------
2224     Summary [   1.000s] 2 tests run: 0 passed, 2 failed, 0 skipped
2225        FAIL [   0.500s] pkg::bin only_one
2226";
2227        assert!(matches!(
2228            extract_combined(Some(100), false, mismatch).extraction,
2229            FailureExtraction::Unknown { .. }
2230        ));
2231
2232        let mut many =
2233            "------------\n     Summary [   1.000s] 40 tests run: 0 passed, 40 failed, 0 skipped\n"
2234                .to_owned();
2235        for i in 0..40 {
2236            let _ = writeln!(many, "        FAIL [   0.010s] pkg::bin test_{i}");
2237        }
2238        assert!(matches!(
2239            extract_combined(Some(100), false, &many).extraction,
2240            FailureExtraction::Unknown { .. }
2241        ));
2242    }
2243
2244    #[test]
2245    fn matching_a_to_a_and_multi_binary_libtest() {
2246        let raw = "\
2247Running tests/alpha.rs (target/debug/deps/alpha-1234)
2248running 2 tests
2249test a_ok ... ok
2250test a_fail ... FAILED
2251
2252failures:
2253    a_fail
2254
2255test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
2256
2257Running tests/beta.rs (target/debug/deps/beta-5678)
2258running 1 test
2259test b_fail ... FAILED
2260
2261failures:
2262    b_fail
2263
2264test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
2265";
2266        let o1 = outcome(Some(101), raw, Some("artifacts/e2e-1.out"));
2267        let o2 = outcome(Some(101), raw, Some("artifacts/e2e-2.out"));
2268        let cmp = compare_attempts("abcdef12", &o1, &o2);
2269        assert_eq!(
2270            cmp.verdict,
2271            ComparisonVerdict::Matching {
2272                failures: vec![
2273                    TerminalFailure {
2274                        suite: Some("tests/alpha.rs (alpha-1234)".to_owned()),
2275                        test: "a_fail".to_owned(),
2276                    },
2277                    TerminalFailure {
2278                        suite: Some("tests/beta.rs (beta-5678)".to_owned()),
2279                        test: "b_fail".to_owned(),
2280                    },
2281                ]
2282            }
2283        );
2284        let event = rerun_event_message("round 1", "cargo test", &cmp);
2285        assert!(event.contains("the failure reproduced"), "{event}");
2286    }
2287
2288    #[test]
2289    fn split_cargo_streams_require_unambiguous_binary_identity() {
2290        let raw = "\
2291running 1 test
2292test test_layout ... FAILED
2293
2294failures:
2295    test_layout
2296
2297test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
2298";
2299        let alpha = "Running tests/alpha.rs (target/debug/deps/alpha-1234)\n";
2300        let beta = "Running tests/beta.rs (target/debug/deps/beta-5678)\n";
2301        let make = |stderr: &str| {
2302            let mut o = outcome(Some(101), raw, None);
2303            o.failure_evidence = Some(extract_streams(Some(101), false, raw, stderr));
2304            o
2305        };
2306        let a = make(alpha);
2307        assert!(matches!(
2308            compare_attempts("head", &a, &make(alpha)).verdict,
2309            ComparisonVerdict::Matching { .. }
2310        ));
2311        assert!(matches!(
2312            compare_attempts("head", &a, &make(beta)).verdict,
2313            ComparisonVerdict::Distinct { .. }
2314        ));
2315        let same_label = "Running tests/alpha.rs (target/debug/deps/alpha-9999)\n";
2316        assert!(matches!(
2317            compare_attempts("head", &a, &make(same_label)).verdict,
2318            ComparisonVerdict::Distinct { .. }
2319        ));
2320        let ambiguous = make(&format!("{alpha}{beta}"));
2321        for unknown in [make(""), ambiguous] {
2322            assert!(matches!(
2323                compare_attempts("head", &unknown, &unknown).verdict,
2324                ComparisonVerdict::Unknown { .. }
2325            ));
2326        }
2327    }
2328
2329    #[test]
2330    fn nextest_captured_libtest_failure_is_not_an_independent_run() {
2331        let raw = "\
2332Starting 1 test across 1 binary
2333        FAIL [   0.100s] pkg::bin outer
2334--- STDOUT: pkg::bin outer ---
2335error: nested command failed
2336running 1 test
2337test inner ... FAILED
2338
2339failures:
2340    inner
2341
2342test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
2343------------
2344     Summary [   0.100s] 1 tests run: 0 passed, 1 failed, 0 skipped
2345        FAIL [   0.100s] pkg::bin outer
2346error: test run failed
2347";
2348        assert_eq!(
2349            extract_streams(Some(100), false, "", raw).extraction,
2350            FailureExtraction::Confirmed {
2351                failures: vec![TerminalFailure {
2352                    suite: Some("pkg::bin".to_owned()),
2353                    test: "outer".to_owned(),
2354                }],
2355            }
2356        );
2357    }
2358
2359    #[test]
2360    fn legacy_failed_twice_is_treated_as_unknown() {
2361        let o = CommandOutcome {
2362            command: "cargo make test".to_owned(),
2363            code: Some(1),
2364            output_tail: format!("{LEGACY_FAILED_TWICE_PREFIX}\nsome output"),
2365            duration_ms: 100,
2366            resource_blocked: false,
2367            artifact: None,
2368            failure_evidence: None,
2369            rerun_comparison: None,
2370        };
2371        let summary = outcome_comparison_summary(&o).unwrap();
2372        assert!(summary.contains("comparison unknown"), "{summary}");
2373        assert!(!summary.contains("reproduced"), "{summary}");
2374    }
2375
2376    #[test]
2377    fn nextest_retries_all_three_fail_counts_final_try_as_one_terminal_failure() {
2378        let raw = "\
2379────────────
2380 Nextest run ID 6593990a-423f-41f7-a282-c227e83a40bd with nextest profile: default
2381    Starting 3510 tests across 20 binaries
2382  TRY 1 FAIL [   0.520s] (─────────) magi-cli::daemon_urgent urgent_task_preempts_queue
2383  stdout ───
2384
2385    running 1 test
2386    test urgent_task_preempts_queue ... FAILED
2387
2388    failures:
2389
2390    failures:
2391        urgent_task_preempts_queue
2392
2393    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.51s
2394
2395  stderr ───
2396
2397    thread 'urgent_task_preempts_queue' panicked at tests/daemon_urgent.rs:120:9:
2398    assertion failed
2399
2400  TRY 2 FAIL [   0.480s] (─────────) magi-cli::daemon_urgent urgent_task_preempts_queue
2401  stdout ───
2402
2403    running 1 test
2404    test urgent_task_preempts_queue ... FAILED
2405
2406    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.47s
2407
2408  TRY 3 FAIL [   0.490s] ( 475/3510) magi-cli::daemon_urgent urgent_task_preempts_queue
2409  stdout ───
2410
2411    running 1 test
2412    test urgent_task_preempts_queue ... FAILED
2413
2414    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.48s
2415
2416────────────
2417     Summary [  95.120s] 3510 tests run: 3509 passed, 1 failed, 0 skipped
2418  TRY 3 FAIL [   0.490s] ( 475/3510) magi-cli::daemon_urgent urgent_task_preempts_queue
2419error: test run failed
2420";
2421        let ev = extract_streams(Some(100), false, "", raw);
2422        assert_eq!(
2423            ev.extraction,
2424            FailureExtraction::Confirmed {
2425                failures: vec![TerminalFailure {
2426                    suite: Some("magi-cli::daemon_urgent".to_owned()),
2427                    test: "urgent_task_preempts_queue".to_owned(),
2428                }],
2429            }
2430        );
2431        // Only TRY 1 and TRY 2 are intermediate retries; TRY 3 is the terminal failure
2432        // and must not be double-counted as an intermediate retry.
2433        assert_eq!(ev.intermediate.try_failure_count, 2);
2434        assert_eq!(
2435            ev.intermediate.try_failures,
2436            vec!["magi-cli::daemon_urgent urgent_task_preempts_queue"]
2437        );
2438        assert_eq!(ev.intermediate.flaky_count, 0);
2439
2440        // Non-FAIL terminal retry statuses (TIMEOUT / ABORT / SIGSEGV) and ASCII placeholders.
2441        let other_statuses = "\
2442------------
2443    Starting 3 tests across 1 binary
2444  TRY 1 TIMEOUT [  60.000s] (---------) pkg::suite test_timeout
2445  TRY 2 TIMEOUT [  60.000s] (  1/3) pkg::suite test_timeout
2446  TRY 1 ABORT   [   0.200s] (---------) pkg::suite test_abort
2447  TRY 2 ABORT   [   0.200s] (  2/3) pkg::suite test_abort
2448  TRY 1 SIGSEGV [   0.100s] (---------) pkg::suite test_sigsegv
2449  TRY 2 SIGSEGV [   0.100s] (  3/3) pkg::suite test_sigsegv
2450------------
2451     Summary [ 120.700s] 3 tests run: 0 passed, 3 failed (1 timed out), 0 skipped
2452  TRY 2 TIMEOUT [  60.000s] (  1/3) pkg::suite test_timeout
2453  TRY 2 ABORT   [   0.200s] (  2/3) pkg::suite test_abort
2454  TRY 2 SIGSEGV [   0.100s] (  3/3) pkg::suite test_sigsegv
2455error: test run failed
2456";
2457        let ev_other = extract_combined(Some(100), false, other_statuses);
2458        assert_eq!(
2459            ev_other.extraction,
2460            FailureExtraction::Confirmed {
2461                failures: vec![
2462                    TerminalFailure {
2463                        suite: Some("pkg::suite".to_owned()),
2464                        test: "test_abort".to_owned(),
2465                    },
2466                    TerminalFailure {
2467                        suite: Some("pkg::suite".to_owned()),
2468                        test: "test_sigsegv".to_owned(),
2469                    },
2470                    TerminalFailure {
2471                        suite: Some("pkg::suite".to_owned()),
2472                        test: "test_timeout".to_owned(),
2473                    },
2474                ],
2475            }
2476        );
2477        assert_eq!(ev_other.intermediate.try_failure_count, 3);
2478    }
2479
2480    #[test]
2481    fn nextest_try_1_fail_then_try_2_pass_flaky_has_zero_terminal_failures() {
2482        // Standalone FLAKY test: TRY 1 fails, TRY 2 passes -> 0 terminal failures,
2483        // TRY 2 PASS is not counted as an intermediate TRY failure.
2484        let flaky_only = "\
2485────────────
2486    Starting 1 test across 1 binary
2487  TRY 1 FAIL [   0.040s] (───) magi-cli::web test_flaky
2488  stdout ───
2489
2490    running 1 test
2491    test test_flaky ... FAILED
2492
2493    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
2494
2495  TRY 2 PASS [   0.024s] (1/1) magi-cli::web test_flaky
2496────────────
2497     Summary [   0.080s] 1 test run: 1 passed (1 flaky), 0 skipped
2498   FLAKY 2/3 [   0.024s] (1/1) magi-cli::web test_flaky
2499";
2500        let ev_flaky_ok = extract_combined(Some(0), false, flaky_only);
2501        assert!(matches!(
2502            ev_flaky_ok.extraction,
2503            FailureExtraction::Unknown { .. }
2504        ));
2505        assert_eq!(ev_flaky_ok.intermediate.try_failure_count, 1);
2506        assert_eq!(ev_flaky_ok.intermediate.flaky_count, 1);
2507        assert_eq!(
2508            ev_flaky_ok.intermediate.flaky,
2509            vec!["magi-cli::web test_flaky"]
2510        );
2511
2512        // Even if the outer command exits non-zero (e.g. a subsequent step fails),
2513        // the FLAKY test yields 0 terminal failures.
2514        let ev_flaky_nonzero = extract_combined(Some(100), false, flaky_only);
2515        assert!(matches!(
2516            ev_flaky_nonzero.extraction,
2517            FailureExtraction::Unknown { ref reason }
2518                if reason.contains("without a complete failing test summary")
2519        ));
2520        assert_eq!(ev_flaky_nonzero.intermediate.try_failure_count, 1);
2521        assert_eq!(ev_flaky_nonzero.intermediate.flaky_count, 1);
2522
2523        // When paired with an actual terminal TRY 3 FAIL test, only the terminal test
2524        // appears in Confirmed failures; the FLAKY test contributes 0 terminal failures.
2525        let mixed = "\
2526────────────
2527    Starting 2 tests across 1 binary
2528  TRY 1 FAIL [   0.040s] (───) magi-cli::web test_flaky
2529  TRY 1 FAIL [   0.044s] (───) magi-cli::web test_persistent
2530  TRY 2 PASS [   0.024s] (1/2) magi-cli::web test_flaky
2531  TRY 2 FAIL [   0.027s] (───) magi-cli::web test_persistent
2532  TRY 3 FAIL [   0.024s] (2/2) magi-cli::web test_persistent
2533────────────
2534     Summary [   0.110s] 2 tests run: 1 passed (1 flaky), 1 failed, 0 skipped
2535   FLAKY 2/3 [   0.024s] (1/2) magi-cli::web test_flaky
2536  TRY 3 FAIL [   0.024s] (2/2) magi-cli::web test_persistent
2537error: test run failed
2538";
2539        let ev_mixed = extract_combined(Some(100), false, mixed);
2540        assert_eq!(
2541            ev_mixed.extraction,
2542            FailureExtraction::Confirmed {
2543                failures: vec![TerminalFailure {
2544                    suite: Some("magi-cli::web".to_owned()),
2545                    test: "test_persistent".to_owned(),
2546                }],
2547            }
2548        );
2549        // 1 from test_flaky TRY 1 + 2 from test_persistent TRY 1 and TRY 2.
2550        assert_eq!(ev_mixed.intermediate.try_failure_count, 3);
2551        assert_eq!(ev_mixed.intermediate.flaky_count, 1);
2552    }
2553
2554    #[test]
2555    fn nextest_retries_matching_and_distinct_across_attempts_with_changing_progress() {
2556        let make_nextest = |progress: &str, suite: &str, test: &str| {
2557            format!(
2558                "\
2559────────────
2560    Starting 3510 tests across 20 binaries
2561  TRY 1 FAIL [   0.400s] (─────────) {suite} {test}
2562  TRY 2 FAIL [   0.400s] (─────────) {suite} {test}
2563  TRY 3 FAIL [   0.410s] ({progress}) {suite} {test}
2564────────────
2565     Summary [  80.000s] 3510 tests run: 3509 passed, 1 failed, 0 skipped
2566  TRY 3 FAIL [   0.410s] ({progress}) {suite} {test}
2567error: test run failed
2568"
2569            )
2570        };
2571
2572        let a1 = outcome(
2573            Some(100),
2574            &make_nextest(" 475/3510", "magi-cli::daemon_urgent", "test_urgent"),
2575            Some("artifacts/e2e-1.out"),
2576        );
2577        let a2_same = outcome(
2578            Some(100),
2579            &make_nextest(" 612/3510", "magi-cli::daemon_urgent", "test_urgent"),
2580            Some("artifacts/e2e-2.out"),
2581        );
2582        let a2_diff = outcome(
2583            Some(100),
2584            &make_nextest(" 510/3510", "magi-cli::daemon_urgent", "test_other"),
2585            Some("artifacts/e2e-3.out"),
2586        );
2587
2588        let cmp_match = compare_attempts("deadbeef1234", &a1, &a2_same);
2589        assert_eq!(
2590            cmp_match.verdict,
2591            ComparisonVerdict::Matching {
2592                failures: vec![TerminalFailure {
2593                    suite: Some("magi-cli::daemon_urgent".to_owned()),
2594                    test: "test_urgent".to_owned(),
2595                }],
2596            }
2597        );
2598
2599        let cmp_distinct = compare_attempts("deadbeef1234", &a1, &a2_diff);
2600        assert_eq!(
2601            cmp_distinct.verdict,
2602            ComparisonVerdict::Distinct {
2603                common: vec![],
2604                first_only: vec![TerminalFailure {
2605                    suite: Some("magi-cli::daemon_urgent".to_owned()),
2606                    test: "test_urgent".to_owned(),
2607                }],
2608                second_only: vec![TerminalFailure {
2609                    suite: Some("magi-cli::daemon_urgent".to_owned()),
2610                    test: "test_other".to_owned(),
2611                }],
2612            }
2613        );
2614    }
2615
2616    #[test]
2617    fn nextest_summary_resolves_multiple_try_lines_and_same_test_name_across_suites() {
2618        let raw = "\
2619────────────
2620    Starting 3 tests across 3 binaries
2621  TRY 1 FAIL [   0.200s] (───) pkg::suite_a shared_name
2622  TRY 2 FAIL [   0.200s] (───) pkg::suite_a shared_name
2623  TRY 3 FAIL [   0.200s] (1/3) pkg::suite_a shared_name
2624  TRY 1 FAIL [   0.200s] (───) pkg::suite_b shared_name
2625  TRY 2 PASS [   0.150s] (2/3) pkg::suite_b shared_name
2626  TRY 1 FAIL [   0.200s] (───) pkg::suite_c shared_name
2627  TRY 2 ABORT [  0.200s] (3/3) pkg::suite_c shared_name
2628────────────
2629     Summary [   1.500s] 3 tests run: 1 passed (1 flaky), 2 failed, 0 skipped
2630  TRY 1 FAIL [   0.200s] (───) pkg::suite_a shared_name
2631  TRY 2 FAIL [   0.200s] (───) pkg::suite_a shared_name
2632  TRY 3 FAIL [   0.200s] (1/3) pkg::suite_a shared_name
2633  TRY 1 FAIL [   0.200s] (───) pkg::suite_b shared_name
2634   FLAKY 2/3 [   0.150s] (2/3) pkg::suite_b shared_name
2635  TRY 2 ABORT [  0.200s] (3/3) pkg::suite_c shared_name
2636error: test run failed
2637";
2638        let ev = extract_combined(Some(100), false, raw);
2639        assert_eq!(
2640            ev.extraction,
2641            FailureExtraction::Confirmed {
2642                failures: vec![
2643                    TerminalFailure {
2644                        suite: Some("pkg::suite_a".to_owned()),
2645                        test: "shared_name".to_owned(),
2646                    },
2647                    TerminalFailure {
2648                        suite: Some("pkg::suite_c".to_owned()),
2649                        test: "shared_name".to_owned(),
2650                    },
2651                ],
2652            }
2653        );
2654        // Deduplicated across execution and Summary:
2655        // suite_a: TRY 1, TRY 2 (2); suite_b: TRY 1 (1); suite_c: TRY 1 (1) => 4 total.
2656        assert_eq!(ev.intermediate.try_failure_count, 4);
2657        assert_eq!(ev.intermediate.flaky_count, 1);
2658    }
2659
2660    #[test]
2661    fn nextest_incomplete_placeholder_superseded_or_duplicate_try_yields_unknown() {
2662        let unicode_placeholder_in_summary = "\
2663────────────
2664     Summary [   1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
2665  TRY 1 FAIL [   0.500s] (───) pkg::bin test_a
2666";
2667        assert!(matches!(
2668            extract_combined(Some(100), false, unicode_placeholder_in_summary).extraction,
2669            FailureExtraction::Unknown { .. }
2670        ));
2671
2672        let ascii_placeholder_in_summary = "\
2673------------
2674     Summary [   1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
2675  TRY 1 FAIL [   0.500s] (---) pkg::bin test_a
2676";
2677        assert!(matches!(
2678            extract_combined(Some(100), false, ascii_placeholder_in_summary).extraction,
2679            FailureExtraction::Unknown { .. }
2680        ));
2681
2682        let superseded_by_later_attempt = "\
2683    Starting 1 test across 1 binary
2684  TRY 1 FAIL [   0.500s] pkg::bin test_a
2685  TRY 2 FAIL [   0.500s] pkg::bin test_a
2686────────────
2687     Summary [   1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
2688  TRY 1 FAIL [   0.500s] pkg::bin test_a
2689";
2690        assert!(matches!(
2691            extract_combined(Some(100), false, superseded_by_later_attempt).extraction,
2692            FailureExtraction::Unknown { .. }
2693        ));
2694
2695        let superseded_by_pass = "\
2696    Starting 1 test across 1 binary
2697  TRY 1 FAIL [   0.500s] pkg::bin test_a
2698  TRY 2 PASS [   0.500s] pkg::bin test_a
2699────────────
2700     Summary [   1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
2701  TRY 1 FAIL [   0.500s] pkg::bin test_a
2702";
2703        assert!(matches!(
2704            extract_combined(Some(100), false, superseded_by_pass).extraction,
2705            FailureExtraction::Unknown { .. }
2706        ));
2707
2708        let duplicate_terminal_try = "\
2709────────────
2710     Summary [   1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
2711  TRY 3 FAIL [   0.500s] (1/1) pkg::bin test_a
2712  TRY 3 FAIL [   0.500s] (1/1) pkg::bin test_a
2713";
2714        assert!(matches!(
2715            extract_combined(Some(100), false, duplicate_terminal_try).extraction,
2716            FailureExtraction::Unknown { .. }
2717        ));
2718
2719        let missing_summary = "\
2720    Starting 1 test across 1 binary
2721  TRY 1 FAIL [   0.500s] (───) pkg::bin test_a
2722  TRY 2 FAIL [   0.500s] (───) pkg::bin test_a
2723  TRY 3 FAIL [   0.500s] (1/1) pkg::bin test_a
2724";
2725        assert!(matches!(
2726            extract_combined(Some(100), false, missing_summary).extraction,
2727            FailureExtraction::Unknown { ref reason } if reason.contains("final summary")
2728        ));
2729    }
2730
2731    #[test]
2732    fn nextest_indented_and_unindented_captured_output_cannot_spoof_summary_or_libtest() {
2733        let indented = "\
2734────────────
2735    Starting 1 test across 1 binary
2736  TRY 1 FAIL [   0.044s] (───) magi-cli::suite real_fail
2737  stdout ───
2738
2739    running 1 test
2740    test inner_spoof ... FAILED
2741
2742    failures:
2743        inner_spoof
2744
2745    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
2746    ------------
2747         Summary [   0.010s] 1 test run: 0 passed, 1 failed, 0 skipped
2748            FAIL [   0.010s] fake::bin fake_summary_fail
2749
2750  stderr ───
2751
2752    thread 'real_fail' panicked at src/lib.rs:10:9:
2753    boom
2754
2755  TRY 2 FAIL [   0.030s] (───) magi-cli::suite real_fail
2756  TRY 3 FAIL [   0.030s] (1/1) magi-cli::suite real_fail
2757────────────
2758     Summary [   0.150s] 1 test run: 0 passed, 1 failed, 0 skipped
2759  TRY 3 FAIL [   0.030s] (1/1) magi-cli::suite real_fail
2760error: test run failed
2761";
2762        let ev = extract_streams(Some(100), false, "", indented);
2763        assert_eq!(
2764            ev.extraction,
2765            FailureExtraction::Confirmed {
2766                failures: vec![TerminalFailure {
2767                    suite: Some("magi-cli::suite".to_owned()),
2768                    test: "real_fail".to_owned(),
2769                }],
2770            }
2771        );
2772        assert_eq!(ev.intermediate.try_failure_count, 2);
2773
2774        // `--no-output-indent` (`── stdout ──` / `── stderr ──`) also isolates captured output.
2775        let unindented = "\
2776────────────
2777    Starting 1 test across 1 binary
2778  TRY 1 FAIL [   0.044s] (───) magi-cli::suite real_fail
2779── stdout ──
2780
2781running 1 test
2782test inner_spoof ... FAILED
2783
2784failures:
2785    inner_spoof
2786
2787test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
2788     Summary [   0.010s] 1 test run: 0 passed, 1 failed, 0 skipped
2789        FAIL [   0.010s] fake::bin fake_summary_fail
2790
2791── stderr ──
2792
2793thread 'real_fail' panicked at src/lib.rs:10:9:
2794boom
2795
2796────────────
2797     Summary [   0.150s] 1 test run: 0 passed, 1 failed, 0 skipped
2798  TRY 3 FAIL [   0.030s] (1/1) magi-cli::suite real_fail
2799error: test run failed
2800";
2801        let ev_unindented = extract_streams(Some(100), false, "", unindented);
2802        assert_eq!(
2803            ev_unindented.extraction,
2804            FailureExtraction::Confirmed {
2805                failures: vec![TerminalFailure {
2806                    suite: Some("magi-cli::suite".to_owned()),
2807                    test: "real_fail".to_owned(),
2808                }],
2809            }
2810        );
2811    }
2812}