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