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