1use std::fmt::Write as _;
13use std::sync::atomic::{AtomicBool, Ordering};
14
15use crate::config::{MergeMode, MergeStyle};
16use crate::run::{
17 CommandOutcome, ContinuationOutcome, E2eStatus, GateStatus, JobStatus, Liveness,
18 OperatorFixOutcome, RunState, RunStatus, tail,
19};
20use crate::stats::Stats;
21use crate::verdict::ReviewVote;
22
23static COLOR: AtomicBool = AtomicBool::new(true);
24
25pub fn set_color(on: bool) {
27 COLOR.store(on, Ordering::Relaxed);
28}
29
30fn paint(text: &str, code: &str) -> String {
31 if COLOR.load(Ordering::Relaxed) {
32 format!("\x1b[{code}m{text}\x1b[0m")
33 } else {
34 text.to_owned()
35 }
36}
37
38fn bold(t: &str) -> String {
39 paint(t, "1")
40}
41fn dim(t: &str) -> String {
42 paint(t, "2")
43}
44fn red(t: &str) -> String {
45 paint(t, "31")
46}
47fn green(t: &str) -> String {
48 paint(t, "32")
49}
50fn yellow(t: &str) -> String {
51 paint(t, "33")
52}
53fn cyan(t: &str) -> String {
54 paint(t, "36")
55}
56
57fn status_word(state: &RunState) -> String {
68 if state.unmerged_by_design() {
69 return cyan("unmerged (no-op by design)");
70 }
71 let text = state.status.display_label();
72 if state.needs_attention() {
73 return bold(&yellow(&format!("{text} - release needs a human")));
74 }
75 match state.status {
76 RunStatus::Merged => bold(&green(text)),
77 RunStatus::Ready => green(text),
78 RunStatus::Stalled => bold(&yellow(text)),
79 RunStatus::Blocked => yellow(text),
80 RunStatus::Failed => red(text),
81 RunStatus::VerifiedNoop => cyan(text),
85 RunStatus::Superseded => dim(text),
88 _ => cyan(text),
89 }
90}
91
92fn vote_tag(vote: ReviewVote) -> String {
96 let text = vote.label();
97 match vote {
98 ReviewVote::Approve => green(text),
99 ReviewVote::ApproveWithFindings => yellow(text),
100 ReviewVote::Reject => red(text),
101 }
102}
103
104pub fn line(state: &RunState) -> String {
106 line_with_liveness(state, Liveness::Unknown)
107}
108
109pub fn line_with_liveness(state: &RunState, live: Liveness) -> String {
112 let winner = state
113 .tally
114 .as_ref()
115 .map_or("-".to_owned(), |t| t.winner.to_string());
116 let agent = state.winner().map_or("-", |c| c.agent.as_str());
117 let quorum = match state.tally.as_ref() {
120 Some(t) if !t.met_quorum => format!(
121 " {}",
122 bold(&red(&format!("quorum {}/{}", t.present, t.judges)))
123 ),
124 Some(t) if t.present > 0 && t.present < t.judges => format!(
125 " {}",
126 yellow(&format!("judges {}/{}", t.present, t.judges))
127 ),
128 _ => String::new(),
129 };
130 let stale = if !state.status.done() && live == Liveness::Dead {
131 format!(
132 " {}",
133 bold(&yellow("STALE — driver exited; resume required"))
134 )
135 } else {
136 String::new()
137 };
138 format!(
139 "{} {:<20} {:>2}c {:>2}j win {} ({}){quorum}{stale} {}",
140 dim(&state.id),
141 status_word(state),
142 state.candidates.len(),
143 state.judgements.len(),
144 winner,
145 agent,
146 first_line(&state.instruction)
147 )
148}
149
150pub fn liveness_notice(state: &RunState, live: Liveness) -> String {
154 if !state.status.done() && live == Liveness::Dead {
155 format!(
156 "{}\n\n",
157 yellow("STALE — the process driving this run exited; resume it to continue.")
158 )
159 } else {
160 String::new()
161 }
162}
163
164pub fn superseded_notice(later: Option<&str>) -> String {
175 match later {
176 Some(later) => format!(
177 "{}\n\n",
178 yellow(&format!(
179 "SUPERSEDED — a later attempt at this task ({later}) replaced it; this record \
180 is kept but is not the one to act on."
181 ))
182 ),
183 None => String::new(),
184 }
185}
186
187fn first_line(text: &str) -> String {
188 let line = text.lines().next().unwrap_or_default();
189 if line.chars().count() > 68 {
190 format!("{}…", line.chars().take(67).collect::<String>())
191 } else {
192 line.to_owned()
193 }
194}
195
196fn short(commit: &str) -> String {
197 commit.chars().take(7).collect()
198}
199
200fn continuation_note(c: &crate::run::ContinuationRecord) -> String {
205 match c.outcome {
206 ContinuationOutcome::NotNeeded => String::new(),
207 ContinuationOutcome::Resumed => format!(" [resumed x{}]", c.attempts),
208 ContinuationOutcome::Exhausted => format!(" [continuation exhausted x{}]", c.attempts),
209 ContinuationOutcome::QuotaLost => " [continuation: quota]".to_owned(),
210 ContinuationOutcome::NoSession => " [no session to resume]".to_owned(),
211 }
212}
213
214fn jobs_section(state: &RunState) -> String {
235 let mut s = String::new();
236 if state.jobs.is_empty() {
237 if state
242 .config
243 .agents
244 .iter()
245 .any(|a| a.kind == crate::config::AgentKind::Codex)
246 {
247 let _ = writeln!(
248 s,
249 "\n{}",
250 dim(
251 "background jobs: no completed command evidence yet for this run (see \
252 active seats above for what is still mid-turn)"
253 )
254 );
255 }
256 return s;
257 }
258 let _ = writeln!(
259 s,
260 "\n{}",
261 bold("background jobs (from each seat's own CLI)")
262 );
263 let mut by_seat: std::collections::BTreeMap<(&str, &str), Vec<&crate::run::JobRecord>> =
264 std::collections::BTreeMap::new();
265 for j in &state.jobs {
266 by_seat
267 .entry((j.node.as_str(), j.seat.as_str()))
268 .or_default()
269 .push(j);
270 }
271 for ((node, seat), records) in by_seat {
272 let _ = writeln!(s, " {node}/{seat}");
273 for j in records {
274 let status = match j.status {
275 JobStatus::Completed => green("completed"),
276 JobStatus::Failed => red("failed"),
277 JobStatus::Unknown => yellow("unknown"),
278 };
279 let _ = writeln!(
280 s,
281 " {} {}{}{} checked {}",
282 dim(&j.id),
283 status,
284 j.exit_code
285 .map_or(String::new(), |c| format!(" (exit {c})")),
286 j.round.map_or(String::new(), |r| format!(" round {r}")),
287 j.checked_at
288 .to_zoned(jiff::tz::TimeZone::system())
289 .strftime("%Y-%m-%d %H:%M:%S")
290 );
291 let desc = first_line(&j.description);
292 if !desc.trim().is_empty() {
293 let _ = writeln!(s, " $ {desc}");
294 }
295 let summary = first_line(&j.result_summary);
296 if !summary.trim().is_empty() {
297 let _ = writeln!(s, " {}", dim(&summary));
298 }
299 }
300 }
301 let _ = writeln!(
302 s,
303 " {}",
304 dim(
305 "(adapter coverage: codex only today; other backends, and a command a CLI never \
306 reported finishing, leave no entry here — that is unknown, never \"nothing ran\")"
307 )
308 );
309 s
310}
311
312pub fn run(state: &RunState) -> String {
314 let mut s = String::new();
315 let _ = writeln!(
316 s,
317 "{} {} {}",
318 bold("magi run"),
319 bold(&state.id),
320 status_word(state)
321 );
322 let _ = writeln!(
323 s,
324 " repo {} ({} @ {})",
325 state.repo.display(),
326 state.base_branch,
327 short(&state.base_commit)
328 );
329 let _ = writeln!(s, " created {}", state.created_local());
330 let _ = writeln!(s, " task {}", first_line(&state.instruction));
331 let _ = writeln!(s, " state {}", state.dir().display());
332
333 let _ = writeln!(s, "\n{}", bold("candidates"));
334 for c in &state.candidates {
335 let flag = match (&c.failed, c.empty, &c.verified_noop) {
336 (Some(e), _, _) => red(&format!("failed: {e}")),
337 (None, true, Some(_)) => cyan("agent-verified no-op (unconfirmed)"),
341 (None, true, None) => yellow("no change"),
342 _ => format!("{} files, {} commits", c.files, c.commits),
343 };
344 let crown = if state.tally.as_ref().is_some_and(|t| t.winner == c.label) {
345 bold(&green(" <- winner"))
346 } else {
347 String::new()
348 };
349 let _ = writeln!(
350 s,
351 " {} {:<12} {:<30} {:>5}s{}",
352 bold(&c.label.to_string()),
353 c.agent,
354 flag,
355 c.duration_ms / 1000,
356 crown
357 );
358 if let Some(evidence) = &c.verified_noop {
359 let _ = writeln!(s, " {}", dim(&first_line(evidence)));
360 } else if !c.summary.trim().is_empty() {
361 let _ = writeln!(s, " {}", dim(&first_line(&c.summary)));
370 }
371 }
372
373 if !state.judgements.is_empty() {
374 let _ = writeln!(s, "\n{}", bold("blind judging"));
375 for j in &state.judgements {
376 match &j.failed {
377 Some(e) => {
378 let _ = writeln!(
379 s,
380 " judge {} {}",
381 j.judge,
382 red(&format!("no ranking: {e}"))
383 );
384 }
385 None => {
386 let _ = writeln!(
387 s,
388 " judge {} {:<12} {} confidence {}",
389 j.judge,
390 j.agent,
391 bold(&j.ranking.iter().collect::<String>()),
392 j.confidence.map_or("-".to_owned(), |c| c.to_string())
393 );
394 }
395 }
396 }
397 }
398
399 if let Some(t) = &state.tally {
400 if t.deliberated {
401 let _ = writeln!(s, "\n{}", bold("deliberation"));
402 for round in &state.deliberation {
403 for turn in &round.turns {
404 let _ = writeln!(
405 s,
406 " r{} judge {} -> {}",
407 round.round,
408 turn.judge,
409 turn.tentative.map_or("-".to_owned(), |c| c.to_string())
410 );
411 }
412 }
413 }
414
415 if !state.votes.is_empty() {
416 let _ = writeln!(s, "\n{}", bold("final votes (collected privately)"));
417 for v in &state.votes {
418 let _ = writeln!(
419 s,
420 " judge {} {:<12} {}{}",
421 v.judge,
422 v.agent,
423 bold(&v.vote.unwrap_or('?').to_string()),
424 if v.changed {
425 yellow(" (changed after deliberation)")
426 } else {
427 String::new()
428 }
429 );
430 }
431 }
432
433 let _ = writeln!(s, "\n{}", bold("tally"));
434 match &t.uncontested {
440 Some(reason) => {
441 let _ = writeln!(
442 s,
443 " judging {}",
444 cyan(&format!("not needed — {reason}"))
445 );
446 }
447 None => {
448 let _ = writeln!(
449 s,
450 " judges {} present{}",
451 if t.met_quorum {
452 green(&format!("{}/{}", t.present, t.judges))
453 } else {
454 red(&format!("{}/{}", t.present, t.judges))
455 },
456 if t.quorum > 0 {
457 format!(" ({quorum} required)", quorum = t.quorum)
458 } else {
459 String::new()
460 }
461 );
462 if !t.met_quorum {
463 let _ = writeln!(
464 s,
465 " {}",
466 bold(&red("BELOW QUORUM — verdict is not trustworthy"))
467 );
468 }
469 let _ = writeln!(
470 s,
471 " first choice {}",
472 t.first_choice
473 .iter()
474 .map(|(k, v)| format!("{k}:{v}"))
475 .collect::<Vec<_>>()
476 .join(" ")
477 );
478 let _ = writeln!(
479 s,
480 " initial {}",
481 match (t.rankings, t.unanimous_initial) {
482 (0, _) => red("no usable ranking"),
483 (1, _) => yellow("one usable ranking - not a consensus"),
484 (_, true) => green("unanimous"),
485 (_, false) => yellow("split"),
486 }
487 );
488 let _ = writeln!(
489 s,
490 " after votes {} ({} judge(s) moved)",
491 if t.unanimous_final {
492 green("unanimous")
493 } else {
494 yellow("still split")
495 },
496 t.changed_votes
497 );
498 if let Some(tb) = &t.tie_break {
499 let _ = writeln!(s, " tie break {tb}");
500 }
501 }
502 }
503 if !state.quota.is_empty() {
504 let _ = writeln!(
505 s,
506 " rate limited {}",
507 state
508 .quota
509 .iter()
510 .map(|q| q.seat.as_str())
511 .collect::<Vec<_>>()
512 .join(", ")
513 );
514 }
515 let _ = writeln!(s, " winner {}", bold(&green(&t.winner.to_string())));
516 }
517
518 if !state.withheld.is_empty() {
519 let _ = writeln!(s, "\n{}", bold("withheld from commit"));
520 for w in &state.withheld {
521 let _ = writeln!(
522 s,
523 " {} {} ({} lockfile; the directory uses {})",
524 yellow("!"),
525 w.path,
526 w.manager,
527 w.kept_by
528 );
529 }
530 }
531
532 if !state.reviews.is_empty() {
533 let _ = writeln!(s, "\n{}", bold("review + verification"));
534 for r in &state.reviews {
535 let raised: usize = r.reviews.iter().map(|x| x.findings.len()).sum();
536 let e2e = match r.e2e_status() {
544 E2eStatus::NotConfigured => dim("no e2e"),
545 E2eStatus::Deferred => yellow(&format!(
546 "e2e deferred{}",
547 r.e2e_defer_reason
548 .as_deref()
549 .map(|why| format!(" ({why})"))
550 .unwrap_or_default()
551 )),
552 E2eStatus::Passed => green("e2e green"),
553 E2eStatus::Failed if r.e2e.iter().any(CommandOutcome::build_failed) => {
554 yellow("e2e could not run (build/link failure)")
555 }
556 E2eStatus::Failed => red("e2e RED"),
557 E2eStatus::ResourceBlocked => {
562 yellow("e2e could not run (shared build cache unavailable)")
563 }
564 };
565 let e2e = if r.verify_retried {
566 format!("{e2e}, retried once")
567 } else {
568 e2e
569 };
570 let status = if r.incomplete() {
574 yellow("incomplete")
575 } else if r.clean {
576 green("clean")
577 } else {
578 yellow("open")
579 };
580 let panel = if r.incomplete() {
584 let missing: Vec<String> = r
585 .reviews
586 .iter()
587 .filter_map(|x| {
588 x.failed
589 .as_ref()
590 .map(|why| format!("review-{}: {why}", x.reviewer))
591 })
592 .collect();
593 format!(
594 " {}/{} reviewers answered ({})",
595 r.answered,
596 r.expected,
597 missing.join(", ")
598 )
599 } else {
600 String::new()
601 };
602 let verdict = r.verdict.map_or(String::new(), |v| {
608 format!(
609 ", verdict {}{}",
610 vote_tag(v),
611 if r.vote_split { " (panel split)" } else { "" }
612 )
613 });
614 let _ = writeln!(
615 s,
616 " round {} {} @ {}{}{panel} {raised} finding(s), {} blocking, {e2e}{verdict}{}",
617 r.round,
618 status,
619 short(&r.head),
620 r.verified_head.as_ref().map_or(String::new(), |head| {
621 format!(
622 " (verified @ {}{})",
623 short(head),
624 r.verified_at.map_or(String::new(), |t| format!(
625 " on {}",
626 t.to_zoned(jiff::tz::TimeZone::system())
627 .strftime("%Y-%m-%d %H:%M:%S")
628 ))
629 )
630 }),
631 r.blocking,
632 r.fix.as_ref().map_or(String::new(), |f| {
633 let tree = if r.progressed {
634 green("changed")
635 } else {
636 yellow("unchanged")
637 };
638 let cont = f
639 .continuation
640 .as_ref()
641 .map_or(String::new(), continuation_note);
642 match &f.failed {
643 Some(reason) => format!(
648 " fix: {}, tree {tree}{}{cont}",
649 yellow(&format!("adoption report lost ({reason})")),
650 if f.committed {
651 String::new()
652 } else {
653 red(" (NO COMMIT)")
654 }
655 ),
656 None => format!(
657 " fix: {} addressed / {} rejected, tree {tree}{}{cont}",
658 f.addressed.len(),
659 f.rejected.len(),
660 if f.committed {
661 String::new()
662 } else {
663 red(" (NO COMMIT)")
664 }
665 ),
666 }
667 })
668 );
669 for o in &r.e2e {
676 let label = if o.resource_blocked {
677 yellow("blocked")
678 } else if o.ok() {
679 green("pass")
680 } else {
681 red("FAIL")
682 };
683 let _ = writeln!(s, " {label} {}", o.command);
684 if !o.ok() {
685 let _ = writeln!(s, "{}", dim(&tail(&o.output_tail, 2_000)));
686 }
687 }
688 for rec in &r.reviews {
689 if let Some(vote) = rec.vote {
690 let _ = writeln!(s, " review-{} vote {}", rec.reviewer, vote_tag(vote));
691 }
692 for f in &rec.findings {
693 let adopted = r
694 .fix
695 .as_ref()
696 .is_some_and(|fix| fix.addressed.contains(&f.id));
697 let _ = writeln!(
698 s,
699 " {} [{:?}] {}{}",
700 dim(&f.id),
701 f.severity,
702 f.title,
703 if adopted {
704 green(" fixed")
705 } else {
706 String::new()
707 }
708 );
709 }
710 }
711 if let Some(fix) = &r.fix {
712 for rej in &fix.rejected {
713 let _ = writeln!(
714 s,
715 " {} {}: {}",
716 dim(&rej.id),
717 yellow("declined"),
718 rej.why
719 );
720 }
721 }
722 if !r.reconsideration.is_empty() {
726 let _ = writeln!(s, " {}", dim("reconsideration:"));
727 for rv in &r.reconsideration {
728 match rv.vote {
729 Some(v) => {
730 let _ = writeln!(
731 s,
732 " review-{} -> {} {}",
733 rv.reviewer,
734 vote_tag(v),
735 rv.reason
736 );
737 }
738 None => {
739 let _ = writeln!(
740 s,
741 " review-{} -> {}",
742 rv.reviewer,
743 red(&format!(
744 "no revote ({})",
745 rv.failed.as_deref().unwrap_or("unknown")
746 ))
747 );
748 }
749 }
750 }
751 }
752 }
753 if state.handed_off_with_open_findings() {
754 let _ = writeln!(
755 s,
756 "\n {}",
757 yellow(&format!(
758 "handed off with {} finding(s) still open — gate and e2e were green; \
759 see above for what a person should still look at",
760 state.open_findings().len()
761 ))
762 );
763 }
764 }
765
766 if !state.operator_fixes.is_empty() {
767 let _ = writeln!(s, "\n{}", bold("operator fix(es)"));
768 for (i, req) in state.operator_fixes.iter().enumerate() {
769 let _ = writeln!(
770 s,
771 " [{}] {} finding(s) at {}{}",
772 i + 1,
773 req.findings.len(),
774 req.requested_at
775 .to_zoned(jiff::tz::TimeZone::system())
776 .strftime("%Y-%m-%d %H:%M:%S"),
777 if req.stale {
778 yellow(" stale head, --allow-stale used")
779 } else {
780 String::new()
781 }
782 );
783 let _ = writeln!(s, " reason: {}", req.reason);
784 for f in &req.findings {
785 let outcome = match &f.outcome {
786 OperatorFixOutcome::Pending => yellow("pending"),
787 OperatorFixOutcome::Addressed => green("addressed"),
788 OperatorFixOutcome::Rejected { why } => red(&format!("rejected: {why}")),
789 OperatorFixOutcome::Unreported => {
790 red("unreported — no adoption report came back")
791 }
792 };
793 let _ = writeln!(
794 s,
795 " {} [{:?}] {} {outcome}",
796 dim(&f.id),
797 f.severity,
798 f.title
799 );
800 }
801 match &req.follow_up_review_run {
802 Some(id) => {
803 let _ = writeln!(s, " re-verified by run {id}");
804 }
805 None if req.fix.as_ref().is_some_and(|fx| fx.committed) => {
806 let _ = writeln!(
807 s,
808 " {}",
809 red("committed, but the follow-up review could not be opened")
810 );
811 }
812 None => {
813 let _ = writeln!(s, " no change committed; nothing to re-verify");
814 }
815 }
816 }
817 }
818
819 if let Some(bs) = &state.base_sync {
820 let _ = writeln!(s, "\n{}", bold("base sync"));
821 let status = if let Some(c) = &bs.conflict {
822 red(&format!("conflict: {}", first_line(c)))
823 } else if bs.behind == 0 {
824 green("in sync")
825 } else {
826 yellow(&format!("{} commit(s) behind, not yet rebased", bs.behind))
827 };
828 let _ = writeln!(
829 s,
830 " {} @ {} {status}{}",
831 state.base_branch,
832 short(&bs.tip),
833 if bs.attempts > 0 {
834 format!(" ({} rebase attempt(s))", bs.attempts)
835 } else {
836 String::new()
837 }
838 );
839 }
840
841 if !state.pre_gate.is_empty() {
842 let _ = writeln!(s, "\n{}", bold("pre_gate"));
843 for o in &state.pre_gate {
844 let _ = writeln!(
845 s,
846 " {} {}",
847 if o.ok() {
848 green("pass")
849 } else {
850 yellow("warn")
851 },
852 o.command
853 );
854 if !o.ok() {
855 let _ = writeln!(s, "{}", dim(&tail(&o.output_tail, 2_000)));
856 }
857 }
858 if let Some(c) = &state.pre_gate_commit {
859 let _ = writeln!(s, " committed mechanical fixes @ {}", short(c));
860 }
861 }
862
863 match state.gate_status() {
867 GateStatus::NotRun => {}
868 GateStatus::PassedWithNoCommands => {
869 let _ = writeln!(s, "\n{}", bold("gate"));
870 let _ = writeln!(s, " {} no gate commands configured", green("pass"));
871 }
872 GateStatus::Passed | GateStatus::Failed => {
873 let _ = writeln!(s, "\n{}", bold("gate"));
874 for o in &state.gate {
875 let _ = writeln!(
876 s,
877 " {} {}",
878 if o.ok() { green("pass") } else { red("FAIL") },
879 o.command
880 );
881 if !o.ok() {
882 let _ = writeln!(s, "{}", dim(&tail(&o.output_tail, 2_000)));
883 }
884 }
885 }
886 }
887
888 if let Some(m) = &state.merge {
889 let _ = writeln!(s, "\n{}", bold("merge"));
890 if m.mode == MergeMode::None {
891 let _ = writeln!(
895 s,
896 " mode None {}",
897 cyan("not landed — nothing to do by design")
898 );
899 if let Some(w) = state.winner() {
900 let _ = writeln!(
901 s,
902 " branch {} still exists, unmerged into {}",
903 w.branch, state.base_branch
904 );
905 }
906 let _ = writeln!(
912 s,
913 " rebase onto {} before merging by hand{}",
914 state.base_branch,
915 if state.config.merge.style == MergeStyle::Squash {
916 ", and pass an explicit commit message — a squash merge \
917 otherwise inherits the candidate's placeholder subject"
918 } else {
919 ""
920 }
921 );
922 let _ = writeln!(s, " {}", m.detail.lines().next().unwrap_or(""));
923 } else {
924 let _ = writeln!(
925 s,
926 " mode {:?} {}\n {}",
927 m.mode,
928 if m.ok {
929 green("ok")
930 } else {
931 yellow("not merged")
932 },
933 m.detail.lines().next().unwrap_or("")
934 );
935 }
936 }
937
938 if let Some(b) = &state.release_bump {
939 let _ = writeln!(s, "\n{}", bold("release bump"));
940 if let Some(v) = &b.version {
941 let _ = writeln!(s, " version v{v}");
942 }
943 if let Some(url) = &b.pr_url {
944 let _ = writeln!(s, " pr {url}");
945 }
946 let _ = writeln!(
947 s,
948 " automerge {}",
949 if b.automerge_enabled {
950 green("enabled")
951 } else if b.merged_directly {
952 green("not needed (CI was already green; merged directly)")
953 } else if b.problem.is_some() {
954 bold(&red("FAILED"))
955 } else {
956 dim("not enabled")
957 }
958 );
959 if let Some(p) = &b.problem {
960 let _ = writeln!(s, " {}", p.lines().next().unwrap_or(""));
961 }
962 if let Some(a) = &b.action_required {
963 let _ = writeln!(s, " {} {a}", bold(&yellow("action required:")));
964 }
965 }
966
967 if !state.leaks.is_empty() {
968 let _ = writeln!(s, "\n{}", bold(&yellow("blindness warnings")));
969 for l in &state.leaks {
970 let _ = writeln!(s, " {} x{} in {}", l.token, l.count, l.site);
971 }
972 }
973
974 if let Some(w) = state.winner()
975 && !w.folded
976 {
977 let _ = writeln!(
978 s,
979 "\n{} {}\n branch {}",
980 bold("winner worktree"),
981 w.worktree.display(),
982 w.branch
983 );
984 }
985 s.push_str(&jobs_section(state));
986 s
987}
988
989pub fn active_seats(state: &RunState, live: Liveness) -> String {
1005 if state.active.is_empty() {
1006 return String::new();
1007 }
1008 let mut s = String::new();
1009 let _ = writeln!(s, "\n{}", bold("running now"));
1010 let now = jiff::Timestamp::now();
1011 match live {
1012 Liveness::Live => {}
1013 Liveness::Dead => {
1014 let _ = writeln!(
1015 s,
1016 " {}",
1017 yellow(
1018 "no live daemon claims this run right now — likely left behind by a killed process"
1019 )
1020 );
1021 }
1022 Liveness::Unknown => {
1023 let overrun = if state.active_all_overrun(now) {
1029 " — every active seat has already run past its own timeout budget"
1030 } else {
1031 ""
1032 };
1033 let _ = writeln!(
1034 s,
1035 " {}",
1036 yellow(&format!(
1037 "whether a process is still driving this run could not be confirmed{overrun}"
1038 ))
1039 );
1040 }
1041 }
1042 for (seat, a) in state.seats_active() {
1043 let retry = if a.attempt > 0 {
1044 format!(" retry {}", a.attempt)
1045 } else {
1046 String::new()
1047 };
1048 let _ = writeln!(
1049 s,
1050 " {:<12} {:<12}{retry} {}s elapsed, {}s left of {}s",
1051 seat,
1052 a.node,
1053 a.elapsed_secs(now),
1054 a.remaining_secs(now),
1055 a.timeout_secs
1056 );
1057 }
1058 for (task, a) in state.tasks_active() {
1059 let retry = if a.attempt > 0 {
1060 format!(" retry {}", a.attempt)
1061 } else {
1062 String::new()
1063 };
1064 let progress = match (a.index, a.total) {
1065 (Some(i), Some(t)) => format!(" ({i}/{t})"),
1066 _ => String::new(),
1067 };
1068 let _ = writeln!(
1069 s,
1070 " {:<12} {:<12}{retry}{progress} {}s elapsed, {}s left of {}s",
1071 task,
1072 a.node,
1073 a.elapsed_secs(now),
1074 a.remaining_secs(now),
1075 a.timeout_secs
1076 );
1077 if let Some(command) = &a.command {
1078 let _ = writeln!(s, " {command}");
1079 }
1080 }
1081 s
1082}
1083
1084pub fn stats(stats: &Stats) -> String {
1086 let t = &stats.totals;
1087 let mut s = String::new();
1088 let _ = writeln!(s, "{}", bold("runs"));
1089 let _ = writeln!(
1090 s,
1091 " {} total - {} merged, {} ready, {} blocked, {} failed ({:.0}% completion)",
1092 t.runs,
1093 t.merged,
1094 t.ready,
1095 t.blocked,
1096 t.failed,
1097 t.completion_rate()
1098 );
1099 if t.tallied > 0 {
1100 let _ = writeln!(
1101 s,
1102 " {} tallied - {} split on first choice ({:.0}%), {} deliberated, \
1103 {} of those changed a mind, {} converged to unanimous",
1104 t.tallied,
1105 t.split,
1106 t.split_rate(),
1107 t.deliberated,
1108 t.minds_changed,
1109 t.converged
1110 );
1111 }
1112
1113 if !stats.agents.is_empty() {
1114 let _ = writeln!(
1115 s,
1116 "\n{}",
1117 bold("implementation (relative, on this workload)")
1118 );
1119 let _ = writeln!(
1120 s,
1121 " {:<14}{:>6}{:>8}{:>8}{:>8}",
1122 "agent", "won", "entered", "rate", "empty"
1123 );
1124 for a in &stats.agents {
1125 let _ = writeln!(
1126 s,
1127 " {:<14}{:>6}{:>8}{:>7.0}%{:>8}",
1128 a.agent,
1129 a.wins,
1130 a.entered,
1131 a.win_rate(),
1132 a.empty
1133 );
1134 }
1135 }
1136
1137 if !stats.reviewers.is_empty() {
1138 let _ = writeln!(s, "\n{}", bold("review"));
1139 let _ = writeln!(
1140 s,
1141 " {:<14}{:>8}{:>10}{:>11}{:>9}{:>9}{:>9}",
1142 "reviewer", "rounds", "submitted", "adopted/rd", "precision", "unique", "timeout"
1143 );
1144 for r in &stats.reviewers {
1145 let _ = writeln!(
1146 s,
1147 " {:<14}{:>8}{:>10}{:>11.2}{:>8.0}%{:>8.0}%{:>8.0}%",
1148 r.agent,
1149 r.rounds,
1150 r.submitted,
1151 r.adopted_per_round(),
1152 r.precision(),
1153 r.unique_rate(),
1154 r.timeout_rate()
1155 );
1156 }
1157 }
1158
1159 if stats.e2e.rounds > 0 || stats.e2e.deferred > 0 {
1160 let _ = writeln!(s, "\n{}", bold("verification"));
1161 let _ = writeln!(
1162 s,
1163 " {} rounds ran e2e, {} failed, {} of those with a clean static \
1164 review ({:.0}% sole detections), {} round(s) deferred it to the fixer",
1165 stats.e2e.rounds,
1166 stats.e2e.failures,
1167 stats.e2e.sole_detections,
1168 stats.e2e.sole_rate(),
1169 stats.e2e.deferred
1170 );
1171 }
1172 s
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177 use super::*;
1178 use crate::config::Config;
1179 use crate::run::{
1180 Candidate, CommandOutcome, FixRecord, MergeOutcome, ReviewRecord, ReviewRound, RunState,
1181 Tally,
1182 };
1183 use std::collections::BTreeMap;
1184 use std::path::PathBuf;
1185 use std::sync::{Mutex, MutexGuard};
1186
1187 static SERIAL: Mutex<()> = Mutex::new(());
1189
1190 fn plain() -> MutexGuard<'static, ()> {
1191 let guard = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
1192 set_color(false);
1193 guard
1194 }
1195
1196 fn state() -> RunState {
1197 crate::run::set_home(std::env::temp_dir().join("magi-report-test-home"));
1202 let mut s = RunState::new(
1203 PathBuf::from("/repo"),
1204 "main".to_owned(),
1205 "abcdef1234".to_owned(),
1206 "add retries to the uploader".to_owned(),
1207 Config::default(),
1208 );
1209 s.candidates = vec![Candidate {
1210 index: 0,
1211 label: 'A',
1212 agent: "opus".to_owned(),
1213 branch: "magi/x/A".to_owned(),
1214 worktree: PathBuf::from("/wt/A"),
1215 summary: String::new(),
1216 stat: String::new(),
1217 files: 3,
1218 commits: 2,
1219 empty: false,
1220 failed: None,
1221 verified_noop: None,
1222 duration_ms: 42_000,
1223 folded: false,
1224 }];
1225 s.tally = Some(Tally {
1226 first_choice: BTreeMap::from([('A', 3)]),
1227 borda: BTreeMap::new(),
1228 winner: 'A',
1229 rankings: 3,
1230 unanimous_initial: true,
1231 deliberated: false,
1232 changed_votes: 0,
1233 unanimous_final: true,
1234 tie_break: None,
1235 judges: 3,
1236 present: 3,
1237 quorum: 2,
1238 met_quorum: true,
1239 uncontested: None,
1240 });
1241 s
1242 }
1243
1244 #[test]
1245 fn run_report_names_the_winner_and_its_author() {
1246 let _guard = plain();
1247 let text = run(&state());
1248 assert!(text.contains("<- winner"), "{text}");
1249 assert!(text.contains("opus"));
1250 assert!(text.contains("3 files, 2 commits"));
1251 assert!(text.contains("winner A"));
1252 assert!(!text.contains('\x1b'), "colour leaked into a plain render");
1253 }
1254
1255 #[test]
1256 fn a_candidates_own_summary_is_surfaced_not_only_kept_in_run_json() {
1257 let _guard = plain();
1263 let mut s = state();
1264 s.candidates[0].summary =
1265 "investigated 6c5e/8df3: both already merged, see talk 07fe.\nmore detail below."
1266 .to_owned();
1267 let text = run(&s);
1268 assert!(
1269 text.contains("investigated 6c5e/8df3: both already merged, see talk 07fe."),
1270 "{text}"
1271 );
1272 }
1273
1274 #[test]
1275 fn a_verified_noop_run_does_not_read_as_a_failure() {
1276 let _guard = plain();
1280 let mut s = state();
1281 s.status = RunStatus::VerifiedNoop;
1282 s.tally = None;
1283 s.candidates = vec![Candidate {
1284 index: 0,
1285 label: 'A',
1286 agent: "opus".to_owned(),
1287 branch: "magi/x/A".to_owned(),
1288 worktree: PathBuf::from("/wt/A"),
1289 summary: String::new(),
1290 stat: String::new(),
1291 files: 0,
1292 commits: 0,
1293 empty: true,
1294 failed: None,
1295 verified_noop: Some("already fixed by b32cfc4, which is on main".to_owned()),
1296 duration_ms: 9_000,
1297 folded: false,
1298 }];
1299 let text = run(&s);
1300 assert!(
1301 text.contains("agent-verified no-op"),
1302 "the status and the candidate flag must both say so: {text}"
1303 );
1304 assert!(
1305 text.contains("already fixed by b32cfc4"),
1306 "the evidence itself must be readable, not just the verdict: {text}"
1307 );
1308 assert!(
1309 !text.to_lowercase().contains("failed"),
1310 "a verified no-op must never read as the failure it is not: {text}"
1311 );
1312 }
1313
1314 #[test]
1315 fn colour_is_emitted_only_when_enabled() {
1316 let _guard = plain();
1317 set_color(true);
1318 let coloured = run(&state());
1319 set_color(false);
1320 let plain = run(&state());
1321 assert!(coloured.contains('\x1b'));
1322 assert!(!plain.contains('\x1b'));
1323 assert!(coloured.len() > plain.len());
1324 }
1325
1326 #[test]
1327 fn list_line_is_single_line() {
1328 let _guard = plain();
1329 let l = line(&state());
1330 assert_eq!(l.lines().count(), 1);
1331 assert!(l.contains("add retries"));
1332 assert!(l.contains("win A (opus)"));
1333 }
1334
1335 #[test]
1336 fn an_uncontested_run_does_not_read_as_a_collapsed_panel() {
1337 let _guard = plain();
1338 let mut s = state();
1339 s.tally = Some(Tally {
1340 first_choice: BTreeMap::from([('A', 0)]),
1341 borda: BTreeMap::new(),
1342 winner: 'A',
1343 rankings: 0,
1344 unanimous_initial: false,
1345 deliberated: false,
1346 changed_votes: 0,
1347 unanimous_final: false,
1348 tie_break: None,
1349 judges: 0,
1350 present: 0,
1351 quorum: 0,
1352 met_quorum: true,
1353 uncontested: Some(
1354 "only candidate A produced a usable change; no panel was asked".to_owned(),
1355 ),
1356 });
1357 let text = run(&s);
1358 assert!(
1359 !text.contains("0/3"),
1360 "no panel sat, so the judges line must not read as one that collapsed: {text}"
1361 );
1362 assert!(!text.contains("no usable ranking"), "{text}");
1363 assert!(!text.contains("still split"), "{text}");
1364 assert!(!text.contains("BELOW QUORUM"), "{text}");
1365 assert!(
1366 text.contains("not needed"),
1367 "the report must say judging was skipped, not silent: {text}"
1368 );
1369 assert!(text.contains("winner A"));
1370 }
1371
1372 #[test]
1373 fn a_below_quorum_run_still_reads_as_a_collapsed_panel() {
1374 let _guard = plain();
1375 let mut s = state();
1376 s.tally = Some(Tally {
1377 first_choice: BTreeMap::from([('A', 1), ('B', 0)]),
1378 borda: BTreeMap::new(),
1379 winner: 'A',
1380 rankings: 1,
1381 unanimous_initial: false,
1382 deliberated: false,
1383 changed_votes: 0,
1384 unanimous_final: false,
1385 tie_break: None,
1386 judges: 3,
1387 present: 1,
1388 quorum: 2,
1389 met_quorum: false,
1390 uncontested: None,
1391 });
1392 let text = run(&s);
1393 assert!(text.contains("1/3"), "{text}");
1394 assert!(
1395 text.contains("BELOW QUORUM"),
1396 "a real collapse must still be flagged: {text}"
1397 );
1398 assert!(
1399 !text.contains("not needed"),
1400 "a collapsed panel must not be described as one that was never asked: {text}"
1401 );
1402 }
1403
1404 #[test]
1405 fn a_mode_none_merge_does_not_read_as_landed() {
1406 let _guard = plain();
1407 let mut s = state();
1408 s.merge = Some(MergeOutcome {
1409 mode: crate::config::MergeMode::None,
1410 ok: true,
1411 detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
1412 });
1413 let text = run(&s);
1414 assert!(
1415 !text.contains(" ok"),
1416 "mode none must not be shown as a landed merge: {text}"
1417 );
1418 assert!(text.contains("not landed"), "{text}");
1419 assert!(
1420 text.contains("branch magi/x/A"),
1421 "the report must say what's left behind: {text}"
1422 );
1423 assert!(
1424 text.contains("rebase"),
1425 "the report must point at the hand-landing steps: {text}"
1426 );
1427 assert!(
1428 !text.contains("placeholder subject"),
1429 "the default merge style is `merge`, which never inherits a \
1430 placeholder subject, so the squash caveat must not appear: {text}"
1431 );
1432 }
1433
1434 #[test]
1435 fn a_mode_none_squash_merge_warns_about_the_placeholder_subject() {
1436 let _guard = plain();
1437 let mut s = state();
1438 s.config.merge.style = MergeStyle::Squash;
1439 s.merge = Some(MergeOutcome {
1440 mode: crate::config::MergeMode::None,
1441 ok: true,
1442 detail: "git -C /repo merge --squash magi/x/A && git -C /repo commit -m \"add \
1443 retries\""
1444 .to_owned(),
1445 });
1446 let text = run(&s);
1447 assert!(
1448 text.contains("placeholder subject"),
1449 "a squash-style manual merge must warn about the missing message: {text}"
1450 );
1451 assert!(text.contains("--squash"), "{text}");
1452 }
1453
1454 #[test]
1455 fn a_ready_run_left_by_merge_mode_none_does_not_read_as_a_plain_ready() {
1456 let _guard = plain();
1457 let mut s = state();
1458 s.status = RunStatus::Ready;
1459 s.merge = Some(MergeOutcome {
1460 mode: crate::config::MergeMode::None,
1461 ok: true,
1462 detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
1463 });
1464
1465 let list = line(&s);
1466 assert!(
1467 !list.contains(" ready "),
1468 "a mode-none run must not read as a plain ready in `magi list`: {list}"
1469 );
1470 assert!(list.contains("no-op by design"), "{list}");
1471
1472 let full = run(&s);
1473 assert!(
1474 !full.contains("magi run") || !full.lines().next().unwrap().contains(" ready"),
1475 "the header line of `magi show` must not say plain ready either: {full}"
1476 );
1477 assert!(full.contains("no-op by design"), "{full}");
1478 }
1479
1480 #[test]
1481 fn an_ordinary_ready_run_still_reads_as_ready() {
1482 let _guard = plain();
1483 let mut s = state();
1484 s.status = RunStatus::Ready;
1485 s.merge = Some(MergeOutcome {
1489 mode: crate::config::MergeMode::Pr,
1490 ok: false,
1491 detail: "https://example.com/pr/1 was closed without merging".to_owned(),
1492 });
1493
1494 let list = line(&s);
1495 assert!(list.contains("ready"), "{list}");
1496 assert!(!list.contains("no-op by design"), "{list}");
1497 }
1498
1499 #[test]
1500 fn the_list_line_does_not_flag_an_uncontested_run_as_short_judges() {
1501 let _guard = plain();
1502 let mut s = state();
1503 s.tally = Some(Tally {
1504 first_choice: BTreeMap::from([('A', 0)]),
1505 borda: BTreeMap::new(),
1506 winner: 'A',
1507 rankings: 0,
1508 unanimous_initial: false,
1509 deliberated: false,
1510 changed_votes: 0,
1511 unanimous_final: false,
1512 tie_break: None,
1513 judges: 0,
1514 present: 0,
1515 quorum: 0,
1516 met_quorum: true,
1517 uncontested: Some("only candidate A produced a usable change".to_owned()),
1518 });
1519 let l = line(&s);
1520 assert!(
1521 !l.contains("judges") && !l.contains("quorum"),
1522 "an uncontested run must not carry the same badge a short panel gets: {l}"
1523 );
1524 }
1525
1526 #[test]
1527 fn long_instructions_are_elided() {
1528 let _guard = plain();
1529 let mut s = state();
1530 s.instruction = "x".repeat(200);
1531 assert!(line(&s).contains('…'));
1532 }
1533
1534 #[test]
1535 fn a_lost_fix_report_reads_differently_from_zero_adoption() {
1536 let _guard = plain();
1537 let mut lost = state();
1538 lost.reviews = vec![ReviewRound {
1539 round: 1,
1540 head: "abc1234".to_owned(),
1541 verified_head: None,
1542 verified_at: None,
1543 reviews: Vec::new(),
1544 e2e: Vec::new(),
1545 verify_retried: false,
1546 e2e_deferred: false,
1547 e2e_defer_reason: None,
1548 fix: Some(FixRecord {
1549 agent: "opus".to_owned(),
1550 addressed: Vec::new(),
1551 rejected: Vec::new(),
1552 notes: String::new(),
1553 committed: true,
1554 failed: Some("timed out".to_owned()),
1555 duration_ms: 0,
1556 continuation: None,
1557 }),
1558 blocking: 3,
1559 answered: 0,
1560 expected: 0,
1561 clean: false,
1562 progressed: false,
1563 vote_split: false,
1564 reconsideration: Vec::new(),
1565 verdict: None,
1566 }];
1567 let text = run(&lost);
1568 assert!(text.contains("adoption report lost (timed out)"), "{text}");
1569 assert!(
1570 !text.contains("0 addressed"),
1571 "a lost report must never read as `0 addressed`: {text}"
1572 );
1573
1574 let mut rejected_all = state();
1575 rejected_all.reviews = vec![ReviewRound {
1576 round: 1,
1577 head: "abc1234".to_owned(),
1578 verified_head: None,
1579 verified_at: None,
1580 reviews: Vec::new(),
1581 e2e: Vec::new(),
1582 verify_retried: false,
1583 e2e_deferred: false,
1584 e2e_defer_reason: None,
1585 fix: Some(FixRecord {
1586 agent: "opus".to_owned(),
1587 addressed: Vec::new(),
1588 rejected: Vec::new(),
1589 notes: String::new(),
1590 committed: true,
1591 failed: None,
1592 duration_ms: 0,
1593 continuation: None,
1594 }),
1595 blocking: 3,
1596 answered: 0,
1597 expected: 0,
1598 clean: false,
1599 progressed: false,
1600 vote_split: false,
1601 reconsideration: Vec::new(),
1602 verdict: None,
1603 }];
1604 let text2 = run(&rejected_all);
1605 assert!(
1606 text2.contains("0 addressed / 0 rejected"),
1607 "a round the fixer actually reported on keeps the count: {text2}"
1608 );
1609 }
1610
1611 #[test]
1612 fn a_split_round_shows_every_seat_vote_and_the_reconsideration() {
1613 use crate::run::ReviewRevoteRecord;
1614 use crate::verdict::ReviewVote;
1615
1616 let _guard = plain();
1617 let mut s = state();
1618 s.reviews = vec![ReviewRound {
1619 round: 1,
1620 head: "abc1234".to_owned(),
1621 verified_head: None,
1622 verified_at: None,
1623 reviews: vec![
1624 ReviewRecord {
1625 attempts: 0,
1626 reviewer: 1,
1627 agent: "alpha".to_owned(),
1628 summary: String::new(),
1629 findings: Vec::new(),
1630 vote: Some(ReviewVote::Approve),
1631 failed: None,
1632 duration_ms: 0,
1633 },
1634 ReviewRecord {
1635 attempts: 0,
1636 reviewer: 2,
1637 agent: "beta".to_owned(),
1638 summary: String::new(),
1639 findings: Vec::new(),
1640 vote: Some(ReviewVote::Reject),
1641 failed: None,
1642 duration_ms: 0,
1643 },
1644 ],
1645 e2e: Vec::new(),
1646 verify_retried: false,
1647 e2e_deferred: false,
1648 e2e_defer_reason: None,
1649 fix: None,
1650 blocking: 0,
1651 answered: 2,
1652 expected: 2,
1653 clean: false,
1654 progressed: false,
1655 vote_split: true,
1656 reconsideration: vec![ReviewRevoteRecord {
1657 reviewer: 2,
1658 agent: "beta".to_owned(),
1659 vote: Some(ReviewVote::ApproveWithFindings),
1660 reason: "the other seat's read holds up".to_owned(),
1661 failed: None,
1662 }],
1663 verdict: Some(ReviewVote::ApproveWithFindings),
1664 }];
1665 let text = run(&s);
1666 assert!(text.contains("review-1 vote"), "{text}");
1667 assert!(text.contains("review-2 vote"), "{text}");
1668 assert!(text.contains("panel split"), "{text}");
1669 assert!(text.contains("reconsideration"), "{text}");
1670 assert!(text.contains("the other seat's read holds up"), "{text}");
1671 }
1672
1673 #[test]
1674 fn an_incomplete_panel_and_a_lost_fix_report_both_stay_on_the_round_line() {
1675 let _guard = plain();
1681 let mut s = state();
1682 s.reviews = vec![ReviewRound {
1683 round: 1,
1684 head: "abc1234".to_owned(),
1685 verified_head: None,
1686 verified_at: None,
1687 reviews: vec![
1688 ReviewRecord {
1689 attempts: 0,
1690 reviewer: 1,
1691 agent: "alpha".to_owned(),
1692 summary: String::new(),
1693 findings: Vec::new(),
1694 vote: None,
1695 failed: None,
1696 duration_ms: 0,
1697 },
1698 ReviewRecord {
1699 attempts: 0,
1700 reviewer: 2,
1701 agent: "beta".to_owned(),
1702 summary: String::new(),
1703 findings: Vec::new(),
1704 vote: None,
1705 failed: Some("agent timed out".to_owned()),
1706 duration_ms: 0,
1707 },
1708 ],
1709 e2e: Vec::new(),
1710 verify_retried: false,
1711 e2e_deferred: false,
1712 e2e_defer_reason: None,
1713 fix: Some(FixRecord {
1714 agent: "opus".to_owned(),
1715 addressed: Vec::new(),
1716 rejected: Vec::new(),
1717 notes: String::new(),
1718 committed: true,
1719 failed: Some("timed out".to_owned()),
1720 duration_ms: 0,
1721 continuation: None,
1722 }),
1723 blocking: 0,
1724 answered: 1,
1725 expected: 2,
1726 clean: false,
1727 progressed: true,
1728 vote_split: false,
1729 reconsideration: Vec::new(),
1730 verdict: None,
1731 }];
1732 let text = run(&s);
1733 assert!(text.contains("incomplete"), "{text}");
1734 assert!(text.contains("1/2 reviewers answered"), "{text}");
1735 assert!(text.contains("review-2: agent timed out"), "{text}");
1736 assert!(text.contains("adoption report lost (timed out)"), "{text}");
1737 assert!(
1738 !text.contains("clean"),
1739 "a round missing half its panel must never render as clean: {text}"
1740 );
1741 }
1742
1743 #[test]
1744 fn a_build_failure_is_not_reported_as_a_test_failure() {
1745 let _guard = plain();
1746 let mut s = state();
1747 s.reviews = vec![ReviewRound {
1748 round: 1,
1749 head: "abc1234".to_owned(),
1750 verified_head: None,
1751 verified_at: None,
1752 reviews: Vec::new(),
1753 e2e: vec![CommandOutcome {
1754 command: "cargo test".to_owned(),
1755 code: Some(1),
1756 output_tail: "LINK : fatal error LNK1104: cannot open file".to_owned(),
1757 duration_ms: 100,
1758 resource_blocked: false,
1759 }],
1760 verify_retried: true,
1761 e2e_deferred: false,
1762 e2e_defer_reason: None,
1763 fix: None,
1764 blocking: 0,
1765 answered: 0,
1766 expected: 0,
1767 clean: false,
1768 progressed: false,
1769 vote_split: false,
1770 reconsideration: Vec::new(),
1771 verdict: None,
1772 }];
1773 let text = run(&s);
1774 assert!(text.contains("could not run"), "{text}");
1775 assert!(text.contains("retried once"), "{text}");
1776 assert!(!text.contains("e2e RED"), "{text}");
1777 }
1778
1779 #[test]
1780 fn a_resource_blocked_e2e_never_reads_as_red_or_as_a_build_failure() {
1781 let _guard = plain();
1782 let mut s = state();
1783 s.reviews = vec![ReviewRound {
1784 round: 1,
1785 head: "abc1234".to_owned(),
1786 verified_head: None,
1787 verified_at: None,
1788 reviews: Vec::new(),
1789 e2e: vec![CommandOutcome {
1790 command: "(waiting for the shared build cache)".to_owned(),
1791 code: None,
1792 output_tail: "held by run x node e2e seat e2e".to_owned(),
1793 duration_ms: 100,
1794 resource_blocked: true,
1795 }],
1796 verify_retried: false,
1797 e2e_deferred: false,
1798 e2e_defer_reason: None,
1799 fix: None,
1800 blocking: 0,
1801 answered: 0,
1802 expected: 0,
1803 clean: false,
1804 progressed: false,
1805 vote_split: false,
1806 reconsideration: Vec::new(),
1807 verdict: None,
1808 }];
1809 let text = run(&s);
1810 assert!(text.contains("shared build cache unavailable"), "{text}");
1811 assert!(!text.contains("e2e RED"), "{text}");
1812 assert!(!text.contains("build/link failure"), "{text}");
1813 }
1814
1815 #[test]
1816 fn a_round_with_more_than_one_e2e_command_names_each_one() {
1817 let _guard = plain();
1822 let mut s = state();
1823 s.reviews = vec![ReviewRound {
1824 round: 1,
1825 head: "abc1234".to_owned(),
1826 verified_head: Some("abc1234".to_owned()),
1827 verified_at: Some(jiff::Timestamp::now()),
1828 reviews: Vec::new(),
1829 e2e: vec![
1830 CommandOutcome {
1831 command: "cargo test --locked --all-targets".to_owned(),
1832 code: Some(0),
1833 output_tail: String::new(),
1834 duration_ms: 0,
1835 resource_blocked: false,
1836 },
1837 CommandOutcome {
1838 command: "cargo make check".to_owned(),
1839 code: Some(1),
1840 output_tail: "clippy: unused import".to_owned(),
1841 duration_ms: 0,
1842 resource_blocked: false,
1843 },
1844 ],
1845 verify_retried: false,
1846 e2e_deferred: false,
1847 e2e_defer_reason: None,
1848 fix: None,
1849 blocking: 0,
1850 answered: 0,
1851 expected: 0,
1852 clean: false,
1853 progressed: false,
1854 vote_split: false,
1855 reconsideration: Vec::new(),
1856 verdict: None,
1857 }];
1858 let text = run(&s);
1859 assert!(text.contains("cargo test --locked --all-targets"), "{text}");
1860 assert!(text.contains("cargo make check"), "{text}");
1861 assert!(text.contains("clippy: unused import"), "{text}");
1862 }
1863
1864 #[test]
1865 fn a_declined_finding_shows_its_reason() {
1866 use crate::verdict::{Finding, Rejection, Severity};
1867
1868 let _guard = plain();
1869 let mut s = state();
1870 s.status = RunStatus::Ready;
1871 s.reviews = vec![ReviewRound {
1872 round: 1,
1873 head: "deadbee".to_owned(),
1874 verified_head: None,
1875 verified_at: None,
1876 reviews: vec![ReviewRecord {
1877 attempts: 0,
1878 reviewer: 1,
1879 agent: "alpha".to_owned(),
1880 summary: String::new(),
1881 findings: vec![Finding {
1882 id: "R1-1-1".to_owned(),
1883 severity: Severity::Major,
1884 file: None,
1885 line: None,
1886 title: "still open".to_owned(),
1887 detail: String::new(),
1888 }],
1889 vote: None,
1890 failed: None,
1891 duration_ms: 0,
1892 }],
1893 e2e: vec![CommandOutcome {
1894 command: "cargo test".to_owned(),
1895 code: Some(0),
1896 output_tail: String::new(),
1897 duration_ms: 0,
1898 resource_blocked: false,
1899 }],
1900 verify_retried: false,
1901 e2e_deferred: false,
1902 e2e_defer_reason: None,
1903 fix: Some(FixRecord {
1904 agent: "alpha".to_owned(),
1905 addressed: Vec::new(),
1906 rejected: vec![Rejection {
1907 id: "R1-1-2".to_owned(),
1908 why: "cannot be triggered from any caller".to_owned(),
1909 }],
1910 notes: String::new(),
1911 committed: true,
1912 failed: None,
1913 duration_ms: 0,
1914 continuation: None,
1915 }),
1916 blocking: 1,
1917 answered: 1,
1918 expected: 1,
1919 clean: false,
1920 progressed: true,
1921 vote_split: false,
1922 reconsideration: Vec::new(),
1923 verdict: None,
1924 }];
1925
1926 let text = run(&s);
1927 assert!(text.contains("R1-1-2"), "{text}");
1928 assert!(text.contains("cannot be triggered"), "{text}");
1929 assert!(text.contains("still open"), "{text}");
1930 assert!(
1931 text.contains("handed off"),
1932 "a mergeable run with an open round must say so: {text}"
1933 );
1934 }
1935
1936 #[test]
1937 fn a_failing_gate_command_shows_its_output() {
1938 let _guard = plain();
1939 let mut s = state();
1940 s.status = RunStatus::Blocked;
1941 s.gate = vec![CommandOutcome {
1942 command: "cargo make check".to_owned(),
1943 code: Some(101),
1944 output_tail: "error[E0308]: mismatched types".to_owned(),
1945 duration_ms: 0,
1946 resource_blocked: false,
1947 }];
1948 s.gate_ran = true;
1949
1950 let text = run(&s);
1951 assert!(text.contains("mismatched types"), "{text}");
1952 }
1953
1954 #[test]
1955 fn a_gate_with_no_commands_configured_shows_a_pass_not_silence() {
1956 let _guard = plain();
1957 let mut s = state();
1958 s.status = RunStatus::Ready;
1959 s.gate_ran = true;
1960 assert!(s.gate.is_empty());
1961
1962 let text = run(&s);
1963 assert!(
1964 text.contains("gate") && text.contains("no gate commands configured"),
1965 "a run gated on nothing must say so, not read as if the gate never ran: {text}"
1966 );
1967 }
1968
1969 #[test]
1970 fn a_gate_that_has_not_run_yet_shows_nothing() {
1971 let _guard = plain();
1972 let s = state();
1973 assert!(!s.gate_ran);
1974 assert!(s.gate.is_empty());
1975
1976 let text = run(&s);
1977 assert!(
1978 !text.contains("no gate commands configured"),
1979 "an unattempted gate must not be shown as a pass: {text}"
1980 );
1981 }
1982
1983 #[test]
1984 fn active_seats_shows_who_has_not_answered_and_how_long_is_left() {
1985 let _guard = plain();
1986 let mut s = state();
1987 s.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
1988 let text = active_seats(&s, Liveness::Live);
1989 assert!(text.contains("running now"));
1990 assert!(text.contains("judge-2"));
1991 assert!(text.contains("judge"));
1992 assert!(!text.contains("no live daemon"), "{text}");
1993 assert!(!text.contains("could not be confirmed"), "{text}");
1994 }
1995
1996 #[test]
1997 fn active_seats_flags_a_leftover_from_a_dead_process() {
1998 let _guard = plain();
1999 let mut s = state();
2000 s.seat_started("implement", "impl-B", std::time::Duration::from_secs(60), 0);
2001 let text = active_seats(&s, Liveness::Dead);
2002 assert!(
2003 text.contains("no live daemon"),
2004 "a stale entry must not read as running: {text}"
2005 );
2006 }
2007
2008 #[test]
2009 fn superseded_notice_names_the_run_that_replaced_it() {
2010 let _guard = plain();
2011 let text = superseded_notice(Some("bbbb"));
2012 assert!(text.contains("SUPERSEDED"), "{text}");
2013 assert!(text.contains("bbbb"), "{text}");
2014 }
2015
2016 #[test]
2017 fn superseded_notice_is_silent_for_the_latest_attempt() {
2018 let _guard = plain();
2019 assert_eq!(superseded_notice(None), "");
2020 }
2021
2022 #[test]
2023 fn list_line_marks_a_nonterminal_run_with_a_dead_driver_stale() {
2024 let _guard = plain();
2025 let mut s = state();
2026 s.status = RunStatus::Reviewing;
2027 let text = line_with_liveness(&s, Liveness::Dead);
2028 assert!(text.contains("STALE"), "{text}");
2029 assert!(text.contains("resume required"), "{text}");
2030 assert!(liveness_notice(&s, Liveness::Dead).contains("STALE"));
2031 }
2032
2033 #[test]
2038 fn active_seats_reports_uncertainty_without_claiming_death() {
2039 let _guard = plain();
2040 let mut s = state();
2041 s.seat_started("review", "review-1", std::time::Duration::from_secs(60), 0);
2042 let text = active_seats(&s, Liveness::Unknown);
2043 assert!(
2044 text.contains("could not be confirmed"),
2045 "an unproven state must read as uncertain, not dead: {text}"
2046 );
2047 assert!(!text.contains("no live daemon"), "{text}");
2048 }
2049
2050 #[test]
2051 fn active_seats_is_empty_when_nothing_is_running() {
2052 let _guard = plain();
2053 assert_eq!(active_seats(&state(), Liveness::Live), "");
2054 }
2055
2056 #[test]
2062 fn active_seats_shows_a_running_verify_task_and_its_command() {
2063 let _guard = plain();
2064 let mut s = state();
2065 s.task_command(
2066 "e2e",
2067 "verify",
2068 0,
2069 "cargo test",
2070 2,
2071 3,
2072 std::time::Duration::from_secs(600),
2073 );
2074 let text = active_seats(&s, Liveness::Live);
2075 assert!(text.contains("e2e"), "{text}");
2076 assert!(text.contains("(2/3)"), "{text}");
2077 assert!(text.contains("cargo test"), "{text}");
2078 }
2079
2080 #[test]
2081 fn no_jobs_section_appears_when_nothing_was_ever_collected() {
2082 let _guard = plain();
2083 assert!(!run(&state()).contains("background jobs"));
2086 }
2087
2088 #[test]
2089 fn a_codex_roster_with_no_completed_jobs_yet_says_so_instead_of_staying_silent() {
2090 let _guard = plain();
2091 let mut s = state();
2092 s.config.agents.push(crate::config::AgentSpec {
2093 id: "codex-one".to_owned(),
2094 kind: crate::config::AgentKind::Codex,
2095 model: None,
2096 command: vec!["codex".to_owned()],
2097 extra_args: Vec::new(),
2098 env: BTreeMap::new(),
2099 prompt_delivery: None,
2100 });
2101 let text = run(&s);
2102 assert!(
2103 text.contains("background jobs"),
2104 "a run that could report this must not read the same as one that never could: \
2105 {text}"
2106 );
2107 assert!(text.contains("no completed command evidence yet"));
2108 }
2109
2110 #[test]
2111 fn recovered_running_and_unreadable_jobs_are_told_apart() {
2112 let _guard = plain();
2113 let mut s = state();
2114 s.jobs = vec![
2115 crate::run::JobRecord {
2116 node: "implement".to_owned(),
2117 round: None,
2118 seat: "impl-A".to_owned(),
2119 id: "item49".to_owned(),
2120 description: "cargo test --test graph_cached_gate".to_owned(),
2121 checked_at: jiff::Timestamp::now(),
2122 status: crate::run::JobStatus::Completed,
2123 exit_code: Some(0),
2124 result_summary: "test result: 2 passed; 0 failed".to_owned(),
2125 source: "codex".to_owned(),
2126 },
2127 crate::run::JobRecord {
2128 node: "fix".to_owned(),
2129 round: None,
2130 seat: "impl-A".to_owned(),
2131 id: "item52".to_owned(),
2132 description: "cargo test --test graph_split".to_owned(),
2133 checked_at: jiff::Timestamp::now(),
2134 status: crate::run::JobStatus::Failed,
2135 exit_code: Some(101),
2136 result_summary: "test result: 1 passed; 1 failed".to_owned(),
2137 source: "codex".to_owned(),
2138 },
2139 crate::run::JobRecord {
2140 node: "fix".to_owned(),
2141 round: None,
2142 seat: "impl-A".to_owned(),
2143 id: "item60".to_owned(),
2144 description: "cargo build".to_owned(),
2145 checked_at: jiff::Timestamp::now(),
2146 status: crate::run::JobStatus::Unknown,
2147 exit_code: None,
2148 result_summary: String::new(),
2149 source: "codex".to_owned(),
2150 },
2151 ];
2152 let text = run(&s);
2153 assert!(text.contains("background jobs"));
2154 assert!(text.contains("item49"));
2155 assert!(text.contains("item52"));
2156 assert!(text.contains("item60"));
2157 assert!(text.contains("completed"));
2161 assert!(text.contains("failed"));
2162 assert!(text.contains("unknown"));
2163 assert!(text.contains("adapter coverage"));
2165 }
2166
2167 #[test]
2168 fn a_jobs_own_round_is_shown_when_known() {
2169 let _guard = plain();
2170 let mut s = state();
2171 s.jobs = vec![crate::run::JobRecord {
2172 node: "review".to_owned(),
2173 round: Some(2),
2174 seat: "review-1".to_owned(),
2175 id: "item9".to_owned(),
2176 description: "cargo test --test graph_cached_gate".to_owned(),
2177 checked_at: jiff::Timestamp::now(),
2178 status: crate::run::JobStatus::Completed,
2179 exit_code: Some(0),
2180 result_summary: "test result: 2 passed; 0 failed".to_owned(),
2181 source: "codex".to_owned(),
2182 }];
2183 let text = run(&s);
2184 assert!(
2185 text.contains("round 2"),
2186 "the round this seat's own command ran in must be visible, distinct from magi's \
2187 own recorded verify: {text}"
2188 );
2189 }
2190
2191 #[test]
2192 fn stats_table_renders_without_runs() {
2193 let _guard = plain();
2194 let text = stats(&Stats::default());
2195 assert!(text.contains("0 total"));
2196 assert!(!text.contains("implementation"));
2197 }
2198}