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