Skip to main content

magi/
report_view.rs

1//! A structured view of the run report, for the web UI.
2//!
3//! [`crate::report::run`] renders a run as ANSI text, and that stays the one
4//! text implementation (the TUI and `magi show` read it). This module is the
5//! second reader of the same [`RunState`]: it decides *which sections exist
6//! and in what order* the way `report::run` does, and leaves every judgement
7//! to the accessors the text report already uses (`e2e_status`,
8//! `gate_status`, `Severity::blocks`, `ReviewRound::incomplete`,
9//! `final_votes`, `handed_off_with_open_findings`). Nothing here re-derives a
10//! verdict; when a section is added to the text report, add it here too.
11//!
12//! The one rule a reader of this file must keep: a tally below quorum is
13//! never *decided*. `Tally::decided` is `met_quorum`, and the winner it names
14//! is `provisional` otherwise, so a stalled run cannot render as a settled one.
15use std::collections::BTreeMap;
16
17use serde::Serialize;
18
19use crate::config::{MergeMode, MergeStyle};
20use crate::run::{
21    CommandOutcome, ContinuationOutcome, E2eStatus, GateStatus, JobStatus, Liveness,
22    OperatorFixOutcome, ReviewRound, RunState, tail,
23};
24use crate::verdict::{Finding, ReviewVote, Severity};
25
26/// Bumped when a field changes meaning; the client falls back to the raw text
27/// for a schema it does not know rather than render a guess.
28pub const SCHEMA: u32 = 1;
29
30/// How many bytes of a command's output the view carries, the same bound the
31/// text report applies.
32const OUTPUT_TAIL: usize = 2_000;
33
34/// How a section should read at a glance.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
36#[serde(rename_all = "snake_case")]
37pub enum Tone {
38    /// Good, finished.
39    Ok,
40    /// Needs a look, nothing is broken.
41    Warn,
42    /// Broken or untrustworthy.
43    Fail,
44    /// Information only.
45    Neutral,
46}
47
48/// The whole report.
49#[derive(Debug, Serialize)]
50pub struct RunReportView {
51    /// [`SCHEMA`].
52    pub schema: u32,
53    /// What `report::run` prints before the first section.
54    pub header: Header,
55    /// In `report::run` order.
56    pub sections: Vec<Section>,
57    /// `report::active_seats`, which is already text and has no structure to
58    /// add. Empty when no seat is mid-answer.
59    pub active_seats: String,
60}
61
62/// The top block.
63#[derive(Debug, Serialize)]
64pub struct Header {
65    /// Run id.
66    pub id: String,
67    /// `RunStatus::display_label`.
68    pub status: String,
69    /// Status as a tone; a stalled run is never `ok`.
70    pub tone: Tone,
71    /// Landed nothing, and that was the configuration.
72    pub unmerged_by_design: bool,
73    /// A release step needs a person.
74    pub needs_attention: bool,
75    /// Repository path.
76    pub repo: String,
77    /// Base branch.
78    pub base_branch: String,
79    /// Base commit, abbreviated.
80    pub base_commit: String,
81    /// Creation time, local.
82    pub created: String,
83    /// First line of the task.
84    pub task: String,
85    /// Where the task came from.
86    pub origin: String,
87    /// Startup kind, branch and durable boundary, when recorded.
88    pub startup: Option<String>,
89    /// Original startup failure, verbatim.
90    pub startup_failure: Option<String>,
91    /// The run's state directory.
92    pub state_dir: String,
93}
94
95/// Fields every section shares.
96#[derive(Debug, Serialize)]
97pub struct Head {
98    /// Heading, as the text report words it.
99    pub title: String,
100    /// At-a-glance state.
101    pub tone: Tone,
102    /// Whether the card starts expanded.
103    pub default_open: bool,
104}
105
106fn head(title: &str, tone: Tone, default_open: bool) -> Head {
107    Head {
108        title: title.to_owned(),
109        tone,
110        default_open,
111    }
112}
113
114/// One card.
115#[derive(Debug, Serialize)]
116#[serde(tag = "kind", rename_all = "snake_case")]
117pub enum Section {
118    /// Implementations.
119    Candidates {
120        /// Title, tone and default state.
121        #[serde(flatten)]
122        head: Head,
123        /// Rows.
124        items: Vec<CandidateRow>,
125    },
126    /// Blind judging, deliberation and final votes.
127    Judging {
128        /// Title, tone and default state.
129        #[serde(flatten)]
130        head: Head,
131        /// One row per judge.
132        judges: Vec<JudgeRow>,
133        /// One line per deliberation turn.
134        deliberation: Vec<String>,
135        /// Full deliberation arguments grouped by round.
136        rounds: Vec<DeliberationRoundView>,
137        /// Final votes.
138        votes: Vec<VoteRow>,
139    },
140    /// The mechanical count.
141    Tally {
142        /// Title, tone and default state.
143        #[serde(flatten)]
144        head: Head,
145        /// The count.
146        tally: TallyView,
147    },
148    /// Operational facts and warnings, with multiline prose preserved.
149    Notes {
150        /// Title, tone and default state.
151        #[serde(flatten)]
152        head: Head,
153        /// Which kind of note.
154        key: &'static str,
155        /// Entries, which may contain multiline prose.
156        lines: Vec<String>,
157    },
158    /// The graft round: runner-up strengths ported onto the winner.
159    Graft {
160        /// Title, tone and default state.
161        #[serde(flatten)]
162        head: Head,
163        /// The round.
164        graft: GraftView,
165    },
166    /// Review + verification, grouped by round.
167    Review {
168        /// Title, tone and default state.
169        #[serde(flatten)]
170        head: Head,
171        /// One entry per round, oldest first.
172        rounds: Vec<RoundView>,
173        /// Set when the loop handed off with findings still open.
174        handed_off: Option<String>,
175    },
176    /// Fixes the operator asked for.
177    OperatorFixes {
178        /// Title, tone and default state.
179        #[serde(flatten)]
180        head: Head,
181        /// One entry per request.
182        requests: Vec<OperatorFixView>,
183    },
184    /// The winner against the base's tip.
185    BaseSync {
186        /// Title, tone and default state.
187        #[serde(flatten)]
188        head: Head,
189        /// The state.
190        base_sync: BaseSyncView,
191    },
192    /// Mechanical pre-gate commands.
193    PreGate {
194        /// Title, tone and default state.
195        #[serde(flatten)]
196        head: Head,
197        /// Per-command results.
198        commands: Vec<CommandView>,
199        /// Mechanical fixes commit, abbreviated.
200        committed: Option<String>,
201    },
202    /// The final gate.
203    Gate {
204        /// Title, tone and default state.
205        #[serde(flatten)]
206        head: Head,
207        /// `passed`, `not_configured` or `failed`.
208        status: &'static str,
209        /// Per-command results.
210        commands: Vec<CommandView>,
211    },
212    /// What happened to the branch.
213    Merge {
214        /// Title, tone and default state.
215        #[serde(flatten)]
216        head: Head,
217        /// The outcome.
218        merge: MergeView,
219    },
220    /// Tasks filed from open findings.
221    Followups {
222        /// Title, tone and default state.
223        #[serde(flatten)]
224        head: Head,
225        /// Rows.
226        items: Vec<FollowupRow>,
227    },
228    /// Release bump after the merge.
229    ReleaseBump {
230        /// Title, tone and default state.
231        #[serde(flatten)]
232        head: Head,
233        /// The bump.
234        bump: ReleaseBumpView,
235    },
236    /// Where the winner lives.
237    WinnerWorktree {
238        /// Title, tone and default state.
239        #[serde(flatten)]
240        head: Head,
241        /// Worktree path.
242        worktree: String,
243        /// Branch.
244        branch: String,
245        /// The tally behind it did not reach quorum.
246        provisional: bool,
247    },
248    /// Commands the seats' own CLIs reported.
249    Jobs {
250        /// Title, tone and default state.
251        #[serde(flatten)]
252        head: Head,
253        /// Per seat.
254        groups: Vec<JobGroup>,
255        /// Why absence is not evidence.
256        coverage: &'static str,
257        /// No evidence yet, though the roster can report it.
258        empty_note: Option<&'static str>,
259    },
260}
261
262/// One implementation.
263#[derive(Debug, Serialize)]
264pub struct CandidateRow {
265    /// Blind label.
266    pub label: String,
267    /// Agent that wrote it.
268    pub agent: String,
269    /// `failed`, `verified_noop`, `no_change` or `changed`.
270    pub state: &'static str,
271    /// The failure, the no-op evidence or the candidate's summary.
272    pub detail: Option<String>,
273    /// Files touched.
274    pub files: usize,
275    /// Commits ahead of base.
276    pub commits: usize,
277    /// Wall-clock seconds.
278    pub duration_secs: u64,
279    /// The tally's winner, and the tally met quorum.
280    pub winner: bool,
281    /// The tally's winner, but the tally did not meet quorum.
282    pub provisional_winner: bool,
283}
284
285/// One judge's ranking.
286#[derive(Debug, Serialize)]
287pub struct JudgeRow {
288    /// Seat number.
289    pub judge: usize,
290    /// Agent.
291    pub agent: String,
292    /// Ranking, best first; empty when none.
293    pub ranking: String,
294    /// Confidence, when given.
295    pub confidence: Option<u8>,
296    /// Why no ranking, when none.
297    pub failed: Option<String>,
298    /// Per-candidate justifications, verbatim.
299    pub reasons: BTreeMap<String, String>,
300    /// Parsed markdown for each candidate's justification.
301    pub reasons_md: BTreeMap<String, Vec<crate::md::Node>>,
302}
303
304/// One judge's final vote.
305#[derive(Debug, Serialize)]
306pub struct VoteRow {
307    /// Seat number.
308    pub judge: usize,
309    /// Agent.
310    pub agent: String,
311    /// The label voted for, `?` when unreadable.
312    pub vote: String,
313    /// Moved after deliberation.
314    pub changed: bool,
315}
316
317/// One turn in a deliberation round.
318#[derive(Debug, Serialize)]
319pub struct DeliberationTurnView {
320    /// Judge seat number.
321    pub judge: usize,
322    /// Agent.
323    pub agent: String,
324    /// Candidate the judge tentatively backed at the end of the turn.
325    pub tentative: Option<String>,
326    /// Raw argument body.
327    pub body: String,
328    /// Parsed markdown tree of the argument.
329    pub body_md: Vec<crate::md::Node>,
330}
331
332/// One round of deliberation.
333#[derive(Debug, Serialize)]
334pub struct DeliberationRoundView {
335    /// 1-based round number.
336    pub round: usize,
337    /// Turns in this round.
338    pub turns: Vec<DeliberationTurnView>,
339}
340
341/// The count.
342#[derive(Debug, Serialize)]
343pub struct TallyView {
344    /// `present >= quorum`, or none was required.
345    pub met_quorum: bool,
346    /// Always `met_quorum`; named so the client has one field to gate on.
347    pub decided: bool,
348    /// The winner is only provisional.
349    pub provisional: bool,
350    /// Winning label.
351    pub winner: String,
352    /// Configured panel size.
353    pub judges: usize,
354    /// Judges who contributed.
355    pub present: usize,
356    /// Judges required.
357    pub quorum: usize,
358    /// Why no panel sat.
359    pub uncontested: Option<String>,
360    /// First choices per label.
361    pub first_choice: BTreeMap<String, usize>,
362    /// `none`, `one`, `unanimous` or `split`.
363    pub initial: &'static str,
364    /// Final votes agreed.
365    pub unanimous_final: bool,
366    /// Judges who moved.
367    pub changed_votes: usize,
368    /// How a tie was broken.
369    pub tie_break: Option<String>,
370    /// Seats lost to a rate limit.
371    pub rate_limited: Vec<String>,
372}
373
374/// One review round.
375#[derive(Debug, Serialize)]
376pub struct RoundView {
377    /// 1-based.
378    pub round: usize,
379    /// `clean`, `open` or `incomplete`.
380    pub status: &'static str,
381    /// Tone of the round.
382    pub tone: Tone,
383    /// Reviewed commit, abbreviated.
384    pub head: String,
385    /// Commit e2e ran against, when recorded.
386    pub verified_head: Option<String>,
387    /// When verification actually ran; unknown on older records.
388    pub verified_at: Option<String>,
389    /// Findings raised across reviewers.
390    pub raised: usize,
391    /// Blocking findings the round recorded.
392    pub blocking: usize,
393    /// Reviewers that answered.
394    pub answered: usize,
395    /// Reviewers expected.
396    pub expected: usize,
397    /// Seats that never answered, `review-N: why`.
398    pub missing: Vec<String>,
399    /// The e2e leg.
400    pub e2e: E2eView,
401    /// The panel's verdict.
402    pub verdict: Option<VerdictView>,
403    /// The fixer's report.
404    pub fix: Option<FixView>,
405    /// Per-command e2e results.
406    pub commands: Vec<CommandView>,
407    /// Per-reviewer votes.
408    pub reviewers: Vec<ReviewerRow>,
409    /// Every finding, plus declined ones the fixer named.
410    pub findings: Vec<FindingView>,
411    /// Revotes after a split.
412    pub reconsideration: Vec<RevoteRow>,
413    /// Starts expanded: the last round, or any round not clean.
414    pub default_open: bool,
415}
416
417/// The e2e leg of a round.
418#[derive(Debug, Serialize)]
419pub struct E2eView {
420    /// `pass`, `fail`, `blocked`, `deferred` or `not_configured`.
421    pub state: &'static str,
422    /// The failure was a build or link failure, not a verdict on the patch.
423    pub build_failed: bool,
424    /// Why it was deferred.
425    pub defer_reason: Option<String>,
426    /// Retried once.
427    pub retried: bool,
428    /// The leg passed only because a failed command passed when run again on
429    /// the same commit; it must not read as a plain pass.
430    pub flaked: bool,
431}
432
433/// A verdict vote.
434#[derive(Debug, Serialize)]
435pub struct VerdictView {
436    /// `approve`, `approve_with_findings` or `reject`.
437    pub vote: &'static str,
438    /// Operator wording.
439    pub label: &'static str,
440    /// The panel split on the way here.
441    pub split: bool,
442}
443
444/// What the fixer reported.
445#[derive(Debug, Serialize)]
446pub struct FixView {
447    /// Agent.
448    pub agent: String,
449    /// Finding ids the fixer reported acting on.
450    pub addressed: usize,
451    /// Finding ids it declined.
452    pub rejected: usize,
453    /// The fix produced a commit.
454    pub committed: bool,
455    /// The tree changed this round.
456    pub tree_changed: bool,
457    /// Why the adoption report is missing; addressed/rejected are unknown then.
458    pub report_lost: Option<String>,
459    /// How the report was recovered, when it needed to be.
460    pub continuation: Option<String>,
461}
462
463/// A reviewer's own line.
464#[derive(Debug, Serialize)]
465pub struct ReviewerRow {
466    /// Seat number.
467    pub reviewer: usize,
468    /// Agent.
469    pub agent: String,
470    /// Initial vote.
471    pub vote: Option<&'static str>,
472    /// Revote when usable, initial vote otherwise, from `final_votes`.
473    pub final_vote: Option<&'static str>,
474    /// The reviewer's original prose, verbatim.
475    pub reason: String,
476    /// Parsed markdown for the original prose.
477    pub reason_md: Vec<crate::md::Node>,
478    /// Why it produced nothing.
479    pub failed: Option<String>,
480}
481
482/// A revote.
483#[derive(Debug, Serialize)]
484pub struct RevoteRow {
485    /// Seat number.
486    pub reviewer: usize,
487    /// The vote, `None` when it was lost.
488    pub vote: Option<&'static str>,
489    /// Reason, or the failure.
490    pub reason: String,
491    /// Parsed markdown for the reason or failure.
492    pub reason_md: Vec<crate::md::Node>,
493}
494
495/// One finding.
496#[derive(Debug, Serialize)]
497pub struct FindingView {
498    /// magi-assigned id.
499    pub id: String,
500    /// Reviewer seat that raised it; `None` for a declined id with no record.
501    pub reviewer: Option<usize>,
502    /// The real severity: `nit`, `minor`, `major` or `blocker`.
503    pub severity: Option<&'static str>,
504    /// One-line summary.
505    pub title: String,
506    /// File.
507    pub file: Option<String>,
508    /// Line.
509    pub line: Option<u32>,
510    /// Holds the merge (`Severity::blocks`).
511    pub blocking: bool,
512    /// `open`, `fixed` (the fixer *reported* acting on it) or `declined`.
513    pub state: &'static str,
514    /// Why the fixer declined.
515    pub declined_why: Option<String>,
516}
517
518/// A shell command's outcome.
519#[derive(Debug, Serialize)]
520pub struct CommandView {
521    /// The command.
522    pub command: String,
523    /// `pass`, `fail` or `blocked`.
524    pub state: &'static str,
525    /// Exit code.
526    pub code: Option<i32>,
527    /// Wall-clock milliseconds.
528    pub duration_ms: u64,
529    /// The last of the output; only for a command that did not pass.
530    pub output_tail: Option<String>,
531}
532
533/// An operator-requested fix.
534#[derive(Debug, Serialize)]
535pub struct OperatorFixView {
536    /// When asked.
537    pub requested_at: String,
538    /// The head was stale.
539    pub stale: bool,
540    /// Why.
541    pub reason: String,
542    /// Findings and what happened to each.
543    pub findings: Vec<OperatorFindingRow>,
544    /// The follow-up review's run.
545    pub follow_up_review_run: Option<String>,
546    /// Committed, but nothing re-verifies it.
547    pub unverified_commit: bool,
548}
549
550/// One operator-fix finding.
551#[derive(Debug, Serialize)]
552pub struct OperatorFindingRow {
553    /// Id.
554    pub id: String,
555    /// Severity.
556    pub severity: &'static str,
557    /// Title.
558    pub title: String,
559    /// `pending`, `addressed`, `rejected` or `unreported`.
560    pub outcome: &'static str,
561    /// Why, for a rejection.
562    pub why: Option<String>,
563}
564
565/// The base-sync state.
566#[derive(Debug, Serialize)]
567pub struct BaseSyncView {
568    /// Base branch.
569    pub base_branch: String,
570    /// Tip checked against.
571    pub tip: String,
572    /// `already_in`, `conflict`, `in_sync` or `behind`.
573    pub state: &'static str,
574    /// Commits behind.
575    pub behind: usize,
576    /// Rebase attempts.
577    pub attempts: usize,
578    /// Active interval consumption, distinct from lifetime attempts.
579    pub episode_used: usize,
580    /// Synchronization reservations allowed in this interval.
581    pub episode_limit: usize,
582    /// Actual next operation for this checkpoint.
583    pub next_action: String,
584    /// The conflict, verbatim.
585    pub conflict: Option<String>,
586    /// `a as b (proof match)`, when already in the base.
587    pub already_in: Option<String>,
588}
589
590/// What happened to the branch.
591#[derive(Debug, Serialize)]
592pub struct MergeView {
593    /// Merge mode, lowercase.
594    pub mode: String,
595    /// `not_landed_by_design`, `published`, `ok`, `empty` or `not_merged`.
596    pub state: &'static str,
597    /// Magi's own detail, verbatim.
598    pub detail: String,
599    /// The branch left unmerged, for the by-design case.
600    pub branch: Option<String>,
601    /// A squash merge inherits the placeholder subject.
602    pub squash_caveat: bool,
603    /// Checks that were red at merge.
604    pub red_at_merge: Vec<String>,
605}
606
607/// A filed follow-up.
608#[derive(Debug, Serialize)]
609pub struct FollowupRow {
610    /// Task id, abbreviated.
611    pub task: String,
612    /// Finding ids it carries.
613    pub findings: Vec<String>,
614}
615
616/// The release bump.
617#[derive(Debug, Serialize)]
618pub struct ReleaseBumpView {
619    /// Version.
620    pub version: Option<String>,
621    /// Pull request.
622    pub pr_url: Option<String>,
623    /// `enabled`, `merged_directly`, `local`, `failed`, `skipped` or `not_enabled`.
624    pub automerge: &'static str,
625    /// Why no bump was made; a skipped bump is not a release.
626    pub skipped: Option<String>,
627    /// The problem, verbatim.
628    pub problem: Option<String>,
629    /// What a person must do.
630    pub action_required: Option<String>,
631}
632
633/// Jobs of one seat.
634#[derive(Debug, Serialize)]
635pub struct JobGroup {
636    /// Graph node.
637    pub node: String,
638    /// Seat.
639    pub seat: String,
640    /// Commands.
641    pub jobs: Vec<JobRow>,
642}
643
644/// One reported command.
645#[derive(Debug, Serialize)]
646pub struct JobRow {
647    /// The CLI's id.
648    pub id: String,
649    /// `completed`, `failed` or `unknown`.
650    pub status: &'static str,
651    /// Exit code.
652    pub exit_code: Option<i32>,
653    /// Review round.
654    pub round: Option<usize>,
655    /// When the evidence was read.
656    pub checked_at: String,
657    /// The command.
658    pub description: String,
659    /// Tail of its output.
660    pub result_summary: String,
661}
662
663fn short(commit: &str) -> String {
664    commit.chars().take(7).collect()
665}
666
667fn first_line(text: &str) -> String {
668    text.lines()
669        .map(str::trim)
670        .find(|l| !l.is_empty())
671        .unwrap_or("")
672        .to_owned()
673}
674
675fn severity_name(s: Severity) -> &'static str {
676    match s {
677        Severity::Nit => "nit",
678        Severity::Minor => "minor",
679        Severity::Major => "major",
680        Severity::Blocker => "blocker",
681    }
682}
683
684fn vote_name(v: ReviewVote) -> &'static str {
685    match v {
686        ReviewVote::Approve => "approve",
687        ReviewVote::ApproveWithFindings => "approve_with_findings",
688        ReviewVote::Reject => "reject",
689    }
690}
691
692fn command(o: &CommandOutcome, warn_instead_of_fail: bool) -> CommandView {
693    let state = if o.resource_blocked {
694        "blocked"
695    } else if o.ok() {
696        "pass"
697    } else if warn_instead_of_fail {
698        "warn"
699    } else {
700        "fail"
701    };
702    CommandView {
703        command: o.command.clone(),
704        state,
705        code: o.code,
706        duration_ms: o.duration_ms,
707        output_tail: (!o.ok()).then(|| crate::run::summarize_verify(&o.output_tail, OUTPUT_TAIL)),
708    }
709}
710
711fn status_tone(state: &RunState) -> Tone {
712    use crate::run::RunStatus as S;
713    if state.needs_attention() {
714        return Tone::Warn;
715    }
716    match state.status {
717        S::Merged | S::Ready => Tone::Ok,
718        S::Failed => Tone::Fail,
719        S::Stalled | S::Blocked => Tone::Warn,
720        _ => Tone::Neutral,
721    }
722}
723
724fn round_view(r: &ReviewRound, last: bool, flaked: bool) -> RoundView {
725    let raised = r.reviews.iter().map(|x| x.findings.len()).sum();
726    let status = if r.incomplete() {
727        "incomplete"
728    } else if r.clean {
729        "clean"
730    } else {
731        "open"
732    };
733    let e2e_state = match r.e2e_status() {
734        E2eStatus::NotConfigured => "not_configured",
735        E2eStatus::Deferred => "deferred",
736        E2eStatus::Passed => "pass",
737        E2eStatus::Failed => "fail",
738        E2eStatus::ResourceBlocked => "blocked",
739    };
740    let e2e = E2eView {
741        state: e2e_state,
742        build_failed: r.e2e_status() == E2eStatus::Failed
743            && r.e2e.iter().any(CommandOutcome::build_failed),
744        defer_reason: r
745            .e2e_defer_reason
746            .clone()
747            .filter(|_| e2e_state == "deferred"),
748        retried: r.verify_retried,
749        flaked: flaked && e2e_state == "pass",
750    };
751    let tone = if e2e_state == "fail" && !e2e.build_failed {
752        Tone::Fail
753    } else if status == "clean" && !e2e.flaked {
754        Tone::Ok
755    } else {
756        Tone::Warn
757    };
758    let missing = if r.incomplete() {
759        r.reviews
760            .iter()
761            .filter_map(|x| {
762                x.failed
763                    .as_ref()
764                    .map(|why| format!("review-{}: {why}", x.reviewer))
765            })
766            .collect()
767    } else {
768        Vec::new()
769    };
770    let fix = r.fix.as_ref().map(|f| FixView {
771        agent: f.agent.clone(),
772        addressed: f.addressed.len(),
773        rejected: f.rejected.len(),
774        committed: f.committed,
775        tree_changed: r.progressed,
776        report_lost: f.failed.clone(),
777        continuation: f.continuation.as_ref().and_then(|c| match c.outcome {
778            ContinuationOutcome::NotNeeded => None,
779            ContinuationOutcome::Resumed => Some(format!("resumed x{}", c.attempts)),
780            ContinuationOutcome::Exhausted => Some(format!("exhausted x{}", c.attempts)),
781            ContinuationOutcome::QuotaLost => Some("quota".to_owned()),
782            ContinuationOutcome::NoSession => Some("no session to resume".to_owned()),
783        }),
784    });
785
786    let mut findings: Vec<FindingView> = Vec::new();
787    for rec in &r.reviews {
788        for f in &rec.findings {
789            findings.push(finding_view(r, rec.reviewer, f));
790        }
791    }
792    // A declined id is shown once, on its own finding. One that matches no
793    // finding (a fixer naming an id the record does not hold) still has to be
794    // visible, never dropped.
795    if let Some(fix) = &r.fix {
796        for rej in &fix.rejected {
797            if !findings.iter().any(|f| f.id == rej.id) {
798                findings.push(FindingView {
799                    id: rej.id.clone(),
800                    reviewer: None,
801                    severity: None,
802                    title: String::new(),
803                    file: None,
804                    line: None,
805                    blocking: false,
806                    state: "declined",
807                    declined_why: Some(rej.why.clone()),
808                });
809            }
810        }
811    }
812
813    let final_votes = r.final_votes();
814
815    RoundView {
816        round: r.round,
817        status,
818        tone,
819        head: short(&r.head),
820        verified_head: r.verified_head.as_deref().map(short),
821        verified_at: r.verified_at.map(|at| at.to_string()),
822        raised,
823        blocking: r.blocking,
824        answered: r.answered,
825        expected: r.expected,
826        missing,
827        e2e,
828        verdict: r.verdict.map(|v| VerdictView {
829            vote: vote_name(v),
830            label: v.label(),
831            split: r.vote_split,
832        }),
833        fix,
834        commands: r.e2e.iter().map(|o| command(o, false)).collect(),
835        reviewers: r
836            .reviews
837            .iter()
838            .map(|x| ReviewerRow {
839                reviewer: x.reviewer,
840                agent: x.agent.clone(),
841                vote: x.vote.map(vote_name),
842                final_vote: final_votes
843                    .iter()
844                    .find(|(reviewer, _, _)| *reviewer == x.reviewer)
845                    .map(|(_, _, vote)| vote_name(*vote)),
846                reason: x.summary.clone(),
847                reason_md: crate::md::to_nodes(&x.summary, &crate::md::ImageBase::None),
848                failed: x.failed.clone(),
849            })
850            .collect(),
851        findings,
852        reconsideration: r
853            .reconsideration
854            .iter()
855            .map(|rv| {
856                let reason = match rv.vote {
857                    Some(_) => rv.reason.clone(),
858                    None => format!("no revote ({})", rv.failed.as_deref().unwrap_or("unknown")),
859                };
860                RevoteRow {
861                    reviewer: rv.reviewer,
862                    vote: rv.vote.map(vote_name),
863                    reason_md: crate::md::to_nodes(&reason, &crate::md::ImageBase::None),
864                    reason,
865                }
866            })
867            .collect(),
868        default_open: last || status != "clean",
869    }
870}
871
872fn finding_view(r: &ReviewRound, reviewer: usize, f: &Finding) -> FindingView {
873    let fixed = r
874        .fix
875        .as_ref()
876        .is_some_and(|fix| fix.addressed.contains(&f.id));
877    let declined = r
878        .fix
879        .as_ref()
880        .and_then(|fix| fix.rejected.iter().find(|x| x.id == f.id));
881    let (state, declined_why) = match (fixed, declined) {
882        (true, _) => ("fixed", None),
883        (false, Some(rej)) => ("declined", Some(rej.why.clone())),
884        (false, None) => ("open", None),
885    };
886    FindingView {
887        id: f.id.clone(),
888        reviewer: Some(reviewer),
889        severity: Some(severity_name(f.severity)),
890        title: f.title.clone(),
891        file: f.file.clone(),
892        line: f.line,
893        blocking: f.severity.blocks(),
894        state,
895        declined_why,
896    }
897}
898
899fn jobs_section(state: &RunState) -> Option<Section> {
900    let codex = state
901        .config
902        .agents
903        .iter()
904        .any(|a| a.kind == crate::config::AgentKind::Codex);
905    if state.jobs.is_empty() && !codex {
906        return None;
907    }
908    let mut by_seat: BTreeMap<(&str, &str), Vec<&crate::run::JobRecord>> = BTreeMap::new();
909    for j in &state.jobs {
910        by_seat
911            .entry((j.node.as_str(), j.seat.as_str()))
912            .or_default()
913            .push(j);
914    }
915    let groups = by_seat
916        .into_iter()
917        .map(|((node, seat), records)| JobGroup {
918            node: node.to_owned(),
919            seat: seat.to_owned(),
920            jobs: records
921                .into_iter()
922                .map(|j| JobRow {
923                    id: j.id.clone(),
924                    status: match j.status {
925                        JobStatus::Completed => "completed",
926                        JobStatus::Failed => "failed",
927                        JobStatus::Unknown => "unknown",
928                    },
929                    exit_code: j.exit_code,
930                    round: j.round,
931                    checked_at: j.checked_at.to_string(),
932                    description: first_line(&j.description),
933                    result_summary: tail(&j.result_summary, OUTPUT_TAIL),
934                })
935                .collect(),
936        })
937        .collect();
938    Some(Section::Jobs {
939        head: head("background jobs", Tone::Neutral, false),
940        groups,
941        coverage: "adapter coverage: codex only today; other backends, and a command a CLI \
942                   never reported finishing, leave no entry here - that is unknown, never \
943                   \"nothing ran\"",
944        empty_note: state.jobs.is_empty().then_some(
945            "no completed command evidence yet for this run (see active seats for what is \
946             still mid-turn)",
947        ),
948    })
949}
950
951/// One strength the judges asked to port and where it stands.
952#[derive(Debug, Serialize)]
953pub struct GraftStrengthView {
954    /// Id the prompt gave it.
955    pub id: String,
956    /// Candidate it came from.
957    pub source: String,
958    /// The strength.
959    pub text: String,
960    /// `adopted` (the fixer's report names it), `rejected`, `unreported` (a
961    /// report exists and omits it) or `unknown` (no report to check against).
962    pub state: &'static str,
963    /// The fixer's reason, for a rejection.
964    pub why: Option<String>,
965}
966
967/// One seat change during the graft.
968#[derive(Debug, Serialize)]
969pub struct GraftHandoverView {
970    /// Agent that failed.
971    pub from: String,
972    /// Agent that took over.
973    pub to: String,
974    /// Why.
975    pub reason: String,
976}
977
978/// The graft card.
979#[derive(Debug, Serialize)]
980pub struct GraftView {
981    /// `applied`, `rolled_back` or `unfinished`.
982    pub outcome: &'static str,
983    /// The rollback reason.
984    pub reason: Option<String>,
985    /// The agent that actually answered the round.
986    pub agent: Option<String>,
987    /// Seat changes, oldest first.
988    pub handovers: Vec<GraftHandoverView>,
989    /// The winning candidate.
990    pub winner: Option<String>,
991    /// Candidates the strengths came from.
992    pub sources: Vec<String>,
993    /// Changed lines the graft introduced (supporting information).
994    pub lines: Option<usize>,
995    /// What the judges asked for, with what the fixer's report confirms.
996    pub requested: Vec<GraftStrengthView>,
997    /// Counts of confirmed, rejected and unconfirmed requests.
998    pub adopted_count: usize,
999    /// Rejected by the fixer.
1000    pub rejected_count: usize,
1001    /// Neither adopted nor rejected in the report, or no report.
1002    pub unconfirmed_count: usize,
1003    /// The fixer's own summary of what it ported, as markdown nodes.
1004    pub notes_md: Vec<crate::md::Node>,
1005    /// The fixer's reasoning before its report, as markdown nodes.
1006    pub reasoning_md: Vec<crate::md::Node>,
1007    /// Details came from `artifacts/` rather than the run record.
1008    pub recovered: bool,
1009    /// Details that could not be shown.
1010    pub unavailable: Vec<crate::graft_report::Unavailable>,
1011    /// Both commits are known, so `GET .../graft.diff` can answer.
1012    pub diff_available: bool,
1013    /// Abbreviated pre-graft commit.
1014    pub pre: String,
1015    /// Abbreviated post-graft commit.
1016    pub post: Option<String>,
1017}
1018
1019fn graft_view(
1020    state: &RunState,
1021    g: &crate::run::GraftRecord,
1022    rec: Option<&crate::graft_report::Recovered>,
1023) -> GraftView {
1024    use crate::graft_report::{Standing, Unavailable, standing};
1025    use crate::run::GraftOutcome;
1026    let mut unavailable: Vec<Unavailable> = Vec::new();
1027    let mut recovered = false;
1028    let requested_src: Vec<_> = if g.requested.is_empty() {
1029        match rec {
1030            Some(r) => {
1031                recovered |= !r.requested.is_empty();
1032                r.requested.clone()
1033            }
1034            None => Vec::new(),
1035        }
1036    } else {
1037        g.requested.clone()
1038    };
1039    let adoption = match (&g.adoption, rec) {
1040        (Some(a), _) => Some(a.clone()),
1041        (None, Some(r)) if g.adoption_error.is_none() => {
1042            recovered |= r.adoption.is_some();
1043            r.adoption.clone()
1044        }
1045        _ => None,
1046    };
1047    if let Some(r) = rec {
1048        unavailable.extend(r.unavailable.iter().cloned());
1049    }
1050    if let Some(e) = &g.adoption_error {
1051        unavailable.push(Unavailable {
1052            what: "adoption",
1053            reason: e.clone(),
1054        });
1055    }
1056    if g.requested.is_empty() && requested_src.is_empty() && rec.is_none() {
1057        unavailable.push(Unavailable {
1058            what: "requested",
1059            reason: "legacy_record".to_owned(),
1060        });
1061    }
1062    if adoption.is_none() && g.adoption_error.is_none() && rec.is_none() {
1063        unavailable.push(Unavailable {
1064            what: "adoption",
1065            reason: "legacy_record".to_owned(),
1066        });
1067    }
1068    let requested: Vec<GraftStrengthView> = requested_src
1069        .iter()
1070        .map(|s| {
1071            let (st, why) = match adoption.as_ref().map(|a| standing(s, a)) {
1072                None => ("unknown", None),
1073                Some(Standing::Adopted) => ("adopted", None),
1074                Some(Standing::Rejected(w)) => ("rejected", Some(w).filter(|w| !w.is_empty())),
1075                Some(Standing::Unreported) => ("unreported", None),
1076            };
1077            GraftStrengthView {
1078                id: s.id.clone(),
1079                source: s.source.to_string(),
1080                text: s.text.clone(),
1081                state: st,
1082                why,
1083            }
1084        })
1085        .collect();
1086    let count = |st: &str| requested.iter().filter(|r| r.state == st).count();
1087    let (adopted_count, rejected_count) = (count("adopted"), count("rejected"));
1088    let mut sources: Vec<String> = requested.iter().map(|r| r.source.clone()).collect();
1089    sources.dedup();
1090    let (outcome, reason) = match &g.outcome {
1091        GraftOutcome::Applied => ("applied", None),
1092        GraftOutcome::WaitingForRestore => ("waiting_for_restore", None),
1093        GraftOutcome::Running => ("unfinished", None),
1094        GraftOutcome::RolledBack(w) => ("rolled_back", Some(w.clone())),
1095    };
1096    let md = |t: &str| {
1097        if t.trim().is_empty() {
1098            Vec::new()
1099        } else {
1100            crate::md::to_nodes(t, &crate::md::ImageBase::None)
1101        }
1102    };
1103    let short = |c: &str| c.chars().take(12).collect::<String>();
1104    if outcome == "applied" && g.post.is_none() {
1105        unavailable.push(Unavailable {
1106            what: "diff",
1107            reason: "no_post_commit".to_owned(),
1108        });
1109    }
1110    GraftView {
1111        outcome,
1112        reason,
1113        agent: g.agent.clone(),
1114        handovers: state
1115            .handovers
1116            .iter()
1117            .filter(|h| h.node == "graft")
1118            .map(|h| GraftHandoverView {
1119                from: h.from.clone(),
1120                to: h.to.clone(),
1121                reason: h.reason.clone(),
1122            })
1123            .collect(),
1124        winner: state.tally.as_ref().map(|t| t.winner.to_string()),
1125        sources,
1126        lines: g.lines,
1127        unconfirmed_count: requested.len() - adopted_count - rejected_count,
1128        adopted_count,
1129        rejected_count,
1130        requested,
1131        notes_md: adoption.as_ref().map(|a| md(&a.notes)).unwrap_or_default(),
1132        reasoning_md: adoption
1133            .as_ref()
1134            .map(|a| md(&a.reasoning))
1135            .unwrap_or_default(),
1136        recovered,
1137        unavailable,
1138        diff_available: g.post.is_some(),
1139        pre: short(&g.pre),
1140        post: g.post.as_deref().map(short),
1141    }
1142}
1143
1144/// Build the view. `live` is [`RunState::liveness`], exactly what the text
1145/// route passes to `report::active_seats`.
1146pub fn build(state: &RunState, live: Liveness) -> RunReportView {
1147    build_with(state, live, None)
1148}
1149
1150/// [`build`] with the graft details recovered from `artifacts/` (see
1151/// [`crate::graft_report::recover`]); `None` shows only what the record holds.
1152pub fn build_with(
1153    state: &RunState,
1154    live: Liveness,
1155    graft: Option<&crate::graft_report::Recovered>,
1156) -> RunReportView {
1157    let mut sections: Vec<Section> = Vec::new();
1158    let met_quorum = state.tally.as_ref().is_none_or(|t| t.met_quorum);
1159
1160    sections.push(Section::Candidates {
1161        head: head(
1162            "candidates",
1163            if state.candidates.iter().any(|c| c.failed.is_some()) {
1164                Tone::Warn
1165            } else {
1166                Tone::Neutral
1167            },
1168            true,
1169        ),
1170        items: state
1171            .candidates
1172            .iter()
1173            .map(|c| {
1174                let is_winner = state.tally.as_ref().is_some_and(|t| t.winner == c.label);
1175                let (st, detail) = match (&c.failed, c.empty, &c.verified_noop) {
1176                    (Some(e), _, _) => ("failed", Some(e.clone())),
1177                    (None, true, Some(ev)) => ("verified_noop", Some(ev.clone())),
1178                    (None, true, None) => (
1179                        "no_change",
1180                        Some(c.summary.clone()).filter(|s| !s.trim().is_empty()),
1181                    ),
1182                    _ => (
1183                        "changed",
1184                        Some(c.summary.clone()).filter(|s| !s.trim().is_empty()),
1185                    ),
1186                };
1187                CandidateRow {
1188                    label: c.label.to_string(),
1189                    agent: c.agent.clone(),
1190                    state: st,
1191                    detail,
1192                    files: c.files,
1193                    commits: c.commits,
1194                    duration_secs: c.duration_ms / 1000,
1195                    winner: is_winner && met_quorum,
1196                    provisional_winner: is_winner && !met_quorum,
1197                }
1198            })
1199            .collect(),
1200    });
1201
1202    if !state.judgements.is_empty() {
1203        sections.push(Section::Judging {
1204            head: head("blind judging", Tone::Neutral, false),
1205            judges: state
1206                .judgements
1207                .iter()
1208                .map(|j| JudgeRow {
1209                    judge: j.judge,
1210                    agent: j.agent.clone(),
1211                    ranking: j.ranking.iter().collect(),
1212                    confidence: j.confidence,
1213                    failed: j.failed.clone(),
1214                    reasons: j.reasons.clone(),
1215                    reasons_md: j
1216                        .reasons
1217                        .iter()
1218                        .map(|(candidate, reason)| {
1219                            (
1220                                candidate.clone(),
1221                                crate::md::to_nodes(reason, &crate::md::ImageBase::None),
1222                            )
1223                        })
1224                        .collect(),
1225                })
1226                .collect(),
1227            deliberation: state
1228                .tally
1229                .as_ref()
1230                .filter(|t| t.deliberated)
1231                .map(|_| {
1232                    state
1233                        .deliberation
1234                        .iter()
1235                        .flat_map(|round| {
1236                            round.turns.iter().map(move |turn| {
1237                                format!(
1238                                    "r{} judge {} -> {}",
1239                                    round.round,
1240                                    turn.judge,
1241                                    turn.tentative.map_or("-".to_owned(), |c| c.to_string())
1242                                )
1243                            })
1244                        })
1245                        .collect()
1246                })
1247                .unwrap_or_default(),
1248            rounds: state
1249                .deliberation
1250                .iter()
1251                .map(|r| DeliberationRoundView {
1252                    round: r.round,
1253                    turns: r
1254                        .turns
1255                        .iter()
1256                        .map(|t| DeliberationTurnView {
1257                            judge: t.judge,
1258                            agent: t.agent.clone(),
1259                            tentative: t.tentative.map(|c| c.to_string()),
1260                            body: t.body.clone(),
1261                            body_md: crate::md::to_nodes(&t.body, &crate::md::ImageBase::None),
1262                        })
1263                        .collect(),
1264                })
1265                .collect(),
1266            votes: state
1267                .votes
1268                .iter()
1269                .map(|v| VoteRow {
1270                    judge: v.judge,
1271                    agent: v.agent.clone(),
1272                    vote: v.vote.unwrap_or('?').to_string(),
1273                    changed: v.changed,
1274                })
1275                .collect(),
1276        });
1277    }
1278
1279    if let Some(t) = &state.tally {
1280        let initial = match (t.rankings, t.unanimous_initial) {
1281            (0, _) => "none",
1282            (1, _) => "one",
1283            (_, true) => "unanimous",
1284            (_, false) => "split",
1285        };
1286        sections.push(Section::Tally {
1287            head: head(
1288                "tally",
1289                if t.met_quorum { Tone::Ok } else { Tone::Fail },
1290                true,
1291            ),
1292            tally: TallyView {
1293                met_quorum: t.met_quorum,
1294                decided: t.met_quorum,
1295                provisional: !t.met_quorum,
1296                winner: t.winner.to_string(),
1297                judges: t.judges,
1298                present: t.present,
1299                quorum: t.quorum,
1300                uncontested: t.uncontested.clone(),
1301                first_choice: t
1302                    .first_choice
1303                    .iter()
1304                    .map(|(k, v)| (k.to_string(), *v))
1305                    .collect(),
1306                initial,
1307                unanimous_final: t.unanimous_final,
1308                changed_votes: t.changed_votes,
1309                tie_break: t.tie_break.clone(),
1310                rate_limited: state.quota.iter().map(|q| q.seat.clone()).collect(),
1311            },
1312        });
1313    }
1314
1315    let notes = |key: &'static str, title: &str, tone: Tone, lines: Vec<String>| {
1316        (!lines.is_empty()).then(|| Section::Notes {
1317            head: head(title, tone, true),
1318            key,
1319            lines,
1320        })
1321    };
1322    if state.tally.is_some() {
1323        sections.extend(notes(
1324            "quota_details",
1325            "unavailable seats",
1326            Tone::Warn,
1327            state
1328                .quota
1329                .iter()
1330                .map(|loss| {
1331                    if loss.cause == crate::agent::QuotaCause::Authentication {
1332                        format!("{} ({}: re-authenticate)", loss.seat, loss.agent)
1333                    } else {
1334                        format!("{} (usage limit)", loss.seat)
1335                    }
1336                })
1337                .collect(),
1338        ));
1339    }
1340    sections.extend(notes(
1341        "handovers",
1342        "seats handed over",
1343        Tone::Warn,
1344        state
1345            .handovers
1346            .iter()
1347            .map(|h| {
1348                format!(
1349                    "{}  {} -> {}  ({}: {})",
1350                    h.seat, h.from, h.to, h.node, h.reason
1351                )
1352            })
1353            .collect(),
1354    ));
1355    sections.extend(notes(
1356        "withheld",
1357        "withheld from commit",
1358        Tone::Warn,
1359        state
1360            .withheld
1361            .iter()
1362            .map(|w| {
1363                format!(
1364                    "{}  ({} lockfile; the directory uses {})",
1365                    w.path, w.manager, w.kept_by
1366                )
1367            })
1368            .collect(),
1369    ));
1370
1371    if let Some(recovery) = &state.recovery {
1372        use crate::recovery::Repair;
1373        let mut lines = vec![recovery.summary()];
1374        if recovery.criteria_inherited {
1375            lines.push("the task's own completion criteria were kept".to_owned());
1376        }
1377        let tone = match &recovery.repair {
1378            Repair::NotStarted => Tone::Neutral,
1379            Repair::WaitingForRestore { .. } => {
1380                lines.push("repair: waiting to restore and retry".to_owned());
1381                Tone::Warn
1382            }
1383            Repair::Started { .. } => {
1384                lines.push("repair: unfinished".to_owned());
1385                Tone::Warn
1386            }
1387            Repair::Done {
1388                failed: Some(why), ..
1389            } => {
1390                lines.push(format!("repair: nothing kept: {why}"));
1391                Tone::Warn
1392            }
1393            Repair::Done {
1394                committed: true, ..
1395            } => {
1396                lines.push("repair: committed".to_owned());
1397                Tone::Ok
1398            }
1399            Repair::Done { .. } => {
1400                lines.push("repair: no commit".to_owned());
1401                Tone::Neutral
1402            }
1403        };
1404        sections.extend(notes("recovery", "recovery", tone, lines));
1405    }
1406
1407    if let Some(g) = &state.graft {
1408        let view = graft_view(state, g, graft);
1409        let tone = match view.outcome {
1410            "applied" if view.unconfirmed_count == 0 && !view.requested.is_empty() => Tone::Ok,
1411            "applied" => Tone::Neutral,
1412            _ => Tone::Warn,
1413        };
1414        sections.push(Section::Graft {
1415            head: head("graft", tone, true),
1416            graft: view,
1417        });
1418    }
1419
1420    if !state.reviews.is_empty() {
1421        let n = state.reviews.len();
1422        let rounds: Vec<RoundView> = state
1423            .reviews
1424            .iter()
1425            .enumerate()
1426            .map(|(i, r)| {
1427                let flaked = state.verify_flakes.iter().any(|f| f.round == Some(r.round));
1428                round_view(r, i + 1 == n, flaked)
1429            })
1430            .collect();
1431        let handed_off = state.handed_off_with_open_findings().then(|| {
1432            format!(
1433                "handed off with {} finding(s) still open - gate and e2e were green; see above \
1434                 for what a person should still look at",
1435                state.open_findings().len()
1436            )
1437        });
1438        let tone = if handed_off.is_some() {
1439            Tone::Warn
1440        } else {
1441            rounds.last().map_or(Tone::Neutral, |r| r.tone)
1442        };
1443        sections.push(Section::Review {
1444            head: head("review + verification", tone, true),
1445            rounds,
1446            handed_off,
1447        });
1448    }
1449
1450    if !state.verify_flakes.is_empty() {
1451        let lines: Vec<String> = state
1452            .verify_flakes
1453            .iter()
1454            .map(|f| {
1455                let tracked = match (&f.task, &f.filing_error) {
1456                    (Some(task), _) if f.filed => format!("filed task {task}"),
1457                    (Some(task), _) => format!("already tracked by task {task}"),
1458                    (None, Some(why)) => format!("no task filed: {why}"),
1459                    (None, None) => "no task filed".to_owned(),
1460                };
1461                format!(
1462                    "`{}` failed, then passed on the same commit {} ({}); {tracked}",
1463                    f.command,
1464                    short(&f.head),
1465                    f.context
1466                )
1467            })
1468            .collect();
1469        sections.extend(notes(
1470            "verify_flakes",
1471            "flaky verification",
1472            Tone::Warn,
1473            lines,
1474        ));
1475    }
1476
1477    if !state.merge_repairs.is_empty() {
1478        let mut lines = Vec::new();
1479        for repair in &state.merge_repairs {
1480            lines.push(format!(
1481                "question {}  head {}  {:?}\n{}",
1482                repair.question,
1483                crate::run::short_of(&repair.head),
1484                repair.phase,
1485                repair.pr
1486            ));
1487            if let Some(why) = &repair.failure {
1488                lines.push(format!("held: {why}"));
1489            }
1490            if let Some(round) = repair.reviews.last() {
1491                for finding in round.reviews.iter().flat_map(|review| &review.findings) {
1492                    lines.push(format!(
1493                        "original [{}] {:?}: {}",
1494                        finding.id, finding.severity, finding.title
1495                    ));
1496                }
1497                for (seat, _, vote) in round.final_votes() {
1498                    lines.push(format!("original reviewer #{seat}: {vote:?}"));
1499                }
1500            }
1501        }
1502        lines.push(
1503            "Repair never approves a merge; updated results require a fresh owner decision."
1504                .to_owned(),
1505        );
1506        sections.extend(notes(
1507            "merge_repairs",
1508            "merge-gate repairs",
1509            Tone::Warn,
1510            lines,
1511        ));
1512    }
1513
1514    if !state.operator_fixes.is_empty() {
1515        sections.push(Section::OperatorFixes {
1516            head: head("operator fix(es)", Tone::Neutral, true),
1517            requests: state
1518                .operator_fixes
1519                .iter()
1520                .map(|req| OperatorFixView {
1521                    requested_at: req.requested_at.to_string(),
1522                    stale: req.stale,
1523                    reason: req.reason.clone(),
1524                    findings: req
1525                        .findings
1526                        .iter()
1527                        .map(|f| {
1528                            let (outcome, why) = match &f.outcome {
1529                                OperatorFixOutcome::Pending => ("pending", None),
1530                                OperatorFixOutcome::Addressed => ("addressed", None),
1531                                OperatorFixOutcome::Rejected { why } => {
1532                                    ("rejected", Some(why.clone()))
1533                                }
1534                                OperatorFixOutcome::Unreported => ("unreported", None),
1535                            };
1536                            OperatorFindingRow {
1537                                id: f.id.clone(),
1538                                severity: severity_name(f.severity),
1539                                title: f.title.clone(),
1540                                outcome,
1541                                why,
1542                            }
1543                        })
1544                        .collect(),
1545                    follow_up_review_run: req.follow_up_review_run.clone(),
1546                    unverified_commit: req.follow_up_review_run.is_none()
1547                        && req.fix.as_ref().is_some_and(|fx| fx.committed),
1548                })
1549                .collect(),
1550        });
1551    }
1552
1553    if let Some(bs) = &state.base_sync {
1554        let (st, tone) = if bs.already_in.is_some() {
1555            ("already_in", Tone::Neutral)
1556        } else if state.resource_block.is_some() {
1557            ("resource_wait", Tone::Warn)
1558        } else if bs.conflict.is_some() {
1559            (
1560                match state.base_sync_recovery.stop.as_ref().map(|s| &s.kind) {
1561                    Some(crate::base_sync_recovery::StopKind::Exhausted) => "exhausted",
1562                    Some(crate::base_sync_recovery::StopKind::Publication) => "publication",
1563                    Some(crate::base_sync_recovery::StopKind::Divergence) => "divergence",
1564                    Some(crate::base_sync_recovery::StopKind::Conflict) => "conflict",
1565                    _ => "stopped",
1566                },
1567                Tone::Fail,
1568            )
1569        } else if bs.behind == 0 {
1570            ("in_sync", Tone::Ok)
1571        } else {
1572            ("behind", Tone::Warn)
1573        };
1574        sections.push(Section::BaseSync {
1575            head: head("base sync", tone, true),
1576            base_sync: BaseSyncView {
1577                base_branch: state.base_branch.clone(),
1578                tip: short(&bs.tip),
1579                state: st,
1580                behind: bs.behind,
1581                attempts: bs.attempts,
1582                episode_used: state.base_episode_used(),
1583                episode_limit: crate::graph::BASE_SYNC_ROUNDS,
1584                next_action: state.base_sync_next_action(),
1585                conflict: bs.conflict.clone(),
1586                already_in: bs
1587                    .already_in
1588                    .as_ref()
1589                    .map(|a| format!("{} ({} match)", a.names(), a.proof.as_str())),
1590            },
1591        });
1592    }
1593
1594    if !state.pre_gate.is_empty() {
1595        let all_ok = state.pre_gate.iter().all(CommandOutcome::ok);
1596        sections.push(Section::PreGate {
1597            head: head(
1598                "pre_gate",
1599                if all_ok { Tone::Ok } else { Tone::Warn },
1600                !all_ok,
1601            ),
1602            commands: state.pre_gate.iter().map(|o| command(o, true)).collect(),
1603            committed: state.pre_gate_commit.as_deref().map(short),
1604        });
1605    }
1606
1607    match state.gate_status() {
1608        GateStatus::NotRun => {}
1609        gs => {
1610            let st = match gs {
1611                GateStatus::NotConfigured => "not_configured",
1612                GateStatus::Passed => "passed",
1613                _ => "failed",
1614            };
1615            sections.push(Section::Gate {
1616                head: head(
1617                    "gate",
1618                    if gs == GateStatus::NotConfigured {
1619                        Tone::Neutral
1620                    } else if gs.ok() {
1621                        Tone::Ok
1622                    } else {
1623                        Tone::Fail
1624                    },
1625                    true,
1626                ),
1627                status: st,
1628                commands: state.gate.iter().map(|o| command(o, false)).collect(),
1629            });
1630        }
1631    }
1632
1633    if let Some(m) = &state.merge {
1634        let by_design = m.mode == MergeMode::None;
1635        let (st, tone) = if by_design {
1636            ("not_landed_by_design", Tone::Neutral)
1637        } else if m.empty {
1638            ("empty", Tone::Warn)
1639        } else if m.ok && state.status == crate::run::RunStatus::Merged {
1640            ("ok", Tone::Ok)
1641        } else if m.ok && m.mode == MergeMode::Pr {
1642            ("published", Tone::Neutral)
1643        } else {
1644            ("not_merged", Tone::Warn)
1645        };
1646        sections.push(Section::Merge {
1647            head: head("merge", tone, true),
1648            merge: MergeView {
1649                mode: format!("{:?}", m.mode).to_lowercase(),
1650                state: st,
1651                detail: m.detail.clone(),
1652                branch: by_design
1653                    .then(|| state.winner().map(|w| w.branch.clone()))
1654                    .flatten(),
1655                squash_caveat: by_design && state.config.merge.style == MergeStyle::Squash,
1656                red_at_merge: state
1657                    .pr
1658                    .as_ref()
1659                    .map(|pr| pr.red_at_merge.clone())
1660                    .unwrap_or_default(),
1661            },
1662        });
1663    }
1664
1665    if !state.followups.is_empty() {
1666        sections.push(Section::Followups {
1667            head: head("follow-ups", Tone::Neutral, true),
1668            items: state
1669                .followups
1670                .iter()
1671                .map(|f| FollowupRow {
1672                    task: crate::queue::short(&f.task).to_owned(),
1673                    findings: f.findings.clone(),
1674                })
1675                .collect(),
1676        });
1677    }
1678
1679    sections.extend(notes(
1680        "release_decision_attempts",
1681        "release decision attempts",
1682        Tone::Neutral,
1683        state
1684            .bump_decision_attempts
1685            .iter()
1686            .enumerate()
1687            .map(|(n, attempt)| format!("{}. {}: {}", n + 1, attempt.agent, attempt.outcome))
1688            .collect(),
1689    ));
1690
1691    if let Some(b) = &state.release_bump {
1692        let automerge = if b.skipped.is_some() && b.pr_url.is_none() {
1693            "skipped"
1694        } else if b.automerge_enabled {
1695            "enabled"
1696        } else if b.merged_directly {
1697            "merged_directly"
1698        } else if b.local {
1699            "local"
1700        } else if b.problem.is_some() {
1701            "failed"
1702        } else {
1703            "not_enabled"
1704        };
1705        sections.push(Section::ReleaseBump {
1706            head: head(
1707                "release bump",
1708                if automerge == "failed"
1709                    || automerge == "skipped"
1710                    || b.action_required.is_some()
1711                    || b.release.as_ref().is_some_and(|release| !release.finished)
1712                {
1713                    Tone::Warn
1714                } else {
1715                    Tone::Neutral
1716                },
1717                true,
1718            ),
1719            bump: ReleaseBumpView {
1720                version: b.version.clone(),
1721                pr_url: b.pr_url.clone(),
1722                automerge,
1723                problem: b.problem.clone(),
1724                action_required: b.action_required.clone(),
1725                skipped: b.skipped.clone(),
1726            },
1727        });
1728        if let Some(release) = &b.release {
1729            let status = if release.finished {
1730                "finished"
1731            } else {
1732                release.failed.as_deref().unwrap_or("unfinished")
1733            };
1734            let mut lines = vec![format!(
1735                "release {} at {}: {status}",
1736                release.tag(),
1737                release.commit
1738            )];
1739            lines.push(format!(
1740                "tag on remote: {}; {} command(s) completed",
1741                release.tag_done, release.done
1742            ));
1743            if let Some(running) = &release.running {
1744                lines.push(format!("started step: {running}"));
1745            }
1746            for step in &release.log {
1747                let code = step.code.map_or("none".to_owned(), |code| code.to_string());
1748                let mut line = format!("{} (exit {code})", step.name);
1749                if let Some(output) = &step.output {
1750                    line.push_str(" output ");
1751                    line.push_str(output);
1752                }
1753                if !step.tail.is_empty() {
1754                    line.push('\n');
1755                    line.push_str(&step.tail);
1756                }
1757                lines.push(line);
1758            }
1759            sections.extend(notes(
1760                "release_execution",
1761                "release execution",
1762                if release.finished {
1763                    Tone::Ok
1764                } else {
1765                    Tone::Warn
1766                },
1767                lines,
1768            ));
1769        }
1770    }
1771
1772    sections.extend(notes(
1773        "leaks",
1774        "blindness warnings",
1775        Tone::Warn,
1776        state
1777            .leaks
1778            .iter()
1779            .map(|l| format!("{} x{} in {}", l.token, l.count, l.site))
1780            .collect(),
1781    ));
1782
1783    if let Some(w) = state.winner()
1784        && !w.folded
1785    {
1786        sections.push(Section::WinnerWorktree {
1787            head: head("winner worktree", Tone::Neutral, true),
1788            worktree: w.worktree.display().to_string(),
1789            branch: w.branch.clone(),
1790            provisional: !met_quorum,
1791        });
1792    }
1793
1794    sections.extend(jobs_section(state));
1795
1796    RunReportView {
1797        schema: SCHEMA,
1798        header: Header {
1799            id: state.id.clone(),
1800            status: state.status.display_label().to_owned(),
1801            tone: status_tone(state),
1802            unmerged_by_design: state.unmerged_by_design(),
1803            needs_attention: state.needs_attention(),
1804            repo: state.repo.display().to_string(),
1805            base_branch: state.base_branch.clone(),
1806            base_commit: short(&state.base_commit),
1807            created: state.created_local(),
1808            task: first_line(&state.instruction),
1809            origin: crate::run::origin_label(state.origin.as_ref()),
1810            startup: state.startup.as_ref().map(|startup| {
1811                format!(
1812                    "{} branch={} stage={} complete={}",
1813                    startup.kind,
1814                    startup.branch.as_deref().unwrap_or("-"),
1815                    startup.stage,
1816                    startup.complete
1817                )
1818            }),
1819            startup_failure: state
1820                .startup
1821                .as_ref()
1822                .and_then(|startup| startup.failure.clone()),
1823            state_dir: state.dir().display().to_string(),
1824        },
1825        sections,
1826        active_seats: crate::report::active_seats(state, live),
1827    }
1828}
1829
1830#[cfg(test)]
1831mod tests {
1832    use super::*;
1833    use crate::config::Config;
1834    use crate::run::{CommandOutcome, FixRecord, ReviewRecord, Tally};
1835    use crate::verdict::Rejection;
1836    use std::path::PathBuf;
1837
1838    fn state() -> RunState {
1839        // `build` names `state.dir()`, which reads the process-global home.
1840        crate::run::pin_test_home();
1841        RunState::new(
1842            PathBuf::from("/repo/magi"),
1843            "main".to_owned(),
1844            "0123456789abcdef".to_owned(),
1845            "Add a thing\n\nlong".to_owned(),
1846            Config::default(),
1847        )
1848    }
1849
1850    fn finding(id: &str, severity: Severity) -> Finding {
1851        Finding {
1852            id: id.to_owned(),
1853            severity,
1854            file: Some("src/a.rs".to_owned()),
1855            line: Some(7),
1856            title: format!("title {id}"),
1857            detail: String::new(),
1858        }
1859    }
1860
1861    fn cmd(code: Option<i32>, blocked: bool) -> CommandOutcome {
1862        CommandOutcome {
1863            command: "cargo test".to_owned(),
1864            code,
1865            output_tail: "boom\n".repeat(1_000),
1866            duration_ms: 5,
1867            resource_blocked: blocked,
1868        }
1869    }
1870
1871    fn round(n: usize) -> ReviewRound {
1872        let mut r: ReviewRound = serde_json::from_value(serde_json::json!({
1873            "round": n, "head": "abcdef0123", "reviews": []
1874        }))
1875        .expect("round");
1876        r.answered = 1;
1877        r.expected = 1;
1878        r.reviews.push(
1879            serde_json::from_value::<ReviewRecord>(serde_json::json!({
1880                "reviewer": 1, "agent": "a"
1881            }))
1882            .expect("record"),
1883        );
1884        r
1885    }
1886
1887    fn tally(met: bool) -> Tally {
1888        serde_json::from_value(serde_json::json!({
1889            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
1890            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
1891            "unanimous_final": true, "judges": 3, "present": if met { 3 } else { 1 },
1892            "quorum": 2, "met_quorum": met, "rankings": 1
1893        }))
1894        .expect("tally")
1895    }
1896
1897    fn kinds(v: &RunReportView) -> Vec<String> {
1898        serde_json::to_value(&v.sections)
1899            .expect("json")
1900            .as_array()
1901            .expect("array")
1902            .iter()
1903            .map(|s| s["kind"].as_str().expect("kind").to_owned())
1904            .collect()
1905    }
1906
1907    #[test]
1908    fn sections_follow_the_text_report_order() {
1909        let mut s = state();
1910        s.tally = Some(tally(true));
1911        s.reviews.push(round(1));
1912        s.base_sync = Some(
1913            serde_json::from_value(serde_json::json!({"tip": "abc", "behind": 0, "attempts": 0}))
1914                .expect("sync"),
1915        );
1916        s.pre_gate.push(cmd(Some(0), false));
1917        s.jobs.push(
1918            serde_json::from_value(serde_json::json!({
1919                "node": "fix", "seat": "fix", "id": "j1", "description": "ls",
1920                "checked_at": "2026-01-01T00:00:00Z", "status": "Completed",
1921                "exit_code": 0, "source": "codex"
1922            }))
1923            .expect("job"),
1924        );
1925        let v = build(&s, Liveness::Unknown);
1926        assert_eq!(
1927            kinds(&v),
1928            [
1929                "candidates",
1930                "tally",
1931                "review",
1932                "base_sync",
1933                "pre_gate",
1934                "jobs"
1935            ]
1936        );
1937        let json = serde_json::to_value(&v).expect("json");
1938        assert_eq!(json["schema"], SCHEMA);
1939        let jobs = json["sections"].as_array().expect("a").last().expect("l");
1940        assert_eq!(jobs["default_open"], false, "jobs start collapsed");
1941        assert_eq!(jobs["groups"][0]["jobs"][0]["status"], "completed");
1942    }
1943
1944    fn note<'a>(json: &'a serde_json::Value, key: &str) -> &'a serde_json::Value {
1945        json["sections"]
1946            .as_array()
1947            .expect("sections")
1948            .iter()
1949            .find(|section| section["kind"] == "notes" && section["key"] == key)
1950            .expect("note")
1951    }
1952
1953    #[test]
1954    fn recovery_notes_preserve_the_recorded_repair_state_and_tone() {
1955        for (repair, expected, tone) in [
1956            (serde_json::json!("not-started"), None, "neutral"),
1957            (
1958                serde_json::json!({"waiting-for-restore": {"before": "abc"}}),
1959                Some("repair: waiting to restore and retry"),
1960                "warn",
1961            ),
1962            (
1963                serde_json::json!({"started": {"before": "abc"}}),
1964                Some("repair: unfinished"),
1965                "warn",
1966            ),
1967            (
1968                serde_json::json!({"done": {
1969                    "before": "abc", "after": "def", "committed": true, "failed": null
1970                }}),
1971                Some("repair: committed"),
1972                "ok",
1973            ),
1974            (
1975                serde_json::json!({"done": {
1976                    "before": "abc", "after": "abc", "committed": false, "failed": null
1977                }}),
1978                Some("repair: no commit"),
1979                "neutral",
1980            ),
1981            (
1982                serde_json::json!({"done": {
1983                    "before": "abc", "after": "abc", "committed": false,
1984                    "failed": "restore failed\ninspect the checkout"
1985                }}),
1986                Some("repair: nothing kept: restore failed\ninspect the checkout"),
1987                "warn",
1988            ),
1989        ] {
1990            let mut s = state();
1991            s.recovery = Some(
1992                serde_json::from_value(serde_json::json!({
1993                    "from_run": "20260902-140501-1234", "generation": 1,
1994                    "mode": "full-review", "reasons": ["head moved\nreview it again"],
1995                    "criteria_inherited": true, "repair": repair
1996                }))
1997                .expect("recovery"),
1998            );
1999            let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("view");
2000            let recovery = note(&json, "recovery");
2001            assert_eq!(recovery["title"], "recovery");
2002            assert_eq!(recovery["tone"], tone);
2003            assert_eq!(recovery["default_open"], true);
2004            assert_eq!(
2005                recovery["lines"][0],
2006                s.recovery.as_ref().expect("record").summary()
2007            );
2008            assert!(
2009                recovery["lines"][0]
2010                    .as_str()
2011                    .unwrap()
2012                    .contains("head moved\nreview it again")
2013            );
2014            assert_eq!(
2015                recovery["lines"][1],
2016                "the task's own completion criteria were kept"
2017            );
2018            if let Some(expected) = expected {
2019                assert_eq!(recovery["lines"][2], expected);
2020            } else {
2021                assert_eq!(recovery["lines"].as_array().unwrap().len(), 2);
2022            }
2023        }
2024    }
2025
2026    #[test]
2027    fn reviewer_final_votes_and_verification_times_keep_initial_evidence() {
2028        let mut s = state();
2029        let mut r = round(1);
2030        r.verified_head = Some("fedcba9876543210".to_owned());
2031        r.verified_at = Some("2026-09-02T14:05:01Z".parse().expect("timestamp"));
2032        r.reviews = serde_json::from_value(serde_json::json!([
2033            {"reviewer": 1, "agent": "one", "vote": "reject",
2034             "summary": "Initial **concern**.\n\nNeeds inspection."},
2035            {"reviewer": 2, "agent": "two", "vote": "approve"},
2036            {"reviewer": 3, "agent": "legacy"}
2037        ]))
2038        .expect("reviewers");
2039        r.reconsideration = serde_json::from_value(serde_json::json!([
2040            {"reviewer": 1, "agent": "one", "vote": "approve_with_findings",
2041             "reason": "Resolved the blocker.\nStill one minor issue."},
2042            {"reviewer": 2, "agent": "two", "vote": null, "failed": "lost\nconnection"}
2043        ]))
2044        .expect("revotes");
2045        s.reviews = vec![r, round(2)];
2046        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("view");
2047        let rounds = &json["sections"][1]["rounds"];
2048        let first = &rounds[0];
2049        assert_eq!(first["verified_head"], "fedcba9");
2050        assert_eq!(first["verified_at"], "2026-09-02T14:05:01Z");
2051        assert!(rounds[1]["verified_head"].is_null());
2052        assert!(
2053            rounds[1]["verified_at"].is_null(),
2054            "old records stay unknown"
2055        );
2056        assert_eq!(first["reviewers"][0]["vote"], "reject");
2057        assert_eq!(first["reviewers"][0]["final_vote"], "approve_with_findings");
2058        assert_eq!(
2059            first["reviewers"][1]["final_vote"], "approve",
2060            "lost revote retains initial vote"
2061        );
2062        assert!(first["reviewers"][2]["final_vote"].is_null());
2063        assert_eq!(
2064            first["reviewers"][0]["reason"],
2065            "Initial **concern**.\n\nNeeds inspection."
2066        );
2067        assert!(
2068            !first["reviewers"][0]["reason_md"]
2069                .as_array()
2070                .unwrap()
2071                .is_empty()
2072        );
2073        assert_eq!(
2074            first["reconsideration"][0]["reason"],
2075            "Resolved the blocker.\nStill one minor issue."
2076        );
2077        assert_eq!(
2078            first["reconsideration"][1]["reason"],
2079            "no revote (lost\nconnection)"
2080        );
2081        assert!(
2082            !first["reconsideration"][0]["reason_md"]
2083                .as_array()
2084                .unwrap()
2085                .is_empty()
2086        );
2087        assert!(
2088            !first["reconsideration"][1]["reason_md"]
2089                .as_array()
2090                .unwrap()
2091                .is_empty()
2092        );
2093    }
2094
2095    #[test]
2096    fn merge_repairs_and_release_execution_keep_facts_order_and_multiline_text() {
2097        let mut s = state();
2098        s.startup = Some(crate::run::Startup {
2099            kind: "review".into(),
2100            branch: Some("topic".into()),
2101            stage: "fetch".into(),
2102            complete: false,
2103            failure: Some("fetch refused\ncredentials expired".into()),
2104        });
2105        let mut original = round(1);
2106        original.reviews[0].vote = Some(ReviewVote::Reject);
2107        original.reviews[0].findings = vec![finding("R1-1-1", Severity::Major)];
2108        original.reconsideration = serde_json::from_value(serde_json::json!([{
2109            "reviewer": 1, "agent": "a", "vote": "approve_with_findings",
2110            "reason": "nonblocking after reconsideration"
2111        }]))
2112        .unwrap();
2113        s.merge_repairs.push(crate::run::MergeRepair {
2114            question: "question-42".into(),
2115            head: "abcdef012345".into(),
2116            pr: "https://example.test/pull/42".into(),
2117            reviews: vec![original],
2118            gate: vec![],
2119            gate_head: None,
2120            gate_fixes: vec![],
2121            pre_gate: vec![],
2122            phase: crate::run::MergeRepairPhase::Failed,
2123            failure: Some("owner decision required\ninspect new results".into()),
2124        });
2125        s.bump_decision_attempts = vec![
2126            crate::bump::DecisionAttempt {
2127                agent: "first".into(),
2128                outcome: "unavailable".into(),
2129            },
2130            crate::bump::DecisionAttempt {
2131                agent: "second".into(),
2132                outcome: "patch\naccepted".into(),
2133            },
2134        ];
2135        s.release_bump = Some(crate::run::ReleaseBump {
2136            version: Some("1.2.3".into()),
2137            local: true,
2138            problem: Some("publish failed\nregistry refused".into()),
2139            release: Some(crate::release_local::Job {
2140                version: "1.2.3".into(),
2141                commit: "fedcba9876543210".into(),
2142                tag_done: true,
2143                done: 1,
2144                failed: Some("registry refused\ntry after approval".into()),
2145                log: vec![crate::release_local::StepLog {
2146                    name: "cargo publish".into(),
2147                    code: Some(1),
2148                    tail: "first output line\nsecond output line".into(),
2149                    output: Some("/logs/publish.log".into()),
2150                }],
2151                ..Default::default()
2152            }),
2153            ..Default::default()
2154        });
2155        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("view");
2156        assert_eq!(json["schema"], 1);
2157        assert_eq!(
2158            json["header"]["startup"],
2159            "review branch=topic stage=fetch complete=false"
2160        );
2161        assert_eq!(
2162            json["header"]["startup_failure"],
2163            "fetch refused\ncredentials expired"
2164        );
2165        let repairs = note(&json, "merge_repairs");
2166        assert_eq!(repairs["tone"], "warn");
2167        assert_eq!(
2168            repairs["lines"][0],
2169            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
2170        );
2171        assert_eq!(
2172            repairs["lines"][1],
2173            "held: owner decision required\ninspect new results"
2174        );
2175        assert_eq!(repairs["lines"][2], "original [R1-1-1] Major: title R1-1-1");
2176        assert_eq!(
2177            repairs["lines"][3],
2178            "original reviewer #1: ApproveWithFindings"
2179        );
2180        assert_eq!(
2181            repairs["lines"][4],
2182            "Repair never approves a merge; updated results require a fresh owner decision."
2183        );
2184        let attempts = note(&json, "release_decision_attempts");
2185        assert_eq!(attempts["tone"], "neutral");
2186        assert_eq!(
2187            attempts["lines"],
2188            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
2189        );
2190        assert_eq!(
2191            json["sections"][3]["bump"]["problem"],
2192            "publish failed\nregistry refused"
2193        );
2194        let execution = note(&json, "release_execution");
2195        assert_eq!(execution["tone"], "warn");
2196        assert_eq!(
2197            execution["lines"][0],
2198            "release v1.2.3 at fedcba9876543210: registry refused\ntry after approval"
2199        );
2200        assert_eq!(
2201            execution["lines"][1],
2202            "tag on remote: true; 1 command(s) completed"
2203        );
2204        assert_eq!(
2205            execution["lines"][2],
2206            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
2207        );
2208        let labels: Vec<_> = json["sections"]
2209            .as_array()
2210            .unwrap()
2211            .iter()
2212            .map(|section| {
2213                section["key"]
2214                    .as_str()
2215                    .or_else(|| section["kind"].as_str())
2216                    .unwrap()
2217            })
2218            .collect();
2219        assert_eq!(
2220            labels,
2221            [
2222                "candidates",
2223                "merge_repairs",
2224                "release_decision_attempts",
2225                "release_bump",
2226                "release_execution"
2227            ]
2228        );
2229
2230        let release = s.release_bump.as_mut().unwrap().release.as_mut().unwrap();
2231        release.failed = None;
2232        release.running = Some("cargo publish".into());
2233        let json = serde_json::to_value(build(&s, Liveness::Unknown)).unwrap();
2234        let execution = note(&json, "release_execution");
2235        assert_eq!(execution["tone"], "warn");
2236        assert_eq!(
2237            execution["lines"][0],
2238            "release v1.2.3 at fedcba9876543210: unfinished"
2239        );
2240        assert_eq!(execution["lines"][2], "started step: cargo publish");
2241
2242        let release = s.release_bump.as_mut().unwrap().release.as_mut().unwrap();
2243        release.finished = true;
2244        release.running = None;
2245        let json = serde_json::to_value(build(&s, Liveness::Unknown)).unwrap();
2246        assert_eq!(note(&json, "release_execution")["tone"], "ok");
2247        assert_eq!(
2248            note(&json, "release_execution")["lines"][0],
2249            "release v1.2.3 at fedcba9876543210: finished"
2250        );
2251    }
2252
2253    #[test]
2254    fn judge_reasons_preserve_candidate_keys_and_markdown_bodies() {
2255        let mut s = state();
2256        s.judgements = serde_json::from_value(serde_json::json!([{
2257            "judge": 1, "seat": "judge-1", "agent": "judge", "ranking": ["A", "B"],
2258            "reasons": {"A": "**Better** tests.\n\nKeeps the API.", "B": "Drops validation."}
2259        }]))
2260        .unwrap();
2261        let json = serde_json::to_value(build(&s, Liveness::Unknown)).unwrap();
2262        let judge = &json["sections"][1]["judges"][0];
2263        assert_eq!(judge["reasons"]["A"], "**Better** tests.\n\nKeeps the API.");
2264        assert_eq!(judge["reasons"]["B"], "Drops validation.");
2265        assert!(!judge["reasons_md"]["A"].as_array().unwrap().is_empty());
2266        assert!(!judge["reasons_md"]["B"].as_array().unwrap().is_empty());
2267    }
2268
2269    #[test]
2270    fn no_change_summaries_and_quota_recovery_guidance_are_not_lost() {
2271        let mut s = state();
2272        s.candidates = serde_json::from_value(serde_json::json!([
2273            {
2274                "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
2275                "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
2276            },
2277            {
2278                "index": 1, "label": "B", "agent": "b", "branch": "b", "worktree": "/b",
2279                "empty": true, "folded": true, "summary": " \n "
2280            }
2281        ]))
2282        .unwrap();
2283        s.tally = Some(tally(false));
2284        s.quota = serde_json::from_value(serde_json::json!([
2285            {
2286                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
2287                "agent": "signed-out", "cause": "authentication"
2288            },
2289            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
2290        ]))
2291        .unwrap();
2292        let json = serde_json::to_value(build(&s, Liveness::Unknown)).unwrap();
2293        let candidates = &json["sections"][0]["items"];
2294        assert_eq!(candidates[0]["state"], "no_change");
2295        assert_eq!(
2296            candidates[0]["detail"],
2297            "Already covered.\nNo patch needed."
2298        );
2299        assert_eq!(candidates[1]["state"], "no_change");
2300        assert!(candidates[1]["detail"].is_null());
2301        assert_eq!(
2302            json["sections"][1]["tally"]["rate_limited"],
2303            serde_json::json!(["judge-1", "judge-2"]),
2304            "the existing seat list remains compatible"
2305        );
2306        let unavailable = note(&json, "quota_details");
2307        assert_eq!(unavailable["tone"], "warn");
2308        assert_eq!(
2309            unavailable["lines"],
2310            serde_json::json!([
2311                "judge-1 (signed-out: re-authenticate)",
2312                "judge-2 (usage limit)"
2313            ])
2314        );
2315    }
2316
2317    #[test]
2318    fn a_stalled_tally_is_never_decided() {
2319        let mut s = state();
2320        s.tally = Some(tally(false));
2321        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("json");
2322        let t = json["sections"]
2323            .as_array()
2324            .expect("a")
2325            .iter()
2326            .find(|x| x["kind"] == "tally")
2327            .expect("tally");
2328        assert_eq!(t["tally"]["met_quorum"], false);
2329        assert_eq!(t["tally"]["decided"], false);
2330        assert_eq!(t["tally"]["provisional"], true);
2331        assert_eq!(t["tone"], "fail");
2332    }
2333
2334    #[test]
2335    fn findings_keep_severity_blocking_and_what_the_fixer_said() {
2336        let mut s = state();
2337        let mut r = round(1);
2338        r.reviews[0].findings = vec![
2339            finding("R1-1-1", Severity::Blocker),
2340            finding("R1-1-2", Severity::Major),
2341            finding("R1-1-3", Severity::Minor),
2342            finding("R1-1-4", Severity::Nit),
2343        ];
2344        r.fix = Some(
2345            serde_json::from_value::<FixRecord>(serde_json::json!({"agent": "f"})).expect("fix"),
2346        );
2347        let fix = r.fix.as_mut().expect("fix");
2348        fix.addressed = vec!["R1-1-1".to_owned()];
2349        fix.rejected = vec![
2350            Rejection {
2351                id: "R1-1-2".to_owned(),
2352                why: "not a bug".to_owned(),
2353            },
2354            Rejection {
2355                id: "R9-9-9".to_owned(),
2356                why: "unknown id".to_owned(),
2357            },
2358        ];
2359        s.reviews.push(r);
2360        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("json");
2361        let review = json["sections"]
2362            .as_array()
2363            .expect("a")
2364            .iter()
2365            .find(|x| x["kind"] == "review")
2366            .expect("review");
2367        let f = &review["rounds"][0]["findings"];
2368        let at = |i: usize| {
2369            (
2370                f[i]["severity"].clone(),
2371                f[i]["blocking"].clone(),
2372                f[i]["state"].clone(),
2373            )
2374        };
2375        assert_eq!(at(0), ("blocker".into(), true.into(), "fixed".into()));
2376        assert_eq!(at(1), ("major".into(), true.into(), "declined".into()));
2377        assert_eq!(f[1]["declined_why"], "not a bug");
2378        assert_eq!(at(2), ("minor".into(), false.into(), "open".into()));
2379        assert_eq!(at(3), ("nit".into(), false.into(), "open".into()));
2380        assert_eq!(
2381            f[4]["id"], "R9-9-9",
2382            "an unmatched declined id is not dropped"
2383        );
2384        assert_eq!(f[4]["state"], "declined");
2385    }
2386
2387    #[test]
2388    fn a_deferred_e2e_is_not_a_failed_one() {
2389        let mut s = state();
2390        let mut deferred = round(1);
2391        deferred.e2e_deferred = true;
2392        deferred.e2e_defer_reason = Some("blocking findings".to_owned());
2393        let mut failed = round(2);
2394        failed.e2e = vec![cmd(Some(1), false)];
2395        let mut blocked = round(3);
2396        blocked.e2e = vec![cmd(None, true)];
2397        let none = round(4);
2398        s.reviews = vec![deferred, failed, blocked, none];
2399        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("json");
2400        let rounds = &json["sections"]
2401            .as_array()
2402            .expect("a")
2403            .iter()
2404            .find(|x| x["kind"] == "review")
2405            .expect("review")["rounds"];
2406        let st = |i: usize| {
2407            rounds[i]["e2e"]["state"]
2408                .as_str()
2409                .expect("state")
2410                .to_owned()
2411        };
2412        assert_eq!(
2413            [st(0), st(1), st(2), st(3)],
2414            ["deferred", "fail", "blocked", "not_configured"]
2415        );
2416        assert_eq!(rounds[0]["e2e"]["defer_reason"], "blocking findings");
2417        let tail = rounds[1]["commands"][0]["output_tail"]
2418            .as_str()
2419            .expect("tail");
2420        assert!(tail.len() < 2_100, "output is bounded: {}", tail.len());
2421    }
2422    fn graft_json(s: &RunState, rec: Option<&crate::graft_report::Recovered>) -> serde_json::Value {
2423        let json = serde_json::to_value(build_with(s, Liveness::Unknown, rec)).expect("json");
2424        json["sections"]
2425            .as_array()
2426            .expect("a")
2427            .iter()
2428            .find(|x| x["kind"] == "graft")
2429            .cloned()
2430            .unwrap_or(serde_json::Value::Null)
2431    }
2432
2433    fn graft_record(outcome: crate::run::GraftOutcome) -> crate::run::GraftRecord {
2434        use crate::run::{GraftAdoption, GraftRejection, GraftStrength};
2435        crate::run::GraftRecord {
2436            pre: "aaaaaaaaaaaaaaaa".to_owned(),
2437            post: Some("bbbbbbbbbbbbbbbb".to_owned()),
2438            lines: Some(25),
2439            limit: Some(227),
2440            agent: Some("astra".to_owned()),
2441            outcome,
2442            requested: vec![
2443                GraftStrength {
2444                    id: "A1".into(),
2445                    source: 'A',
2446                    text: "Build Persona directly in the test".into(),
2447                },
2448                GraftStrength {
2449                    id: "A2".into(),
2450                    source: 'A',
2451                    text: "Cache the lookup".into(),
2452                },
2453                GraftStrength {
2454                    id: "A3".into(),
2455                    source: 'A',
2456                    text: "Rename the helper".into(),
2457                },
2458            ],
2459            adoption: Some(GraftAdoption {
2460                addressed: vec!["A1".into()],
2461                rejected: vec![GraftRejection {
2462                    id: "A2".into(),
2463                    why: "too large".into(),
2464                }],
2465                notes: "ported <script>alert(1)</script>".into(),
2466                reasoning: "thinking".into(),
2467            }),
2468            adoption_error: None,
2469        }
2470    }
2471
2472    #[test]
2473    fn an_applied_graft_separates_requested_from_confirmed() {
2474        let mut s = state();
2475        s.graft = Some(graft_record(crate::run::GraftOutcome::Applied));
2476        s.handovers.push(crate::run::Handover {
2477            at: jiff::Timestamp::now(),
2478            node: "graft".into(),
2479            seat: "graft".into(),
2480            from: "sonnet".into(),
2481            to: "astra".into(),
2482            reason: "timed out".into(),
2483        });
2484        let g = &graft_json(&s, None)["graft"];
2485        assert_eq!(g["outcome"], "applied");
2486        assert_eq!(g["agent"], "astra");
2487        assert_eq!(g["handovers"][0]["from"], "sonnet");
2488        assert_eq!(g["lines"], 25);
2489        assert!(g.get("limit").is_none());
2490        let st: Vec<_> = g["requested"]
2491            .as_array()
2492            .expect("a")
2493            .iter()
2494            .map(|r| r["state"].as_str().expect("s").to_owned())
2495            .collect();
2496        assert_eq!(st, ["adopted", "rejected", "unreported"]);
2497        assert_eq!(g["requested"][1]["why"], "too large");
2498        assert_eq!(g["adopted_count"], 1);
2499        assert_eq!(g["unconfirmed_count"], 1);
2500        assert_eq!(g["diff_available"], true);
2501    }
2502
2503    #[test]
2504    fn historical_graft_limits_are_readable_but_not_displayed() {
2505        let mut s = state();
2506        let old = serde_json::to_value(graft_record(crate::run::GraftOutcome::Applied)).unwrap();
2507        assert_eq!(old["limit"], 227);
2508        let mut record: crate::run::GraftRecord = serde_json::from_value(old).unwrap();
2509        assert_eq!(record.limit, Some(227));
2510        record.lines = None;
2511        s.graft = Some(record);
2512        let view = graft_json(&s, None);
2513        assert!(view["graft"]["lines"].is_null());
2514        assert!(view["graft"].get("limit").is_none());
2515        let text = crate::report::run(&s);
2516        assert!(text.contains("changed lines unavailable"));
2517        assert!(!text.contains("limit 227"));
2518        assert!(!text.contains("0 changed lines"));
2519
2520        s.graft.as_mut().unwrap().lines = Some(25);
2521        let text = crate::report::run(&s);
2522        assert!(text.contains("25 changed lines"));
2523        assert!(!text.contains("limit 227"));
2524    }
2525
2526    #[test]
2527    fn a_rolled_back_graft_carries_its_reason_and_no_diff() {
2528        let mut s = state();
2529        let mut g = graft_record(crate::run::GraftOutcome::RolledBack("too big".into()));
2530        g.post = None;
2531        s.graft = Some(g);
2532        let v = graft_json(&s, None);
2533        assert_eq!(v["graft"]["outcome"], "rolled_back");
2534        assert_eq!(v["graft"]["reason"], "too big");
2535        assert_eq!(v["graft"]["diff_available"], false);
2536        assert_eq!(v["tone"], "warn");
2537    }
2538
2539    #[test]
2540    fn a_legacy_record_says_unavailable_and_claims_nothing() {
2541        let mut s = state();
2542        let mut g = graft_record(crate::run::GraftOutcome::Applied);
2543        g.requested.clear();
2544        g.adoption = None;
2545        s.graft = Some(g);
2546        let v = graft_json(&s, None);
2547        let reasons: Vec<_> = v["graft"]["unavailable"]
2548            .as_array()
2549            .expect("a")
2550            .iter()
2551            .map(|u| u["reason"].as_str().expect("s"))
2552            .collect();
2553        assert_eq!(reasons, ["legacy_record", "legacy_record"]);
2554        assert_eq!(v["graft"]["requested"].as_array().expect("a").len(), 0);
2555        assert_eq!(v["graft"]["adopted_count"], 0);
2556    }
2557
2558    #[test]
2559    fn recovered_details_fill_a_legacy_record_and_are_marked() {
2560        let mut s = state();
2561        let mut g = graft_record(crate::run::GraftOutcome::Applied);
2562        let requested = std::mem::take(&mut g.requested);
2563        let adoption = g.adoption.take();
2564        s.graft = Some(g);
2565        let rec = crate::graft_report::Recovered {
2566            requested,
2567            adoption,
2568            unavailable: Vec::new(),
2569        };
2570        let g = &graft_json(&s, Some(&rec))["graft"];
2571        assert_eq!(g["recovered"], true);
2572        assert_eq!(g["requested"][0]["state"], "adopted");
2573    }
2574
2575    #[test]
2576    fn agent_text_stays_text_in_the_view() {
2577        let mut s = state();
2578        let mut g = graft_record(crate::run::GraftOutcome::Applied);
2579        g.requested[0].text = "<img src=x onerror=alert(1)>".into();
2580        s.graft = Some(g);
2581        let v = graft_json(&s, None);
2582        assert_eq!(
2583            v["graft"]["requested"][0]["text"],
2584            "<img src=x onerror=alert(1)>"
2585        );
2586        // Prose goes through the markdown tree, which has no raw-HTML node.
2587        let notes = v["graft"]["notes_md"].to_string();
2588        assert!(!notes.contains("\"html\""), "{notes}");
2589    }
2590}