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