Skip to main content

magi/
report.rs

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