Skip to main content

magi/
report_view.rs

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