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(ev)) => ("verified_noop", Some(ev.clone())),
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 bs.behind == 0 {
1611            ("in_sync", Tone::Ok)
1612        } else {
1613            ("behind", Tone::Warn)
1614        };
1615        sections.push(Section::BaseSync {
1616            head: head("base sync", tone, true),
1617            base_sync: BaseSyncView {
1618                base_branch: state.base_branch.clone(),
1619                tip: short(&bs.tip),
1620                state: st,
1621                behind: bs.behind,
1622                attempts: bs.attempts,
1623                episode_used: state.base_episode_used(),
1624                episode_limit: crate::graph::BASE_SYNC_ROUNDS,
1625                next_action: state.base_sync_next_action(),
1626                conflict: bs.conflict.clone(),
1627                already_in: bs
1628                    .already_in
1629                    .as_ref()
1630                    .map(|a| format!("{} ({} match)", a.names(), a.proof.as_str())),
1631            },
1632        });
1633    }
1634
1635    if !state.pre_gate.is_empty() {
1636        let all_ok = state.pre_gate.iter().all(CommandOutcome::ok);
1637        sections.push(Section::PreGate {
1638            head: head(
1639                "pre_gate",
1640                if all_ok { Tone::Ok } else { Tone::Warn },
1641                !all_ok,
1642            ),
1643            commands: state.pre_gate.iter().map(|o| command(o, true)).collect(),
1644            committed: state.pre_gate_commit.as_deref().map(short),
1645        });
1646    }
1647
1648    if let Some(e) = &state.head_e2e
1649        && !e.outcomes.is_empty()
1650    {
1651        sections.push(Section::Verification {
1652            head: head(
1653                "current head e2e",
1654                if e.passed { Tone::Ok } else { Tone::Fail },
1655                !e.passed,
1656            ),
1657            key: "head_e2e",
1658            commit: short(&e.head),
1659            passed: e.passed,
1660            commands: e.outcomes.iter().map(|o| command(o, false)).collect(),
1661        });
1662    }
1663
1664    if let Some(e) = &state.gate_repair_e2e
1665        && !e.outcomes.is_empty()
1666    {
1667        sections.push(Section::Verification {
1668            head: head(
1669                "gate repair e2e",
1670                if e.passed { Tone::Ok } else { Tone::Fail },
1671                !e.passed,
1672            ),
1673            key: "gate_repair_e2e",
1674            commit: short(&e.head),
1675            passed: e.passed,
1676            commands: e.outcomes.iter().map(|o| command(o, false)).collect(),
1677        });
1678    }
1679
1680    match state.gate_status() {
1681        GateStatus::NotRun => {}
1682        gs => {
1683            let st = match gs {
1684                GateStatus::NotConfigured => "not_configured",
1685                GateStatus::Passed => "passed",
1686                _ => "failed",
1687            };
1688            sections.push(Section::Gate {
1689                head: head(
1690                    "gate",
1691                    if gs == GateStatus::NotConfigured {
1692                        Tone::Neutral
1693                    } else if gs.ok() {
1694                        Tone::Ok
1695                    } else {
1696                        Tone::Fail
1697                    },
1698                    true,
1699                ),
1700                status: st,
1701                commands: state.gate.iter().map(|o| command(o, false)).collect(),
1702            });
1703        }
1704    }
1705
1706    if let Some(m) = &state.merge {
1707        let by_design = m.mode == MergeMode::None;
1708        let (st, tone) = if by_design {
1709            ("not_landed_by_design", Tone::Neutral)
1710        } else if m.empty {
1711            ("empty", Tone::Warn)
1712        } else if m.ok && state.status == crate::run::RunStatus::Merged {
1713            ("ok", Tone::Ok)
1714        } else if m.ok && m.mode == MergeMode::Pr {
1715            ("published", Tone::Neutral)
1716        } else {
1717            ("not_merged", Tone::Warn)
1718        };
1719        sections.push(Section::Merge {
1720            head: head("merge", tone, true),
1721            merge: MergeView {
1722                mode: format!("{:?}", m.mode).to_lowercase(),
1723                state: st,
1724                detail: m.detail.clone(),
1725                branch: by_design
1726                    .then(|| state.winner().map(|w| w.branch.clone()))
1727                    .flatten(),
1728                squash_caveat: by_design && state.config.merge.style == MergeStyle::Squash,
1729                red_at_merge: state
1730                    .pr
1731                    .as_ref()
1732                    .map(|pr| pr.red_at_merge.clone())
1733                    .unwrap_or_default(),
1734            },
1735        });
1736    }
1737
1738    if !state.followups.is_empty() {
1739        sections.push(Section::Followups {
1740            head: head("follow-ups", Tone::Neutral, true),
1741            items: state
1742                .followups
1743                .iter()
1744                .map(|f| FollowupRow {
1745                    task: crate::queue::short(&f.task).to_owned(),
1746                    findings: f.findings.clone(),
1747                })
1748                .collect(),
1749        });
1750    }
1751
1752    sections.extend(notes(
1753        "release_decision_attempts",
1754        "release decision attempts",
1755        Tone::Neutral,
1756        state
1757            .bump_decision_attempts
1758            .iter()
1759            .enumerate()
1760            .map(|(n, attempt)| format!("{}. {}: {}", n + 1, attempt.agent, attempt.outcome))
1761            .collect(),
1762    ));
1763
1764    if let Some(b) = &state.release_bump {
1765        let automerge = if b.skipped.is_some() && b.pr_url.is_none() {
1766            "skipped"
1767        } else if b.automerge_enabled {
1768            "enabled"
1769        } else if b.merged_directly {
1770            "merged_directly"
1771        } else if b.local {
1772            "local"
1773        } else if b.problem.is_some() {
1774            "failed"
1775        } else {
1776            "not_enabled"
1777        };
1778        sections.push(Section::ReleaseBump {
1779            head: head(
1780                "release bump",
1781                if automerge == "failed"
1782                    || automerge == "skipped"
1783                    || b.action_required.is_some()
1784                    || b.release.as_ref().is_some_and(|release| !release.finished)
1785                {
1786                    Tone::Warn
1787                } else {
1788                    Tone::Neutral
1789                },
1790                true,
1791            ),
1792            bump: ReleaseBumpView {
1793                version: b.version.clone(),
1794                pr_url: b.pr_url.clone(),
1795                automerge,
1796                problem: b.problem.clone(),
1797                action_required: b.action_required.clone(),
1798                skipped: b.skipped.clone(),
1799            },
1800        });
1801        if let Some(release) = &b.release {
1802            let status = if release.finished {
1803                "finished"
1804            } else {
1805                release.failed.as_deref().unwrap_or("unfinished")
1806            };
1807            let mut lines = vec![format!(
1808                "release {} at {}: {status}",
1809                release.tag(),
1810                release.commit
1811            )];
1812            lines.push(format!(
1813                "tag on remote: {}; {} command(s) completed",
1814                release.tag_done, release.done
1815            ));
1816            if let Some(running) = &release.running {
1817                lines.push(format!("started step: {running}"));
1818            }
1819            for step in &release.log {
1820                let code = step.code.map_or("none".to_owned(), |code| code.to_string());
1821                let mut line = format!("{} (exit {code})", step.name);
1822                if let Some(output) = &step.output {
1823                    line.push_str(" output ");
1824                    line.push_str(output);
1825                }
1826                if !step.tail.is_empty() {
1827                    line.push('\n');
1828                    line.push_str(&step.tail);
1829                }
1830                lines.push(line);
1831            }
1832            sections.extend(notes(
1833                "release_execution",
1834                "release execution",
1835                if release.finished {
1836                    Tone::Ok
1837                } else {
1838                    Tone::Warn
1839                },
1840                lines,
1841            ));
1842        }
1843    }
1844
1845    sections.extend(notes(
1846        "leaks",
1847        "blindness warnings",
1848        Tone::Warn,
1849        state
1850            .leaks
1851            .iter()
1852            .map(|l| format!("{} x{} in {}", l.token, l.count, l.site))
1853            .collect(),
1854    ));
1855
1856    if let Some(w) = state.winner()
1857        && !w.folded
1858    {
1859        sections.push(Section::WinnerWorktree {
1860            head: head("winner worktree", Tone::Neutral, true),
1861            worktree: w.worktree.display().to_string(),
1862            branch: w.branch.clone(),
1863            provisional: !met_quorum,
1864        });
1865    }
1866
1867    sections.extend(jobs_section(state));
1868
1869    RunReportView {
1870        schema: SCHEMA,
1871        header: Header {
1872            id: state.id.clone(),
1873            status: state.status.display_label().to_owned(),
1874            tone: status_tone(state),
1875            unmerged_by_design: state.unmerged_by_design(),
1876            needs_attention: state.needs_attention(),
1877            repo: state.repo.display().to_string(),
1878            base_branch: state.base_branch.clone(),
1879            base_commit: short(&state.base_commit),
1880            created: state.created_local(),
1881            task: first_line(&state.instruction),
1882            origin: crate::run::origin_label(state.origin.as_ref()),
1883            startup: state.startup.as_ref().map(|startup| {
1884                format!(
1885                    "{} branch={} stage={} complete={}",
1886                    startup.kind,
1887                    startup.branch.as_deref().unwrap_or("-"),
1888                    startup.stage,
1889                    startup.complete
1890                )
1891            }),
1892            startup_failure: state
1893                .startup
1894                .as_ref()
1895                .and_then(|startup| startup.failure.clone()),
1896            state_dir: state.dir().display().to_string(),
1897        },
1898        sections,
1899        active_seats: crate::report::active_seats(state, live),
1900    }
1901}
1902
1903#[cfg(test)]
1904mod tests {
1905    use super::*;
1906    use crate::config::Config;
1907    use crate::run::{CommandOutcome, FixRecord, ReviewRecord, Tally};
1908    use crate::verdict::Rejection;
1909    use std::path::PathBuf;
1910
1911    fn state() -> RunState {
1912        // `build` names `state.dir()`, which reads the process-global home.
1913        crate::run::pin_test_home();
1914        RunState::new(
1915            PathBuf::from("/repo/magi"),
1916            "main".to_owned(),
1917            "0123456789abcdef".to_owned(),
1918            "Add a thing\n\nlong".to_owned(),
1919            Config::default(),
1920        )
1921    }
1922
1923    fn finding(id: &str, severity: Severity) -> Finding {
1924        Finding {
1925            id: id.to_owned(),
1926            severity,
1927            file: Some("src/a.rs".to_owned()),
1928            line: Some(7),
1929            title: format!("title {id}"),
1930            detail: String::new(),
1931        }
1932    }
1933
1934    fn cmd(code: Option<i32>, blocked: bool) -> CommandOutcome {
1935        CommandOutcome {
1936            command: "cargo test".to_owned(),
1937            code,
1938            output_tail: "boom\n".repeat(1_000),
1939            duration_ms: 5,
1940            resource_blocked: blocked,
1941            ..Default::default()
1942        }
1943    }
1944
1945    fn round(n: usize) -> ReviewRound {
1946        let mut r: ReviewRound = serde_json::from_value(serde_json::json!({
1947            "round": n, "head": "abcdef0123", "reviews": []
1948        }))
1949        .expect("round");
1950        r.answered = 1;
1951        r.expected = 1;
1952        r.reviews.push(
1953            serde_json::from_value::<ReviewRecord>(serde_json::json!({
1954                "reviewer": 1, "agent": "a"
1955            }))
1956            .expect("record"),
1957        );
1958        r
1959    }
1960
1961    fn tally(met: bool) -> Tally {
1962        serde_json::from_value(serde_json::json!({
1963            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
1964            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
1965            "unanimous_final": true, "judges": 3, "present": if met { 3 } else { 1 },
1966            "quorum": 2, "met_quorum": met, "rankings": 1
1967        }))
1968        .expect("tally")
1969    }
1970
1971    fn kinds(v: &RunReportView) -> Vec<String> {
1972        serde_json::to_value(&v.sections)
1973            .expect("json")
1974            .as_array()
1975            .expect("array")
1976            .iter()
1977            .map(|s| s["kind"].as_str().expect("kind").to_owned())
1978            .collect()
1979    }
1980
1981    #[test]
1982    fn sections_follow_the_text_report_order() {
1983        let mut s = state();
1984        s.tally = Some(tally(true));
1985        s.reviews.push(round(1));
1986        s.base_sync = Some(
1987            serde_json::from_value(serde_json::json!({"tip": "abc", "behind": 0, "attempts": 0}))
1988                .expect("sync"),
1989        );
1990        s.pre_gate.push(cmd(Some(0), false));
1991        s.jobs.push(
1992            serde_json::from_value(serde_json::json!({
1993                "node": "fix", "seat": "fix", "id": "j1", "description": "ls",
1994                "checked_at": "2026-01-01T00:00:00Z", "status": "Completed",
1995                "exit_code": 0, "source": "codex"
1996            }))
1997            .expect("job"),
1998        );
1999        let v = build(&s, Liveness::Unknown);
2000        assert_eq!(
2001            kinds(&v),
2002            [
2003                "candidates",
2004                "tally",
2005                "review",
2006                "base_sync",
2007                "pre_gate",
2008                "jobs"
2009            ]
2010        );
2011        let json = serde_json::to_value(&v).expect("json");
2012        assert_eq!(json["schema"], SCHEMA);
2013        let jobs = json["sections"].as_array().expect("a").last().expect("l");
2014        assert_eq!(jobs["default_open"], false, "jobs start collapsed");
2015        assert_eq!(jobs["groups"][0]["jobs"][0]["status"], "completed");
2016    }
2017
2018    fn note<'a>(json: &'a serde_json::Value, key: &str) -> &'a serde_json::Value {
2019        json["sections"]
2020            .as_array()
2021            .expect("sections")
2022            .iter()
2023            .find(|section| section["kind"] == "notes" && section["key"] == key)
2024            .expect("note")
2025    }
2026
2027    #[test]
2028    fn recovery_notes_preserve_the_recorded_repair_state_and_tone() {
2029        for (repair, expected, tone) in [
2030            (serde_json::json!("not-started"), None, "neutral"),
2031            (
2032                serde_json::json!({"waiting-for-restore": {"before": "abc"}}),
2033                Some("repair: waiting to restore and retry"),
2034                "warn",
2035            ),
2036            (
2037                serde_json::json!({"started": {"before": "abc"}}),
2038                Some("repair: unfinished"),
2039                "warn",
2040            ),
2041            (
2042                serde_json::json!({"done": {
2043                    "before": "abc", "after": "def", "committed": true, "failed": null
2044                }}),
2045                Some("repair: committed"),
2046                "ok",
2047            ),
2048            (
2049                serde_json::json!({"done": {
2050                    "before": "abc", "after": "abc", "committed": false, "failed": null
2051                }}),
2052                Some("repair: no commit"),
2053                "neutral",
2054            ),
2055            (
2056                serde_json::json!({"done": {
2057                    "before": "abc", "after": "abc", "committed": false,
2058                    "failed": "restore failed\ninspect the checkout"
2059                }}),
2060                Some("repair: nothing kept: restore failed\ninspect the checkout"),
2061                "warn",
2062            ),
2063        ] {
2064            let mut s = state();
2065            s.recovery = Some(
2066                serde_json::from_value(serde_json::json!({
2067                    "from_run": "20260902-140501-1234", "generation": 1,
2068                    "mode": "full-review", "reasons": ["head moved\nreview it again"],
2069                    "criteria_inherited": true, "repair": repair
2070                }))
2071                .expect("recovery"),
2072            );
2073            let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("view");
2074            let recovery = note(&json, "recovery");
2075            assert_eq!(recovery["title"], "recovery");
2076            assert_eq!(recovery["tone"], tone);
2077            assert_eq!(recovery["default_open"], true);
2078            assert_eq!(
2079                recovery["lines"][0],
2080                s.recovery.as_ref().expect("record").summary()
2081            );
2082            assert!(
2083                recovery["lines"][0]
2084                    .as_str()
2085                    .unwrap()
2086                    .contains("head moved\nreview it again")
2087            );
2088            assert_eq!(
2089                recovery["lines"][1],
2090                "the task's own completion criteria were kept"
2091            );
2092            if let Some(expected) = expected {
2093                assert_eq!(recovery["lines"][2], expected);
2094            } else {
2095                assert_eq!(recovery["lines"].as_array().unwrap().len(), 2);
2096            }
2097        }
2098    }
2099
2100    #[test]
2101    fn reviewer_final_votes_and_verification_times_keep_initial_evidence() {
2102        let mut s = state();
2103        let mut r = round(1);
2104        r.verified_head = Some("fedcba9876543210".to_owned());
2105        r.verified_at = Some("2026-09-02T14:05:01Z".parse().expect("timestamp"));
2106        r.reviews = serde_json::from_value(serde_json::json!([
2107            {"reviewer": 1, "agent": "one", "vote": "reject",
2108             "summary": "Initial **concern**.\n\nNeeds inspection."},
2109            {"reviewer": 2, "agent": "two", "vote": "approve"},
2110            {"reviewer": 3, "agent": "legacy"}
2111        ]))
2112        .expect("reviewers");
2113        r.reconsideration = serde_json::from_value(serde_json::json!([
2114            {"reviewer": 1, "agent": "one", "vote": "approve_with_findings",
2115             "reason": "Resolved the blocker.\nStill one minor issue."},
2116            {"reviewer": 2, "agent": "two", "vote": null, "failed": "lost\nconnection"}
2117        ]))
2118        .expect("revotes");
2119        s.reviews = vec![r, round(2)];
2120        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("view");
2121        let rounds = &json["sections"][1]["rounds"];
2122        let first = &rounds[0];
2123        assert_eq!(first["verified_head"], "fedcba9");
2124        assert_eq!(first["verified_at"], "2026-09-02T14:05:01Z");
2125        assert!(rounds[1]["verified_head"].is_null());
2126        assert!(
2127            rounds[1]["verified_at"].is_null(),
2128            "old records stay unknown"
2129        );
2130        assert_eq!(first["reviewers"][0]["vote"], "reject");
2131        assert_eq!(first["reviewers"][0]["final_vote"], "approve_with_findings");
2132        assert_eq!(
2133            first["reviewers"][1]["final_vote"], "approve",
2134            "lost revote retains initial vote"
2135        );
2136        assert!(first["reviewers"][2]["final_vote"].is_null());
2137        assert_eq!(
2138            first["reviewers"][0]["reason"],
2139            "Initial **concern**.\n\nNeeds inspection."
2140        );
2141        assert!(
2142            !first["reviewers"][0]["reason_md"]
2143                .as_array()
2144                .unwrap()
2145                .is_empty()
2146        );
2147        assert_eq!(
2148            first["reconsideration"][0]["reason"],
2149            "Resolved the blocker.\nStill one minor issue."
2150        );
2151        assert_eq!(
2152            first["reconsideration"][1]["reason"],
2153            "no revote (lost\nconnection)"
2154        );
2155        assert!(
2156            !first["reconsideration"][0]["reason_md"]
2157                .as_array()
2158                .unwrap()
2159                .is_empty()
2160        );
2161        assert!(
2162            !first["reconsideration"][1]["reason_md"]
2163                .as_array()
2164                .unwrap()
2165                .is_empty()
2166        );
2167    }
2168
2169    #[test]
2170    fn merge_repairs_and_release_execution_keep_facts_order_and_multiline_text() {
2171        let mut s = state();
2172        s.startup = Some(crate::run::Startup {
2173            kind: "review".into(),
2174            branch: Some("topic".into()),
2175            stage: "fetch".into(),
2176            complete: false,
2177            failure: Some("fetch refused\ncredentials expired".into()),
2178        });
2179        let mut original = round(1);
2180        original.reviews[0].vote = Some(ReviewVote::Reject);
2181        original.reviews[0].findings = vec![finding("R1-1-1", Severity::Major)];
2182        original.reconsideration = serde_json::from_value(serde_json::json!([{
2183            "reviewer": 1, "agent": "a", "vote": "approve_with_findings",
2184            "reason": "nonblocking after reconsideration"
2185        }]))
2186        .unwrap();
2187        s.merge_repairs.push(crate::run::MergeRepair {
2188            question: "question-42".into(),
2189            head: "abcdef012345".into(),
2190            pr: "https://example.test/pull/42".into(),
2191            reviews: vec![original],
2192            gate: vec![],
2193            gate_head: None,
2194            gate_fixes: vec![],
2195            pre_gate: vec![],
2196            phase: crate::run::MergeRepairPhase::Failed,
2197            failure: Some("owner decision required\ninspect new results".into()),
2198        });
2199        s.bump_decision_attempts = vec![
2200            crate::bump::DecisionAttempt {
2201                agent: "first".into(),
2202                outcome: "unavailable".into(),
2203            },
2204            crate::bump::DecisionAttempt {
2205                agent: "second".into(),
2206                outcome: "patch\naccepted".into(),
2207            },
2208        ];
2209        s.release_bump = Some(crate::run::ReleaseBump {
2210            version: Some("1.2.3".into()),
2211            local: true,
2212            problem: Some("publish failed\nregistry refused".into()),
2213            release: Some(crate::release_local::Job {
2214                version: "1.2.3".into(),
2215                commit: "fedcba9876543210".into(),
2216                tag_done: true,
2217                done: 1,
2218                failed: Some("registry refused\ntry after approval".into()),
2219                log: vec![crate::release_local::StepLog {
2220                    name: "cargo publish".into(),
2221                    code: Some(1),
2222                    tail: "first output line\nsecond output line".into(),
2223                    output: Some("/logs/publish.log".into()),
2224                }],
2225                ..Default::default()
2226            }),
2227            ..Default::default()
2228        });
2229        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("view");
2230        assert_eq!(json["schema"], 1);
2231        assert_eq!(
2232            json["header"]["startup"],
2233            "review branch=topic stage=fetch complete=false"
2234        );
2235        assert_eq!(
2236            json["header"]["startup_failure"],
2237            "fetch refused\ncredentials expired"
2238        );
2239        let repairs = note(&json, "merge_repairs");
2240        assert_eq!(repairs["tone"], "warn");
2241        assert_eq!(
2242            repairs["lines"][0],
2243            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
2244        );
2245        assert_eq!(
2246            repairs["lines"][1],
2247            "held: owner decision required\ninspect new results"
2248        );
2249        assert_eq!(repairs["lines"][2], "original [R1-1-1] Major: title R1-1-1");
2250        assert_eq!(
2251            repairs["lines"][3],
2252            "original reviewer #1: ApproveWithFindings"
2253        );
2254        assert_eq!(
2255            repairs["lines"][4],
2256            "Repair never approves a merge; updated results require a fresh owner decision."
2257        );
2258        let attempts = note(&json, "release_decision_attempts");
2259        assert_eq!(attempts["tone"], "neutral");
2260        assert_eq!(
2261            attempts["lines"],
2262            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
2263        );
2264        assert_eq!(
2265            json["sections"][3]["bump"]["problem"],
2266            "publish failed\nregistry refused"
2267        );
2268        let execution = note(&json, "release_execution");
2269        assert_eq!(execution["tone"], "warn");
2270        assert_eq!(
2271            execution["lines"][0],
2272            "release v1.2.3 at fedcba9876543210: registry refused\ntry after approval"
2273        );
2274        assert_eq!(
2275            execution["lines"][1],
2276            "tag on remote: true; 1 command(s) completed"
2277        );
2278        assert_eq!(
2279            execution["lines"][2],
2280            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
2281        );
2282        let labels: Vec<_> = json["sections"]
2283            .as_array()
2284            .unwrap()
2285            .iter()
2286            .map(|section| {
2287                section["key"]
2288                    .as_str()
2289                    .or_else(|| section["kind"].as_str())
2290                    .unwrap()
2291            })
2292            .collect();
2293        assert_eq!(
2294            labels,
2295            [
2296                "candidates",
2297                "merge_repairs",
2298                "release_decision_attempts",
2299                "release_bump",
2300                "release_execution"
2301            ]
2302        );
2303
2304        let release = s.release_bump.as_mut().unwrap().release.as_mut().unwrap();
2305        release.failed = None;
2306        release.running = Some("cargo publish".into());
2307        let json = serde_json::to_value(build(&s, Liveness::Unknown)).unwrap();
2308        let execution = note(&json, "release_execution");
2309        assert_eq!(execution["tone"], "warn");
2310        assert_eq!(
2311            execution["lines"][0],
2312            "release v1.2.3 at fedcba9876543210: unfinished"
2313        );
2314        assert_eq!(execution["lines"][2], "started step: cargo publish");
2315
2316        let release = s.release_bump.as_mut().unwrap().release.as_mut().unwrap();
2317        release.finished = true;
2318        release.running = None;
2319        let json = serde_json::to_value(build(&s, Liveness::Unknown)).unwrap();
2320        assert_eq!(note(&json, "release_execution")["tone"], "ok");
2321        assert_eq!(
2322            note(&json, "release_execution")["lines"][0],
2323            "release v1.2.3 at fedcba9876543210: finished"
2324        );
2325    }
2326
2327    #[test]
2328    fn judge_reasons_preserve_candidate_keys_and_markdown_bodies() {
2329        let mut s = state();
2330        s.judgements = serde_json::from_value(serde_json::json!([{
2331            "judge": 1, "seat": "judge-1", "agent": "judge", "ranking": ["A", "B"],
2332            "reasons": {"A": "**Better** tests.\n\nKeeps the API.", "B": "Drops validation."}
2333        }]))
2334        .unwrap();
2335        let json = serde_json::to_value(build(&s, Liveness::Unknown)).unwrap();
2336        let judge = &json["sections"][1]["judges"][0];
2337        assert_eq!(judge["reasons"]["A"], "**Better** tests.\n\nKeeps the API.");
2338        assert_eq!(judge["reasons"]["B"], "Drops validation.");
2339        assert!(!judge["reasons_md"]["A"].as_array().unwrap().is_empty());
2340        assert!(!judge["reasons_md"]["B"].as_array().unwrap().is_empty());
2341    }
2342
2343    #[test]
2344    fn no_change_summaries_and_quota_recovery_guidance_are_not_lost() {
2345        let mut s = state();
2346        s.candidates = serde_json::from_value(serde_json::json!([
2347            {
2348                "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
2349                "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
2350            },
2351            {
2352                "index": 1, "label": "B", "agent": "b", "branch": "b", "worktree": "/b",
2353                "empty": true, "folded": true, "summary": " \n "
2354            }
2355        ]))
2356        .unwrap();
2357        s.tally = Some(tally(false));
2358        s.quota = serde_json::from_value(serde_json::json!([
2359            {
2360                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
2361                "agent": "signed-out", "cause": "authentication"
2362            },
2363            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
2364        ]))
2365        .unwrap();
2366        let json = serde_json::to_value(build(&s, Liveness::Unknown)).unwrap();
2367        let candidates = &json["sections"][0]["items"];
2368        assert_eq!(candidates[0]["state"], "no_change");
2369        assert_eq!(
2370            candidates[0]["detail"],
2371            "Already covered.\nNo patch needed."
2372        );
2373        assert_eq!(candidates[1]["state"], "no_change");
2374        assert!(candidates[1]["detail"].is_null());
2375        assert_eq!(
2376            json["sections"][1]["tally"]["rate_limited"],
2377            serde_json::json!(["judge-1", "judge-2"]),
2378            "the existing seat list remains compatible"
2379        );
2380        let unavailable = note(&json, "quota_details");
2381        assert_eq!(unavailable["tone"], "warn");
2382        assert_eq!(
2383            unavailable["lines"],
2384            serde_json::json!([
2385                "judge-1 (signed-out: re-authenticate)",
2386                "judge-2 (usage limit)"
2387            ])
2388        );
2389    }
2390
2391    #[test]
2392    fn a_stalled_tally_is_never_decided() {
2393        let mut s = state();
2394        s.tally = Some(tally(false));
2395        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("json");
2396        let t = json["sections"]
2397            .as_array()
2398            .expect("a")
2399            .iter()
2400            .find(|x| x["kind"] == "tally")
2401            .expect("tally");
2402        assert_eq!(t["tally"]["met_quorum"], false);
2403        assert_eq!(t["tally"]["decided"], false);
2404        assert_eq!(t["tally"]["provisional"], true);
2405        assert_eq!(t["tone"], "fail");
2406    }
2407
2408    #[test]
2409    fn findings_keep_severity_blocking_and_what_the_fixer_said() {
2410        let mut s = state();
2411        let mut r = round(1);
2412        r.reviews[0].findings = vec![
2413            finding("R1-1-1", Severity::Blocker),
2414            finding("R1-1-2", Severity::Major),
2415            finding("R1-1-3", Severity::Minor),
2416            finding("R1-1-4", Severity::Nit),
2417        ];
2418        r.fix = Some(
2419            serde_json::from_value::<FixRecord>(serde_json::json!({"agent": "f"})).expect("fix"),
2420        );
2421        let fix = r.fix.as_mut().expect("fix");
2422        fix.addressed = vec!["R1-1-1".to_owned()];
2423        fix.rejected = vec![
2424            Rejection {
2425                id: "R1-1-2".to_owned(),
2426                why: "not a bug".to_owned(),
2427            },
2428            Rejection {
2429                id: "R9-9-9".to_owned(),
2430                why: "unknown id".to_owned(),
2431            },
2432        ];
2433        s.reviews.push(r);
2434        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("json");
2435        let review = json["sections"]
2436            .as_array()
2437            .expect("a")
2438            .iter()
2439            .find(|x| x["kind"] == "review")
2440            .expect("review");
2441        let f = &review["rounds"][0]["findings"];
2442        let at = |i: usize| {
2443            (
2444                f[i]["severity"].clone(),
2445                f[i]["blocking"].clone(),
2446                f[i]["state"].clone(),
2447            )
2448        };
2449        assert_eq!(at(0), ("blocker".into(), true.into(), "fixed".into()));
2450        assert_eq!(at(1), ("major".into(), true.into(), "declined".into()));
2451        assert_eq!(f[1]["declined_why"], "not a bug");
2452        assert_eq!(at(2), ("minor".into(), false.into(), "open".into()));
2453        assert_eq!(at(3), ("nit".into(), false.into(), "open".into()));
2454        assert_eq!(
2455            f[4]["id"], "R9-9-9",
2456            "an unmatched declined id is not dropped"
2457        );
2458        assert_eq!(f[4]["state"], "declined");
2459    }
2460
2461    #[test]
2462    fn a_deferred_e2e_is_not_a_failed_one() {
2463        let mut s = state();
2464        let mut deferred = round(1);
2465        deferred.e2e_deferred = true;
2466        deferred.e2e_defer_reason = Some("blocking findings".to_owned());
2467        let mut failed = round(2);
2468        failed.e2e = vec![cmd(Some(1), false)];
2469        let mut blocked = round(3);
2470        blocked.e2e = vec![cmd(None, true)];
2471        let none = round(4);
2472        s.reviews = vec![deferred, failed, blocked, none];
2473        let json = serde_json::to_value(build(&s, Liveness::Unknown)).expect("json");
2474        let rounds = &json["sections"]
2475            .as_array()
2476            .expect("a")
2477            .iter()
2478            .find(|x| x["kind"] == "review")
2479            .expect("review")["rounds"];
2480        let st = |i: usize| {
2481            rounds[i]["e2e"]["state"]
2482                .as_str()
2483                .expect("state")
2484                .to_owned()
2485        };
2486        assert_eq!(
2487            [st(0), st(1), st(2), st(3)],
2488            ["deferred", "fail", "blocked", "not_configured"]
2489        );
2490        assert_eq!(rounds[0]["e2e"]["defer_reason"], "blocking findings");
2491        let tail = rounds[1]["commands"][0]["output_tail"]
2492            .as_str()
2493            .expect("tail");
2494        assert!(tail.len() < 2_100, "output is bounded: {}", tail.len());
2495    }
2496    fn graft_json(s: &RunState, rec: Option<&crate::graft_report::Recovered>) -> serde_json::Value {
2497        let json = serde_json::to_value(build_with(s, Liveness::Unknown, rec)).expect("json");
2498        json["sections"]
2499            .as_array()
2500            .expect("a")
2501            .iter()
2502            .find(|x| x["kind"] == "graft")
2503            .cloned()
2504            .unwrap_or(serde_json::Value::Null)
2505    }
2506
2507    fn graft_record(outcome: crate::run::GraftOutcome) -> crate::run::GraftRecord {
2508        use crate::run::{GraftAdoption, GraftRejection, GraftStrength};
2509        crate::run::GraftRecord {
2510            pre: "aaaaaaaaaaaaaaaa".to_owned(),
2511            post: Some("bbbbbbbbbbbbbbbb".to_owned()),
2512            lines: Some(25),
2513            limit: Some(227),
2514            agent: Some("astra".to_owned()),
2515            outcome,
2516            requested: vec![
2517                GraftStrength {
2518                    id: "A1".into(),
2519                    source: 'A',
2520                    text: "Build Persona directly in the test".into(),
2521                },
2522                GraftStrength {
2523                    id: "A2".into(),
2524                    source: 'A',
2525                    text: "Cache the lookup".into(),
2526                },
2527                GraftStrength {
2528                    id: "A3".into(),
2529                    source: 'A',
2530                    text: "Rename the helper".into(),
2531                },
2532            ],
2533            adoption: Some(GraftAdoption {
2534                addressed: vec!["A1".into()],
2535                rejected: vec![GraftRejection {
2536                    id: "A2".into(),
2537                    why: "too large".into(),
2538                }],
2539                notes: "ported <script>alert(1)</script>".into(),
2540                reasoning: "thinking".into(),
2541            }),
2542            adoption_error: None,
2543        }
2544    }
2545
2546    #[test]
2547    fn an_applied_graft_separates_requested_from_confirmed() {
2548        let mut s = state();
2549        s.graft = Some(graft_record(crate::run::GraftOutcome::Applied));
2550        s.handovers.push(crate::run::Handover {
2551            at: jiff::Timestamp::now(),
2552            node: "graft".into(),
2553            seat: "graft".into(),
2554            from: "sonnet".into(),
2555            to: "astra".into(),
2556            reason: "timed out".into(),
2557        });
2558        let g = &graft_json(&s, None)["graft"];
2559        assert_eq!(g["outcome"], "applied");
2560        assert_eq!(g["agent"], "astra");
2561        assert_eq!(g["handovers"][0]["from"], "sonnet");
2562        assert_eq!(g["lines"], 25);
2563        assert!(g.get("limit").is_none());
2564        let st: Vec<_> = g["requested"]
2565            .as_array()
2566            .expect("a")
2567            .iter()
2568            .map(|r| r["state"].as_str().expect("s").to_owned())
2569            .collect();
2570        assert_eq!(st, ["adopted", "rejected", "unreported"]);
2571        assert_eq!(g["requested"][1]["why"], "too large");
2572        assert_eq!(g["adopted_count"], 1);
2573        assert_eq!(g["unconfirmed_count"], 1);
2574        assert_eq!(g["diff_available"], true);
2575    }
2576
2577    #[test]
2578    fn historical_graft_limits_are_readable_but_not_displayed() {
2579        let mut s = state();
2580        let old = serde_json::to_value(graft_record(crate::run::GraftOutcome::Applied)).unwrap();
2581        assert_eq!(old["limit"], 227);
2582        let mut record: crate::run::GraftRecord = serde_json::from_value(old).unwrap();
2583        assert_eq!(record.limit, Some(227));
2584        record.lines = None;
2585        s.graft = Some(record);
2586        let view = graft_json(&s, None);
2587        assert!(view["graft"]["lines"].is_null());
2588        assert!(view["graft"].get("limit").is_none());
2589        let text = crate::report::run(&s);
2590        assert!(text.contains("changed lines unavailable"));
2591        assert!(!text.contains("limit 227"));
2592        assert!(!text.contains("0 changed lines"));
2593
2594        s.graft.as_mut().unwrap().lines = Some(25);
2595        let text = crate::report::run(&s);
2596        assert!(text.contains("25 changed lines"));
2597        assert!(!text.contains("limit 227"));
2598    }
2599
2600    #[test]
2601    fn a_rolled_back_graft_carries_its_reason_and_no_diff() {
2602        let mut s = state();
2603        let mut g = graft_record(crate::run::GraftOutcome::RolledBack("too big".into()));
2604        g.post = None;
2605        s.graft = Some(g);
2606        let v = graft_json(&s, None);
2607        assert_eq!(v["graft"]["outcome"], "rolled_back");
2608        assert_eq!(v["graft"]["reason"], "too big");
2609        assert_eq!(v["graft"]["diff_available"], false);
2610        assert_eq!(v["tone"], "warn");
2611    }
2612
2613    #[test]
2614    fn a_legacy_record_says_unavailable_and_claims_nothing() {
2615        let mut s = state();
2616        let mut g = graft_record(crate::run::GraftOutcome::Applied);
2617        g.requested.clear();
2618        g.adoption = None;
2619        s.graft = Some(g);
2620        let v = graft_json(&s, None);
2621        let reasons: Vec<_> = v["graft"]["unavailable"]
2622            .as_array()
2623            .expect("a")
2624            .iter()
2625            .map(|u| u["reason"].as_str().expect("s"))
2626            .collect();
2627        assert_eq!(reasons, ["legacy_record", "legacy_record"]);
2628        assert_eq!(v["graft"]["requested"].as_array().expect("a").len(), 0);
2629        assert_eq!(v["graft"]["adopted_count"], 0);
2630    }
2631
2632    #[test]
2633    fn recovered_details_fill_a_legacy_record_and_are_marked() {
2634        let mut s = state();
2635        let mut g = graft_record(crate::run::GraftOutcome::Applied);
2636        let requested = std::mem::take(&mut g.requested);
2637        let adoption = g.adoption.take();
2638        s.graft = Some(g);
2639        let rec = crate::graft_report::Recovered {
2640            requested,
2641            adoption,
2642            unavailable: Vec::new(),
2643        };
2644        let g = &graft_json(&s, Some(&rec))["graft"];
2645        assert_eq!(g["recovered"], true);
2646        assert_eq!(g["requested"][0]["state"], "adopted");
2647    }
2648
2649    #[test]
2650    fn agent_text_stays_text_in_the_view() {
2651        let mut s = state();
2652        let mut g = graft_record(crate::run::GraftOutcome::Applied);
2653        g.requested[0].text = "<img src=x onerror=alert(1)>".into();
2654        s.graft = Some(g);
2655        let v = graft_json(&s, None);
2656        assert_eq!(
2657            v["graft"]["requested"][0]["text"],
2658            "<img src=x onerror=alert(1)>"
2659        );
2660        // Prose goes through the markdown tree, which has no raw-HTML node.
2661        let notes = v["graft"]["notes_md"].to_string();
2662        assert!(!notes.contains("\"html\""), "{notes}");
2663    }
2664}