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