Skip to main content

magi/
recovery.rs

1//! Carrying an earlier attempt's evidence into the run that takes its branch over.
2//!
3//! A task whose previous run stopped on a failed verification used to reopen
4//! its branch as a context-free review-only run: the new reviewers and fixer
5//! never saw the failing command's output, the review decisions or the
6//! unresolved findings, and round 1 started from scratch.
7//!
8//! [`assess`] is pure. From the earlier run's record and the relation of the
9//! branch tip to the commit that run reviewed it decides between
10//!
11//! * [`Mode::VerifyRepair`]: the earlier panel found nothing blocking and only
12//!   verification failed, on exactly the commit that is about to be reviewed.
13//!   The fixer gets the failure first, then the review is scoped to what
14//!   changed since the reviewed commit.
15//! * [`Mode::FullReview`]: anything doubtful. The reviewers still see the
16//!   earlier context, but nothing is scoped and no approval is carried; each
17//!   [`RecoveryRecord::reasons`] entry says why.
18//!
19//! Inherited verification is evidence for a prompt, never a result: it is not
20//! copied into [`crate::run::ReviewRound`], so verification always runs again
21//! on the commit that is going to land.
22
23use serde::{Deserialize, Serialize};
24
25use crate::run::{CommandOutcome, E2eStatus, ReviewRound, RunState};
26
27/// Restore an interrupted repair and confirm its original commit before any review.
28pub(crate) async fn restore_repair(wt: &std::path::Path, before: &str) -> anyhow::Result<()> {
29    crate::git::restore_to(wt, before).await?;
30    let tip = crate::git::rev_parse(wt, "HEAD").await?;
31    anyhow::ensure!(tip == before, "the winner is at {tip}, not {before}");
32    Ok(())
33}
34
35fn short(sha: &str) -> &str {
36    sha.get(..8).unwrap_or(sha)
37}
38use crate::verdict::{Finding, ReviewVote};
39
40/// How many times evidence may be handed from one run to the next. Past this
41/// the successor starts as a plain full review.
42pub const MAX_GENERATION: u32 = 2;
43
44/// Longest output tail carried into a prompt, in bytes.
45pub const TAIL_MAX: usize = 6_000;
46
47/// Longest scoped diff shown to a reviewer, in bytes.
48pub const SINCE_DIFF_MAX: usize = 60_000;
49
50/// What the review after a takeover does with the earlier run.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "kebab-case")]
53pub enum Mode {
54    /// One repair fix with the failure in hand, then a review scoped to the
55    /// changes since the reviewed commit.
56    VerifyRepair,
57    /// The whole patch is reviewed again; the earlier run is context only.
58    FullReview,
59}
60
61/// Which check failed.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "kebab-case")]
64pub enum Source {
65    /// The round's `verify.e2e`.
66    E2e,
67    /// The final `verify.gate`.
68    Gate,
69}
70
71/// The failed verification the earlier run stopped on.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct Evidence {
74    /// Which check.
75    pub source: Source,
76    /// The command, as configured.
77    pub command: String,
78    /// Exit code, `None` on timeout or signal.
79    pub code: Option<i32>,
80    /// Scrubbed, clipped tail of its output.
81    pub output_tail: String,
82    /// The commit it was run against.
83    pub head: String,
84    /// Saved artifact reference, when recorded.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub artifact: Option<String>,
87    /// Extracted terminal failure set and intermediate notes, when recorded.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub failure_evidence: Option<crate::verify_evidence::FailureEvidence>,
90    /// Structured two-attempt comparison when the command failed twice on the same commit.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub rerun_comparison: Option<crate::verify_evidence::RerunComparison>,
93}
94
95/// One earlier review round, reduced to its decision.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct PriorRound {
98    /// Round number in the earlier run.
99    pub round: usize,
100    /// The commit it reviewed.
101    pub head: String,
102    /// Findings that held the merge.
103    pub blocking: usize,
104    /// Seats that answered, of `expected`.
105    pub answered: usize,
106    /// Seats the round expected.
107    pub expected: usize,
108    /// The round's verdict, when a vote was usable.
109    pub verdict: Option<ReviewVote>,
110}
111
112/// Where the one repair fix stands. Saved before the fixer is called, so a
113/// resume never repairs twice.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(rename_all = "kebab-case")]
116pub enum Repair {
117    /// Not attempted (yet, or not applicable).
118    NotStarted,
119    /// The fixer was called from this commit and has not been settled.
120    Started {
121        /// HEAD before the call.
122        before: String,
123    },
124    /// The seat could not start. Restore under coordination before retrying.
125    WaitingForRestore {
126        /// HEAD before the blocked attempt (or its earlier fallback).
127        before: String,
128    },
129    /// Settled.
130    Done {
131        /// HEAD before the call.
132        before: String,
133        /// HEAD after it.
134        after: String,
135        /// The fixer's own commit or rescue commit moved HEAD.
136        committed: bool,
137        /// Why nothing was kept (the worktree was restored to `before`).
138        failed: Option<String>,
139    },
140}
141
142/// What a run inherited from the attempt it took over, and why.
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct RecoveryRecord {
145    /// The earlier run.
146    pub from_run: String,
147    /// How many hand-overs of evidence lie behind this one.
148    pub generation: u32,
149    /// The decision.
150    pub mode: Mode,
151    /// For [`Mode::FullReview`]: every reason a narrower recovery was not
152    /// justified. Empty for [`Mode::VerifyRepair`].
153    #[serde(default)]
154    pub reasons: Vec<String>,
155    /// The earlier run's last reviewed commit, when it had one.
156    #[serde(default)]
157    pub reviewed_head: Option<String>,
158    /// The earlier rounds' decisions.
159    #[serde(default)]
160    pub rounds: Vec<PriorRound>,
161    /// Findings the last earlier round left open.
162    #[serde(default)]
163    pub open_findings: Vec<Finding>,
164    /// The failed verification, when one was recorded.
165    #[serde(default)]
166    pub evidence: Option<Evidence>,
167    /// The task's own statement replaced the commit-log stand-in.
168    #[serde(default)]
169    pub criteria_inherited: bool,
170    /// The repair fix.
171    #[serde(default = "not_started")]
172    pub repair: Repair,
173}
174
175fn not_started() -> Repair {
176    Repair::NotStarted
177}
178
179/// How the branch tip relates to the commit the earlier run reviewed.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum Relation {
182    /// The same commit.
183    Same,
184    /// The reviewed commit is a proper ancestor: commits were added after it.
185    Descendant,
186    /// Not an ancestor: rebased, rewritten or unknown to this repository.
187    Diverged,
188}
189
190/// Clip `text` to its last `max` bytes on a char boundary.
191pub fn tail_of(text: &str, max: usize) -> String {
192    if text.len() <= max {
193        return text.to_owned();
194    }
195    let mut start = text.len() - max;
196    while !text.is_char_boundary(start) {
197        start += 1;
198    }
199    format!("[...]\n{}", &text[start..])
200}
201
202/// Clip `text` to its first `max` bytes on a char boundary.
203pub fn head_of(text: &str, max: usize) -> String {
204    if text.len() <= max {
205        return text.to_owned();
206    }
207    let mut end = max;
208    while !text.is_char_boundary(end) {
209        end -= 1;
210    }
211    format!("{}\n[... truncated]", &text[..end])
212}
213
214fn evidence_from(round: &ReviewRound, prior: &RunState) -> Option<Evidence> {
215    let scrub = |s: &str| {
216        crate::scrub::scrub(
217            &crate::run::summarize_verify(s, TAIL_MAX),
218            &crate::scrub::Identity::current(),
219        )
220    };
221    let build = |source: Source, o: &CommandOutcome, head: &str| Evidence {
222        source,
223        command: o.command.clone(),
224        code: o.code,
225        output_tail: scrub(&o.output_tail),
226        head: head.to_owned(),
227        artifact: o.artifact.clone(),
228        failure_evidence: o.failure_evidence.clone(),
229        rerun_comparison: o.rerun_comparison.as_ref().map(|c| c.scrubbed(scrub)),
230    };
231    let failed = |o: &&CommandOutcome| !o.ok() && !o.resource_blocked;
232    // Current head / gate-repair e2e takes precedence when present and red on a head;
233    // when it already passed, do not carry an older resolved round failure forward.
234    if let Some(e) = &prior.head_e2e
235        && !e.passed
236        && let Some(o) = e.outcomes.iter().find(failed)
237    {
238        return Some(build(Source::E2e, o, &e.head));
239    }
240    if let Some(e) = &prior.gate_repair_e2e
241        && !e.passed
242        && let Some(o) = e.outcomes.iter().find(failed)
243    {
244        return Some(build(Source::E2e, o, &e.head));
245    }
246    if prior.head_e2e.as_ref().is_none_or(|e| !e.passed)
247        && prior.gate_repair_e2e.as_ref().is_none_or(|e| !e.passed)
248        && round.e2e_status() == E2eStatus::Failed
249        && let (Some(o), Some(head)) = (round.e2e.iter().find(failed), &round.verified_head)
250    {
251        return Some(build(Source::E2e, o, head));
252    }
253    // The gate runs on the tree the last round left; it is only evidence about
254    // that round's head while no gate fix moved the tree afterwards.
255    if prior.gate_ran
256        && prior.gate_fixes.is_empty()
257        && let Some(o) = prior.gate.iter().find(failed)
258    {
259        return Some(build(Source::Gate, o, &round.head));
260    }
261    None
262}
263
264/// The record for a run that takes `prior` over. Pure.
265///
266/// `prior` is `None` when the earlier attempt's record could not be read.
267/// `base_now` is the base commit the new run reviews against and `relation`
268/// how the branch tip stands to the earlier run's last reviewed commit.
269pub fn assess(
270    from_run: &str,
271    prior: Option<&RunState>,
272    base_now: &str,
273    relation: Relation,
274) -> RecoveryRecord {
275    let mut rec = RecoveryRecord {
276        from_run: from_run.to_owned(),
277        generation: 0,
278        mode: Mode::FullReview,
279        reasons: Vec::new(),
280        reviewed_head: None,
281        rounds: Vec::new(),
282        open_findings: Vec::new(),
283        evidence: None,
284        criteria_inherited: false,
285        repair: Repair::NotStarted,
286    };
287    let Some(prior) = prior else {
288        rec.reasons
289            .push("the earlier run's record could not be read".to_owned());
290        return rec;
291    };
292    rec.generation = prior.recovery.as_ref().map_or(0, |r| r.generation) + 1;
293    rec.rounds = prior
294        .reviews
295        .iter()
296        .map(|r| PriorRound {
297            round: r.round,
298            head: r.head.clone(),
299            blocking: r.blocking,
300            answered: r.answered,
301            expected: r.expected,
302            verdict: r.verdict,
303        })
304        .collect();
305    let Some(last) = prior.reviews.last() else {
306        rec.reasons
307            .push("the earlier run never completed a review round".to_owned());
308        return rec;
309    };
310    rec.reviewed_head = Some(last.head.clone());
311    rec.open_findings = last
312        .reviews
313        .iter()
314        .flat_map(|r| r.findings.iter().cloned())
315        .collect();
316    rec.evidence = evidence_from(last, prior);
317
318    if rec.generation > MAX_GENERATION {
319        rec.reasons.push(format!(
320            "evidence has already been handed over {MAX_GENERATION} times"
321        ));
322    }
323    if last.answered < last.expected || last.reviews.iter().any(|r| r.failed.is_some()) {
324        rec.reasons.push(format!(
325            "only {} of {} reviewer seat(s) answered the last round; a panel that did not \
326             answer is not a clean one",
327            last.answered, last.expected
328        ));
329    }
330    if last.blocking > 0 {
331        rec.reasons.push(format!(
332            "the last round still had {} blocking finding(s)",
333            last.blocking
334        ));
335    }
336    match &rec.evidence {
337        None => rec
338            .reasons
339            .push("no failed verification with a known command was recorded".to_owned()),
340        Some(e) if e.output_tail.trim().is_empty() => rec
341            .reasons
342            .push("the failed verification kept no output to act on".to_owned()),
343        Some(e) if e.head != last.head => {
344            let sync = prior.base_sync.as_ref().map_or_else(
345                || "no base sync recorded".to_owned(),
346                |sync| {
347                    format!(
348                        "base sync to {}, {} rebase attempt(s), conflict: {}",
349                        sync.tip,
350                        sync.attempts,
351                        sync.conflict.as_deref().unwrap_or("none")
352                    )
353                },
354            );
355            rec.reasons.push(format!(
356                "the failed verification was about a different commit {} than the one reviewed {}; \
357                 {sync}; additional review is required before approval can carry forward",
358                e.head, last.head,
359            ));
360        }
361        Some(_) => {}
362    }
363    match relation {
364        Relation::Same => {}
365        Relation::Descendant => rec.reasons.push(
366            "commits were added after the reviewed commit; they were never reviewed".to_owned(),
367        ),
368        Relation::Diverged => rec.reasons.push(
369            "the reviewed commit is not an ancestor of the branch: it was rebased or rewritten"
370                .to_owned(),
371        ),
372    }
373    if prior.base_commit != base_now {
374        rec.reasons.push(format!(
375            "the base moved from {} to {}",
376            short(&prior.base_commit),
377            short(base_now)
378        ));
379    }
380    if rec.reasons.is_empty() {
381        rec.mode = Mode::VerifyRepair;
382    }
383    rec
384}
385
386/// Re-check a [`Mode::VerifyRepair`] record against the tree the review is
387/// about to look at (a base sync may have rebased it after the takeover was
388/// assessed). Returns true when it was downgraded. Pure.
389pub fn recheck(rec: &mut RecoveryRecord, head: &str) -> bool {
390    if rec.mode != Mode::VerifyRepair {
391        return false;
392    }
393    let Some(reviewed) = rec.reviewed_head.as_deref() else {
394        return false;
395    };
396    if reviewed == head {
397        return false;
398    }
399    rec.mode = Mode::FullReview;
400    rec.reasons.push(format!(
401        "the branch moved from {} to {} before the review started (rebased onto the base or \
402         changed); the earlier approval does not carry",
403        short(reviewed),
404        short(head)
405    ));
406    true
407}
408
409impl RecoveryRecord {
410    /// One line for the event log, `magi show` and the web.
411    pub fn summary(&self) -> String {
412        let from = crate::run::short_of(&self.from_run);
413        match self.mode {
414            Mode::VerifyRepair => format!(
415                "inherited from run {from}: reviewed commit, {} round(s), failed verification \
416                 `{}`; repair first, then a review scoped to the changes since",
417                self.rounds.len(),
418                self.evidence.as_ref().map_or("?", |e| e.command.as_str())
419            ),
420            Mode::FullReview => format!(
421                "full review after run {from}: {}",
422                if self.reasons.is_empty() {
423                    "no narrower recovery applied".to_owned()
424                } else {
425                    self.reasons.join("; ")
426                }
427            ),
428        }
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435    use crate::run::ReviewRecord;
436    use crate::verdict::Severity;
437
438    fn outcome(code: i32, tail: &str) -> CommandOutcome {
439        CommandOutcome {
440            command: "cargo test".to_owned(),
441            code: Some(code),
442            output_tail: tail.to_owned(),
443            duration_ms: 1,
444            resource_blocked: false,
445            ..Default::default()
446        }
447    }
448
449    fn seat(failed: bool, findings: Vec<Finding>) -> ReviewRecord {
450        ReviewRecord {
451            reviewer: 1,
452            agent: "a".to_owned(),
453            summary: String::new(),
454            findings,
455            vote: Some(ReviewVote::Approve),
456            failed: failed.then(|| "timed out".to_owned()),
457            duration_ms: 0,
458            attempts: 0,
459        }
460    }
461
462    fn round(head: &str, e2e: Vec<CommandOutcome>) -> ReviewRound {
463        ReviewRound {
464            round: 3,
465            head: head.to_owned(),
466            verified_head: Some(head.to_owned()),
467            verified_at: None,
468            reviews: vec![seat(false, Vec::new())],
469            e2e,
470            verify_retried: false,
471            e2e_deferred: false,
472            e2e_defer_reason: None,
473            fix: None,
474            blocking: 0,
475            answered: 1,
476            expected: 1,
477            clean: false,
478            progressed: false,
479            vote_split: false,
480            reconsideration: Vec::new(),
481            verdict: Some(ReviewVote::Approve),
482        }
483    }
484
485    fn prior(round: ReviewRound) -> RunState {
486        let mut s = RunState::new(
487            std::path::PathBuf::from("/tmp/x"),
488            "main".to_owned(),
489            "base1".to_owned(),
490            "task".to_owned(),
491            crate::config::Config::default(),
492        );
493        s.reviews.push(round);
494        s
495    }
496
497    fn failing() -> RunState {
498        prior(round("aaa111", vec![outcome(101, "1 failed: quiet_spawn")]))
499    }
500
501    #[test]
502    fn unchanged_commit_with_a_nonblocking_failed_verification_is_a_verify_repair() {
503        let r = assess("r1", Some(&failing()), "base1", Relation::Same);
504        assert_eq!(r.mode, Mode::VerifyRepair, "{:?}", r.reasons);
505        assert!(r.reasons.is_empty());
506        assert_eq!(r.generation, 1);
507        let e = r.evidence.unwrap();
508        assert_eq!(e.command, "cargo test");
509        assert_eq!(e.head, "aaa111");
510        assert!(e.output_tail.contains("quiet_spawn"));
511    }
512
513    #[test]
514    fn verification_recovery_preserves_panic_before_large_backtrace() {
515        let output = format!(
516            "[full output: artifacts/e2e-1.out]\n---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
517            "  41: 0x1234 - backtrace frame\n".repeat(10000)
518        );
519        let p = prior(round("aaa111", vec![outcome(101, &output)]));
520        let r = assess("r1", Some(&p), "base1", Relation::Same);
521        let prompt = crate::prompt::recovery_fix("repair widget", &r, 2, "en");
522        assert!(prompt.contains("panicked at widget.rs:12"));
523        assert!(prompt.contains("assertion failed: widget missing"));
524        let evidence = r.evidence.unwrap();
525        assert!(evidence.output_tail.len() <= TAIL_MAX);
526        assert!(evidence.output_tail.contains("panicked at widget.rs:12"));
527        assert!(
528            evidence
529                .output_tail
530                .contains("assertion failed: widget missing")
531        );
532        assert!(evidence.output_tail.contains("artifacts/e2e-1.out"));
533    }
534
535    #[test]
536    fn descendant_rebased_and_moved_base_widen_the_review() {
537        let p = failing();
538        let d = assess("r1", Some(&p), "base1", Relation::Descendant);
539        assert_eq!(d.mode, Mode::FullReview);
540        assert!(d.reasons[0].contains("never reviewed"));
541        let x = assess("r1", Some(&p), "base1", Relation::Diverged);
542        assert_eq!(x.mode, Mode::FullReview);
543        assert!(x.reasons[0].contains("rebased"));
544        let b = assess("r1", Some(&p), "base2", Relation::Same);
545        assert_eq!(b.mode, Mode::FullReview);
546        assert!(b.reasons[0].contains("base moved"));
547        // The evidence still travels as context.
548        assert!(b.evidence.is_some());
549    }
550
551    #[test]
552    fn missing_or_empty_evidence_falls_back_to_a_full_review() {
553        let none = prior(round("aaa111", Vec::new()));
554        let r = assess("r1", Some(&none), "base1", Relation::Same);
555        assert_eq!(r.mode, Mode::FullReview);
556        assert!(r.reasons[0].contains("no failed verification"));
557        let empty = prior(round("aaa111", vec![outcome(1, "  \n")]));
558        let r = assess("r1", Some(&empty), "base1", Relation::Same);
559        assert_eq!(r.mode, Mode::FullReview);
560        assert!(r.reasons[0].contains("no output"));
561        let r = assess("r1", None, "base1", Relation::Same);
562        assert_eq!(r.mode, Mode::FullReview);
563        assert!(r.reasons[0].contains("could not be read"));
564    }
565
566    #[test]
567    fn evidence_about_another_commit_is_not_reused() {
568        let mut p = failing();
569        p.reviews[0].verified_head = Some("bbb222".to_owned());
570        let r = assess("r1", Some(&p), "base1", Relation::Same);
571        assert_eq!(r.mode, Mode::FullReview);
572        assert!(r.reasons[0].contains("different commit"));
573    }
574
575    #[test]
576    fn a_timed_out_seat_or_a_blocking_finding_is_never_a_clean_panel() {
577        let mut p = failing();
578        p.reviews[0].answered = 0;
579        p.reviews[0].reviews[0] = seat(true, Vec::new());
580        let r = assess("r1", Some(&p), "base1", Relation::Same);
581        assert_eq!(r.mode, Mode::FullReview);
582        assert!(r.reasons[0].contains("did not answer"));
583
584        let mut p = failing();
585        p.reviews[0].blocking = 1;
586        p.reviews[0].reviews[0].findings = vec![Finding {
587            id: "R3-1-1".to_owned(),
588            severity: Severity::Major,
589            file: None,
590            line: None,
591            title: "t".to_owned(),
592            detail: String::new(),
593        }];
594        let r = assess("r1", Some(&p), "base1", Relation::Same);
595        assert_eq!(r.mode, Mode::FullReview);
596        assert_eq!(r.open_findings.len(), 1);
597    }
598
599    #[test]
600    fn generations_are_bounded() {
601        let mut p = failing();
602        let mut inherited = assess("r0", Some(&failing()), "base1", Relation::Same);
603        inherited.generation = MAX_GENERATION;
604        p.recovery = Some(inherited);
605        let r = assess("r1", Some(&p), "base1", Relation::Same);
606        assert_eq!(r.generation, MAX_GENERATION + 1);
607        assert_eq!(r.mode, Mode::FullReview);
608        assert!(r.reasons[0].contains("handed over"));
609    }
610
611    #[test]
612    fn a_gate_failure_counts_only_while_no_gate_fix_moved_the_tree() {
613        let mut p = prior(round("aaa111", Vec::new()));
614        p.gate_ran = true;
615        p.gate = vec![outcome(2, "gate red")];
616        let r = assess("r1", Some(&p), "base1", Relation::Same);
617        assert_eq!(r.mode, Mode::VerifyRepair);
618        assert_eq!(r.evidence.unwrap().source, Source::Gate);
619        p.gate_fixes.push(crate::run::GateFixRecord {
620            agent: "a".to_owned(),
621            failed: Vec::new(),
622            notes: String::new(),
623            committed: true,
624            error: None,
625        });
626        let r = assess("r1", Some(&p), "base1", Relation::Same);
627        assert_eq!(r.mode, Mode::FullReview);
628    }
629
630    #[test]
631    fn recheck_downgrades_a_moved_branch() {
632        let mut r = assess("r1", Some(&failing()), "base1", Relation::Same);
633        assert!(!recheck(&mut r, "aaa111"));
634        assert_eq!(r.mode, Mode::VerifyRepair);
635        assert!(recheck(&mut r, "ccc333"));
636        assert_eq!(r.mode, Mode::FullReview);
637        assert!(r.reasons[0].contains("moved"));
638    }
639
640    #[test]
641    fn tails_are_clipped_on_char_boundaries() {
642        let s = "あ".repeat(100);
643        assert!(tail_of(&s, 10).len() < 30);
644        assert!(head_of(&s, 10).starts_with('あ'));
645        assert_eq!(tail_of("ok", 10), "ok");
646    }
647
648    #[test]
649    fn recovery_carries_rerun_comparison_and_artifacts_into_fix_prompt() {
650        use crate::verify_evidence::{
651            AttemptEvidence, ComparisonVerdict, FailureExtraction, IntermediateNotes,
652            RerunComparison, TerminalFailure,
653        };
654        let mut o = outcome(100, "nextest isolated_build_cache failure");
655        o.artifact = Some("artifacts/e2e-4.out".to_owned());
656        o.rerun_comparison = Some(RerunComparison {
657            head: "aaa111".to_owned(),
658            first: AttemptEvidence {
659                attempt: 1,
660                code: Some(101),
661                duration_ms: 1000,
662                artifact: Some("artifacts/e2e-3.out".to_owned()),
663                excerpt: "chat unit test failed".to_owned(),
664                extraction: FailureExtraction::Confirmed {
665                    failures: vec![TerminalFailure {
666                        suite: None,
667                        test: "talk::tests::chat_timeout".to_owned(),
668                    }],
669                },
670                intermediate: IntermediateNotes::default(),
671            },
672            second: AttemptEvidence {
673                attempt: 2,
674                code: Some(100),
675                duration_ms: 2000,
676                artifact: Some("artifacts/e2e-4.out".to_owned()),
677                excerpt: "isolated_build_cache failed".to_owned(),
678                extraction: FailureExtraction::Confirmed {
679                    failures: vec![TerminalFailure {
680                        suite: Some("magi-cli::isolated_build_cache".to_owned()),
681                        test: "test_cache".to_owned(),
682                    }],
683                },
684                intermediate: IntermediateNotes::default(),
685            },
686            verdict: ComparisonVerdict::Distinct {
687                common: vec![],
688                first_only: vec![TerminalFailure {
689                    suite: None,
690                    test: "talk::tests::chat_timeout".to_owned(),
691                }],
692                second_only: vec![TerminalFailure {
693                    suite: Some("magi-cli::isolated_build_cache".to_owned()),
694                    test: "test_cache".to_owned(),
695                }],
696            },
697        });
698        let p = prior(round("aaa111", vec![o]));
699        let r = assess("r1", Some(&p), "base1", Relation::Same);
700        assert_eq!(r.mode, Mode::VerifyRepair);
701        let prompt = crate::prompt::recovery_fix("repair", &r, 2, "en");
702        assert!(prompt.contains("distinct terminal failure(s)"), "{prompt}");
703        assert!(prompt.contains("talk::tests::chat_timeout"), "{prompt}");
704        assert!(prompt.contains("isolated_build_cache"), "{prompt}");
705        assert!(prompt.contains("artifacts/e2e-3.out"), "{prompt}");
706        assert!(prompt.contains("artifacts/e2e-4.out"), "{prompt}");
707    }
708}