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