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.local {
1016                dim(
1017                    "not used (release.mode = local: merged on your approval, released by magi serve)",
1018                )
1019            } else if b.problem.is_some() {
1020                bold(&red("FAILED"))
1021            } else {
1022                dim("not enabled")
1023            }
1024        );
1025        if let Some(p) = &b.problem {
1026            let _ = writeln!(s, "  {}", p.lines().next().unwrap_or(""));
1027        }
1028        if let Some(j) = &b.release {
1029            let state = if j.finished {
1030                "finished"
1031            } else {
1032                j.failed.as_deref().unwrap_or("unfinished")
1033            };
1034            let _ = writeln!(s, "  release {} at {}: {state}", j.tag(), j.commit);
1035            for l in &j.log {
1036                let code = l.code.map_or("none".to_owned(), |c| c.to_string());
1037                let _ = write!(s, "    {} (exit {code})", l.name);
1038                if let Some(o) = &l.output {
1039                    let _ = write!(s, " output {o}");
1040                }
1041                let _ = writeln!(s);
1042            }
1043        }
1044        if let Some(a) = &b.action_required {
1045            let _ = writeln!(s, "  {} {a}", bold(&yellow("action required:")));
1046        }
1047    }
1048
1049    if !state.leaks.is_empty() {
1050        let _ = writeln!(s, "\n{}", bold(&yellow("blindness warnings")));
1051        for l in &state.leaks {
1052            let _ = writeln!(s, "  {} x{} in {}", l.token, l.count, l.site);
1053        }
1054    }
1055
1056    if let Some(w) = state.winner()
1057        && !w.folded
1058    {
1059        let _ = writeln!(
1060            s,
1061            "\n{} {}\n  branch {}",
1062            bold("winner worktree"),
1063            w.worktree.display(),
1064            w.branch
1065        );
1066    }
1067    s.push_str(&jobs_section(state));
1068    s
1069}
1070
1071/// The seats currently mid-answer, for `magi show` and the raw report route.
1072///
1073/// Separate from [`run`] on purpose: [`run`] is printed straight after `magi
1074/// run` / `magi review`'s own `execute()`, and by then this process has
1075/// nothing left in flight to report; the TUI does not track daemon liveness
1076/// either. Only a caller reading someone *else's* run — `magi show <id>`, or
1077/// the web UI's raw-report route — needs this, and both already know how to
1078/// ask whether a daemon is currently driving it.
1079///
1080/// `live` is [`RunState::liveness`]: whether a daemon's heartbeat currently
1081/// names this run, or — absent that claim — whether `driver_pid` still
1082/// answers alive. An [`ActiveSeat`](crate::run::ActiveSeat) left behind by a
1083/// killed process is not lied about as running just because nobody has
1084/// cleared it from disk yet — see that type's own docs for why an entry
1085/// alone is not proof of anything.
1086pub fn active_seats(state: &RunState, live: Liveness) -> String {
1087    if state.active.is_empty() {
1088        return String::new();
1089    }
1090    let mut s = String::new();
1091    let _ = writeln!(s, "\n{}", bold("running now"));
1092    let now = jiff::Timestamp::now();
1093    match live {
1094        Liveness::Live => {}
1095        Liveness::Dead => {
1096            let _ = writeln!(
1097                s,
1098                "  {}",
1099                yellow(
1100                    "no live daemon claims this run right now — likely left behind by a killed process"
1101                )
1102            );
1103        }
1104        Liveness::Unknown => {
1105            // `active_all_overrun` is never treated as proof of death here —
1106            // only ever mentioned alongside "could not confirm", since a
1107            // seat legitimately overrunning its budget while the process
1108            // driving it tears the attempt down looks identical on disk (see
1109            // `RunState::active_all_overrun`'s own doc).
1110            let overrun = if state.active_all_overrun(now) {
1111                " — every active seat has already run past its own timeout budget"
1112            } else {
1113                ""
1114            };
1115            let _ = writeln!(
1116                s,
1117                "  {}",
1118                yellow(&format!(
1119                    "whether a process is still driving this run could not be confirmed{overrun}"
1120                ))
1121            );
1122        }
1123    }
1124    for (seat, a) in state.seats_active() {
1125        let retry = if a.attempt > 0 {
1126            format!(" retry {}", a.attempt)
1127        } else {
1128            String::new()
1129        };
1130        let _ = writeln!(
1131            s,
1132            "  {:<12} {:<12}{retry}  {}s elapsed, {}s left of {}s",
1133            seat,
1134            a.node,
1135            a.elapsed_secs(now),
1136            a.remaining_secs(now),
1137            a.timeout_secs
1138        );
1139    }
1140    for (task, a) in state.tasks_active() {
1141        let retry = if a.attempt > 0 {
1142            format!(" retry {}", a.attempt)
1143        } else {
1144            String::new()
1145        };
1146        let progress = match (a.index, a.total) {
1147            (Some(i), Some(t)) => format!(" ({i}/{t})"),
1148            _ => String::new(),
1149        };
1150        let _ = writeln!(
1151            s,
1152            "  {:<12} {:<12}{retry}{progress}  {}s elapsed, {}s left of {}s",
1153            task,
1154            a.node,
1155            a.elapsed_secs(now),
1156            a.remaining_secs(now),
1157            a.timeout_secs
1158        );
1159        if let Some(command) = &a.command {
1160            let _ = writeln!(s, "               {command}");
1161        }
1162    }
1163    s
1164}
1165
1166/// Render a whole number of seconds as `1h02m`, `3m05s` or `42s`.
1167fn fmt_secs(secs: i64) -> String {
1168    let secs = secs.max(0);
1169    let h = secs / 3600;
1170    let m = (secs % 3600) / 60;
1171    let s = secs % 60;
1172    if h > 0 {
1173        format!("{h}h{m:02}m")
1174    } else if m > 0 {
1175        format!("{m}m{s:02}s")
1176    } else {
1177        format!("{s}s")
1178    }
1179}
1180
1181/// A fixed-width text bar, `value` proportional to `max` out of `width` cells.
1182///
1183/// Any positive value draws at least one cell, so a short-but-nonzero
1184/// duration is never mistaken for an unmeasured one.
1185fn bar(value: f64, max: f64, width: usize) -> String {
1186    if max <= 0.0 || value <= 0.0 {
1187        return String::new();
1188    }
1189    let cells = ((value / max) * width as f64)
1190        .round()
1191        .clamp(1.0, width as f64) as usize;
1192    "█".repeat(cells)
1193}
1194
1195/// Per-repository summary table: repo name, run count, completion rate.
1196///
1197/// `main.rs`'s `Command::Stats` is what decides *whether* to print this —
1198/// only ahead of the plain (no `--repo`) report, and only when `repos.len() >
1199/// 1` — this function only renders whatever it is handed.
1200pub fn repo_summary(repos: &[RepoStats]) -> String {
1201    let mut s = String::new();
1202    let _ = writeln!(s, "{}", bold("repos"));
1203
1204    // Two different checkouts can share a leaf directory name (`magi` under
1205    // two different roots); disambiguate only those with their parent
1206    // directory rather than paying the extra noise on every row.
1207    let mut name_counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
1208    for r in repos {
1209        *name_counts.entry(r.name.as_str()).or_insert(0) += 1;
1210    }
1211
1212    for r in repos {
1213        let label = if name_counts.get(r.name.as_str()).copied().unwrap_or(0) > 1 {
1214            match r.repo.parent().and_then(|p| p.file_name()) {
1215                Some(parent) => format!("{} ({})", r.name, parent.to_string_lossy()),
1216                None => r.name.clone(),
1217            }
1218        } else {
1219            r.name.clone()
1220        };
1221        let _ = writeln!(
1222            s,
1223            "  {}  {} runs  {:.0}% completion",
1224            label,
1225            r.stats.totals.runs,
1226            r.stats.totals.completion_rate()
1227        );
1228    }
1229    s
1230}
1231
1232/// Aggregate tables, for `magi stats`.
1233pub fn stats(stats: &Stats) -> String {
1234    let t = &stats.totals;
1235    let mut s = String::new();
1236    let _ = writeln!(s, "{}", bold("runs"));
1237    let _ = writeln!(
1238        s,
1239        "  {} total - {} merged, {} ready, {} blocked, {} failed ({:.0}% completion)",
1240        t.runs,
1241        t.merged,
1242        t.ready,
1243        t.blocked,
1244        t.failed,
1245        t.completion_rate()
1246    );
1247    if t.tallied > 0 {
1248        let _ = writeln!(
1249            s,
1250            "  {} tallied - {} split on first choice ({:.0}%), {} deliberated, \
1251             {} of those changed a mind, {} converged to unanimous",
1252            t.tallied,
1253            t.split,
1254            t.split_rate(),
1255            t.deliberated,
1256            t.minds_changed,
1257            t.converged
1258        );
1259    }
1260
1261    if !stats.agents.is_empty() {
1262        let _ = writeln!(
1263            s,
1264            "\n{}",
1265            bold("implementation (relative, on this workload)")
1266        );
1267        let _ = writeln!(
1268            s,
1269            "  {:<14}{:>6}{:>8}{:>8}{:>8}",
1270            "agent", "won", "entered", "rate", "empty"
1271        );
1272        for a in &stats.agents {
1273            let _ = writeln!(
1274                s,
1275                "  {:<14}{:>6}{:>8}{:>7.0}%{:>8}",
1276                a.agent,
1277                a.wins,
1278                a.entered,
1279                a.win_rate(),
1280                a.empty
1281            );
1282        }
1283    }
1284
1285    if !stats.reviewers.is_empty() {
1286        let _ = writeln!(s, "\n{}", bold("review"));
1287        let _ = writeln!(
1288            s,
1289            "  {:<14}{:>8}{:>10}{:>11}{:>9}{:>9}{:>9}",
1290            "reviewer", "rounds", "submitted", "adopted/rd", "precision", "unique", "timeout"
1291        );
1292        for r in &stats.reviewers {
1293            let _ = writeln!(
1294                s,
1295                "  {:<14}{:>8}{:>10}{:>11.2}{:>8.0}%{:>8.0}%{:>8.0}%",
1296                r.agent,
1297                r.rounds,
1298                r.submitted,
1299                r.adopted_per_round(),
1300                r.precision(),
1301                r.unique_rate(),
1302                r.timeout_rate()
1303            );
1304        }
1305    }
1306
1307    if !stats.advisors.is_empty() {
1308        let _ = writeln!(
1309            s,
1310            "\n{} {}",
1311            bold("design deliberation"),
1312            dim(
1313                "(approximate: reflection is read off word overlap with the synthesis brief, not a precise attribution)"
1314            )
1315        );
1316        let _ = writeln!(
1317            s,
1318            "  {:<14}{:>7}{:>10}{:>8}{:>8}{:>9}{:>10}",
1319            "advisor", "seats", "proposed", "strong", "faint", "absent", "reflect%"
1320        );
1321        for a in &stats.advisors {
1322            let _ = writeln!(
1323                s,
1324                "  {:<14}{:>7}{:>10}{:>8}{:>8}{:>9}{:>9.0}%",
1325                a.agent,
1326                a.seated,
1327                a.proposed,
1328                a.strong,
1329                a.faint,
1330                a.absent,
1331                a.reflection_rate()
1332            );
1333        }
1334    }
1335
1336    if stats.release_bumps.merged > 0 {
1337        let b = &stats.release_bumps;
1338        let _ = writeln!(s, "\n{}", bold("release bumps"));
1339        let _ = writeln!(
1340            s,
1341            "  {} of {} merged run(s) recorded a bump ({:.0}%)",
1342            b.recorded,
1343            b.merged,
1344            b.coverage_rate()
1345        );
1346        let _ = writeln!(
1347            s,
1348            "  {} release PR(s) opened, {} automerge enabled ({:.0}%), {} merged directly",
1349            b.pr_opened,
1350            b.automerge_enabled,
1351            b.automerge_rate(),
1352            b.merged_directly
1353        );
1354        let _ = writeln!(
1355            s,
1356            "  {} clean, {} needed a human ({:.0}%)",
1357            b.clean(),
1358            b.needs_attention,
1359            b.attention_rate()
1360        );
1361    }
1362
1363    if stats.e2e.rounds > 0 || stats.e2e.deferred > 0 {
1364        let _ = writeln!(s, "\n{}", bold("verification"));
1365        let _ = writeln!(
1366            s,
1367            "  {} rounds ran e2e, {} failed, {} of those with a clean static \
1368             review ({:.0}% sole detections), {} round(s) deferred it to the fixer",
1369            stats.e2e.rounds,
1370            stats.e2e.failures,
1371            stats.e2e.sole_detections,
1372            stats.e2e.sole_rate(),
1373            stats.e2e.deferred
1374        );
1375    }
1376
1377    if !stats.nodes.is_empty() {
1378        let _ = writeln!(
1379            s,
1380            "\n{}",
1381            bold("node durations (first to last event, per run)")
1382        );
1383        let max_mean = stats
1384            .nodes
1385            .iter()
1386            .map(|n| n.mean_secs())
1387            .fold(0.0_f64, f64::max);
1388        for n in &stats.nodes {
1389            let unmeasured = if n.single > 0 {
1390                format!("  {}", dim(&format!("{} unmeasured", n.single)))
1391            } else {
1392                String::new()
1393            };
1394            let _ = writeln!(
1395                s,
1396                "  {:<14}{:>6} runs{:>8} mean{:>8} max  {}{unmeasured}",
1397                n.node,
1398                n.runs,
1399                fmt_secs(n.mean_secs().round() as i64),
1400                fmt_secs(n.max_secs),
1401                bar(n.mean_secs(), max_mean, 20)
1402            );
1403        }
1404    }
1405    s
1406}
1407
1408#[cfg(test)]
1409mod tests {
1410    use super::*;
1411    use crate::config::Config;
1412    use crate::run::{
1413        Candidate, CommandOutcome, FixRecord, MergeOutcome, ReviewRecord, ReviewRound, RunState,
1414        Tally,
1415    };
1416    use std::collections::BTreeMap;
1417    use std::path::PathBuf;
1418    use std::sync::{Mutex, MutexGuard};
1419
1420    /// `COLOR` is process-global, so these tests cannot run concurrently.
1421    static SERIAL: Mutex<()> = Mutex::new(());
1422
1423    fn plain() -> MutexGuard<'static, ()> {
1424        let guard = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
1425        set_color(false);
1426        guard
1427    }
1428
1429    fn state() -> RunState {
1430        // `run()` prints `state.dir()`, which reads the process-global home;
1431        // pinning it here keeps this test off the operator's real one. The
1432        // directory itself is never read, only its path printed, so nothing
1433        // needs to create or clean it up.
1434        crate::run::pin_test_home();
1435        let mut s = RunState::new(
1436            PathBuf::from("/repo"),
1437            "main".to_owned(),
1438            "abcdef1234".to_owned(),
1439            "add retries to the uploader".to_owned(),
1440            Config::default(),
1441        );
1442        s.candidates = vec![Candidate {
1443            index: 0,
1444            label: 'A',
1445            agent: "opus".to_owned(),
1446            branch: "magi/x/A".to_owned(),
1447            worktree: PathBuf::from("/wt/A"),
1448            summary: String::new(),
1449            stat: String::new(),
1450            files: 3,
1451            commits: 2,
1452            empty: false,
1453            failed: None,
1454            verified_noop: None,
1455            duration_ms: 42_000,
1456            folded: false,
1457        }];
1458        s.tally = Some(Tally {
1459            first_choice: BTreeMap::from([('A', 3)]),
1460            borda: BTreeMap::new(),
1461            winner: 'A',
1462            rankings: 3,
1463            unanimous_initial: true,
1464            deliberated: false,
1465            changed_votes: 0,
1466            unanimous_final: true,
1467            tie_break: None,
1468            judges: 3,
1469            present: 3,
1470            quorum: 2,
1471            met_quorum: true,
1472            uncontested: None,
1473        });
1474        s
1475    }
1476
1477    #[test]
1478    fn run_report_names_the_winner_and_its_author() {
1479        let _guard = plain();
1480        let text = run(&state());
1481        assert!(text.contains("<- winner"), "{text}");
1482        assert!(text.contains("opus"));
1483        assert!(text.contains("3 files, 2 commits"));
1484        assert!(text.contains("winner        A"));
1485        assert!(!text.contains('\x1b'), "colour leaked into a plain render");
1486    }
1487
1488    #[test]
1489    fn a_candidates_own_summary_is_surfaced_not_only_kept_in_run_json() {
1490        // Recorded on every run (`prompt::implement`'s `## SUMMARY`), but
1491        // `run()` used to never print it at all — silent even when the
1492        // summary was the one place an implementer explained itself (e.g.
1493        // an investigation task's findings), and readable only by opening
1494        // `run.json` by hand.
1495        let _guard = plain();
1496        let mut s = state();
1497        s.candidates[0].summary =
1498            "investigated 6c5e/8df3: both already merged, see talk 07fe.\nmore detail below."
1499                .to_owned();
1500        let text = run(&s);
1501        assert!(
1502            text.contains("investigated 6c5e/8df3: both already merged, see talk 07fe."),
1503            "{text}"
1504        );
1505    }
1506
1507    #[test]
1508    fn a_verified_noop_run_does_not_read_as_a_failure() {
1509        // Same spirit as `a_mode_none_merge_does_not_read_as_landed`: a run
1510        // that settled without landing anything must not be misreadable as
1511        // the ordinary failure it is not.
1512        let _guard = plain();
1513        let mut s = state();
1514        s.status = RunStatus::VerifiedNoop;
1515        s.tally = None;
1516        s.candidates = vec![Candidate {
1517            index: 0,
1518            label: 'A',
1519            agent: "opus".to_owned(),
1520            branch: "magi/x/A".to_owned(),
1521            worktree: PathBuf::from("/wt/A"),
1522            summary: String::new(),
1523            stat: String::new(),
1524            files: 0,
1525            commits: 0,
1526            empty: true,
1527            failed: None,
1528            verified_noop: Some("already fixed by b32cfc4, which is on main".to_owned()),
1529            duration_ms: 9_000,
1530            folded: false,
1531        }];
1532        let text = run(&s);
1533        assert!(
1534            text.contains("agent-verified no-op"),
1535            "the status and the candidate flag must both say so: {text}"
1536        );
1537        assert!(
1538            text.contains("already fixed by b32cfc4"),
1539            "the evidence itself must be readable, not just the verdict: {text}"
1540        );
1541        assert!(
1542            !text.to_lowercase().contains("failed"),
1543            "a verified no-op must never read as the failure it is not: {text}"
1544        );
1545    }
1546
1547    #[test]
1548    fn colour_is_emitted_only_when_enabled() {
1549        let _guard = plain();
1550        set_color(true);
1551        let coloured = run(&state());
1552        set_color(false);
1553        let plain = run(&state());
1554        assert!(coloured.contains('\x1b'));
1555        assert!(!plain.contains('\x1b'));
1556        assert!(coloured.len() > plain.len());
1557    }
1558
1559    #[test]
1560    fn list_line_is_single_line() {
1561        let _guard = plain();
1562        let l = line(&state());
1563        assert_eq!(l.lines().count(), 1);
1564        assert!(l.contains("add retries"));
1565        assert!(l.contains("win A (opus)"));
1566    }
1567
1568    #[test]
1569    fn an_uncontested_run_does_not_read_as_a_collapsed_panel() {
1570        let _guard = plain();
1571        let mut s = state();
1572        s.tally = Some(Tally {
1573            first_choice: BTreeMap::from([('A', 0)]),
1574            borda: BTreeMap::new(),
1575            winner: 'A',
1576            rankings: 0,
1577            unanimous_initial: false,
1578            deliberated: false,
1579            changed_votes: 0,
1580            unanimous_final: false,
1581            tie_break: None,
1582            judges: 0,
1583            present: 0,
1584            quorum: 0,
1585            met_quorum: true,
1586            uncontested: Some(
1587                "only candidate A produced a usable change; no panel was asked".to_owned(),
1588            ),
1589        });
1590        let text = run(&s);
1591        assert!(
1592            !text.contains("0/3"),
1593            "no panel sat, so the judges line must not read as one that collapsed: {text}"
1594        );
1595        assert!(!text.contains("no usable ranking"), "{text}");
1596        assert!(!text.contains("still split"), "{text}");
1597        assert!(!text.contains("BELOW QUORUM"), "{text}");
1598        assert!(
1599            text.contains("not needed"),
1600            "the report must say judging was skipped, not silent: {text}"
1601        );
1602        assert!(text.contains("winner        A"));
1603    }
1604
1605    #[test]
1606    fn a_below_quorum_run_still_reads_as_a_collapsed_panel() {
1607        let _guard = plain();
1608        let mut s = state();
1609        s.tally = Some(Tally {
1610            first_choice: BTreeMap::from([('A', 1), ('B', 0)]),
1611            borda: BTreeMap::new(),
1612            winner: 'A',
1613            rankings: 1,
1614            unanimous_initial: false,
1615            deliberated: false,
1616            changed_votes: 0,
1617            unanimous_final: false,
1618            tie_break: None,
1619            judges: 3,
1620            present: 1,
1621            quorum: 2,
1622            met_quorum: false,
1623            uncontested: None,
1624        });
1625        let text = run(&s);
1626        assert!(text.contains("1/3"), "{text}");
1627        assert!(
1628            text.contains("BELOW QUORUM"),
1629            "a real collapse must still be flagged: {text}"
1630        );
1631        assert!(
1632            !text.contains("not needed"),
1633            "a collapsed panel must not be described as one that was never asked: {text}"
1634        );
1635    }
1636
1637    #[test]
1638    fn a_mode_none_merge_does_not_read_as_landed() {
1639        let _guard = plain();
1640        let mut s = state();
1641        s.merge = Some(MergeOutcome {
1642            mode: crate::config::MergeMode::None,
1643            ok: true,
1644            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
1645            empty: false,
1646        });
1647        let text = run(&s);
1648        assert!(
1649            !text.contains("  ok"),
1650            "mode none must not be shown as a landed merge: {text}"
1651        );
1652        assert!(text.contains("not landed"), "{text}");
1653        assert!(
1654            text.contains("branch magi/x/A"),
1655            "the report must say what's left behind: {text}"
1656        );
1657        assert!(
1658            text.contains("rebase"),
1659            "the report must point at the hand-landing steps: {text}"
1660        );
1661        assert!(
1662            !text.contains("placeholder subject"),
1663            "the default merge style is `merge`, which never inherits a \
1664             placeholder subject, so the squash caveat must not appear: {text}"
1665        );
1666    }
1667
1668    #[test]
1669    fn a_mode_none_squash_merge_warns_about_the_placeholder_subject() {
1670        let _guard = plain();
1671        let mut s = state();
1672        s.config.merge.style = MergeStyle::Squash;
1673        s.merge = Some(MergeOutcome {
1674            mode: crate::config::MergeMode::None,
1675            ok: true,
1676            detail: "git -C /repo merge --squash magi/x/A && git -C /repo commit -m \"add \
1677                      retries\""
1678                .to_owned(),
1679            empty: false,
1680        });
1681        let text = run(&s);
1682        assert!(
1683            text.contains("placeholder subject"),
1684            "a squash-style manual merge must warn about the missing message: {text}"
1685        );
1686        assert!(text.contains("--squash"), "{text}");
1687    }
1688
1689    #[test]
1690    fn a_ready_run_left_by_merge_mode_none_does_not_read_as_a_plain_ready() {
1691        let _guard = plain();
1692        let mut s = state();
1693        s.status = RunStatus::Ready;
1694        s.merge = Some(MergeOutcome {
1695            mode: crate::config::MergeMode::None,
1696            ok: true,
1697            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
1698            empty: false,
1699        });
1700
1701        let list = line(&s);
1702        assert!(
1703            !list.contains(" ready "),
1704            "a mode-none run must not read as a plain ready in `magi list`: {list}"
1705        );
1706        assert!(list.contains("no-op by design"), "{list}");
1707
1708        let full = run(&s);
1709        assert!(
1710            !full.contains("magi run") || !full.lines().next().unwrap().contains(" ready"),
1711            "the header line of `magi show` must not say plain ready either: {full}"
1712        );
1713        assert!(full.contains("no-op by design"), "{full}");
1714    }
1715
1716    #[test]
1717    fn an_ordinary_ready_run_still_reads_as_ready() {
1718        let _guard = plain();
1719        let mut s = state();
1720        s.status = RunStatus::Ready;
1721        // A PR closed without merging also ends at `Ready` (see `land.rs`),
1722        // and unlike the honest mode-none no-op it must keep reading as a
1723        // plain `ready` — the label exists to flag design, not every non-merge.
1724        s.merge = Some(MergeOutcome {
1725            mode: crate::config::MergeMode::Pr,
1726            ok: false,
1727            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
1728            empty: false,
1729        });
1730
1731        let list = line(&s);
1732        assert!(list.contains("ready"), "{list}");
1733        assert!(!list.contains("no-op by design"), "{list}");
1734    }
1735
1736    #[test]
1737    fn the_list_line_does_not_flag_an_uncontested_run_as_short_judges() {
1738        let _guard = plain();
1739        let mut s = state();
1740        s.tally = Some(Tally {
1741            first_choice: BTreeMap::from([('A', 0)]),
1742            borda: BTreeMap::new(),
1743            winner: 'A',
1744            rankings: 0,
1745            unanimous_initial: false,
1746            deliberated: false,
1747            changed_votes: 0,
1748            unanimous_final: false,
1749            tie_break: None,
1750            judges: 0,
1751            present: 0,
1752            quorum: 0,
1753            met_quorum: true,
1754            uncontested: Some("only candidate A produced a usable change".to_owned()),
1755        });
1756        let l = line(&s);
1757        assert!(
1758            !l.contains("judges") && !l.contains("quorum"),
1759            "an uncontested run must not carry the same badge a short panel gets: {l}"
1760        );
1761    }
1762
1763    #[test]
1764    fn long_instructions_are_elided() {
1765        let _guard = plain();
1766        let mut s = state();
1767        s.instruction = "x".repeat(200);
1768        assert!(line(&s).contains('…'));
1769    }
1770
1771    #[test]
1772    fn a_lost_fix_report_reads_differently_from_zero_adoption() {
1773        let _guard = plain();
1774        let mut lost = state();
1775        lost.reviews = vec![ReviewRound {
1776            round: 1,
1777            head: "abc1234".to_owned(),
1778            verified_head: None,
1779            verified_at: None,
1780            reviews: Vec::new(),
1781            e2e: Vec::new(),
1782            verify_retried: false,
1783            e2e_deferred: false,
1784            e2e_defer_reason: None,
1785            fix: Some(FixRecord {
1786                agent: "opus".to_owned(),
1787                addressed: Vec::new(),
1788                rejected: Vec::new(),
1789                notes: String::new(),
1790                committed: true,
1791                failed: Some("timed out".to_owned()),
1792                duration_ms: 0,
1793                continuation: None,
1794            }),
1795            blocking: 3,
1796            answered: 0,
1797            expected: 0,
1798            clean: false,
1799            progressed: false,
1800            vote_split: false,
1801            reconsideration: Vec::new(),
1802            verdict: None,
1803        }];
1804        let text = run(&lost);
1805        assert!(text.contains("adoption report lost (timed out)"), "{text}");
1806        assert!(
1807            !text.contains("0 addressed"),
1808            "a lost report must never read as `0 addressed`: {text}"
1809        );
1810
1811        let mut rejected_all = state();
1812        rejected_all.reviews = vec![ReviewRound {
1813            round: 1,
1814            head: "abc1234".to_owned(),
1815            verified_head: None,
1816            verified_at: None,
1817            reviews: Vec::new(),
1818            e2e: Vec::new(),
1819            verify_retried: false,
1820            e2e_deferred: false,
1821            e2e_defer_reason: None,
1822            fix: Some(FixRecord {
1823                agent: "opus".to_owned(),
1824                addressed: Vec::new(),
1825                rejected: Vec::new(),
1826                notes: String::new(),
1827                committed: true,
1828                failed: None,
1829                duration_ms: 0,
1830                continuation: None,
1831            }),
1832            blocking: 3,
1833            answered: 0,
1834            expected: 0,
1835            clean: false,
1836            progressed: false,
1837            vote_split: false,
1838            reconsideration: Vec::new(),
1839            verdict: None,
1840        }];
1841        let text2 = run(&rejected_all);
1842        assert!(
1843            text2.contains("0 addressed / 0 rejected"),
1844            "a round the fixer actually reported on keeps the count: {text2}"
1845        );
1846    }
1847
1848    #[test]
1849    fn a_split_round_shows_every_seat_vote_and_the_reconsideration() {
1850        use crate::run::ReviewRevoteRecord;
1851        use crate::verdict::ReviewVote;
1852
1853        let _guard = plain();
1854        let mut s = state();
1855        s.reviews = vec![ReviewRound {
1856            round: 1,
1857            head: "abc1234".to_owned(),
1858            verified_head: None,
1859            verified_at: None,
1860            reviews: vec![
1861                ReviewRecord {
1862                    attempts: 0,
1863                    reviewer: 1,
1864                    agent: "alpha".to_owned(),
1865                    summary: String::new(),
1866                    findings: Vec::new(),
1867                    vote: Some(ReviewVote::Approve),
1868                    failed: None,
1869                    duration_ms: 0,
1870                },
1871                ReviewRecord {
1872                    attempts: 0,
1873                    reviewer: 2,
1874                    agent: "beta".to_owned(),
1875                    summary: String::new(),
1876                    findings: Vec::new(),
1877                    vote: Some(ReviewVote::Reject),
1878                    failed: None,
1879                    duration_ms: 0,
1880                },
1881            ],
1882            e2e: Vec::new(),
1883            verify_retried: false,
1884            e2e_deferred: false,
1885            e2e_defer_reason: None,
1886            fix: None,
1887            blocking: 0,
1888            answered: 2,
1889            expected: 2,
1890            clean: false,
1891            progressed: false,
1892            vote_split: true,
1893            reconsideration: vec![ReviewRevoteRecord {
1894                reviewer: 2,
1895                agent: "beta".to_owned(),
1896                vote: Some(ReviewVote::ApproveWithFindings),
1897                reason: "the other seat's read holds up".to_owned(),
1898                failed: None,
1899            }],
1900            verdict: Some(ReviewVote::ApproveWithFindings),
1901        }];
1902        let text = run(&s);
1903        assert!(text.contains("review-1 vote"), "{text}");
1904        assert!(text.contains("review-2 vote"), "{text}");
1905        assert!(text.contains("panel split"), "{text}");
1906        assert!(text.contains("reconsideration"), "{text}");
1907        assert!(text.contains("the other seat's read holds up"), "{text}");
1908    }
1909
1910    #[test]
1911    fn an_incomplete_panel_and_a_lost_fix_report_both_stay_on_the_round_line() {
1912        // Two independent facts share this one line, and each arrived from a
1913        // different change: a seat that never answered, and a fixer whose
1914        // adoption report was lost. Rendering either must not shadow the
1915        // other, and neither may collapse into the plain `clean`/`open`
1916        // pair the line used to carry.
1917        let _guard = plain();
1918        let mut s = state();
1919        s.reviews = vec![ReviewRound {
1920            round: 1,
1921            head: "abc1234".to_owned(),
1922            verified_head: None,
1923            verified_at: None,
1924            reviews: vec![
1925                ReviewRecord {
1926                    attempts: 0,
1927                    reviewer: 1,
1928                    agent: "alpha".to_owned(),
1929                    summary: String::new(),
1930                    findings: Vec::new(),
1931                    vote: None,
1932                    failed: None,
1933                    duration_ms: 0,
1934                },
1935                ReviewRecord {
1936                    attempts: 0,
1937                    reviewer: 2,
1938                    agent: "beta".to_owned(),
1939                    summary: String::new(),
1940                    findings: Vec::new(),
1941                    vote: None,
1942                    failed: Some("agent timed out".to_owned()),
1943                    duration_ms: 0,
1944                },
1945            ],
1946            e2e: Vec::new(),
1947            verify_retried: false,
1948            e2e_deferred: false,
1949            e2e_defer_reason: None,
1950            fix: Some(FixRecord {
1951                agent: "opus".to_owned(),
1952                addressed: Vec::new(),
1953                rejected: Vec::new(),
1954                notes: String::new(),
1955                committed: true,
1956                failed: Some("timed out".to_owned()),
1957                duration_ms: 0,
1958                continuation: None,
1959            }),
1960            blocking: 0,
1961            answered: 1,
1962            expected: 2,
1963            clean: false,
1964            progressed: true,
1965            vote_split: false,
1966            reconsideration: Vec::new(),
1967            verdict: None,
1968        }];
1969        let text = run(&s);
1970        assert!(text.contains("incomplete"), "{text}");
1971        assert!(text.contains("1/2 reviewers answered"), "{text}");
1972        assert!(text.contains("review-2: agent timed out"), "{text}");
1973        assert!(text.contains("adoption report lost (timed out)"), "{text}");
1974        assert!(
1975            !text.contains("clean"),
1976            "a round missing half its panel must never render as clean: {text}"
1977        );
1978    }
1979
1980    #[test]
1981    fn a_build_failure_is_not_reported_as_a_test_failure() {
1982        let _guard = plain();
1983        let mut s = state();
1984        s.reviews = vec![ReviewRound {
1985            round: 1,
1986            head: "abc1234".to_owned(),
1987            verified_head: None,
1988            verified_at: None,
1989            reviews: Vec::new(),
1990            e2e: vec![CommandOutcome {
1991                command: "cargo test".to_owned(),
1992                code: Some(1),
1993                output_tail: "LINK : fatal error LNK1104: cannot open file".to_owned(),
1994                duration_ms: 100,
1995                resource_blocked: false,
1996            }],
1997            verify_retried: true,
1998            e2e_deferred: false,
1999            e2e_defer_reason: None,
2000            fix: None,
2001            blocking: 0,
2002            answered: 0,
2003            expected: 0,
2004            clean: false,
2005            progressed: false,
2006            vote_split: false,
2007            reconsideration: Vec::new(),
2008            verdict: None,
2009        }];
2010        let text = run(&s);
2011        assert!(text.contains("could not run"), "{text}");
2012        assert!(text.contains("retried once"), "{text}");
2013        assert!(!text.contains("e2e RED"), "{text}");
2014    }
2015
2016    #[test]
2017    fn a_resource_blocked_e2e_never_reads_as_red_or_as_a_build_failure() {
2018        let _guard = plain();
2019        let mut s = state();
2020        s.reviews = vec![ReviewRound {
2021            round: 1,
2022            head: "abc1234".to_owned(),
2023            verified_head: None,
2024            verified_at: None,
2025            reviews: Vec::new(),
2026            e2e: vec![CommandOutcome {
2027                command: "(waiting for the shared build cache)".to_owned(),
2028                code: None,
2029                output_tail: "held by run x node e2e seat e2e".to_owned(),
2030                duration_ms: 100,
2031                resource_blocked: true,
2032            }],
2033            verify_retried: false,
2034            e2e_deferred: false,
2035            e2e_defer_reason: None,
2036            fix: None,
2037            blocking: 0,
2038            answered: 0,
2039            expected: 0,
2040            clean: false,
2041            progressed: false,
2042            vote_split: false,
2043            reconsideration: Vec::new(),
2044            verdict: None,
2045        }];
2046        let text = run(&s);
2047        assert!(text.contains("shared build cache unavailable"), "{text}");
2048        assert!(!text.contains("e2e RED"), "{text}");
2049        assert!(!text.contains("build/link failure"), "{text}");
2050    }
2051
2052    #[test]
2053    fn a_round_with_more_than_one_e2e_command_names_each_one() {
2054        // The aggregate `e2e RED` label says the round's overall verdict,
2055        // never which of several `verify.e2e` commands actually failed —
2056        // `magi show` must list each command by name, the same way it
2057        // already does for `gate`.
2058        let _guard = plain();
2059        let mut s = state();
2060        s.reviews = vec![ReviewRound {
2061            round: 1,
2062            head: "abc1234".to_owned(),
2063            verified_head: Some("abc1234".to_owned()),
2064            verified_at: Some(jiff::Timestamp::now()),
2065            reviews: Vec::new(),
2066            e2e: vec![
2067                CommandOutcome {
2068                    command: "cargo test --locked --all-targets".to_owned(),
2069                    code: Some(0),
2070                    output_tail: String::new(),
2071                    duration_ms: 0,
2072                    resource_blocked: false,
2073                },
2074                CommandOutcome {
2075                    command: "cargo make check".to_owned(),
2076                    code: Some(1),
2077                    output_tail: "clippy: unused import".to_owned(),
2078                    duration_ms: 0,
2079                    resource_blocked: false,
2080                },
2081            ],
2082            verify_retried: false,
2083            e2e_deferred: false,
2084            e2e_defer_reason: None,
2085            fix: None,
2086            blocking: 0,
2087            answered: 0,
2088            expected: 0,
2089            clean: false,
2090            progressed: false,
2091            vote_split: false,
2092            reconsideration: Vec::new(),
2093            verdict: None,
2094        }];
2095        let text = run(&s);
2096        assert!(text.contains("cargo test --locked --all-targets"), "{text}");
2097        assert!(text.contains("cargo make check"), "{text}");
2098        assert!(text.contains("clippy: unused import"), "{text}");
2099    }
2100
2101    #[test]
2102    fn a_declined_finding_shows_its_reason() {
2103        use crate::verdict::{Finding, Rejection, Severity};
2104
2105        let _guard = plain();
2106        let mut s = state();
2107        s.status = RunStatus::Ready;
2108        s.reviews = vec![ReviewRound {
2109            round: 1,
2110            head: "deadbee".to_owned(),
2111            verified_head: None,
2112            verified_at: None,
2113            reviews: vec![ReviewRecord {
2114                attempts: 0,
2115                reviewer: 1,
2116                agent: "alpha".to_owned(),
2117                summary: String::new(),
2118                findings: vec![Finding {
2119                    id: "R1-1-1".to_owned(),
2120                    severity: Severity::Major,
2121                    file: None,
2122                    line: None,
2123                    title: "still open".to_owned(),
2124                    detail: String::new(),
2125                }],
2126                vote: None,
2127                failed: None,
2128                duration_ms: 0,
2129            }],
2130            e2e: vec![CommandOutcome {
2131                command: "cargo test".to_owned(),
2132                code: Some(0),
2133                output_tail: String::new(),
2134                duration_ms: 0,
2135                resource_blocked: false,
2136            }],
2137            verify_retried: false,
2138            e2e_deferred: false,
2139            e2e_defer_reason: None,
2140            fix: Some(FixRecord {
2141                agent: "alpha".to_owned(),
2142                addressed: Vec::new(),
2143                rejected: vec![Rejection {
2144                    id: "R1-1-2".to_owned(),
2145                    why: "cannot be triggered from any caller".to_owned(),
2146                }],
2147                notes: String::new(),
2148                committed: true,
2149                failed: None,
2150                duration_ms: 0,
2151                continuation: None,
2152            }),
2153            blocking: 1,
2154            answered: 1,
2155            expected: 1,
2156            clean: false,
2157            progressed: true,
2158            vote_split: false,
2159            reconsideration: Vec::new(),
2160            verdict: None,
2161        }];
2162
2163        let text = run(&s);
2164        assert!(text.contains("R1-1-2"), "{text}");
2165        assert!(text.contains("cannot be triggered"), "{text}");
2166        assert!(text.contains("still open"), "{text}");
2167        assert!(
2168            text.contains("handed off"),
2169            "a mergeable run with an open round must say so: {text}"
2170        );
2171    }
2172
2173    #[test]
2174    fn a_failing_gate_command_shows_its_output() {
2175        let _guard = plain();
2176        let mut s = state();
2177        s.status = RunStatus::Blocked;
2178        s.gate = vec![CommandOutcome {
2179            command: "cargo make check".to_owned(),
2180            code: Some(101),
2181            output_tail: "error[E0308]: mismatched types".to_owned(),
2182            duration_ms: 0,
2183            resource_blocked: false,
2184        }];
2185        s.gate_ran = true;
2186
2187        let text = run(&s);
2188        assert!(text.contains("mismatched types"), "{text}");
2189    }
2190
2191    #[test]
2192    fn a_gate_with_no_commands_configured_shows_a_pass_not_silence() {
2193        let _guard = plain();
2194        let mut s = state();
2195        s.status = RunStatus::Ready;
2196        s.gate_ran = true;
2197        assert!(s.gate.is_empty());
2198
2199        let text = run(&s);
2200        assert!(
2201            text.contains("gate") && text.contains("no gate commands configured"),
2202            "a run gated on nothing must say so, not read as if the gate never ran: {text}"
2203        );
2204    }
2205
2206    #[test]
2207    fn a_gate_that_has_not_run_yet_shows_nothing() {
2208        let _guard = plain();
2209        let s = state();
2210        assert!(!s.gate_ran);
2211        assert!(s.gate.is_empty());
2212
2213        let text = run(&s);
2214        assert!(
2215            !text.contains("no gate commands configured"),
2216            "an unattempted gate must not be shown as a pass: {text}"
2217        );
2218    }
2219
2220    #[test]
2221    fn active_seats_shows_who_has_not_answered_and_how_long_is_left() {
2222        let _guard = plain();
2223        let mut s = state();
2224        s.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
2225        let text = active_seats(&s, Liveness::Live);
2226        assert!(text.contains("running now"));
2227        assert!(text.contains("judge-2"));
2228        assert!(text.contains("judge"));
2229        assert!(!text.contains("no live daemon"), "{text}");
2230        assert!(!text.contains("could not be confirmed"), "{text}");
2231    }
2232
2233    #[test]
2234    fn active_seats_flags_a_leftover_from_a_dead_process() {
2235        let _guard = plain();
2236        let mut s = state();
2237        s.seat_started("implement", "impl-B", std::time::Duration::from_secs(60), 0);
2238        let text = active_seats(&s, Liveness::Dead);
2239        assert!(
2240            text.contains("no live daemon"),
2241            "a stale entry must not read as running: {text}"
2242        );
2243    }
2244
2245    #[test]
2246    fn superseded_notice_names_the_run_that_replaced_it() {
2247        let _guard = plain();
2248        let text = superseded_notice(Some("bbbb"));
2249        assert!(text.contains("SUPERSEDED"), "{text}");
2250        assert!(text.contains("bbbb"), "{text}");
2251    }
2252
2253    #[test]
2254    fn superseded_notice_is_silent_for_the_latest_attempt() {
2255        let _guard = plain();
2256        assert_eq!(superseded_notice(None), "");
2257    }
2258
2259    #[test]
2260    fn list_line_marks_a_nonterminal_run_with_a_dead_driver_stale() {
2261        let _guard = plain();
2262        let mut s = state();
2263        s.status = RunStatus::Reviewing;
2264        let text = line_with_liveness(&s, Liveness::Dead);
2265        assert!(text.contains("STALE"), "{text}");
2266        assert!(text.contains("resume required"), "{text}");
2267        assert!(liveness_notice(&s, Liveness::Dead).contains("STALE"));
2268    }
2269
2270    /// A manual `magi run` / `magi review` claims no daemon, but its
2271    /// `driver_pid` still answers — this is `Unknown`, never `Dead`: see
2272    /// `RunState::liveness`'s own doc for why an unconfirmed process is never
2273    /// folded into "confirmed dead".
2274    #[test]
2275    fn active_seats_reports_uncertainty_without_claiming_death() {
2276        let _guard = plain();
2277        let mut s = state();
2278        s.seat_started("review", "review-1", std::time::Duration::from_secs(60), 0);
2279        let text = active_seats(&s, Liveness::Unknown);
2280        assert!(
2281            text.contains("could not be confirmed"),
2282            "an unproven state must read as uncertain, not dead: {text}"
2283        );
2284        assert!(!text.contains("no live daemon"), "{text}");
2285    }
2286
2287    #[test]
2288    fn active_seats_is_empty_when_nothing_is_running() {
2289        let _guard = plain();
2290        assert_eq!(active_seats(&state(), Liveness::Live), "");
2291    }
2292
2293    /// A running `verify.e2e` / `verify.gate` task is shown alongside seats,
2294    /// with which command is currently running and how far through the list
2295    /// it is — the gap the addendum's second item names: a review-only run
2296    /// that spends minutes inside `cargo test` between reviewer answers and
2297    /// the fix's own commit had nothing at all to show for it before this.
2298    #[test]
2299    fn active_seats_shows_a_running_verify_task_and_its_command() {
2300        let _guard = plain();
2301        let mut s = state();
2302        s.task_command(
2303            "e2e",
2304            "verify",
2305            0,
2306            "cargo test",
2307            2,
2308            3,
2309            std::time::Duration::from_secs(600),
2310        );
2311        let text = active_seats(&s, Liveness::Live);
2312        assert!(text.contains("e2e"), "{text}");
2313        assert!(text.contains("(2/3)"), "{text}");
2314        assert!(text.contains("cargo test"), "{text}");
2315    }
2316
2317    #[test]
2318    fn no_jobs_section_appears_when_nothing_was_ever_collected() {
2319        let _guard = plain();
2320        // The common case today (every backend but codex): silence, not a
2321        // clutter line repeated on every single `magi show`.
2322        assert!(!run(&state()).contains("background jobs"));
2323    }
2324
2325    #[test]
2326    fn a_codex_roster_with_no_completed_jobs_yet_says_so_instead_of_staying_silent() {
2327        let _guard = plain();
2328        let mut s = state();
2329        s.config.agents.push(crate::config::AgentSpec {
2330            id: "codex-one".to_owned(),
2331            kind: crate::config::AgentKind::Codex,
2332            model: None,
2333            command: vec!["codex".to_owned()],
2334            extra_args: Vec::new(),
2335            env: BTreeMap::new(),
2336            prompt_delivery: None,
2337        });
2338        let text = run(&s);
2339        assert!(
2340            text.contains("background jobs"),
2341            "a run that could report this must not read the same as one that never could: \
2342             {text}"
2343        );
2344        assert!(text.contains("no completed command evidence yet"));
2345    }
2346
2347    #[test]
2348    fn recovered_running_and_unreadable_jobs_are_told_apart() {
2349        let _guard = plain();
2350        let mut s = state();
2351        s.jobs = vec![
2352            crate::run::JobRecord {
2353                node: "implement".to_owned(),
2354                round: None,
2355                seat: "impl-A".to_owned(),
2356                id: "item49".to_owned(),
2357                description: "cargo test --test graph_cached_gate".to_owned(),
2358                checked_at: jiff::Timestamp::now(),
2359                status: crate::run::JobStatus::Completed,
2360                exit_code: Some(0),
2361                result_summary: "test result: 2 passed; 0 failed".to_owned(),
2362                source: "codex".to_owned(),
2363            },
2364            crate::run::JobRecord {
2365                node: "fix".to_owned(),
2366                round: None,
2367                seat: "impl-A".to_owned(),
2368                id: "item52".to_owned(),
2369                description: "cargo test --test graph_split".to_owned(),
2370                checked_at: jiff::Timestamp::now(),
2371                status: crate::run::JobStatus::Failed,
2372                exit_code: Some(101),
2373                result_summary: "test result: 1 passed; 1 failed".to_owned(),
2374                source: "codex".to_owned(),
2375            },
2376            crate::run::JobRecord {
2377                node: "fix".to_owned(),
2378                round: None,
2379                seat: "impl-A".to_owned(),
2380                id: "item60".to_owned(),
2381                description: "cargo build".to_owned(),
2382                checked_at: jiff::Timestamp::now(),
2383                status: crate::run::JobStatus::Unknown,
2384                exit_code: None,
2385                result_summary: String::new(),
2386                source: "codex".to_owned(),
2387            },
2388        ];
2389        let text = run(&s);
2390        assert!(text.contains("background jobs"));
2391        assert!(text.contains("item49"));
2392        assert!(text.contains("item52"));
2393        assert!(text.contains("item60"));
2394        // The three states this run actually has evidence for must read
2395        // differently from one another — never collapsed into a single
2396        // "ran" or "did not run".
2397        assert!(text.contains("completed"));
2398        assert!(text.contains("failed"));
2399        assert!(text.contains("unknown"));
2400        // Coverage limit stated once, not fabricated per seat.
2401        assert!(text.contains("adapter coverage"));
2402    }
2403
2404    #[test]
2405    fn a_jobs_own_round_is_shown_when_known() {
2406        let _guard = plain();
2407        let mut s = state();
2408        s.jobs = vec![crate::run::JobRecord {
2409            node: "review".to_owned(),
2410            round: Some(2),
2411            seat: "review-1".to_owned(),
2412            id: "item9".to_owned(),
2413            description: "cargo test --test graph_cached_gate".to_owned(),
2414            checked_at: jiff::Timestamp::now(),
2415            status: crate::run::JobStatus::Completed,
2416            exit_code: Some(0),
2417            result_summary: "test result: 2 passed; 0 failed".to_owned(),
2418            source: "codex".to_owned(),
2419        }];
2420        let text = run(&s);
2421        assert!(
2422            text.contains("round 2"),
2423            "the round this seat's own command ran in must be visible, distinct from magi's \
2424             own recorded verify: {text}"
2425        );
2426    }
2427
2428    #[test]
2429    fn stats_table_renders_without_runs() {
2430        let _guard = plain();
2431        let text = stats(&Stats::default());
2432        assert!(text.contains("0 total"));
2433        assert!(!text.contains("implementation"));
2434        assert!(!text.contains("node durations"));
2435    }
2436
2437    #[test]
2438    fn repo_summary_lists_run_count_and_completion_rate() {
2439        let _guard = plain();
2440        let a = crate::stats::RepoStats {
2441            repo: PathBuf::from("/repos/a"),
2442            name: "a".to_owned(),
2443            stats: Stats {
2444                totals: crate::stats::Totals {
2445                    runs: 4,
2446                    merged: 2,
2447                    ready: 1,
2448                    ..Default::default()
2449                },
2450                ..Default::default()
2451            },
2452        };
2453        let text = repo_summary(&[a]);
2454        assert!(text.contains("repos"), "{text}");
2455        assert!(text.contains("a  4 runs  75% completion"), "{text}");
2456    }
2457
2458    #[test]
2459    fn repo_summary_disambiguates_colliding_names_with_the_parent_directory() {
2460        let _guard = plain();
2461        let a = crate::stats::RepoStats {
2462            repo: PathBuf::from("/roots/one/magi"),
2463            name: "magi".to_owned(),
2464            stats: Stats::default(),
2465        };
2466        let b = crate::stats::RepoStats {
2467            repo: PathBuf::from("/roots/two/magi"),
2468            name: "magi".to_owned(),
2469            stats: Stats::default(),
2470        };
2471        let text = repo_summary(&[a, b]);
2472        assert!(text.contains("magi (one)"), "{text}");
2473        assert!(text.contains("magi (two)"), "{text}");
2474    }
2475
2476    #[test]
2477    fn stats_table_renders_advisor_reflection() {
2478        let _guard = plain();
2479        let st = Stats {
2480            advisors: vec![crate::stats::AdvisorStats {
2481                agent: "alpha".to_owned(),
2482                seated: 3,
2483                proposed: 2,
2484                absent: 1,
2485                faint: 1,
2486                strong: 1,
2487            }],
2488            ..Default::default()
2489        };
2490        let text = stats(&st);
2491        assert!(text.contains("design deliberation"));
2492        assert!(
2493            text.contains("approximate"),
2494            "must note the heuristic: {text}"
2495        );
2496        assert!(text.contains("alpha"));
2497        assert!(text.contains("50%"));
2498    }
2499
2500    #[test]
2501    fn stats_table_shows_release_bump_coverage_even_when_nothing_was_recorded() {
2502        // A repository that has merged runs but never wired up (or never hit)
2503        // the release-bump step must still show "0 of N merged runs recorded
2504        // a bump" - hiding the whole section on `recorded == 0` would make
2505        // that gap invisible instead of reporting it.
2506        let _guard = plain();
2507        let st = Stats {
2508            release_bumps: crate::stats::ReleaseBumpStats {
2509                merged: 3,
2510                ..Default::default()
2511            },
2512            ..Default::default()
2513        };
2514        let text = stats(&st);
2515        assert!(text.contains("release bumps"), "{text}");
2516        assert!(
2517            text.contains("0 of 3 merged run(s) recorded a bump"),
2518            "{text}"
2519        );
2520    }
2521
2522    #[test]
2523    fn stats_table_renders_release_bump_coverage_and_attention() {
2524        let _guard = plain();
2525        let st = Stats {
2526            release_bumps: crate::stats::ReleaseBumpStats {
2527                merged: 4,
2528                recorded: 2,
2529                pr_opened: 2,
2530                automerge_enabled: 1,
2531                merged_directly: 0,
2532                needs_attention: 1,
2533            },
2534            ..Default::default()
2535        };
2536        let text = stats(&st);
2537        assert!(text.contains("release bumps"), "{text}");
2538        assert!(
2539            text.contains("2 of 4 merged run(s) recorded a bump (50%)"),
2540            "{text}"
2541        );
2542        assert!(text.contains("1 clean, 1 needed a human (50%)"), "{text}");
2543    }
2544
2545    #[test]
2546    fn stats_table_renders_node_durations_with_a_bar_and_unmeasured_count() {
2547        let _guard = plain();
2548        let st = Stats {
2549            nodes: vec![
2550                crate::stats::NodeDuration {
2551                    node: "implement".to_owned(),
2552                    runs: 2,
2553                    total_secs: 200,
2554                    max_secs: 150,
2555                    single: 1,
2556                },
2557                crate::stats::NodeDuration {
2558                    node: "gate".to_owned(),
2559                    runs: 0,
2560                    total_secs: 0,
2561                    max_secs: 0,
2562                    single: 3,
2563                },
2564            ],
2565            ..Default::default()
2566        };
2567        let text = stats(&st);
2568        assert!(text.contains("node durations"));
2569        assert!(text.contains("implement"));
2570        assert!(text.contains("2 runs"));
2571        assert!(text.contains('█'), "the leader must draw a bar: {text}");
2572        assert!(text.contains("1 unmeasured"));
2573        assert!(text.contains("gate"));
2574        assert!(text.contains("3 unmeasured"));
2575        assert!(!text.contains('\x1b'), "colour leaked into a plain render");
2576    }
2577}