Skip to main content

magi/
report.rs

1//! Terminal rendering.
2//!
3//! A run produces a lot of state; the report exists so the operator can decide
4//! what to do next without opening `run.json`. It leads with the disagreement,
5//! because that is the part that carries information: three judges agreeing
6//! tells you nothing the winner's diff does not.
7//!
8//! Colour is a six-line local implementation rather than a crate. The
9//! alternatives all decide *for* you whether the stream supports colour, which
10//! makes the output untestable — `assert!(text.contains("winner  A"))` fails on
11//! an escape sequence the test never asked for.
12use std::fmt::Write as _;
13use std::sync::atomic::{AtomicBool, Ordering};
14
15use crate::config::{MergeMode, MergeStyle};
16use crate::run::{
17    CommandOutcome, ContinuationOutcome, E2eStatus, GateStatus, JobStatus, Liveness,
18    OperatorFixOutcome, RunState, RunStatus, tail,
19};
20use crate::stats::{RepoStats, Stats};
21use crate::verdict::ReviewVote;
22
23static COLOR: AtomicBool = AtomicBool::new(true);
24
25/// Turn colour on or off for every subsequent render.
26pub fn set_color(on: bool) {
27    COLOR.store(on, Ordering::Relaxed);
28}
29
30fn paint(text: &str, code: &str) -> String {
31    if COLOR.load(Ordering::Relaxed) {
32        format!("\x1b[{code}m{text}\x1b[0m")
33    } else {
34        text.to_owned()
35    }
36}
37
38fn bold(t: &str) -> String {
39    paint(t, "1")
40}
41fn dim(t: &str) -> String {
42    paint(t, "2")
43}
44fn red(t: &str) -> String {
45    paint(t, "31")
46}
47fn green(t: &str) -> String {
48    paint(t, "32")
49}
50fn yellow(t: &str) -> String {
51    paint(t, "33")
52}
53fn cyan(t: &str) -> String {
54    paint(t, "36")
55}
56
57/// Colour for a status word.
58///
59/// `Stalled` is deliberately not green: a run whose judges were taken out by a
60/// rate limit must not look like a healthy `Ready` in a one-line listing.
61///
62/// A `Ready` reached via `[merge] mode = "none"` is a second case that must
63/// not look like a plain `Ready`: that run is done for good, never picked up
64/// by the PR-polling merge watcher or anything else, while an ordinary
65/// `Ready` (a PR closed without merging, an already-concluded re-entry) may
66/// still be a live landing candidate. See [`RunState::unmerged_by_design`].
67fn status_word(state: &RunState) -> String {
68    if state.unmerged_by_design() {
69        return cyan("unmerged (no-op by design)");
70    }
71    let text = state.status.display_label();
72    if state.needs_attention() {
73        return bold(&yellow(&format!("{text} - release needs a human")));
74    }
75    match state.status {
76        RunStatus::Merged => bold(&green(text)),
77        RunStatus::Ready => green(text),
78        RunStatus::Stalled => bold(&yellow(text)),
79        RunStatus::Blocked => yellow(text),
80        RunStatus::Failed => red(text),
81        // Not `Failed`'s red: every candidate agreed, with evidence, that
82        // nothing belongs in this worktree — the opposite of a run that
83        // could not do the work. See `RunStatus::VerifiedNoop`'s own doc.
84        RunStatus::VerifiedNoop => cyan(text),
85        // Muted, not `Blocked`'s yellow: nothing here needs a human's
86        // attention any more, a later attempt already settled the task.
87        RunStatus::Superseded => dim(text),
88        // Neither green nor red: this run landed nothing, and nothing is
89        // wrong - the change reached the base by another route.
90        RunStatus::AlreadyInBase => dim(text),
91        _ => cyan(text),
92    }
93}
94
95/// Colour for a reviewer vote — the same scale a finding's severity gets:
96/// green for no reservations, yellow for proceed-but-look-at-this, red for a
97/// vote that says stop.
98fn vote_tag(vote: ReviewVote) -> String {
99    let text = vote.label();
100    match vote {
101        ReviewVote::Approve => green(text),
102        ReviewVote::ApproveWithFindings => yellow(text),
103        ReviewVote::Reject => red(text),
104    }
105}
106
107/// One-line summary, for `magi list`.
108pub fn line(state: &RunState) -> String {
109    line_with_liveness(state, Liveness::Unknown)
110}
111
112/// [`line`] with the independent process-liveness observation available to
113/// `magi list`.
114pub fn line_with_liveness(state: &RunState, live: Liveness) -> String {
115    let winner = state
116        .tally
117        .as_ref()
118        .map_or("-".to_owned(), |t| t.winner.to_string());
119    let agent = state.winner().map_or("-", |c| c.agent.as_str());
120    // A below-quorum verdict carries an explicit stamp so a row in a listing
121    // reads "stalled" and "2/3 judges" without opening the report.
122    let quorum = match state.tally.as_ref() {
123        Some(t) if !t.met_quorum => format!(
124            "  {}",
125            bold(&red(&format!("quorum {}/{}", t.present, t.judges)))
126        ),
127        Some(t) if t.present > 0 && t.present < t.judges => format!(
128            "  {}",
129            yellow(&format!("judges {}/{}", t.present, t.judges))
130        ),
131        _ => String::new(),
132    };
133    let stale = if !state.status.done() && live == Liveness::Dead {
134        format!(
135            "  {}",
136            bold(&yellow("STALE — driver exited; resume required"))
137        )
138    } else {
139        String::new()
140    };
141    // The full unknown wording is for `magi show`; a row only needs to say
142    // there is no record.
143    let origin = state
144        .origin
145        .as_ref()
146        .map_or("origin unknown".to_owned(), crate::run::Origin::label);
147    format!(
148        "{}  {:<20}  {:>2}c {:>2}j  win {} ({}){quorum}{stale}  {}  {}",
149        dim(&state.id),
150        status_word(state),
151        state.candidates.len(),
152        state.judgements.len(),
153        winner,
154        agent,
155        dim(&format!("[{origin}]")),
156        first_line(&state.instruction)
157    )
158}
159
160/// A plainly visible verdict for a non-terminal run whose recorded driver is
161/// gone. Kept separate from [`active_seats`] because a process can die at a
162/// node boundary with no active seat left in the saved state.
163pub fn liveness_notice(state: &RunState, live: Liveness) -> String {
164    if !state.status.done() && live == Liveness::Dead {
165        format!(
166            "{}\n\n",
167            yellow("STALE — the process driving this run exited; resume it to continue.")
168        )
169    } else {
170        String::new()
171    }
172}
173
174/// A plainly visible note for a run a later attempt at the same task already
175/// replaced — the terminal counterpart of the web UI's "Superseded by …"
176/// line. `later` is the short id of that later attempt, or `None` when this
177/// run is not superseded at all (the common case).
178///
179/// Kept as its own function, concatenated by the caller, rather than an
180/// argument threaded through [`run`] itself: `run` is called from `bump.rs`,
181/// `tui.rs` and every `magi show`/`magi list` path with no notion of "what
182/// replaced this", and adding a parameter there would mean guessing `None`
183/// at every one of those call sites instead of only at the one that knows.
184pub fn superseded_notice(later: Option<&str>) -> String {
185    match later {
186        Some(later) => format!(
187            "{}\n\n",
188            yellow(&format!(
189                "SUPERSEDED — a later attempt at this task ({later}) replaced it; this record \
190                 is kept but is not the one to act on."
191            ))
192        ),
193        None => String::new(),
194    }
195}
196
197fn first_line(text: &str) -> String {
198    let line = text.lines().next().unwrap_or_default();
199    if line.chars().count() > 68 {
200        format!("{}…", line.chars().take(67).collect::<String>())
201    } else {
202        line.to_owned()
203    }
204}
205
206fn short(commit: &str) -> String {
207    commit.chars().take(7).collect()
208}
209
210/// A short badge for a [`crate::run::ContinuationRecord`], distinguishing
211/// "the seat's own report needed to be resumed" from "there was nothing to
212/// address" — a fixer that has never needed this stays silent here, exactly
213/// as a record predating the feature (`continuation: None`) does too.
214fn continuation_note(c: &crate::run::ContinuationRecord) -> String {
215    match c.outcome {
216        ContinuationOutcome::NotNeeded => String::new(),
217        ContinuationOutcome::Resumed => format!(" [resumed x{}]", c.attempts),
218        ContinuationOutcome::Exhausted => format!(" [continuation exhausted x{}]", c.attempts),
219        ContinuationOutcome::QuotaLost => " [continuation: quota]".to_owned(),
220        ContinuationOutcome::NoSession => " [no session to resume]".to_owned(),
221    }
222}
223
224/// Commands seats' own CLIs reported running, across every node — see
225/// [`crate::run::JobRecord`]. Read-only: renders whatever `run.json` already
226/// holds, does not query anything live and does not spawn an agent.
227///
228/// A CLI this crate has no adapter for (every backend but Codex, as of this
229/// writing) never appears here at all — silence is "no evidence", not "no
230/// jobs ran", which the trailing coverage line exists to say once rather
231/// than per seat.
232///
233/// There is deliberately no "running" state anywhere in this. A command a
234/// CLI never reported finishing has no way to be told apart from one that
235/// never started at all: the CLI that would report it has, by construction,
236/// already stopped talking (killed by a timeout, or a park) by the time that
237/// question matters, so no event — real or guessed at — could ever answer
238/// it. Guessing at an unconfirmed event shape to manufacture a "running"
239/// entry is exactly the fabrication this feature must not do; recording that
240/// limit instead is what the task asks for here. `magi show`'s own
241/// seat-completion state ([`active_seats`]) still answers a related but
242/// different question honestly — "has this seat's own turn answered yet" —
243/// and stays the right place to look for that.
244fn jobs_section(state: &RunState) -> String {
245    let mut s = String::new();
246    if state.jobs.is_empty() {
247        // Not silent when it would matter: a run whose roster can actually
248        // report this (Codex, today) but has not yet says so explicitly, so
249        // "no adapter for this backend" and "nothing reported yet" are never
250        // the same blank space to a reader.
251        if state
252            .config
253            .agents
254            .iter()
255            .any(|a| a.kind == crate::config::AgentKind::Codex)
256        {
257            let _ = writeln!(
258                s,
259                "\n{}",
260                dim(
261                    "background jobs: no completed command evidence yet for this run (see \
262                     active seats above for what is still mid-turn)"
263                )
264            );
265        }
266        return s;
267    }
268    let _ = writeln!(
269        s,
270        "\n{}",
271        bold("background jobs (from each seat's own CLI)")
272    );
273    let mut by_seat: std::collections::BTreeMap<(&str, &str), Vec<&crate::run::JobRecord>> =
274        std::collections::BTreeMap::new();
275    for j in &state.jobs {
276        by_seat
277            .entry((j.node.as_str(), j.seat.as_str()))
278            .or_default()
279            .push(j);
280    }
281    for ((node, seat), records) in by_seat {
282        let _ = writeln!(s, "  {node}/{seat}");
283        for j in records {
284            let status = match j.status {
285                JobStatus::Completed => green("completed"),
286                JobStatus::Failed => red("failed"),
287                JobStatus::Unknown => yellow("unknown"),
288            };
289            let _ = writeln!(
290                s,
291                "    {} {}{}{}  checked {}",
292                dim(&j.id),
293                status,
294                j.exit_code
295                    .map_or(String::new(), |c| format!(" (exit {c})")),
296                j.round.map_or(String::new(), |r| format!("  round {r}")),
297                j.checked_at
298                    .to_zoned(jiff::tz::TimeZone::system())
299                    .strftime("%Y-%m-%d %H:%M:%S")
300            );
301            let desc = first_line(&j.description);
302            if !desc.trim().is_empty() {
303                let _ = writeln!(s, "      $ {desc}");
304            }
305            let summary = first_line(&j.result_summary);
306            if !summary.trim().is_empty() {
307                let _ = writeln!(s, "      {}", dim(&summary));
308            }
309        }
310    }
311    let _ = writeln!(
312        s,
313        "  {}",
314        dim(
315            "(adapter coverage: codex only today; other backends, and a command a CLI never \
316             reported finishing, leave no entry here — that is unknown, never \"nothing ran\")"
317        )
318    );
319    s
320}
321
322/// Full report for one run.
323pub fn run(state: &RunState) -> String {
324    let mut s = String::new();
325    let _ = writeln!(
326        s,
327        "{} {}  {}",
328        bold("magi run"),
329        bold(&state.id),
330        status_word(state)
331    );
332    let _ = writeln!(
333        s,
334        "  repo    {} ({} @ {})",
335        state.repo.display(),
336        state.base_branch,
337        short(&state.base_commit)
338    );
339    let _ = writeln!(s, "  created {}", state.created_local());
340    let _ = writeln!(s, "  task    {}", first_line(&state.instruction));
341    let _ = writeln!(
342        s,
343        "  origin  {}",
344        crate::run::origin_label(state.origin.as_ref())
345    );
346    let _ = writeln!(s, "  state   {}", state.dir().display());
347
348    let _ = writeln!(s, "\n{}", bold("candidates"));
349    for c in &state.candidates {
350        let flag = match (&c.failed, c.empty, &c.verified_noop) {
351            (Some(e), _, _) => red(&format!("failed: {e}")),
352            // Neither red (nothing failed) nor plain yellow "no change" (that
353            // reads as an unexplained loss): the candidate gave a reason a
354            // human still has to check, not a claim magi itself confirmed.
355            (None, true, Some(_)) => cyan("agent-verified no-op (unconfirmed)"),
356            (None, true, None) => yellow("no change"),
357            _ => format!("{} files, {} commits", c.files, c.commits),
358        };
359        let crown = if state.tally.as_ref().is_some_and(|t| t.winner == c.label) {
360            bold(&green("  <- winner"))
361        } else {
362            String::new()
363        };
364        let _ = writeln!(
365            s,
366            "  {}  {:<12} {:<30} {:>5}s{}",
367            bold(&c.label.to_string()),
368            c.agent,
369            flag,
370            c.duration_ms / 1000,
371            crown
372        );
373        if let Some(evidence) = &c.verified_noop {
374            let _ = writeln!(s, "      {}", dim(&first_line(evidence)));
375        } else if !c.summary.trim().is_empty() {
376            // The candidate's own account of what it did and why — the
377            // "## SUMMARY" `prompt::implement` asks for — was recorded on
378            // every run but never surfaced here, which left `magi show`
379            // silent about it even when the summary was the whole point (an
380            // implementer explaining *why* it wrote nothing, short of a
381            // verified no-op's own line above). One line, matching the
382            // house style other prose fields get in this report (see the
383            // review findings' `detail` below); the rest is in `run.json`.
384            let _ = writeln!(s, "      {}", dim(&first_line(&c.summary)));
385        }
386    }
387
388    if !state.judgements.is_empty() {
389        let _ = writeln!(s, "\n{}", bold("blind judging"));
390        for j in &state.judgements {
391            match &j.failed {
392                Some(e) => {
393                    let _ = writeln!(
394                        s,
395                        "  judge {}  {}",
396                        j.judge,
397                        red(&format!("no ranking: {e}"))
398                    );
399                }
400                None => {
401                    let _ = writeln!(
402                        s,
403                        "  judge {}  {:<12} {}  confidence {}",
404                        j.judge,
405                        j.agent,
406                        bold(&j.ranking.iter().collect::<String>()),
407                        j.confidence.map_or("-".to_owned(), |c| c.to_string())
408                    );
409                }
410            }
411        }
412    }
413
414    if let Some(t) = &state.tally {
415        if t.deliberated {
416            let _ = writeln!(s, "\n{}", bold("deliberation"));
417            for round in &state.deliberation {
418                for turn in &round.turns {
419                    let _ = writeln!(
420                        s,
421                        "  r{} judge {} -> {}",
422                        round.round,
423                        turn.judge,
424                        turn.tentative.map_or("-".to_owned(), |c| c.to_string())
425                    );
426                }
427            }
428        }
429
430        if !state.votes.is_empty() {
431            let _ = writeln!(s, "\n{}", bold("final votes (collected privately)"));
432            for v in &state.votes {
433                let _ = writeln!(
434                    s,
435                    "  judge {}  {:<12} {}{}",
436                    v.judge,
437                    v.agent,
438                    bold(&v.vote.unwrap_or('?').to_string()),
439                    if v.changed {
440                        yellow("  (changed after deliberation)")
441                    } else {
442                        String::new()
443                    }
444                );
445            }
446        }
447
448        let _ = writeln!(s, "\n{}", bold("tally"));
449        // A tally with no panel (`uncontested`) must not fall through the
450        // judges/first-choice/after-votes lines below: they are written
451        // unconditionally and every one of them reads, in the words a panel
452        // that collapsed would also produce, as a run that lost its judges
453        // rather than one that never needed them.
454        match &t.uncontested {
455            Some(reason) => {
456                let _ = writeln!(
457                    s,
458                    "  judging       {}",
459                    cyan(&format!("not needed — {reason}"))
460                );
461            }
462            None => {
463                let _ = writeln!(
464                    s,
465                    "  judges        {} present{}",
466                    if t.met_quorum {
467                        green(&format!("{}/{}", t.present, t.judges))
468                    } else {
469                        red(&format!("{}/{}", t.present, t.judges))
470                    },
471                    if t.quorum > 0 {
472                        format!(" ({quorum} required)", quorum = t.quorum)
473                    } else {
474                        String::new()
475                    }
476                );
477                if !t.met_quorum {
478                    let _ = writeln!(
479                        s,
480                        "  {}",
481                        bold(&red("BELOW QUORUM — verdict is not trustworthy"))
482                    );
483                }
484                let _ = writeln!(
485                    s,
486                    "  first choice  {}",
487                    t.first_choice
488                        .iter()
489                        .map(|(k, v)| format!("{k}:{v}"))
490                        .collect::<Vec<_>>()
491                        .join("  ")
492                );
493                let _ = writeln!(
494                    s,
495                    "  initial       {}",
496                    match (t.rankings, t.unanimous_initial) {
497                        (0, _) => red("no usable ranking"),
498                        (1, _) => yellow("one usable ranking - not a consensus"),
499                        (_, true) => green("unanimous"),
500                        (_, false) => yellow("split"),
501                    }
502                );
503                let _ = writeln!(
504                    s,
505                    "  after votes   {}  ({} judge(s) moved)",
506                    if t.unanimous_final {
507                        green("unanimous")
508                    } else {
509                        yellow("still split")
510                    },
511                    t.changed_votes
512                );
513                if let Some(tb) = &t.tie_break {
514                    let _ = writeln!(s, "  tie break     {tb}");
515                }
516            }
517        }
518        if !state.quota.is_empty() {
519            let _ = writeln!(
520                s,
521                "  rate limited  {}",
522                state
523                    .quota
524                    .iter()
525                    .map(|q| q.seat.as_str())
526                    .collect::<Vec<_>>()
527                    .join(", ")
528            );
529        }
530        let _ = writeln!(s, "  winner        {}", bold(&green(&t.winner.to_string())));
531    }
532
533    if !state.handovers.is_empty() {
534        let _ = writeln!(s, "\n{}", bold("seats handed over"));
535        for h in &state.handovers {
536            let _ = writeln!(
537                s,
538                "  {} {}  {} -> {}  ({}: {})",
539                yellow("~"),
540                h.seat,
541                h.from,
542                h.to,
543                h.node,
544                h.reason
545            );
546        }
547    }
548
549    if !state.withheld.is_empty() {
550        let _ = writeln!(s, "\n{}", bold("withheld from commit"));
551        for w in &state.withheld {
552            let _ = writeln!(
553                s,
554                "  {} {}  ({} lockfile; the directory uses {})",
555                yellow("!"),
556                w.path,
557                w.manager,
558                w.kept_by
559            );
560        }
561    }
562
563    if let Some(r) = &state.recovery {
564        let _ = writeln!(s, "\n{}", bold("recovery"));
565        let _ = writeln!(s, "  {}", r.summary());
566        if r.criteria_inherited {
567            let _ = writeln!(s, "  the task's own completion criteria were kept");
568        }
569        match &r.repair {
570            crate::recovery::Repair::NotStarted => {}
571            crate::recovery::Repair::WaitingForRestore { .. } => {
572                let _ = writeln!(s, "  repair: waiting to restore and retry");
573            }
574            crate::recovery::Repair::Started { .. } => {
575                let _ = writeln!(s, "  repair: {}", yellow("unfinished"));
576            }
577            crate::recovery::Repair::Done {
578                committed, failed, ..
579            } => {
580                let _ = match failed {
581                    Some(why) => writeln!(s, "  repair: {} {why}", yellow("nothing kept:")),
582                    None if *committed => writeln!(s, "  repair: {}", green("committed")),
583                    None => writeln!(s, "  repair: no commit"),
584                };
585            }
586        }
587    }
588
589    if let Some(g) = &state.graft {
590        let _ = writeln!(s, "\n{}", bold("graft"));
591        let size = match (g.lines, g.limit) {
592            (Some(l), Some(m)) => format!("  {l} changed lines (limit {m})"),
593            (None, Some(m)) => format!("  limit {m} changed lines"),
594            _ => String::new(),
595        };
596        let _ = match &g.outcome {
597            crate::run::GraftOutcome::Applied => writeln!(s, "  {}{size}", green("applied")),
598            crate::run::GraftOutcome::WaitingForRestore => {
599                writeln!(s, "  {}{size}", yellow("waiting to restore and retry"))
600            }
601            crate::run::GraftOutcome::Running => writeln!(s, "  {}{size}", yellow("unfinished")),
602            crate::run::GraftOutcome::RolledBack(why) => {
603                writeln!(s, "  {} {why}{size}", yellow("rolled back:"))
604            }
605        };
606        if let Some(a) = &g.agent {
607            let chain: Vec<String> = state
608                .handovers
609                .iter()
610                .filter(|h| h.node == "graft")
611                .map(|h| format!("{} -> {}", h.from, h.to))
612                .collect();
613            let via = if chain.is_empty() {
614                String::new()
615            } else {
616                format!("  (handovers: {})", chain.join(", "))
617            };
618            let _ = writeln!(s, "  by {a}{via}");
619        }
620        if !g.requested.is_empty() {
621            let view = crate::report_view::build(state, Liveness::Unknown);
622            if let Some(crate::report_view::Section::Graft { graft, .. }) = view
623                .sections
624                .iter()
625                .find(|x| matches!(x, crate::report_view::Section::Graft { .. }))
626            {
627                let _ = writeln!(
628                    s,
629                    "  requested {}  confirmed adopted {}  rejected {}  unconfirmed {}",
630                    graft.requested.len(),
631                    graft.adopted_count,
632                    graft.rejected_count,
633                    graft.unconfirmed_count
634                );
635            }
636        }
637        if let Some(n) = g
638            .adoption
639            .as_ref()
640            .and_then(|a| a.notes.lines().find(|l| !l.trim().is_empty()))
641        {
642            let _ = writeln!(s, "  fixer notes: {}", n.trim());
643        }
644    }
645
646    if !state.reviews.is_empty() {
647        let _ = writeln!(s, "\n{}", bold("review + verification"));
648        for r in &state.reviews {
649            let raised: usize = r.reviews.iter().map(|x| x.findings.len()).sum();
650            // A build/link failure is not a verdict on the patch (a shared
651            // `CARGO_TARGET_DIR` link race looks exactly like one), so it
652            // must not read the same as a real test failure. And a deferred
653            // round is not a passed one: `e2e.is_empty()` alone cannot tell
654            // "not configured" from "skipped on purpose" apart, which is
655            // exactly why `e2e_status` exists rather than reading `e2e`
656            // directly here.
657            let e2e = match r.e2e_status() {
658                E2eStatus::NotConfigured => dim("no e2e"),
659                E2eStatus::Deferred => yellow(&format!(
660                    "e2e deferred{}",
661                    r.e2e_defer_reason
662                        .as_deref()
663                        .map(|why| format!(" ({why})"))
664                        .unwrap_or_default()
665                )),
666                E2eStatus::Passed => green("e2e green"),
667                E2eStatus::Failed if r.e2e.iter().any(CommandOutcome::build_failed) => {
668                    yellow("e2e could not run (build/link failure)")
669                }
670                E2eStatus::Failed => red("e2e RED"),
671                // Magi's own admission it could not get a command to run —
672                // never the same yellow/red a real attempt earns, since
673                // nothing here is evidence about the patch (see
674                // `E2eStatus::ResourceBlocked`'s own doc).
675                E2eStatus::ResourceBlocked => {
676                    yellow("e2e could not run (shared build cache unavailable)")
677                }
678            };
679            let e2e = if r.verify_retried {
680                format!("{e2e}, retried once")
681            } else {
682                e2e
683            };
684            // Three distinct facts, not two: a round can be *open* (blocking
685            // findings still standing), *incomplete* (a seat never answered,
686            // so what the round says is missing input) or genuinely clean.
687            let status = if r.incomplete() {
688                yellow("incomplete")
689            } else if r.clean {
690                green("clean")
691            } else {
692                yellow("open")
693            };
694            // A missing seat must stay visible even when `warn` policy let
695            // the round gate as clean: the reader should never have to take
696            // "clean" on faith when the panel wasn't full.
697            let panel = if r.incomplete() {
698                let missing: Vec<String> = r
699                    .reviews
700                    .iter()
701                    .filter_map(|x| {
702                        x.failed
703                            .as_ref()
704                            .map(|why| format!("review-{}: {why}", x.reviewer))
705                    })
706                    .collect();
707                format!(
708                    "  {}/{} reviewers answered ({})",
709                    r.answered,
710                    r.expected,
711                    missing.join(", ")
712                )
713            } else {
714                String::new()
715            };
716            // The verdict is the one thing this loop cannot derive from
717            // `blocking`/`e2e` alone: three seats can agree there is nothing
718            // blocking and still split on whether the patch is fine to
719            // proceed as-is, which is exactly the disagreement a vote exists
720            // to surface.
721            let verdict = r.verdict.map_or(String::new(), |v| {
722                format!(
723                    ", verdict {}{}",
724                    vote_tag(v),
725                    if r.vote_split { " (panel split)" } else { "" }
726                )
727            });
728            let _ = writeln!(
729                s,
730                "  round {}  {} @ {}{}{panel}  {raised} finding(s), {} blocking, {e2e}{verdict}{}",
731                r.round,
732                status,
733                short(&r.head),
734                r.verified_head.as_ref().map_or(String::new(), |head| {
735                    format!(
736                        " (verified @ {}{})",
737                        short(head),
738                        r.verified_at.map_or(String::new(), |t| format!(
739                            " on {}",
740                            t.to_zoned(jiff::tz::TimeZone::system())
741                                .strftime("%Y-%m-%d %H:%M:%S")
742                        ))
743                    )
744                }),
745                r.blocking,
746                r.fix.as_ref().map_or(String::new(), |f| {
747                    let tree = if r.progressed {
748                        green("changed")
749                    } else {
750                        yellow("unchanged")
751                    };
752                    let cont = f
753                        .continuation
754                        .as_ref()
755                        .map_or(String::new(), continuation_note);
756                    match &f.failed {
757                        // Never the same shape as "N addressed / M rejected": the
758                        // fixer's diff may well have landed (see the `fix` node's
759                        // own event), but whether it addressed anything is
760                        // unknown, not zero.
761                        Some(reason) => format!(
762                            "  fix: {}, tree {tree}{}{cont}",
763                            yellow(&format!("adoption report lost ({reason})")),
764                            if f.committed {
765                                String::new()
766                            } else {
767                                red(" (NO COMMIT)")
768                            }
769                        ),
770                        None => format!(
771                            "  fix: {} addressed / {} rejected, tree {tree}{}{cont}",
772                            f.addressed.len(),
773                            f.rejected.len(),
774                            if f.committed {
775                                String::new()
776                            } else {
777                                red(" (NO COMMIT)")
778                            }
779                        ),
780                    }
781                })
782            );
783            // The aggregate label above (`e2e`) says the round's overall
784            // verdict; it never named the commands themselves, so a round
785            // with more than one `verify.e2e` command left no way to tell
786            // which one actually failed or was blocked without opening
787            // `run.json` by hand — the same gap `gate`'s own per-command
788            // listing above already closes for the final gate.
789            for o in &r.e2e {
790                let label = if o.resource_blocked {
791                    yellow("blocked")
792                } else if o.ok() {
793                    green("pass")
794                } else {
795                    red("FAIL")
796                };
797                let _ = writeln!(s, "    {label}  {}", o.command);
798                if !o.ok() {
799                    let _ = writeln!(s, "{}", dim(&tail(&o.output_tail, 2_000)));
800                }
801            }
802            for rec in &r.reviews {
803                if let Some(vote) = rec.vote {
804                    let _ = writeln!(s, "      review-{} vote {}", rec.reviewer, vote_tag(vote));
805                }
806                for f in &rec.findings {
807                    let adopted = r
808                        .fix
809                        .as_ref()
810                        .is_some_and(|fix| fix.addressed.contains(&f.id));
811                    let _ = writeln!(
812                        s,
813                        "      {} [{:?}] {}{}",
814                        dim(&f.id),
815                        f.severity,
816                        f.title,
817                        if adopted {
818                            green("  fixed")
819                        } else {
820                            String::new()
821                        }
822                    );
823                }
824            }
825            if let Some(fix) = &r.fix {
826                for rej in &fix.rejected {
827                    let _ = writeln!(
828                        s,
829                        "      {} {}: {}",
830                        dim(&rej.id),
831                        yellow("declined"),
832                        rej.why
833                    );
834                }
835            }
836            // Reconsideration only ever has entries when the round's initial
837            // votes split — an empty list here means the panel agreed the
838            // first time, same as an empty `deliberation` for judges.
839            if !r.reconsideration.is_empty() {
840                let _ = writeln!(s, "      {}", dim("reconsideration:"));
841                for rv in &r.reconsideration {
842                    match rv.vote {
843                        Some(v) => {
844                            let _ = writeln!(
845                                s,
846                                "        review-{} -> {}  {}",
847                                rv.reviewer,
848                                vote_tag(v),
849                                rv.reason
850                            );
851                        }
852                        None => {
853                            let _ = writeln!(
854                                s,
855                                "        review-{} -> {}",
856                                rv.reviewer,
857                                red(&format!(
858                                    "no revote ({})",
859                                    rv.failed.as_deref().unwrap_or("unknown")
860                                ))
861                            );
862                        }
863                    }
864                }
865            }
866        }
867        if state.handed_off_with_open_findings() {
868            let _ = writeln!(
869                s,
870                "\n  {}",
871                yellow(&format!(
872                    "handed off with {} finding(s) still open — gate and e2e were green; \
873                     see above for what a person should still look at",
874                    state.open_findings().len()
875                ))
876            );
877        }
878    }
879
880    if !state.merge_repairs.is_empty() {
881        let _ = writeln!(s, "\n{}", bold("merge-gate repairs"));
882        for r in &state.merge_repairs {
883            let _ = writeln!(
884                s,
885                "  question {}  head {}  {:?}\n  {}",
886                r.question,
887                crate::run::short_of(&r.head),
888                r.phase,
889                r.pr
890            );
891            if let Some(why) = &r.failure {
892                let _ = writeln!(s, "  held: {why}");
893            }
894            if let Some(round) = r.reviews.last() {
895                for f in round.reviews.iter().flat_map(|rec| &rec.findings) {
896                    let _ = writeln!(s, "  original [{}] {:?}: {}", f.id, f.severity, f.title);
897                }
898                for (seat, _, vote) in round.final_votes() {
899                    let _ = writeln!(s, "  original reviewer #{seat}: {:?}", vote);
900                }
901            }
902        }
903        s.push_str(
904            "  Repair never approves a merge; updated results require a fresh owner decision.\n",
905        );
906    }
907
908    if !state.operator_fixes.is_empty() {
909        let _ = writeln!(s, "\n{}", bold("operator fix(es)"));
910        for (i, req) in state.operator_fixes.iter().enumerate() {
911            let _ = writeln!(
912                s,
913                "  [{}] {} finding(s) at {}{}",
914                i + 1,
915                req.findings.len(),
916                req.requested_at
917                    .to_zoned(jiff::tz::TimeZone::system())
918                    .strftime("%Y-%m-%d %H:%M:%S"),
919                if req.stale {
920                    yellow("  stale head, --allow-stale used")
921                } else {
922                    String::new()
923                }
924            );
925            let _ = writeln!(s, "      reason: {}", req.reason);
926            for f in &req.findings {
927                let outcome = match &f.outcome {
928                    OperatorFixOutcome::Pending => yellow("pending"),
929                    OperatorFixOutcome::Addressed => green("addressed"),
930                    OperatorFixOutcome::Rejected { why } => red(&format!("rejected: {why}")),
931                    OperatorFixOutcome::Unreported => {
932                        red("unreported — no adoption report came back")
933                    }
934                };
935                let _ = writeln!(
936                    s,
937                    "      {} [{:?}] {}  {outcome}",
938                    dim(&f.id),
939                    f.severity,
940                    f.title
941                );
942            }
943            match &req.follow_up_review_run {
944                Some(id) => {
945                    let _ = writeln!(s, "      re-verified by run {id}");
946                }
947                None if req.fix.as_ref().is_some_and(|fx| fx.committed) => {
948                    let _ = writeln!(
949                        s,
950                        "      {}",
951                        red("committed, but the follow-up review could not be opened")
952                    );
953                }
954                None => {
955                    let _ = writeln!(s, "      no change committed; nothing to re-verify");
956                }
957            }
958        }
959    }
960
961    if let Some(bs) = &state.base_sync {
962        let _ = writeln!(s, "\n{}", bold("base sync"));
963        let status = if let Some(a) = &bs.already_in {
964            dim(&format!(
965                "already in {} as {} ({} match) - nothing left to land",
966                state.base_branch,
967                a.names(),
968                a.proof.as_str()
969            ))
970        } else if let Some(c) = &bs.conflict {
971            red(&format!("conflict: {}", first_line(c)))
972        } else if bs.behind == 0 {
973            green("in sync")
974        } else {
975            yellow(&format!("{} commit(s) behind, not yet rebased", bs.behind))
976        };
977        let _ = writeln!(
978            s,
979            "  {} @ {}  {status}{}",
980            state.base_branch,
981            short(&bs.tip),
982            if bs.attempts > 0 {
983                format!("  ({} rebase attempt(s))", bs.attempts)
984            } else {
985                String::new()
986            }
987        );
988    }
989
990    if !state.pre_gate.is_empty() {
991        let _ = writeln!(s, "\n{}", bold("pre_gate"));
992        for o in &state.pre_gate {
993            let _ = writeln!(
994                s,
995                "  {}  {}",
996                if o.ok() {
997                    green("pass")
998                } else {
999                    yellow("warn")
1000                },
1001                o.command
1002            );
1003            if !o.ok() {
1004                let _ = writeln!(s, "{}", dim(&tail(&o.output_tail, 2_000)));
1005            }
1006        }
1007        if let Some(c) = &state.pre_gate_commit {
1008            let _ = writeln!(s, "  committed mechanical fixes @ {}", short(c));
1009        }
1010    }
1011
1012    // `state.gate.is_empty()` alone cannot tell "never ran" apart from "ran
1013    // with nothing configured" — see `RunState::gate_status`'s own doc — so
1014    // this reads the accessor rather than the raw list.
1015    match state.gate_status() {
1016        GateStatus::NotRun => {}
1017        GateStatus::PassedWithNoCommands => {
1018            let _ = writeln!(s, "\n{}", bold("gate"));
1019            let _ = writeln!(s, "  {}  no gate commands configured", green("pass"));
1020        }
1021        GateStatus::Passed | GateStatus::Failed => {
1022            let _ = writeln!(s, "\n{}", bold("gate"));
1023            for o in &state.gate {
1024                let _ = writeln!(
1025                    s,
1026                    "  {}  {}",
1027                    if o.ok() { green("pass") } else { red("FAIL") },
1028                    o.command
1029                );
1030                if !o.ok() {
1031                    let _ = writeln!(s, "{}", dim(&tail(&o.output_tail, 2_000)));
1032                }
1033            }
1034        }
1035    }
1036
1037    if let Some(m) = &state.merge {
1038        let _ = writeln!(s, "\n{}", bold("merge"));
1039        if m.mode == MergeMode::None {
1040            // `ok: true` here means "magi did nothing, as configured", not
1041            // "landed" — a green `ok` next to a shell command reads as done,
1042            // and the branch is still sitting unmerged.
1043            let _ = writeln!(
1044                s,
1045                "  mode None  {}",
1046                cyan("not landed — nothing to do by design")
1047            );
1048            if let Some(w) = state.winner() {
1049                let _ = writeln!(
1050                    s,
1051                    "  branch {} still exists, unmerged into {}",
1052                    w.branch, state.base_branch
1053                );
1054            }
1055            // The squash caveat only applies to that one style: `--no-ff` and
1056            // `--ff-only` never inherit a candidate's placeholder subject,
1057            // since neither ever discards the pull request body `message`
1058            // that `manual_merge_command` (graph.rs) already puts on the
1059            // squash commit's `-m`.
1060            let _ = writeln!(
1061                s,
1062                "  rebase onto {} before merging by hand{}",
1063                state.base_branch,
1064                if state.config.merge.style == MergeStyle::Squash {
1065                    ", and pass an explicit commit message — a squash merge \
1066                     otherwise inherits the candidate's placeholder subject"
1067                } else {
1068                    ""
1069                }
1070            );
1071            let _ = writeln!(s, "  {}", m.detail.lines().next().unwrap_or(""));
1072        } else {
1073            let _ = writeln!(
1074                s,
1075                "  mode {:?}  {}\n  {}",
1076                m.mode,
1077                if m.ok {
1078                    green("ok")
1079                } else if m.empty {
1080                    yellow("empty candidate — nothing to land")
1081                } else {
1082                    yellow("not merged")
1083                },
1084                m.detail.lines().next().unwrap_or("")
1085            );
1086        }
1087        if let Some(pr) = &state.pr
1088            && !pr.red_at_merge.is_empty()
1089        {
1090            let _ = writeln!(
1091                s,
1092                "  {} {}",
1093                yellow("merged with red checks:"),
1094                pr.red_at_merge.join(", ")
1095            );
1096        }
1097    }
1098
1099    if !state.followups.is_empty() {
1100        let _ = writeln!(s, "\n{}", bold("follow-ups"));
1101        for f in &state.followups {
1102            let _ = writeln!(
1103                s,
1104                "  {} {}",
1105                crate::queue::short(&f.task),
1106                f.findings.join(", ")
1107            );
1108        }
1109    }
1110
1111    if !state.bump_decision_attempts.is_empty() {
1112        let _ = writeln!(s, "\n{}", bold("release decision attempts"));
1113        for (n, attempt) in state.bump_decision_attempts.iter().enumerate() {
1114            let _ = writeln!(s, "  {}. {}: {}", n + 1, attempt.agent, attempt.outcome);
1115        }
1116    }
1117    if let Some(b) = &state.release_bump {
1118        let _ = writeln!(s, "\n{}", bold("release bump"));
1119        if let Some(v) = &b.version {
1120            let _ = writeln!(s, "  version v{v}");
1121        }
1122        if let Some(url) = &b.pr_url {
1123            let _ = writeln!(s, "  pr {url}");
1124        }
1125        let _ = writeln!(
1126            s,
1127            "  automerge {}",
1128            if b.automerge_enabled {
1129                green("enabled")
1130            } else if b.merged_directly {
1131                green("not needed (CI was already green; merged directly)")
1132            } else if b.local {
1133                dim(
1134                    "not used (release.mode = local: merged on your approval, released by magi serve)",
1135                )
1136            } else if b.problem.is_some() {
1137                bold(&red("FAILED"))
1138            } else {
1139                dim("not enabled")
1140            }
1141        );
1142        if let Some(p) = &b.problem {
1143            let _ = writeln!(s, "  {}", p.lines().next().unwrap_or(""));
1144        }
1145        if let Some(j) = &b.release {
1146            let state = if j.finished {
1147                "finished"
1148            } else {
1149                j.failed.as_deref().unwrap_or("unfinished")
1150            };
1151            let _ = writeln!(s, "  release {} at {}: {state}", j.tag(), j.commit);
1152            for l in &j.log {
1153                let code = l.code.map_or("none".to_owned(), |c| c.to_string());
1154                let _ = write!(s, "    {} (exit {code})", l.name);
1155                if let Some(o) = &l.output {
1156                    let _ = write!(s, " output {o}");
1157                }
1158                let _ = writeln!(s);
1159            }
1160        }
1161        if let Some(a) = &b.action_required {
1162            let _ = writeln!(s, "  {} {a}", bold(&yellow("action required:")));
1163        }
1164    }
1165
1166    if !state.leaks.is_empty() {
1167        let _ = writeln!(s, "\n{}", bold(&yellow("blindness warnings")));
1168        for l in &state.leaks {
1169            let _ = writeln!(s, "  {} x{} in {}", l.token, l.count, l.site);
1170        }
1171    }
1172
1173    if let Some(w) = state.winner()
1174        && !w.folded
1175    {
1176        let _ = writeln!(
1177            s,
1178            "\n{} {}\n  branch {}",
1179            bold("winner worktree"),
1180            w.worktree.display(),
1181            w.branch
1182        );
1183    }
1184    s.push_str(&jobs_section(state));
1185    s
1186}
1187
1188/// The seats currently mid-answer, for `magi show` and the raw report route.
1189///
1190/// Separate from [`run`] on purpose: [`run`] is printed straight after `magi
1191/// run` / `magi review`'s own `execute()`, and by then this process has
1192/// nothing left in flight to report; the TUI does not track daemon liveness
1193/// either. Only a caller reading someone *else's* run — `magi show <id>`, or
1194/// the web UI's raw-report route — needs this, and both already know how to
1195/// ask whether a daemon is currently driving it.
1196///
1197/// `live` is [`RunState::liveness`]: whether a daemon's heartbeat currently
1198/// names this run, or — absent that claim — whether `driver_pid` still
1199/// answers alive. An [`ActiveSeat`](crate::run::ActiveSeat) left behind by a
1200/// killed process is not lied about as running just because nobody has
1201/// cleared it from disk yet — see that type's own docs for why an entry
1202/// alone is not proof of anything.
1203pub fn active_seats(state: &RunState, live: Liveness) -> String {
1204    let mut s = String::new();
1205    // A run that stopped on an infrastructure wait says so: no agent failed
1206    // and none was asked, and a resume asks the same ones.
1207    if let Some(b) = &state.resource_block {
1208        let _ = writeln!(
1209            s,
1210            "\n{}\n  {}: {} stayed busy past the resource-wait limit; no agent was started \
1211             ({}). Resume to ask the same agents again.",
1212            bold("waiting on a resource"),
1213            b.node,
1214            b.kind,
1215            b.detail
1216        );
1217    }
1218    if state.active.is_empty() {
1219        return s;
1220    }
1221    let _ = writeln!(s, "\n{}", bold("running now"));
1222    let now = jiff::Timestamp::now();
1223    match live {
1224        Liveness::Live => {}
1225        Liveness::Dead => {
1226            let _ = writeln!(
1227                s,
1228                "  {}",
1229                yellow(
1230                    "no live daemon claims this run right now — likely left behind by a killed process"
1231                )
1232            );
1233        }
1234        Liveness::Unknown => {
1235            // `active_all_overrun` is never treated as proof of death here —
1236            // only ever mentioned alongside "could not confirm", since a
1237            // seat legitimately overrunning its budget while the process
1238            // driving it tears the attempt down looks identical on disk (see
1239            // `RunState::active_all_overrun`'s own doc).
1240            let overrun = if state.active_all_overrun(now) {
1241                " — every active seat has already run past its own timeout budget"
1242            } else {
1243                ""
1244            };
1245            let _ = writeln!(
1246                s,
1247                "  {}",
1248                yellow(&format!(
1249                    "whether a process is still driving this run could not be confirmed{overrun}"
1250                ))
1251            );
1252        }
1253    }
1254    for (seat, a) in state.seats_active() {
1255        let retry = if a.attempt > 0 {
1256            format!(" retry {}", a.attempt)
1257        } else {
1258            String::new()
1259        };
1260        // Before the CLI is spawned there is no agent budget to count down.
1261        if let Some(w) = state.resource_wait.as_ref().filter(|w| w.node == a.node) {
1262            let _ = writeln!(
1263                s,
1264                "  {:<12} {:<12}{retry}  waiting for the {} ({}), {}s of {}s; agent not started yet",
1265                seat,
1266                a.node,
1267                w.kind,
1268                w.holder,
1269                (now.as_second() - w.since.as_second()).max(0),
1270                w.limit_secs
1271            );
1272            continue;
1273        }
1274        let _ = writeln!(
1275            s,
1276            "  {:<12} {:<12}{retry}  {}s elapsed, {}s left of {}s",
1277            seat,
1278            a.node,
1279            a.elapsed_secs(now),
1280            a.remaining_secs(now),
1281            a.timeout_secs
1282        );
1283    }
1284    for (task, a) in state.tasks_active() {
1285        let retry = if a.attempt > 0 {
1286            format!(" retry {}", a.attempt)
1287        } else {
1288            String::new()
1289        };
1290        let progress = match (a.index, a.total) {
1291            (Some(i), Some(t)) => format!(" ({i}/{t})"),
1292            _ => String::new(),
1293        };
1294        let _ = writeln!(
1295            s,
1296            "  {:<12} {:<12}{retry}{progress}  {}s elapsed, {}s left of {}s",
1297            task,
1298            a.node,
1299            a.elapsed_secs(now),
1300            a.remaining_secs(now),
1301            a.timeout_secs
1302        );
1303        if let Some(command) = &a.command {
1304            let _ = writeln!(s, "               {command}");
1305        }
1306    }
1307    s
1308}
1309
1310/// Render a whole number of seconds as `1h02m`, `3m05s` or `42s`.
1311fn fmt_secs(secs: i64) -> String {
1312    let secs = secs.max(0);
1313    let h = secs / 3600;
1314    let m = (secs % 3600) / 60;
1315    let s = secs % 60;
1316    if h > 0 {
1317        format!("{h}h{m:02}m")
1318    } else if m > 0 {
1319        format!("{m}m{s:02}s")
1320    } else {
1321        format!("{s}s")
1322    }
1323}
1324
1325/// A fixed-width text bar, `value` proportional to `max` out of `width` cells.
1326///
1327/// Any positive value draws at least one cell, so a short-but-nonzero
1328/// duration is never mistaken for an unmeasured one.
1329fn bar(value: f64, max: f64, width: usize) -> String {
1330    if max <= 0.0 || value <= 0.0 {
1331        return String::new();
1332    }
1333    let cells = ((value / max) * width as f64)
1334        .round()
1335        .clamp(1.0, width as f64) as usize;
1336    "█".repeat(cells)
1337}
1338
1339/// Per-repository summary table: repo name, run count, completion rate.
1340///
1341/// `main.rs`'s `Command::Stats` is what decides *whether* to print this —
1342/// only ahead of the plain (no `--repo`) report, and only when `repos.len() >
1343/// 1` — this function only renders whatever it is handed.
1344pub fn repo_summary(repos: &[RepoStats]) -> String {
1345    let mut s = String::new();
1346    let _ = writeln!(s, "{}", bold("repos"));
1347
1348    // Two different checkouts can share a leaf directory name (`magi` under
1349    // two different roots); disambiguate only those with their parent
1350    // directory rather than paying the extra noise on every row.
1351    let mut name_counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
1352    for r in repos {
1353        *name_counts.entry(r.name.as_str()).or_insert(0) += 1;
1354    }
1355
1356    for r in repos {
1357        let label = if name_counts.get(r.name.as_str()).copied().unwrap_or(0) > 1 {
1358            match r.repo.parent().and_then(|p| p.file_name()) {
1359                Some(parent) => format!("{} ({})", r.name, parent.to_string_lossy()),
1360                None => r.name.clone(),
1361            }
1362        } else {
1363            r.name.clone()
1364        };
1365        let _ = writeln!(
1366            s,
1367            "  {}  {} runs  {:.0}% completion",
1368            label,
1369            r.stats.totals.runs,
1370            r.stats.totals.completion_rate()
1371        );
1372    }
1373    s
1374}
1375
1376/// Aggregate tables, for `magi stats`.
1377pub fn stats(stats: &Stats) -> String {
1378    let t = &stats.totals;
1379    let mut s = String::new();
1380    let _ = writeln!(s, "{}", bold("runs"));
1381    let _ = writeln!(
1382        s,
1383        "  {} total - {} merged, {} ready, {} blocked, {} failed ({:.0}% completion)",
1384        t.runs,
1385        t.merged,
1386        t.ready,
1387        t.blocked,
1388        t.failed,
1389        t.completion_rate()
1390    );
1391    if t.tallied > 0 {
1392        let _ = writeln!(
1393            s,
1394            "  {} tallied - {} split on first choice ({:.0}%), {} deliberated, \
1395             {} of those changed a mind, {} converged to unanimous",
1396            t.tallied,
1397            t.split,
1398            t.split_rate(),
1399            t.deliberated,
1400            t.minds_changed,
1401            t.converged
1402        );
1403    }
1404
1405    if !stats.retired_hidden.is_empty() {
1406        let n = stats.retired_hidden.len();
1407        let _ = writeln!(
1408            s,
1409            "{n} retired agent{} hidden: {} (magi stats --all to show)\n",
1410            if n == 1 { "" } else { "s" },
1411            stats.retired_hidden.join(", ")
1412        );
1413    }
1414
1415    let has_competitive = stats.agents.iter().any(|a| a.competitive_entered > 0);
1416    if has_competitive {
1417        let mut comp_agents = stats.agents.clone();
1418        comp_agents.retain(|a| a.competitive_entered > 0);
1419        comp_agents.sort_by(|a, b| {
1420            let a_tier = if a.competitive_entered < 10 { 1 } else { 0 };
1421            let b_tier = if b.competitive_entered < 10 { 1 } else { 0 };
1422            a_tier
1423                .cmp(&b_tier)
1424                .then(
1425                    b.competitive_win_rate()
1426                        .total_cmp(&a.competitive_win_rate()),
1427                )
1428                .then(b.competitive_entered.cmp(&a.competitive_entered))
1429                .then(a.agent.cmp(&b.agent))
1430        });
1431
1432        let _ = writeln!(
1433            s,
1434            "\n{}",
1435            bold("implementation (competitive runs, 2+ candidates)")
1436        );
1437        let _ = writeln!(
1438            s,
1439            "  {:<14}{:>6}{:>8}{:>8}{:>8}",
1440            "agent", "won", "entered", "rate", "empty"
1441        );
1442        for a in &comp_agents {
1443            let low_n_marker = if a.competitive_entered < 10 {
1444                format!(" {}", dim("low n"))
1445            } else {
1446                String::new()
1447            };
1448            let _ = writeln!(
1449                s,
1450                "  {:<14}{:>6}{:>8}{:>7.0}%{:>8}{}",
1451                a.agent,
1452                a.competitive_wins,
1453                a.competitive_entered,
1454                a.competitive_win_rate(),
1455                a.empty,
1456                low_n_marker
1457            );
1458        }
1459    }
1460
1461    let has_solo = stats.agents.iter().any(|a| a.solo_entered > 0);
1462    if has_solo {
1463        let mut solo_agents = stats.agents.clone();
1464        solo_agents.retain(|a| a.solo_entered > 0);
1465        solo_agents.sort_by(|a, b| {
1466            let a_tier = if a.solo_entered < 10 { 1 } else { 0 };
1467            let b_tier = if b.solo_entered < 10 { 1 } else { 0 };
1468            a_tier
1469                .cmp(&b_tier)
1470                .then(b.solo_adoption_rate().total_cmp(&a.solo_adoption_rate()))
1471                .then(b.solo_entered.cmp(&a.solo_entered))
1472                .then(a.agent.cmp(&b.agent))
1473        });
1474
1475        let _ = writeln!(
1476            s,
1477            "\n{}",
1478            bold("implementation (solo runs, completion/adoption rate)")
1479        );
1480        let _ = writeln!(
1481            s,
1482            "  {:<14}{:>8}{:>8}{:>8}",
1483            "agent", "adopted", "entered", "rate"
1484        );
1485        for a in &solo_agents {
1486            let low_n_marker = if a.solo_entered < 10 {
1487                format!(" {}", dim("low n"))
1488            } else {
1489                String::new()
1490            };
1491            let _ = writeln!(
1492                s,
1493                "  {:<14}{:>8}{:>8}{:>7.0}%{}",
1494                a.agent,
1495                a.solo_adopted,
1496                a.solo_entered,
1497                a.solo_adoption_rate(),
1498                low_n_marker
1499            );
1500        }
1501    }
1502
1503    if !stats.reviewers.is_empty() {
1504        let _ = writeln!(s, "\n{}", bold("review"));
1505        let _ = writeln!(
1506            s,
1507            "  {:<14}{:>8}{:>10}{:>11}{:>9}{:>9}{:>9}",
1508            "reviewer", "rounds", "submitted", "adopted/rd", "precision", "unique", "timeout"
1509        );
1510        for r in &stats.reviewers {
1511            let _ = writeln!(
1512                s,
1513                "  {:<14}{:>8}{:>10}{:>11.2}{:>8.0}%{:>8.0}%{:>8.0}%",
1514                r.agent,
1515                r.rounds,
1516                r.submitted,
1517                r.adopted_per_round(),
1518                r.precision(),
1519                r.unique_rate(),
1520                r.timeout_rate()
1521            );
1522        }
1523    }
1524
1525    if !stats.advisors.is_empty() {
1526        let _ = writeln!(
1527            s,
1528            "\n{} {}",
1529            bold("design deliberation"),
1530            dim(
1531                "(approximate: reflection is read off word overlap with the synthesis brief, not a precise attribution)"
1532            )
1533        );
1534        let _ = writeln!(
1535            s,
1536            "  {:<14}{:>7}{:>10}{:>8}{:>8}{:>9}{:>10}",
1537            "advisor", "seats", "proposed", "strong", "faint", "absent", "reflect%"
1538        );
1539        for a in &stats.advisors {
1540            let _ = writeln!(
1541                s,
1542                "  {:<14}{:>7}{:>10}{:>8}{:>8}{:>9}{:>9.0}%",
1543                a.agent,
1544                a.seated,
1545                a.proposed,
1546                a.strong,
1547                a.faint,
1548                a.absent,
1549                a.reflection_rate()
1550            );
1551        }
1552    }
1553
1554    if stats.release_bumps.merged > 0 {
1555        let b = &stats.release_bumps;
1556        let _ = writeln!(s, "\n{}", bold("release bumps"));
1557        let _ = writeln!(
1558            s,
1559            "  {} of {} merged run(s) recorded a bump ({:.0}%)",
1560            b.recorded,
1561            b.merged,
1562            b.coverage_rate()
1563        );
1564        let _ = writeln!(
1565            s,
1566            "  {} release PR(s) opened, {} automerge enabled ({:.0}%), {} merged directly",
1567            b.pr_opened,
1568            b.automerge_enabled,
1569            b.automerge_rate(),
1570            b.merged_directly
1571        );
1572        let _ = writeln!(
1573            s,
1574            "  {} clean, {} needed a human ({:.0}%)",
1575            b.clean(),
1576            b.needs_attention,
1577            b.attention_rate()
1578        );
1579    }
1580
1581    if stats.e2e.rounds > 0 || stats.e2e.deferred > 0 {
1582        let _ = writeln!(s, "\n{}", bold("verification"));
1583        let _ = writeln!(
1584            s,
1585            "  {} rounds ran e2e, {} failed, {} of those with a clean static \
1586             review ({:.0}% sole detections), {} round(s) deferred it to the fixer",
1587            stats.e2e.rounds,
1588            stats.e2e.failures,
1589            stats.e2e.sole_detections,
1590            stats.e2e.sole_rate(),
1591            stats.e2e.deferred
1592        );
1593    }
1594
1595    if !stats.nodes.is_empty() {
1596        let _ = writeln!(
1597            s,
1598            "\n{}",
1599            bold("node durations (first to last event, per run)")
1600        );
1601        let max_mean = stats
1602            .nodes
1603            .iter()
1604            .map(|n| n.mean_secs())
1605            .fold(0.0_f64, f64::max);
1606        for n in &stats.nodes {
1607            let unmeasured = if n.single > 0 {
1608                format!("  {}", dim(&format!("{} unmeasured", n.single)))
1609            } else {
1610                String::new()
1611            };
1612            let _ = writeln!(
1613                s,
1614                "  {:<14}{:>6} runs{:>8} mean{:>8} max  {}{unmeasured}",
1615                n.node,
1616                n.runs,
1617                fmt_secs(n.mean_secs().round() as i64),
1618                fmt_secs(n.max_secs),
1619                bar(n.mean_secs(), max_mean, 20)
1620            );
1621        }
1622    }
1623    s
1624}
1625
1626#[cfg(test)]
1627mod tests {
1628    use super::*;
1629    use crate::config::Config;
1630    use crate::run::{
1631        Candidate, CommandOutcome, FixRecord, MergeOutcome, ReviewRecord, ReviewRound, RunState,
1632        Tally,
1633    };
1634    use std::collections::BTreeMap;
1635    use std::path::PathBuf;
1636    use std::sync::{Mutex, MutexGuard};
1637
1638    /// `COLOR` is process-global, so these tests cannot run concurrently.
1639    static SERIAL: Mutex<()> = Mutex::new(());
1640
1641    fn plain() -> MutexGuard<'static, ()> {
1642        let guard = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
1643        set_color(false);
1644        guard
1645    }
1646
1647    fn state() -> RunState {
1648        // `run()` prints `state.dir()`, which reads the process-global home;
1649        // pinning it here keeps this test off the operator's real one. The
1650        // directory itself is never read, only its path printed, so nothing
1651        // needs to create or clean it up.
1652        crate::run::pin_test_home();
1653        let mut s = RunState::new(
1654            PathBuf::from("/repo"),
1655            "main".to_owned(),
1656            "abcdef1234".to_owned(),
1657            "add retries to the uploader".to_owned(),
1658            Config::default(),
1659        );
1660        s.candidates = vec![Candidate {
1661            index: 0,
1662            label: 'A',
1663            agent: "opus".to_owned(),
1664            branch: "magi/x/A".to_owned(),
1665            worktree: PathBuf::from("/wt/A"),
1666            summary: String::new(),
1667            stat: String::new(),
1668            files: 3,
1669            commits: 2,
1670            empty: false,
1671            failed: None,
1672            verified_noop: None,
1673            duration_ms: 42_000,
1674            folded: false,
1675        }];
1676        s.tally = Some(Tally {
1677            first_choice: BTreeMap::from([('A', 3)]),
1678            borda: BTreeMap::new(),
1679            winner: 'A',
1680            rankings: 3,
1681            unanimous_initial: true,
1682            deliberated: false,
1683            changed_votes: 0,
1684            unanimous_final: true,
1685            tie_break: None,
1686            judges: 3,
1687            present: 3,
1688            quorum: 2,
1689            met_quorum: true,
1690            uncontested: None,
1691        });
1692        s
1693    }
1694
1695    #[test]
1696    fn run_report_names_the_winner_and_its_author() {
1697        let _guard = plain();
1698        let text = run(&state());
1699        assert!(text.contains("<- winner"), "{text}");
1700        assert!(text.contains("opus"));
1701        assert!(text.contains("3 files, 2 commits"));
1702        assert!(text.contains("winner        A"));
1703        assert!(!text.contains('\x1b'), "colour leaked into a plain render");
1704    }
1705
1706    #[test]
1707    fn a_candidates_own_summary_is_surfaced_not_only_kept_in_run_json() {
1708        // Recorded on every run (`prompt::implement`'s `## SUMMARY`), but
1709        // `run()` used to never print it at all — silent even when the
1710        // summary was the one place an implementer explained itself (e.g.
1711        // an investigation task's findings), and readable only by opening
1712        // `run.json` by hand.
1713        let _guard = plain();
1714        let mut s = state();
1715        s.candidates[0].summary =
1716            "investigated 6c5e/8df3: both already merged, see talk 07fe.\nmore detail below."
1717                .to_owned();
1718        let text = run(&s);
1719        assert!(
1720            text.contains("investigated 6c5e/8df3: both already merged, see talk 07fe."),
1721            "{text}"
1722        );
1723    }
1724
1725    #[test]
1726    fn a_verified_noop_run_does_not_read_as_a_failure() {
1727        // Same spirit as `a_mode_none_merge_does_not_read_as_landed`: a run
1728        // that settled without landing anything must not be misreadable as
1729        // the ordinary failure it is not.
1730        let _guard = plain();
1731        let mut s = state();
1732        s.status = RunStatus::VerifiedNoop;
1733        s.tally = None;
1734        s.candidates = vec![Candidate {
1735            index: 0,
1736            label: 'A',
1737            agent: "opus".to_owned(),
1738            branch: "magi/x/A".to_owned(),
1739            worktree: PathBuf::from("/wt/A"),
1740            summary: String::new(),
1741            stat: String::new(),
1742            files: 0,
1743            commits: 0,
1744            empty: true,
1745            failed: None,
1746            verified_noop: Some("already fixed by b32cfc4, which is on main".to_owned()),
1747            duration_ms: 9_000,
1748            folded: false,
1749        }];
1750        let text = run(&s);
1751        assert!(
1752            text.contains("agent-verified no-op"),
1753            "the status and the candidate flag must both say so: {text}"
1754        );
1755        assert!(
1756            text.contains("already fixed by b32cfc4"),
1757            "the evidence itself must be readable, not just the verdict: {text}"
1758        );
1759        assert!(
1760            !text.to_lowercase().contains("failed"),
1761            "a verified no-op must never read as the failure it is not: {text}"
1762        );
1763    }
1764
1765    #[test]
1766    fn colour_is_emitted_only_when_enabled() {
1767        let _guard = plain();
1768        set_color(true);
1769        let coloured = run(&state());
1770        set_color(false);
1771        let plain = run(&state());
1772        assert!(coloured.contains('\x1b'));
1773        assert!(!plain.contains('\x1b'));
1774        assert!(coloured.len() > plain.len());
1775    }
1776
1777    #[test]
1778    fn list_line_is_single_line() {
1779        let _guard = plain();
1780        let l = line(&state());
1781        assert_eq!(l.lines().count(), 1);
1782        assert!(l.contains("add retries"));
1783        assert!(l.contains("win A (opus)"));
1784    }
1785
1786    #[test]
1787    fn an_uncontested_run_does_not_read_as_a_collapsed_panel() {
1788        let _guard = plain();
1789        let mut s = state();
1790        s.tally = Some(Tally {
1791            first_choice: BTreeMap::from([('A', 0)]),
1792            borda: BTreeMap::new(),
1793            winner: 'A',
1794            rankings: 0,
1795            unanimous_initial: false,
1796            deliberated: false,
1797            changed_votes: 0,
1798            unanimous_final: false,
1799            tie_break: None,
1800            judges: 0,
1801            present: 0,
1802            quorum: 0,
1803            met_quorum: true,
1804            uncontested: Some(
1805                "only candidate A produced a usable change; no panel was asked".to_owned(),
1806            ),
1807        });
1808        let text = run(&s);
1809        assert!(
1810            !text.contains("0/3"),
1811            "no panel sat, so the judges line must not read as one that collapsed: {text}"
1812        );
1813        assert!(!text.contains("no usable ranking"), "{text}");
1814        assert!(!text.contains("still split"), "{text}");
1815        assert!(!text.contains("BELOW QUORUM"), "{text}");
1816        assert!(
1817            text.contains("not needed"),
1818            "the report must say judging was skipped, not silent: {text}"
1819        );
1820        assert!(text.contains("winner        A"));
1821    }
1822
1823    #[test]
1824    fn a_below_quorum_run_still_reads_as_a_collapsed_panel() {
1825        let _guard = plain();
1826        let mut s = state();
1827        s.tally = Some(Tally {
1828            first_choice: BTreeMap::from([('A', 1), ('B', 0)]),
1829            borda: BTreeMap::new(),
1830            winner: 'A',
1831            rankings: 1,
1832            unanimous_initial: false,
1833            deliberated: false,
1834            changed_votes: 0,
1835            unanimous_final: false,
1836            tie_break: None,
1837            judges: 3,
1838            present: 1,
1839            quorum: 2,
1840            met_quorum: false,
1841            uncontested: None,
1842        });
1843        let text = run(&s);
1844        assert!(text.contains("1/3"), "{text}");
1845        assert!(
1846            text.contains("BELOW QUORUM"),
1847            "a real collapse must still be flagged: {text}"
1848        );
1849        assert!(
1850            !text.contains("not needed"),
1851            "a collapsed panel must not be described as one that was never asked: {text}"
1852        );
1853    }
1854
1855    #[test]
1856    fn a_mode_none_merge_does_not_read_as_landed() {
1857        let _guard = plain();
1858        let mut s = state();
1859        s.merge = Some(MergeOutcome {
1860            mode: crate::config::MergeMode::None,
1861            ok: true,
1862            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
1863            empty: false,
1864        });
1865        let text = run(&s);
1866        assert!(
1867            !text.contains("  ok"),
1868            "mode none must not be shown as a landed merge: {text}"
1869        );
1870        assert!(text.contains("not landed"), "{text}");
1871        assert!(
1872            text.contains("branch magi/x/A"),
1873            "the report must say what's left behind: {text}"
1874        );
1875        assert!(
1876            text.contains("rebase"),
1877            "the report must point at the hand-landing steps: {text}"
1878        );
1879        assert!(
1880            !text.contains("placeholder subject"),
1881            "the default merge style is `merge`, which never inherits a \
1882             placeholder subject, so the squash caveat must not appear: {text}"
1883        );
1884    }
1885
1886    #[test]
1887    fn a_mode_none_squash_merge_warns_about_the_placeholder_subject() {
1888        let _guard = plain();
1889        let mut s = state();
1890        s.config.merge.style = MergeStyle::Squash;
1891        s.merge = Some(MergeOutcome {
1892            mode: crate::config::MergeMode::None,
1893            ok: true,
1894            detail: "git -C /repo merge --squash magi/x/A && git -C /repo commit -m \"add \
1895                      retries\""
1896                .to_owned(),
1897            empty: false,
1898        });
1899        let text = run(&s);
1900        assert!(
1901            text.contains("placeholder subject"),
1902            "a squash-style manual merge must warn about the missing message: {text}"
1903        );
1904        assert!(text.contains("--squash"), "{text}");
1905    }
1906
1907    #[test]
1908    fn a_ready_run_left_by_merge_mode_none_does_not_read_as_a_plain_ready() {
1909        let _guard = plain();
1910        let mut s = state();
1911        s.status = RunStatus::Ready;
1912        s.merge = Some(MergeOutcome {
1913            mode: crate::config::MergeMode::None,
1914            ok: true,
1915            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
1916            empty: false,
1917        });
1918
1919        let list = line(&s);
1920        assert!(
1921            !list.contains(" ready "),
1922            "a mode-none run must not read as a plain ready in `magi list`: {list}"
1923        );
1924        assert!(list.contains("no-op by design"), "{list}");
1925
1926        let full = run(&s);
1927        assert!(
1928            !full.contains("magi run") || !full.lines().next().unwrap().contains(" ready"),
1929            "the header line of `magi show` must not say plain ready either: {full}"
1930        );
1931        assert!(full.contains("no-op by design"), "{full}");
1932    }
1933
1934    #[test]
1935    fn an_ordinary_ready_run_still_reads_as_ready() {
1936        let _guard = plain();
1937        let mut s = state();
1938        s.status = RunStatus::Ready;
1939        // A PR closed without merging also ends at `Ready` (see `land.rs`),
1940        // and unlike the honest mode-none no-op it must keep reading as a
1941        // plain `ready` — the label exists to flag design, not every non-merge.
1942        s.merge = Some(MergeOutcome {
1943            mode: crate::config::MergeMode::Pr,
1944            ok: false,
1945            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
1946            empty: false,
1947        });
1948
1949        let list = line(&s);
1950        assert!(list.contains("ready"), "{list}");
1951        assert!(!list.contains("no-op by design"), "{list}");
1952    }
1953
1954    #[test]
1955    fn the_list_line_does_not_flag_an_uncontested_run_as_short_judges() {
1956        let _guard = plain();
1957        let mut s = state();
1958        s.tally = Some(Tally {
1959            first_choice: BTreeMap::from([('A', 0)]),
1960            borda: BTreeMap::new(),
1961            winner: 'A',
1962            rankings: 0,
1963            unanimous_initial: false,
1964            deliberated: false,
1965            changed_votes: 0,
1966            unanimous_final: false,
1967            tie_break: None,
1968            judges: 0,
1969            present: 0,
1970            quorum: 0,
1971            met_quorum: true,
1972            uncontested: Some("only candidate A produced a usable change".to_owned()),
1973        });
1974        let l = line(&s);
1975        assert!(
1976            !l.contains("judges") && !l.contains("quorum"),
1977            "an uncontested run must not carry the same badge a short panel gets: {l}"
1978        );
1979    }
1980
1981    #[test]
1982    fn long_instructions_are_elided() {
1983        let _guard = plain();
1984        let mut s = state();
1985        s.instruction = "x".repeat(200);
1986        assert!(line(&s).contains('…'));
1987    }
1988
1989    #[test]
1990    fn a_lost_fix_report_reads_differently_from_zero_adoption() {
1991        let _guard = plain();
1992        let mut lost = state();
1993        lost.reviews = vec![ReviewRound {
1994            round: 1,
1995            head: "abc1234".to_owned(),
1996            verified_head: None,
1997            verified_at: None,
1998            reviews: Vec::new(),
1999            e2e: Vec::new(),
2000            verify_retried: false,
2001            e2e_deferred: false,
2002            e2e_defer_reason: None,
2003            fix: Some(FixRecord {
2004                agent: "opus".to_owned(),
2005                addressed: Vec::new(),
2006                rejected: Vec::new(),
2007                notes: String::new(),
2008                committed: true,
2009                failed: Some("timed out".to_owned()),
2010                duration_ms: 0,
2011                continuation: None,
2012            }),
2013            blocking: 3,
2014            answered: 0,
2015            expected: 0,
2016            clean: false,
2017            progressed: false,
2018            vote_split: false,
2019            reconsideration: Vec::new(),
2020            verdict: None,
2021        }];
2022        let text = run(&lost);
2023        assert!(text.contains("adoption report lost (timed out)"), "{text}");
2024        assert!(
2025            !text.contains("0 addressed"),
2026            "a lost report must never read as `0 addressed`: {text}"
2027        );
2028
2029        let mut rejected_all = state();
2030        rejected_all.reviews = vec![ReviewRound {
2031            round: 1,
2032            head: "abc1234".to_owned(),
2033            verified_head: None,
2034            verified_at: None,
2035            reviews: Vec::new(),
2036            e2e: Vec::new(),
2037            verify_retried: false,
2038            e2e_deferred: false,
2039            e2e_defer_reason: None,
2040            fix: Some(FixRecord {
2041                agent: "opus".to_owned(),
2042                addressed: Vec::new(),
2043                rejected: Vec::new(),
2044                notes: String::new(),
2045                committed: true,
2046                failed: None,
2047                duration_ms: 0,
2048                continuation: None,
2049            }),
2050            blocking: 3,
2051            answered: 0,
2052            expected: 0,
2053            clean: false,
2054            progressed: false,
2055            vote_split: false,
2056            reconsideration: Vec::new(),
2057            verdict: None,
2058        }];
2059        let text2 = run(&rejected_all);
2060        assert!(
2061            text2.contains("0 addressed / 0 rejected"),
2062            "a round the fixer actually reported on keeps the count: {text2}"
2063        );
2064    }
2065
2066    #[test]
2067    fn a_split_round_shows_every_seat_vote_and_the_reconsideration() {
2068        use crate::run::ReviewRevoteRecord;
2069        use crate::verdict::ReviewVote;
2070
2071        let _guard = plain();
2072        let mut s = state();
2073        s.reviews = vec![ReviewRound {
2074            round: 1,
2075            head: "abc1234".to_owned(),
2076            verified_head: None,
2077            verified_at: None,
2078            reviews: vec![
2079                ReviewRecord {
2080                    attempts: 0,
2081                    reviewer: 1,
2082                    agent: "alpha".to_owned(),
2083                    summary: String::new(),
2084                    findings: Vec::new(),
2085                    vote: Some(ReviewVote::Approve),
2086                    failed: None,
2087                    duration_ms: 0,
2088                },
2089                ReviewRecord {
2090                    attempts: 0,
2091                    reviewer: 2,
2092                    agent: "beta".to_owned(),
2093                    summary: String::new(),
2094                    findings: Vec::new(),
2095                    vote: Some(ReviewVote::Reject),
2096                    failed: None,
2097                    duration_ms: 0,
2098                },
2099            ],
2100            e2e: Vec::new(),
2101            verify_retried: false,
2102            e2e_deferred: false,
2103            e2e_defer_reason: None,
2104            fix: None,
2105            blocking: 0,
2106            answered: 2,
2107            expected: 2,
2108            clean: false,
2109            progressed: false,
2110            vote_split: true,
2111            reconsideration: vec![ReviewRevoteRecord {
2112                reviewer: 2,
2113                agent: "beta".to_owned(),
2114                vote: Some(ReviewVote::ApproveWithFindings),
2115                reason: "the other seat's read holds up".to_owned(),
2116                failed: None,
2117            }],
2118            verdict: Some(ReviewVote::ApproveWithFindings),
2119        }];
2120        let text = run(&s);
2121        assert!(text.contains("review-1 vote"), "{text}");
2122        assert!(text.contains("review-2 vote"), "{text}");
2123        assert!(text.contains("panel split"), "{text}");
2124        assert!(text.contains("reconsideration"), "{text}");
2125        assert!(text.contains("the other seat's read holds up"), "{text}");
2126    }
2127
2128    #[test]
2129    fn an_incomplete_panel_and_a_lost_fix_report_both_stay_on_the_round_line() {
2130        // Two independent facts share this one line, and each arrived from a
2131        // different change: a seat that never answered, and a fixer whose
2132        // adoption report was lost. Rendering either must not shadow the
2133        // other, and neither may collapse into the plain `clean`/`open`
2134        // pair the line used to carry.
2135        let _guard = plain();
2136        let mut s = state();
2137        s.reviews = vec![ReviewRound {
2138            round: 1,
2139            head: "abc1234".to_owned(),
2140            verified_head: None,
2141            verified_at: None,
2142            reviews: vec![
2143                ReviewRecord {
2144                    attempts: 0,
2145                    reviewer: 1,
2146                    agent: "alpha".to_owned(),
2147                    summary: String::new(),
2148                    findings: Vec::new(),
2149                    vote: None,
2150                    failed: None,
2151                    duration_ms: 0,
2152                },
2153                ReviewRecord {
2154                    attempts: 0,
2155                    reviewer: 2,
2156                    agent: "beta".to_owned(),
2157                    summary: String::new(),
2158                    findings: Vec::new(),
2159                    vote: None,
2160                    failed: Some("agent timed out".to_owned()),
2161                    duration_ms: 0,
2162                },
2163            ],
2164            e2e: Vec::new(),
2165            verify_retried: false,
2166            e2e_deferred: false,
2167            e2e_defer_reason: None,
2168            fix: Some(FixRecord {
2169                agent: "opus".to_owned(),
2170                addressed: Vec::new(),
2171                rejected: Vec::new(),
2172                notes: String::new(),
2173                committed: true,
2174                failed: Some("timed out".to_owned()),
2175                duration_ms: 0,
2176                continuation: None,
2177            }),
2178            blocking: 0,
2179            answered: 1,
2180            expected: 2,
2181            clean: false,
2182            progressed: true,
2183            vote_split: false,
2184            reconsideration: Vec::new(),
2185            verdict: None,
2186        }];
2187        let text = run(&s);
2188        assert!(text.contains("incomplete"), "{text}");
2189        assert!(text.contains("1/2 reviewers answered"), "{text}");
2190        assert!(text.contains("review-2: agent timed out"), "{text}");
2191        assert!(text.contains("adoption report lost (timed out)"), "{text}");
2192        assert!(
2193            !text.contains("clean"),
2194            "a round missing half its panel must never render as clean: {text}"
2195        );
2196    }
2197
2198    #[test]
2199    fn a_build_failure_is_not_reported_as_a_test_failure() {
2200        let _guard = plain();
2201        let mut s = state();
2202        s.reviews = vec![ReviewRound {
2203            round: 1,
2204            head: "abc1234".to_owned(),
2205            verified_head: None,
2206            verified_at: None,
2207            reviews: Vec::new(),
2208            e2e: vec![CommandOutcome {
2209                command: "cargo test".to_owned(),
2210                code: Some(1),
2211                output_tail: "LINK : fatal error LNK1104: cannot open file".to_owned(),
2212                duration_ms: 100,
2213                resource_blocked: false,
2214            }],
2215            verify_retried: true,
2216            e2e_deferred: false,
2217            e2e_defer_reason: None,
2218            fix: None,
2219            blocking: 0,
2220            answered: 0,
2221            expected: 0,
2222            clean: false,
2223            progressed: false,
2224            vote_split: false,
2225            reconsideration: Vec::new(),
2226            verdict: None,
2227        }];
2228        let text = run(&s);
2229        assert!(text.contains("could not run"), "{text}");
2230        assert!(text.contains("retried once"), "{text}");
2231        assert!(!text.contains("e2e RED"), "{text}");
2232    }
2233
2234    #[test]
2235    fn a_resource_blocked_e2e_never_reads_as_red_or_as_a_build_failure() {
2236        let _guard = plain();
2237        let mut s = state();
2238        s.reviews = vec![ReviewRound {
2239            round: 1,
2240            head: "abc1234".to_owned(),
2241            verified_head: None,
2242            verified_at: None,
2243            reviews: Vec::new(),
2244            e2e: vec![CommandOutcome {
2245                command: "(waiting for the shared build cache)".to_owned(),
2246                code: None,
2247                output_tail: "held by run x node e2e seat e2e".to_owned(),
2248                duration_ms: 100,
2249                resource_blocked: true,
2250            }],
2251            verify_retried: false,
2252            e2e_deferred: false,
2253            e2e_defer_reason: None,
2254            fix: None,
2255            blocking: 0,
2256            answered: 0,
2257            expected: 0,
2258            clean: false,
2259            progressed: false,
2260            vote_split: false,
2261            reconsideration: Vec::new(),
2262            verdict: None,
2263        }];
2264        let text = run(&s);
2265        assert!(text.contains("shared build cache unavailable"), "{text}");
2266        assert!(!text.contains("e2e RED"), "{text}");
2267        assert!(!text.contains("build/link failure"), "{text}");
2268    }
2269
2270    #[test]
2271    fn a_round_with_more_than_one_e2e_command_names_each_one() {
2272        // The aggregate `e2e RED` label says the round's overall verdict,
2273        // never which of several `verify.e2e` commands actually failed —
2274        // `magi show` must list each command by name, the same way it
2275        // already does for `gate`.
2276        let _guard = plain();
2277        let mut s = state();
2278        s.reviews = vec![ReviewRound {
2279            round: 1,
2280            head: "abc1234".to_owned(),
2281            verified_head: Some("abc1234".to_owned()),
2282            verified_at: Some(jiff::Timestamp::now()),
2283            reviews: Vec::new(),
2284            e2e: vec![
2285                CommandOutcome {
2286                    command: "cargo test --locked --all-targets".to_owned(),
2287                    code: Some(0),
2288                    output_tail: String::new(),
2289                    duration_ms: 0,
2290                    resource_blocked: false,
2291                },
2292                CommandOutcome {
2293                    command: "cargo make check".to_owned(),
2294                    code: Some(1),
2295                    output_tail: "clippy: unused import".to_owned(),
2296                    duration_ms: 0,
2297                    resource_blocked: false,
2298                },
2299            ],
2300            verify_retried: false,
2301            e2e_deferred: false,
2302            e2e_defer_reason: None,
2303            fix: None,
2304            blocking: 0,
2305            answered: 0,
2306            expected: 0,
2307            clean: false,
2308            progressed: false,
2309            vote_split: false,
2310            reconsideration: Vec::new(),
2311            verdict: None,
2312        }];
2313        let text = run(&s);
2314        assert!(text.contains("cargo test --locked --all-targets"), "{text}");
2315        assert!(text.contains("cargo make check"), "{text}");
2316        assert!(text.contains("clippy: unused import"), "{text}");
2317    }
2318
2319    #[test]
2320    fn a_declined_finding_shows_its_reason() {
2321        use crate::verdict::{Finding, Rejection, Severity};
2322
2323        let _guard = plain();
2324        let mut s = state();
2325        s.status = RunStatus::Ready;
2326        s.reviews = vec![ReviewRound {
2327            round: 1,
2328            head: "deadbee".to_owned(),
2329            verified_head: None,
2330            verified_at: None,
2331            reviews: vec![ReviewRecord {
2332                attempts: 0,
2333                reviewer: 1,
2334                agent: "alpha".to_owned(),
2335                summary: String::new(),
2336                findings: vec![Finding {
2337                    id: "R1-1-1".to_owned(),
2338                    severity: Severity::Major,
2339                    file: None,
2340                    line: None,
2341                    title: "still open".to_owned(),
2342                    detail: String::new(),
2343                }],
2344                vote: None,
2345                failed: None,
2346                duration_ms: 0,
2347            }],
2348            e2e: vec![CommandOutcome {
2349                command: "cargo test".to_owned(),
2350                code: Some(0),
2351                output_tail: String::new(),
2352                duration_ms: 0,
2353                resource_blocked: false,
2354            }],
2355            verify_retried: false,
2356            e2e_deferred: false,
2357            e2e_defer_reason: None,
2358            fix: Some(FixRecord {
2359                agent: "alpha".to_owned(),
2360                addressed: Vec::new(),
2361                rejected: vec![Rejection {
2362                    id: "R1-1-2".to_owned(),
2363                    why: "cannot be triggered from any caller".to_owned(),
2364                }],
2365                notes: String::new(),
2366                committed: true,
2367                failed: None,
2368                duration_ms: 0,
2369                continuation: None,
2370            }),
2371            blocking: 1,
2372            answered: 1,
2373            expected: 1,
2374            clean: false,
2375            progressed: true,
2376            vote_split: false,
2377            reconsideration: Vec::new(),
2378            verdict: None,
2379        }];
2380
2381        let text = run(&s);
2382        assert!(text.contains("R1-1-2"), "{text}");
2383        assert!(text.contains("cannot be triggered"), "{text}");
2384        assert!(text.contains("still open"), "{text}");
2385        assert!(
2386            text.contains("handed off"),
2387            "a mergeable run with an open round must say so: {text}"
2388        );
2389    }
2390
2391    #[test]
2392    fn a_failing_gate_command_shows_its_output() {
2393        let _guard = plain();
2394        let mut s = state();
2395        s.status = RunStatus::Blocked;
2396        s.gate = vec![CommandOutcome {
2397            command: "cargo make check".to_owned(),
2398            code: Some(101),
2399            output_tail: "error[E0308]: mismatched types".to_owned(),
2400            duration_ms: 0,
2401            resource_blocked: false,
2402        }];
2403        s.gate_ran = true;
2404
2405        let text = run(&s);
2406        assert!(text.contains("mismatched types"), "{text}");
2407    }
2408
2409    #[test]
2410    fn a_gate_with_no_commands_configured_shows_a_pass_not_silence() {
2411        let _guard = plain();
2412        let mut s = state();
2413        s.status = RunStatus::Ready;
2414        s.gate_ran = true;
2415        assert!(s.gate.is_empty());
2416
2417        let text = run(&s);
2418        assert!(
2419            text.contains("gate") && text.contains("no gate commands configured"),
2420            "a run gated on nothing must say so, not read as if the gate never ran: {text}"
2421        );
2422    }
2423
2424    #[test]
2425    fn a_gate_that_has_not_run_yet_shows_nothing() {
2426        let _guard = plain();
2427        let s = state();
2428        assert!(!s.gate_ran);
2429        assert!(s.gate.is_empty());
2430
2431        let text = run(&s);
2432        assert!(
2433            !text.contains("no gate commands configured"),
2434            "an unattempted gate must not be shown as a pass: {text}"
2435        );
2436    }
2437
2438    #[test]
2439    fn active_seats_shows_who_has_not_answered_and_how_long_is_left() {
2440        let _guard = plain();
2441        let mut s = state();
2442        s.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
2443        let text = active_seats(&s, Liveness::Live);
2444        assert!(text.contains("running now"));
2445        assert!(text.contains("judge-2"));
2446        assert!(text.contains("judge"));
2447        assert!(!text.contains("no live daemon"), "{text}");
2448        assert!(!text.contains("could not be confirmed"), "{text}");
2449    }
2450
2451    #[test]
2452    fn active_seats_flags_a_leftover_from_a_dead_process() {
2453        let _guard = plain();
2454        let mut s = state();
2455        s.seat_started("implement", "impl-B", std::time::Duration::from_secs(60), 0);
2456        let text = active_seats(&s, Liveness::Dead);
2457        assert!(
2458            text.contains("no live daemon"),
2459            "a stale entry must not read as running: {text}"
2460        );
2461    }
2462
2463    #[test]
2464    fn superseded_notice_names_the_run_that_replaced_it() {
2465        let _guard = plain();
2466        let text = superseded_notice(Some("bbbb"));
2467        assert!(text.contains("SUPERSEDED"), "{text}");
2468        assert!(text.contains("bbbb"), "{text}");
2469    }
2470
2471    #[test]
2472    fn superseded_notice_is_silent_for_the_latest_attempt() {
2473        let _guard = plain();
2474        assert_eq!(superseded_notice(None), "");
2475    }
2476
2477    #[test]
2478    fn list_line_marks_a_nonterminal_run_with_a_dead_driver_stale() {
2479        let _guard = plain();
2480        let mut s = state();
2481        s.status = RunStatus::Reviewing;
2482        let text = line_with_liveness(&s, Liveness::Dead);
2483        assert!(text.contains("STALE"), "{text}");
2484        assert!(text.contains("resume required"), "{text}");
2485        assert!(liveness_notice(&s, Liveness::Dead).contains("STALE"));
2486    }
2487
2488    /// A manual `magi run` / `magi review` claims no daemon, but its
2489    /// `driver_pid` still answers — this is `Unknown`, never `Dead`: see
2490    /// `RunState::liveness`'s own doc for why an unconfirmed process is never
2491    /// folded into "confirmed dead".
2492    #[test]
2493    fn active_seats_reports_uncertainty_without_claiming_death() {
2494        let _guard = plain();
2495        let mut s = state();
2496        s.seat_started("review", "review-1", std::time::Duration::from_secs(60), 0);
2497        let text = active_seats(&s, Liveness::Unknown);
2498        assert!(
2499            text.contains("could not be confirmed"),
2500            "an unproven state must read as uncertain, not dead: {text}"
2501        );
2502        assert!(!text.contains("no live daemon"), "{text}");
2503    }
2504
2505    #[test]
2506    fn active_seats_is_empty_when_nothing_is_running() {
2507        let _guard = plain();
2508        assert_eq!(active_seats(&state(), Liveness::Live), "");
2509    }
2510
2511    /// A running `verify.e2e` / `verify.gate` task is shown alongside seats,
2512    /// with which command is currently running and how far through the list
2513    /// it is — the gap the addendum's second item names: a review-only run
2514    /// that spends minutes inside `cargo test` between reviewer answers and
2515    /// the fix's own commit had nothing at all to show for it before this.
2516    #[test]
2517    fn active_seats_shows_a_running_verify_task_and_its_command() {
2518        let _guard = plain();
2519        let mut s = state();
2520        s.task_command(
2521            "e2e",
2522            "verify",
2523            0,
2524            "cargo test",
2525            2,
2526            3,
2527            std::time::Duration::from_secs(600),
2528        );
2529        let text = active_seats(&s, Liveness::Live);
2530        assert!(text.contains("e2e"), "{text}");
2531        assert!(text.contains("(2/3)"), "{text}");
2532        assert!(text.contains("cargo test"), "{text}");
2533    }
2534
2535    #[test]
2536    fn no_jobs_section_appears_when_nothing_was_ever_collected() {
2537        let _guard = plain();
2538        // The common case today (every backend but codex): silence, not a
2539        // clutter line repeated on every single `magi show`.
2540        assert!(!run(&state()).contains("background jobs"));
2541    }
2542
2543    #[test]
2544    fn a_codex_roster_with_no_completed_jobs_yet_says_so_instead_of_staying_silent() {
2545        let _guard = plain();
2546        let mut s = state();
2547        s.config.agents.push(crate::config::AgentSpec {
2548            id: "codex-one".to_owned(),
2549            kind: crate::config::AgentKind::Codex,
2550            model: None,
2551            command: vec!["codex".to_owned()],
2552            extra_args: Vec::new(),
2553            env: BTreeMap::new(),
2554            prompt_delivery: None,
2555        });
2556        let text = run(&s);
2557        assert!(
2558            text.contains("background jobs"),
2559            "a run that could report this must not read the same as one that never could: \
2560             {text}"
2561        );
2562        assert!(text.contains("no completed command evidence yet"));
2563    }
2564
2565    #[test]
2566    fn recovered_running_and_unreadable_jobs_are_told_apart() {
2567        let _guard = plain();
2568        let mut s = state();
2569        s.jobs = vec![
2570            crate::run::JobRecord {
2571                node: "implement".to_owned(),
2572                round: None,
2573                seat: "impl-A".to_owned(),
2574                id: "item49".to_owned(),
2575                description: "cargo test --test graph_cached_gate".to_owned(),
2576                checked_at: jiff::Timestamp::now(),
2577                status: crate::run::JobStatus::Completed,
2578                exit_code: Some(0),
2579                result_summary: "test result: 2 passed; 0 failed".to_owned(),
2580                source: "codex".to_owned(),
2581            },
2582            crate::run::JobRecord {
2583                node: "fix".to_owned(),
2584                round: None,
2585                seat: "impl-A".to_owned(),
2586                id: "item52".to_owned(),
2587                description: "cargo test --test graph_split".to_owned(),
2588                checked_at: jiff::Timestamp::now(),
2589                status: crate::run::JobStatus::Failed,
2590                exit_code: Some(101),
2591                result_summary: "test result: 1 passed; 1 failed".to_owned(),
2592                source: "codex".to_owned(),
2593            },
2594            crate::run::JobRecord {
2595                node: "fix".to_owned(),
2596                round: None,
2597                seat: "impl-A".to_owned(),
2598                id: "item60".to_owned(),
2599                description: "cargo build".to_owned(),
2600                checked_at: jiff::Timestamp::now(),
2601                status: crate::run::JobStatus::Unknown,
2602                exit_code: None,
2603                result_summary: String::new(),
2604                source: "codex".to_owned(),
2605            },
2606        ];
2607        let text = run(&s);
2608        assert!(text.contains("background jobs"));
2609        assert!(text.contains("item49"));
2610        assert!(text.contains("item52"));
2611        assert!(text.contains("item60"));
2612        // The three states this run actually has evidence for must read
2613        // differently from one another — never collapsed into a single
2614        // "ran" or "did not run".
2615        assert!(text.contains("completed"));
2616        assert!(text.contains("failed"));
2617        assert!(text.contains("unknown"));
2618        // Coverage limit stated once, not fabricated per seat.
2619        assert!(text.contains("adapter coverage"));
2620    }
2621
2622    #[test]
2623    fn a_jobs_own_round_is_shown_when_known() {
2624        let _guard = plain();
2625        let mut s = state();
2626        s.jobs = vec![crate::run::JobRecord {
2627            node: "review".to_owned(),
2628            round: Some(2),
2629            seat: "review-1".to_owned(),
2630            id: "item9".to_owned(),
2631            description: "cargo test --test graph_cached_gate".to_owned(),
2632            checked_at: jiff::Timestamp::now(),
2633            status: crate::run::JobStatus::Completed,
2634            exit_code: Some(0),
2635            result_summary: "test result: 2 passed; 0 failed".to_owned(),
2636            source: "codex".to_owned(),
2637        }];
2638        let text = run(&s);
2639        assert!(
2640            text.contains("round 2"),
2641            "the round this seat's own command ran in must be visible, distinct from magi's \
2642             own recorded verify: {text}"
2643        );
2644    }
2645
2646    #[test]
2647    fn stats_table_renders_without_runs() {
2648        let _guard = plain();
2649        let text = stats(&Stats::default());
2650        assert!(text.contains("0 total"));
2651        assert!(!text.contains("implementation"));
2652        assert!(!text.contains("node durations"));
2653    }
2654
2655    #[test]
2656    fn repo_summary_lists_run_count_and_completion_rate() {
2657        let _guard = plain();
2658        let a = crate::stats::RepoStats {
2659            repo: PathBuf::from("/repos/a"),
2660            name: "a".to_owned(),
2661            stats: Stats {
2662                totals: crate::stats::Totals {
2663                    runs: 4,
2664                    merged: 2,
2665                    ready: 1,
2666                    ..Default::default()
2667                },
2668                ..Default::default()
2669            },
2670        };
2671        let text = repo_summary(&[a]);
2672        assert!(text.contains("repos"), "{text}");
2673        assert!(text.contains("a  4 runs  75% completion"), "{text}");
2674    }
2675
2676    #[test]
2677    fn repo_summary_disambiguates_colliding_names_with_the_parent_directory() {
2678        let _guard = plain();
2679        let a = crate::stats::RepoStats {
2680            repo: PathBuf::from("/roots/one/magi"),
2681            name: "magi".to_owned(),
2682            stats: Stats::default(),
2683        };
2684        let b = crate::stats::RepoStats {
2685            repo: PathBuf::from("/roots/two/magi"),
2686            name: "magi".to_owned(),
2687            stats: Stats::default(),
2688        };
2689        let text = repo_summary(&[a, b]);
2690        assert!(text.contains("magi (one)"), "{text}");
2691        assert!(text.contains("magi (two)"), "{text}");
2692    }
2693
2694    #[test]
2695    fn stats_table_renders_advisor_reflection() {
2696        let _guard = plain();
2697        let st = Stats {
2698            advisors: vec![crate::stats::AdvisorStats {
2699                agent: "alpha".to_owned(),
2700                seated: 3,
2701                proposed: 2,
2702                absent: 1,
2703                faint: 1,
2704                strong: 1,
2705            }],
2706            ..Default::default()
2707        };
2708        let text = stats(&st);
2709        assert!(text.contains("design deliberation"));
2710        assert!(
2711            text.contains("approximate"),
2712            "must note the heuristic: {text}"
2713        );
2714        assert!(text.contains("alpha"));
2715        assert!(text.contains("50%"));
2716    }
2717
2718    #[test]
2719    fn stats_table_shows_release_bump_coverage_even_when_nothing_was_recorded() {
2720        // A repository that has merged runs but never wired up (or never hit)
2721        // the release-bump step must still show "0 of N merged runs recorded
2722        // a bump" - hiding the whole section on `recorded == 0` would make
2723        // that gap invisible instead of reporting it.
2724        let _guard = plain();
2725        let st = Stats {
2726            release_bumps: crate::stats::ReleaseBumpStats {
2727                merged: 3,
2728                ..Default::default()
2729            },
2730            ..Default::default()
2731        };
2732        let text = stats(&st);
2733        assert!(text.contains("release bumps"), "{text}");
2734        assert!(
2735            text.contains("0 of 3 merged run(s) recorded a bump"),
2736            "{text}"
2737        );
2738    }
2739
2740    #[test]
2741    fn stats_table_renders_release_bump_coverage_and_attention() {
2742        let _guard = plain();
2743        let st = Stats {
2744            release_bumps: crate::stats::ReleaseBumpStats {
2745                merged: 4,
2746                recorded: 2,
2747                pr_opened: 2,
2748                automerge_enabled: 1,
2749                merged_directly: 0,
2750                needs_attention: 1,
2751            },
2752            ..Default::default()
2753        };
2754        let text = stats(&st);
2755        assert!(text.contains("release bumps"), "{text}");
2756        assert!(
2757            text.contains("2 of 4 merged run(s) recorded a bump (50%)"),
2758            "{text}"
2759        );
2760        assert!(text.contains("1 clean, 1 needed a human (50%)"), "{text}");
2761    }
2762
2763    #[test]
2764    fn stats_table_renders_node_durations_with_a_bar_and_unmeasured_count() {
2765        let _guard = plain();
2766        let st = Stats {
2767            nodes: vec![
2768                crate::stats::NodeDuration {
2769                    node: "implement".to_owned(),
2770                    runs: 2,
2771                    total_secs: 200,
2772                    max_secs: 150,
2773                    single: 1,
2774                },
2775                crate::stats::NodeDuration {
2776                    node: "gate".to_owned(),
2777                    runs: 0,
2778                    total_secs: 0,
2779                    max_secs: 0,
2780                    single: 3,
2781                },
2782            ],
2783            ..Default::default()
2784        };
2785        let text = stats(&st);
2786        assert!(text.contains("node durations"));
2787        assert!(text.contains("implement"));
2788        assert!(text.contains("2 runs"));
2789        assert!(text.contains('█'), "the leader must draw a bar: {text}");
2790        assert!(text.contains("1 unmeasured"));
2791        assert!(text.contains("gate"));
2792        assert!(text.contains("3 unmeasured"));
2793        assert!(!text.contains('\x1b'), "colour leaked into a plain render");
2794    }
2795
2796    #[test]
2797    fn implementation_rates_use_independent_low_n_boundaries() {
2798        let _guard = plain();
2799        for (competitive_n, solo_n) in [(9, 10), (10, 9)] {
2800            let text = stats(&Stats {
2801                agents: vec![crate::stats::AgentStats {
2802                    agent: "alpha".to_owned(),
2803                    competitive_entered: competitive_n,
2804                    competitive_wins: 1,
2805                    solo_entered: solo_n,
2806                    solo_adopted: 2,
2807                    ..Default::default()
2808                }],
2809                ..Default::default()
2810            });
2811            let (competitive, solo) = text
2812                .split_once("implementation (solo runs, completion/adoption rate)")
2813                .unwrap();
2814            for (section, n, numerator) in [(competitive, competitive_n, 1), (solo, solo_n, 2)] {
2815                let row = section.lines().find(|line| line.contains("alpha")).unwrap();
2816                let cells: Vec<_> = row.split_whitespace().collect();
2817                assert_eq!(cells[1], numerator.to_string());
2818                assert_eq!(cells[2], n.to_string());
2819                assert_eq!(row.contains("low n"), n < 10);
2820            }
2821        }
2822    }
2823
2824    #[test]
2825    fn stats_table_renders_competitive_and_solo_tables_with_low_n() {
2826        let _guard = plain();
2827        let st = Stats {
2828            agents: vec![
2829                crate::stats::AgentStats {
2830                    agent: "alpha".to_owned(),
2831                    entered: 15,
2832                    wins: 10,
2833                    empty: 0,
2834                    competitive_entered: 12,
2835                    competitive_wins: 9,
2836                    solo_entered: 3,
2837                    solo_adopted: 1,
2838                },
2839                crate::stats::AgentStats {
2840                    agent: "beta".to_owned(),
2841                    entered: 5,
2842                    wins: 2,
2843                    empty: 1,
2844                    competitive_entered: 4,
2845                    competitive_wins: 2,
2846                    solo_entered: 1,
2847                    solo_adopted: 0,
2848                },
2849            ],
2850            ..Default::default()
2851        };
2852        let text = stats(&st);
2853        assert!(text.contains("implementation (competitive runs, 2+ candidates)"));
2854        assert!(text.contains("alpha"));
2855        assert!(text.contains("75%"));
2856        assert!(text.contains("beta"));
2857        assert!(text.contains("50%"));
2858        assert!(text.contains("implementation (solo runs, completion/adoption rate)"));
2859        assert!(text.contains("33%"));
2860        assert!(text.contains("low n"));
2861    }
2862}