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