Skip to main content

magi/
verify_evidence.rs

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