1use std::collections::{BTreeMap, BTreeSet};
42use std::fmt::Write as _;
43use std::path::{Path, PathBuf};
44use std::sync::Arc;
45use std::time::Duration;
46
47use anyhow::{Context as _, Result, bail};
48use jiff::Timestamp;
49use serde::{Deserialize, Serialize};
50
51use crate::agent::{self, Invocation, SeatState};
52use crate::ask;
53use crate::config::MergeMode;
54use crate::git;
55use crate::proc::Quiet as _;
56use crate::prompt;
57use crate::run::{
58 ContestedHandoff, LandApproval, LandReruns, MergeOutcome, RunState, RunStatus, tail,
59};
60
61pub const POLL: Duration = Duration::from_secs(30);
67
68pub const WAIT_CEILING: Duration = Duration::from_secs(45 * 60);
74
75pub const CHECKS_GRACE: Duration = Duration::from_secs(3 * 60);
87
88const LOG_TAIL: usize = 4_000;
91
92const MAX_LOGS: usize = 3;
95
96pub const MARKER: &str = "<!-- magi:land -->";
102
103const NOT_A_REVIEW: [&str; 3] = [
112 "skip review by coderabbit.ai",
113 "summarize by coderabbit.ai",
114 "<!-- tips_start -->",
115];
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum PrLifecycle {
120 Open,
122 Merged,
124 Closed,
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum Checks {
131 Pending,
133 Green,
136 Red,
138 Unknown,
140}
141
142impl PrLifecycle {
143 pub fn as_str(self) -> &'static str {
145 match self {
146 Self::Open => "open",
147 Self::Merged => "merged",
148 Self::Closed => "closed",
149 }
150 }
151}
152
153impl Checks {
154 pub fn as_str(self) -> &'static str {
156 match self {
157 Self::Pending => "pending",
158 Self::Green => "green",
159 Self::Red => "red",
160 Self::Unknown => "unknown",
161 }
162 }
163}
164
165#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct ReviewComment {
168 pub author: String,
170 pub path: Option<String>,
172 pub line: Option<u64>,
174 pub body: String,
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct PrState {
181 pub url: String,
183 pub number: u64,
185 pub state: PrLifecycle,
187 pub checks: Checks,
189 pub failing: Vec<String>,
191 pub review_comments: Vec<ReviewComment>,
193 pub blocking: Blocking,
195}
196
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Blocking {
211 No,
213 Yes,
215 Conflict,
217 Behind,
219 Unsaid,
223}
224
225impl Blocking {
226 fn of(raw: &str) -> Self {
228 match raw.to_ascii_uppercase().as_str() {
229 "CLEAN" | "UNSTABLE" | "HAS_HOOKS" => Self::No,
232 "DIRTY" => Self::Conflict,
233 "BEHIND" => Self::Behind,
234 "" | "UNKNOWN" => Self::Unsaid,
235 _ => Self::Yes,
237 }
238 }
239
240 #[must_use]
242 pub fn stops_a_merge(self) -> bool {
243 !matches!(self, Self::No)
244 }
245}
246
247#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum Step {
250 Wait,
252 Rebase,
260 Fix {
262 reason: String,
264 },
265 Merge,
267 Done {
269 merged: bool,
271 },
272 GiveUp {
274 reason: String,
276 },
277}
278
279pub(crate) fn merged_after_all(
301 argv: &[String],
302 stderr: &str,
303 after: Option<PrLifecycle>,
304) -> Option<MergeOutcome> {
305 if after? != PrLifecycle::Merged {
306 return None;
307 }
308 Some(MergeOutcome {
309 mode: MergeMode::Pr,
310 ok: true,
311 detail: format!(
312 "gh {} (the command reported `{}`, but the pull request is merged)",
313 argv.join(" "),
314 stderr.trim()
315 ),
316 empty: false,
317 })
318}
319
320pub fn decide(pr: &PrState, round: usize, budget: usize, waited: Duration) -> Step {
340 decide_with(pr, round, budget, waited, CiExpectation::Expected)
341}
342
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub enum CiExpectation {
346 Expected,
349 Absent,
352}
353
354pub fn decide_with(
357 pr: &PrState,
358 round: usize,
359 budget: usize,
360 waited: Duration,
361 ci: CiExpectation,
362) -> Step {
363 match pr.state {
364 PrLifecycle::Merged => return Step::Done { merged: true },
365 PrLifecycle::Closed => return Step::Done { merged: false },
366 PrLifecycle::Open => {}
367 }
368
369 if matches!(pr.blocking, Blocking::Conflict | Blocking::Behind) {
372 return Step::Rebase;
373 }
374
375 let spent = round >= budget;
376 let checks = match ci {
377 CiExpectation::Expected => pr.checks,
378 CiExpectation::Absent => Checks::Green,
379 };
380 match checks {
381 Checks::Pending => Step::Wait,
382 Checks::Unknown if waited < CHECKS_GRACE => Step::Wait,
383 Checks::Unknown => Step::GiveUp {
384 reason: format!(
385 "no check status is readable on the pull request after {} minute(s); \
386 refusing to merge on a guess",
387 CHECKS_GRACE.as_secs() / 60
388 ),
389 },
390 Checks::Red if pr.blocking == Blocking::Unsaid && waited < CHECKS_GRACE => Step::Wait,
397 Checks::Red if !pr.blocking.stops_a_merge() && pr.review_comments.is_empty() => Step::Merge,
398 Checks::Red => {
399 let what = format!(
400 "{} check(s) failing: {}",
401 pr.failing.len(),
402 pr.failing.join(", ")
403 );
404 if spent {
405 Step::GiveUp {
406 reason: format!("{what} — still red after {budget} fix round(s)"),
407 }
408 } else {
409 Step::Fix { reason: what }
410 }
411 }
412 Checks::Green if pr.review_comments.is_empty() => Step::Merge,
413 Checks::Green => {
414 let what = format!(
415 "{} but {} review comment(s) are unresolved: {}",
416 if ci == CiExpectation::Absent {
417 "CI is not expected"
418 } else {
419 "checks are green"
420 },
421 pr.review_comments.len(),
422 authors(&pr.review_comments)
423 );
424 if spent {
425 Step::GiveUp {
426 reason: format!("{what} — still unresolved after {budget} fix round(s)"),
427 }
428 } else {
429 Step::Fix { reason: what }
430 }
431 }
432 }
433}
434
435fn authors(comments: &[ReviewComment]) -> String {
437 let mut seen: Vec<&str> = Vec::new();
438 for c in comments {
439 if !seen.contains(&c.author.as_str()) {
440 seen.push(&c.author);
441 }
442 }
443 seen.join(", ")
444}
445
446pub fn merge_argv(number: u64, subject: &str) -> Vec<String> {
450 vec![
451 "pr".to_owned(),
452 "merge".to_owned(),
453 number.to_string(),
454 "--squash".to_owned(),
455 "--delete-branch".to_owned(),
456 "--subject".to_owned(),
457 subject.to_owned(),
458 ]
459}
460
461pub fn merge_argv_at(number: u64, subject: &str, head: &str) -> Vec<String> {
467 let mut argv = merge_argv(number, subject);
468 argv.push("--match-head-commit".to_owned());
469 argv.push(head.to_owned());
470 argv
471}
472
473pub fn disable_automerge_argv(number: u64) -> Vec<String> {
478 ["pr", "merge", &number.to_string(), "--disable-auto"]
479 .map(str::to_owned)
480 .to_vec()
481}
482
483fn direct_merge_is_safe(
489 fresh: Option<&Seen>,
490 approved_head: &str,
491 shown: &BTreeSet<String>,
492 round: usize,
493 budget: usize,
494 waited: Duration,
495 ci: CiExpectation,
496) -> bool {
497 let Some(fresh) = fresh else {
498 return false;
499 };
500 if fresh.pr.state != PrLifecycle::Open {
501 return false;
502 }
503 let Some(bound) = bound_head(&fresh.head, &fresh.rollup_head, None) else {
504 return false;
505 };
506 if !bound.eq_ignore_ascii_case(approved_head) {
507 return false;
508 }
509 let mut pr = fresh.pr.clone();
510 pr.review_comments.retain(|c| !shown.contains(&c.body));
511 decide_with(&pr, round, budget, waited, ci) == Step::Merge
512}
513
514fn waiting_on(
521 merge_state: &str,
522 contexts: &[CheckInfo],
523 required_set: Option<&BTreeSet<String>>,
524) -> String {
525 let state = if merge_state.is_empty() {
526 "unknown"
527 } else {
528 merge_state
529 };
530 let tag = |c: &CheckInfo| match c.verdict {
531 Verdict::Fail => "failed",
532 _ => "pending",
533 };
534 let unsettled: Vec<&CheckInfo> = contexts
535 .iter()
536 .filter(|c| c.verdict != Verdict::Pass)
537 .collect();
538 let required: Vec<String> = unsettled
539 .iter()
540 .filter(|c| c.required == Some(true))
541 .map(|c| format!("{} ({})", c.label, tag(c)))
542 .collect();
543 let unknown: Vec<String> = unsettled
544 .iter()
545 .filter(|c| c.required.is_none())
546 .map(|c| format!("{} ({})", c.label, tag(c)))
547 .collect();
548 let never: Vec<&str> = required_set
552 .map(|set| {
553 set.iter()
554 .filter(|name| !contexts.iter().any(|c| c.label.eq_ignore_ascii_case(name)))
555 .map(String::as_str)
556 .collect()
557 })
558 .unwrap_or_default();
559 let mut out = format!("merge state: {state}");
560 if !never.is_empty() {
561 let _ = write!(
562 out,
563 "; required checks never reported: {}",
564 never.join(", ")
565 );
566 }
567 if !required.is_empty() {
568 let _ = write!(
569 out,
570 "; required checks not passing: {}",
571 required.join(", ")
572 );
573 }
574 if !unknown.is_empty() {
575 let _ = write!(
576 out,
577 "; whether these are required could not be read, so they may be: {}",
578 unknown.join(", ")
579 );
580 }
581 if required.is_empty() && unknown.is_empty() && never.is_empty() {
582 if required_set.is_some() {
583 out.push_str(
584 "; no required check is pending, failing or unreported, so GitHub is probably \
585 waiting for a review or another branch rule",
586 );
587 } else {
588 out.push_str(
589 "; the required check list could not be read, so a required check that was \
590 never reported cannot be ruled out",
591 );
592 }
593 }
594 out
595}
596
597pub fn merge_subject(pr_title: &str, instruction: &str) -> String {
604 let title = pr_title.trim();
605 if !title.is_empty() && !title.starts_with("magi: candidate") {
606 return title.to_owned();
607 }
608 let first = instruction
609 .lines()
610 .map(str::trim)
611 .find(|l| !l.is_empty())
612 .unwrap_or("magi: land the winning candidate");
613 first.trim_start_matches(['#', ' ']).to_owned()
614}
615
616pub const APPROVE: &str = "merge";
618
619pub const HOLD: &str = "hold";
621
622pub const REPAIR: &str = "fix findings and re-review";
624
625pub fn repair_available(state: &RunState) -> bool {
628 state.reviews.last().is_some_and(|r| {
629 state.open_findings().iter().any(|f| f.severity.blocks())
630 || r.final_votes()
631 .iter()
632 .any(|(_, _, v)| *v == crate::verdict::ReviewVote::Reject)
633 })
634}
635
636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
638pub enum ApprovalReason {
639 EveryMerge,
641 OpenBlockingFindings,
643 FinalReject,
645 ExistingDecision,
647 AfterRepair,
649}
650
651pub fn approval_reasons(state: &RunState) -> Vec<ApprovalReason> {
654 let mut reasons = Vec::new();
655 if state.owner_hold(crate::config::OwnerHold::LandApproval) {
656 reasons.push(ApprovalReason::EveryMerge);
657 }
658 if state.owner_hold(crate::config::OwnerHold::HoldContestedMerge) {
659 if state.open_findings().iter().any(|f| f.severity.blocks()) {
660 reasons.push(ApprovalReason::OpenBlockingFindings);
661 }
662 if state.reviews.last().is_some_and(|r| {
663 r.final_votes()
664 .iter()
665 .any(|(_, _, v)| *v == crate::verdict::ReviewVote::Reject)
666 }) {
667 reasons.push(ApprovalReason::FinalReject);
668 }
669 }
670 if state.land_approval.is_some() {
671 reasons.push(ApprovalReason::ExistingDecision);
672 }
673 if !state.merge_repairs.is_empty() || !state.repair_grants.is_empty() {
674 reasons.push(ApprovalReason::AfterRepair);
675 }
676 reasons
677}
678
679fn approval_excerpt(text: &str, max_chars: usize) -> String {
682 if text.chars().count() <= max_chars {
683 text.to_owned()
684 } else {
685 let mut excerpt: String = text.chars().take(max_chars.saturating_sub(1)).collect();
686 excerpt.push('…');
687 excerpt
688 }
689}
690
691fn approval_evidence(state: &RunState) -> String {
695 const TITLE_CHARS: usize = 100;
696 const REASON_CHARS: usize = 300;
697 let reason = |text: &str| approval_excerpt(text, REASON_CHARS);
698 let ja = words(&state.config.graph.language).html_lang == "ja";
699 let mut s = if ja {
700 "承認が必要な理由:\n"
701 } else {
702 "Approval required because:\n"
703 }
704 .to_owned();
705 for reason in approval_reasons(state) {
706 let label = match (reason, ja) {
707 (ApprovalReason::EveryMerge, false) => {
708 "land_approval=true: owner approval for every merge"
709 }
710 (ApprovalReason::EveryMerge, true) => {
711 "land_approval=true: すべてのマージに所有者の承認が必要"
712 }
713 (ApprovalReason::OpenBlockingFindings, false) => {
714 "hold_contested_merge=true: open Major-or-above internal findings"
715 }
716 (ApprovalReason::OpenBlockingFindings, true) => {
717 "hold_contested_merge=true: Major 以上の内部指摘が未解決"
718 }
719 (ApprovalReason::FinalReject, false) => {
720 "hold_contested_merge=true: final reviewer reject after reconsideration (even without Major findings)"
721 }
722 (ApprovalReason::FinalReject, true) => {
723 "hold_contested_merge=true: 再考後の最終票が reject(Major 指摘がなくても承認が必要)"
724 }
725 (ApprovalReason::ExistingDecision, false) => {
726 "existing owner decision: changing controls cannot bypass it"
727 }
728 (ApprovalReason::ExistingDecision, true) => {
729 "既存の所有者判断: 設定変更では迂回できません"
730 }
731 (ApprovalReason::AfterRepair, false) => {
732 "fresh owner approval after merge repair, even with an unchanged head"
733 }
734 (ApprovalReason::AfterRepair, true) => {
735 "マージ修復後の新しい所有者承認(head に変更がなくても必要)"
736 }
737 };
738 let control = match reason {
739 ApprovalReason::EveryMerge => Some(crate::config::OwnerHold::LandApproval),
740 ApprovalReason::OpenBlockingFindings | ApprovalReason::FinalReject => {
741 Some(crate::config::OwnerHold::HoldContestedMerge)
742 }
743 _ => None,
744 };
745 let source = control
746 .filter(|c| !c.base_value(&state.config.graph))
747 .and_then(|c| state.branch_owner_holds.iter().find(|h| h.control == c));
748 if let Some(source) = source {
749 if ja {
750 let _ = writeln!(
751 s,
752 "- {}=true(レビュー対象ブランチの {} 由来, {})",
753 source.control.key(),
754 source.file,
755 source.head
756 );
757 } else {
758 let _ = writeln!(
759 s,
760 "- {}=true from the reviewed branch's {} ({})",
761 source.control.key(),
762 source.file,
763 source.head
764 );
765 }
766 }
767 let _ = writeln!(s, "- {label}");
768 }
769 s.push_str(if ja {
770 "\n再考後の各レビュアーの最終票:\n"
771 } else {
772 "\nFinal reviewer votes after reconsideration:\n"
773 });
774 if let Some(round) = state.reviews.last() {
775 let votes = round.final_votes();
776 for r in &round.reviews {
777 let vote = votes
778 .iter()
779 .find(|(seat, _, _)| *seat == r.reviewer)
780 .map(|(_, _, v)| v.label())
781 .unwrap_or(if ja { "記録なし" } else { "not recorded" });
782 let _ = writeln!(s, "#{} ({}): {vote}", r.reviewer, r.agent);
783 let rv = round
784 .reconsideration
785 .iter()
786 .find(|rv| rv.reviewer == r.reviewer);
787 if let Some(rv) = rv.filter(|rv| rv.vote.is_some()) {
788 let initial = r.vote.map(|v| v.label()).unwrap_or("?");
789 let _ = writeln!(
790 s,
791 " {}: {initial} → {vote}",
792 if ja { "再考" } else { "reconsideration" }
793 );
794 let _ = writeln!(
795 s,
796 " {}: {}",
797 if ja { "理由" } else { "reason" },
798 reason(if rv.reason.trim().is_empty() {
799 if ja { "記録なし" } else { "not recorded" }
800 } else {
801 &rv.reason
802 })
803 );
804 } else {
805 let _ = writeln!(
806 s,
807 " {}: {}",
808 if ja {
809 "初回票を保持・理由"
810 } else {
811 "initial vote retained; reason"
812 },
813 reason(if r.summary.trim().is_empty() {
814 if ja { "記録なし" } else { "not recorded" }
815 } else {
816 &r.summary
817 })
818 );
819 if let Some(rv) = rv {
820 let _ = writeln!(
821 s,
822 " {}: {}",
823 if ja {
824 "再投票の回答なし"
825 } else {
826 "no reconsideration vote"
827 },
828 reason(rv.failed.as_deref().unwrap_or(if ja {
829 "理由の記録なし"
830 } else {
831 "reason not recorded"
832 }))
833 );
834 }
835 }
836 if let Some(failed) = &r.failed {
837 let _ = writeln!(
838 s,
839 " {}: {}",
840 if ja { "回答なし" } else { "no answer" },
841 reason(failed)
842 );
843 }
844 }
845 } else {
846 s.push_str(if ja {
847 "レビュー記録なし\n"
848 } else {
849 "No review recorded\n"
850 });
851 }
852 s.push_str(if ja { "\n内部レビュー指摘(最終ラウンド): 採用申告や gate 成功だけでは個別指摘の解決確認にはなりません。\n" } else { "\nInternal review findings (last round): adoption claims or a passing gate alone do not confirm individual resolution.\n" });
853 let findings = state.last_round_findings();
854 for f in &findings {
855 let _ = writeln!(
856 s,
857 "[{}] {} {}:{}: {}\n{}",
858 f.id,
859 f.severity,
860 f.file.as_deref().unwrap_or("?"),
861 f.line.map(|l| l.to_string()).unwrap_or_else(|| "?".into()),
862 approval_excerpt(&f.title, TITLE_CHARS),
863 reason(&f.detail)
864 );
865 let mut evidence = false;
866 for fix in state.reviews.iter().filter_map(|r| r.fix.as_ref()).chain(
867 state
868 .operator_fixes
869 .iter()
870 .filter_map(|request| request.fix.as_ref()),
871 ) {
872 if fix.addressed.contains(&f.id) {
873 evidence = true;
874 let _ = writeln!(
875 s,
876 " {} ({}): {}",
877 if ja {
878 "採用申告(解決未確認)"
879 } else {
880 "claimed addressed (resolution unconfirmed)"
881 },
882 fix.agent,
883 reason(&fix.notes)
884 );
885 }
886 for rejection in fix.rejected.iter().filter(|r| r.id == f.id) {
887 evidence = true;
888 let _ = writeln!(
889 s,
890 " {}: {}",
891 if ja { "不採用理由" } else { "declined" },
892 reason(&rejection.why)
893 );
894 }
895 }
896 if !evidence {
897 s.push_str(if ja {
898 " 採用・解決確認の記録なし\n"
899 } else {
900 " No adoption or resolution evidence recorded\n"
901 });
902 }
903 }
904 if findings.is_empty() {
905 s.push_str(if ja {
906 "最終ラウンドに指摘の記録なし\n"
907 } else {
908 "No findings recorded in the last round\n"
909 });
910 }
911 s
912}
913
914pub fn approval_choices(state: &RunState) -> Vec<String> {
916 let mut choices = vec![
917 APPROVE.to_owned(),
918 HOLD.to_owned(),
919 REPAIR.to_owned(),
920 crate::merge_decision::WITHDRAW.to_owned(),
921 crate::merge_decision::DISMISS.to_owned(),
922 ];
923 choices.extend(
924 state
925 .config
926 .agents
927 .iter()
928 .map(|a| format!("{}{id}", crate::merge_decision::REIMPLEMENT, id = a.id)),
929 );
930 choices
931}
932
933pub fn upgrade_repair_choice(q: &mut ask::Question, state: &RunState) -> bool {
936 if q.node != APPROVAL_NODE
937 || !state
938 .land_approval
939 .as_ref()
940 .is_some_and(|a| a.question == q.id)
941 {
942 return false;
943 }
944 let before = (q.choices.clone(), q.actions.clone(), q.merge_target.clone());
945 if q.status.open() {
946 q.actions.remove(HOLD);
949 for choice in approval_choices(state) {
950 if !q.choices.contains(&choice) {
951 q.choices.push(choice);
952 }
953 }
954 if q.merge_target.is_none() {
955 q.merge_target = state.pr.as_ref().map(|pr| crate::merge_decision::Target {
956 pr: pr.url.clone(),
957 head: state.land_approval.as_ref().unwrap().head.clone(),
958 language: state.config.graph.language.clone(),
959 });
960 }
961 }
962 for choice in q.choices.clone() {
963 if (q.status.open()
964 && crate::merge_decision::stops(&choice)
965 && choice != HOLD
966 && choice != crate::merge_decision::DISMISS)
967 || (choice == REPAIR && (q.status.open() || q.resolution().as_deref() == Some(REPAIR)))
968 {
969 q.actions.insert(
970 choice,
971 ask::ChoiceAction::Resume {
972 run: state.id.clone(),
973 },
974 );
975 }
976 }
977 before != (q.choices.clone(), q.actions.clone(), q.merge_target.clone())
978}
979
980pub const APPROVAL_NODE: &str = "land-approval";
986
987pub const DIFF_MAX_LINES: usize = 400;
995
996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
998pub enum Approval {
999 Merge,
1001 Repair,
1003 Hold,
1005}
1006
1007pub fn approval(answer: Option<&str>) -> Approval {
1015 match answer {
1016 Some(a) if a.trim().eq_ignore_ascii_case(APPROVE) => Approval::Merge,
1017 Some(a) if a.trim() == REPAIR => Approval::Repair,
1018 _ => Approval::Hold,
1019 }
1020}
1021
1022#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1024enum ApprovalGate {
1025 Approved,
1027 Repair,
1029 Held,
1032 Pending,
1034}
1035
1036fn esc(s: &str) -> String {
1046 let mut out = String::with_capacity(s.len());
1047 for c in s.chars() {
1048 match c {
1049 '&' => out.push_str("&"),
1050 '<' => out.push_str("<"),
1051 '>' => out.push_str(">"),
1052 '"' => out.push_str("""),
1053 '\'' => out.push_str("'"),
1054 _ => out.push(c),
1055 }
1056 }
1057 out
1058}
1059
1060#[derive(Debug, Clone, PartialEq, Eq)]
1062struct StatRow {
1063 path: String,
1064 added: Option<u64>,
1066 removed: Option<u64>,
1067}
1068
1069impl StatRow {
1070 fn churn(&self) -> u64 {
1073 self.added.unwrap_or(0) + self.removed.unwrap_or(0)
1074 }
1075}
1076
1077fn parse_numstat(numstat: &str) -> Vec<StatRow> {
1083 let mut rows: Vec<StatRow> = numstat
1084 .lines()
1085 .filter_map(|line| {
1086 let mut parts = line.splitn(3, '\t');
1087 let added = parts.next()?.trim();
1088 let removed = parts.next()?.trim();
1089 let path = parts.next()?.trim();
1090 if path.is_empty() {
1091 return None;
1092 }
1093 Some(StatRow {
1094 path: path.to_owned(),
1095 added: added.parse().ok(),
1096 removed: removed.parse().ok(),
1097 })
1098 })
1099 .collect();
1100 rows.sort_by(|a, b| b.churn().cmp(&a.churn()).then_with(|| a.path.cmp(&b.path)));
1103 rows
1104}
1105
1106fn diff_row(line: &str) -> (&'static str, &'static str, &str) {
1115 if line.starts_with("+++") || line.starts_with("---") {
1116 (" ", "color:#57606a;font-weight:600", line)
1117 } else if let Some(body) = line.strip_prefix('+') {
1118 ("+", "background:#e6ffec;color:#0a3622", body)
1119 } else if let Some(body) = line.strip_prefix('-') {
1120 ("-", "background:#ffebe9;color:#5c1a17", body)
1121 } else if line.starts_with("@@") {
1122 ("~", "background:#eef2ff;color:#3730a3", line)
1123 } else if let Some(body) = line.strip_prefix(' ') {
1124 (" ", "", body)
1125 } else {
1126 (" ", "color:#57606a;font-weight:600", line)
1127 }
1128}
1129
1130struct Words {
1139 html_lang: &'static str,
1140 task: &'static str,
1141 what_changed: &'static str,
1142 review_verdict: &'static str,
1143 reviewer: &'static str,
1144 reviewer_no_answer: &'static str,
1145 checks: &'static str,
1146 nothing_failing: &'static str,
1147 files_changed: &'static str,
1148 commits: &'static str,
1149 no_commits: &'static str,
1150 comments: &'static str,
1151 no_comments: &'static str,
1152 diff: &'static str,
1153 truncated: &'static str,
1154 lands_as: &'static str,
1155}
1156
1157const EN: Words = Words {
1158 html_lang: "en",
1159 task: "Task",
1160 what_changed: "What changed",
1161 review_verdict: "Review verdict",
1162 reviewer: "Reviewer",
1163 reviewer_no_answer: "produced no answer",
1164 checks: "Checks",
1165 nothing_failing: "Nothing failing.",
1166 files_changed: "file(s) changed",
1167 commits: "Commits being squashed",
1168 no_commits: "No commit subjects could be read from the branch.",
1169 comments: "External PR review comments",
1170 no_comments: "No unaddressed external PR comments at this observation. This does not mean internal findings are resolved.",
1171 diff: "Diff",
1172 truncated: "Truncated",
1173 lands_as: "They land as one commit titled",
1174};
1175
1176const JA: Words = Words {
1177 html_lang: "ja",
1178 task: "タスク",
1179 what_changed: "変更内容",
1180 review_verdict: "レビューの結論",
1181 reviewer: "レビュアー",
1182 reviewer_no_answer: "回答なし",
1183 checks: "チェック",
1184 nothing_failing: "失敗しているものはありません。",
1185 files_changed: "ファイル変更",
1186 commits: "squash されるコミット",
1187 no_commits: "ブランチからコミット件名を読めませんでした。",
1188 comments: "外部 PR レビューコメント",
1189 no_comments: "この時点で未対応の外部 PR コメントはありません。内部指摘の解決を意味するものではありません。",
1190 diff: "差分",
1191 truncated: "省略",
1192 lands_as: "これらは次の件名の1コミットとして入ります:",
1193};
1194
1195impl Words {
1196 fn lands_as_tail(&self) -> &'static str {
1200 if self.html_lang == "ja" {
1201 "。この件名も承認の対象です。"
1202 } else {
1203 ", which you are approving too."
1204 }
1205 }
1206
1207 fn approval_summary(&self, number: u64, subject: &str) -> String {
1209 if self.html_lang == "ja" {
1210 format!("プルリクエスト #{number} をマージ: {subject}")
1211 } else {
1212 format!("merge pull request #{number}: {subject}")
1213 }
1214 }
1215
1216 fn approval_detail(
1218 &self,
1219 url: &str,
1220 base: &str,
1221 subject: &str,
1222 contested: Option<&ContestedHandoff>,
1223 ) -> String {
1224 let body = if self.html_lang == "ja" {
1225 format!(
1226 "{url} はチェックが緑で、`{base}` へ `{subject}` として squash \
1227 できる状態です。差分の要約・パッチ・squash されるコミットは\
1228 下のパネルにあります。"
1229 )
1230 } else {
1231 format!(
1232 "{url} is green and ready to squash into `{base}` as `{subject}`. \
1233 The panel holds the diffstat, the patch and the commits being squashed."
1234 )
1235 };
1236 match contested {
1237 Some(c) => format!("{}\n\n{body}", self.contested_reason(url, c)),
1238 None => body,
1239 }
1240 }
1241
1242 fn contested_reason(&self, url: &str, c: &ContestedHandoff) -> String {
1245 const SHOWN: usize = 5;
1246 const TITLE_CHARS: usize = 100;
1247 let ja = self.html_lang == "ja";
1248 let mut out = if ja {
1249 format!(
1250 "{url} は、マージ承認がオフでも保留しています。レビューが予算切れで終わった\
1251 時点で、却下票を伴う重大な未解決の指摘が残っているためです。\n"
1252 )
1253 } else {
1254 format!(
1255 "{url} is held for approval although merge approvals are off: the \
1256 review ended with blocking findings still open and a reviewer \
1257 voting reject.\n"
1258 )
1259 };
1260 for f in c.findings.iter().take(SHOWN) {
1261 let at = match (&f.file, f.line) {
1262 (Some(file), Some(line)) => format!("{file}:{line}"),
1263 (Some(file), None) => file.clone(),
1264 _ => (if ja { "場所未指定" } else { "no location" }).to_owned(),
1265 };
1266 let title: String = f.title.chars().take(TITLE_CHARS).collect();
1267 let _ = writeln!(out, "- {} {} {at}: {title}", f.id, f.severity);
1268 }
1269 if c.findings.len() > SHOWN {
1270 let more = c.findings.len() - SHOWN;
1271 let _ = writeln!(
1272 out,
1273 "{}",
1274 if ja {
1275 format!("- ほか {more} 件")
1276 } else {
1277 format!("- and {more} more")
1278 }
1279 );
1280 }
1281 let seats: Vec<String> = c
1282 .rejecters
1283 .iter()
1284 .map(|(seat, agent)| format!("#{seat} ({agent})"))
1285 .collect();
1286 let _ = write!(
1287 out,
1288 "{} {}",
1289 if ja {
1290 "却下したレビュアー:"
1291 } else {
1292 "Rejected by reviewer:"
1293 },
1294 seats.join(", ")
1295 );
1296 out
1297 }
1298
1299 fn truncated_note(
1301 &self,
1302 omitted: usize,
1303 total: usize,
1304 shown: usize,
1305 where_: &str,
1306 base: &str,
1307 head: &str,
1308 ) -> String {
1309 if self.html_lang == "ja" {
1310 format!(
1311 "先頭 {shown} 行のあと、差分 {total} 行のうち {omitted} 行を省略しました。\
1312 全体は <code>{where_}</code>(<code>git diff {base}...{head}</code>)と\
1313 プルリクエストにあります。"
1314 )
1315 } else {
1316 format!(
1317 "{omitted} of {total} diff lines omitted after the first {shown}. \
1318 The whole patch is in <code>{where_}</code> \
1319 (<code>git diff {base}...{head}</code>) and on the pull request."
1320 )
1321 }
1322 }
1323}
1324
1325fn words(language: &str) -> &'static Words {
1328 if crate::lang::is_japanese(language) {
1329 &JA
1330 } else {
1331 &EN
1332 }
1333}
1334
1335pub fn approval_panel(
1347 state: &RunState,
1348 pr: &PrState,
1349 diffstat: &str,
1350 diff: &str,
1351 commits: &[String],
1352 subject: &str,
1353) -> String {
1354 let rows = parse_numstat(diffstat);
1355 let w = words(&state.config.graph.language);
1356 let mut h = String::with_capacity(4_096 + diff.len().min(200_000));
1357
1358 let _ = writeln!(
1359 h,
1360 "<!doctype html>\n<html lang=\"{}\">\n<head>\n<meta charset=\"utf-8\">\n\
1361 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
1362 w.html_lang
1363 );
1364 let _ = writeln!(
1365 h,
1366 "<title>merge #{} — {}</title>\n</head>",
1367 pr.number,
1368 esc(subject)
1369 );
1370 h.push_str(
1371 "<body style=\"margin:0;padding:12px;font:15px/1.5 -apple-system,\
1372 'Segoe UI',system-ui,sans-serif;color:#1f2328;background:#fff;\
1373 word-break:break-word\">\n",
1374 );
1375
1376 let _ = writeln!(
1378 h,
1379 "<h1 style=\"margin:0 0 4px;font-size:19px\">Merge #{} into \
1380 <code style=\"background:#f6f8fa;padding:1px 4px;border-radius:4px\">{}</code></h1>\n\
1381 <p style=\"margin:0 0 4px;font-size:17px;font-weight:600\">{}</p>\n\
1382 <p style=\"margin:0 0 12px;font-size:13px;color:#57606a\">squash merge · run {} · \
1383 <a href=\"{}\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:#0969da\">{}</a></p>",
1384 pr.number,
1385 esc(&state.base_branch),
1386 esc(subject),
1387 esc(&state.id),
1388 esc(&pr.url),
1389 esc(&pr.url),
1390 );
1391
1392 let _ = writeln!(
1393 h,
1394 "<section style=\"padding:12px;background:#fff8c5;border:1px solid #9a6700;border-radius:6px;white-space:pre-wrap\">{}</section>",
1395 esc(&approval_evidence(state))
1396 );
1397
1398 let _ = writeln!(
1401 h,
1402 "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>\n\
1403 <p style=\"margin:0;font-size:13px;white-space:pre-wrap\">{}</p>",
1404 w.task,
1405 esc(&state.instruction)
1406 );
1407
1408 if let Some(summary) = state
1410 .winner()
1411 .map(|c| c.summary.as_str())
1412 .filter(|s| !s.is_empty())
1413 {
1414 let _ = writeln!(
1415 h,
1416 "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>\n\
1417 <p style=\"margin:0;font-size:13px;white-space:pre-wrap\">{}</p>",
1418 w.what_changed,
1419 esc(summary)
1420 );
1421 }
1422
1423 if let Some(round) = state.reviews.last() {
1426 let _ = writeln!(
1427 h,
1428 "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1429 w.review_verdict
1430 );
1431 for r in &round.reviews {
1432 let body = match &r.failed {
1439 Some(reason) => format!("{}: {}", w.reviewer_no_answer, esc(reason)),
1440 None => esc(&r.summary),
1441 };
1442 let _ = writeln!(
1443 h,
1444 "<div style=\"margin:0 0 8px;padding:8px;background:#f6f8fa;\
1445 border-radius:6px\">\
1446 <div style=\"font-size:12px;color:#57606a\">{} {} · {}</div>\
1447 <div style=\"white-space:pre-wrap;font-size:13px\">{}</div></div>",
1448 w.reviewer,
1449 r.reviewer,
1450 esc(&r.agent),
1451 body,
1452 );
1453 }
1454 }
1455
1456 let _ = writeln!(
1457 h,
1458 "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}: {}</h2>",
1459 w.checks,
1460 esc(pr.checks.as_str())
1461 );
1462 if pr.failing.is_empty() {
1463 let _ = writeln!(
1464 h,
1465 "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>",
1466 w.nothing_failing
1467 );
1468 } else {
1469 h.push_str("<ul style=\"margin:0;padding-left:20px;font-size:13px\">\n");
1470 for f in &pr.failing {
1471 let _ = writeln!(h, "<li>{}</li>", esc(f));
1472 }
1473 h.push_str("</ul>\n");
1474 }
1475
1476 let _ = writeln!(
1479 h,
1480 "<h2 style=\"margin:16px 0 6px;font-size:15px\">{} {}</h2>",
1481 rows.len(),
1482 w.files_changed
1483 );
1484 h.push_str(
1485 "<table style=\"width:100%;border-collapse:collapse;font-size:13px\">\n\
1486 <thead><tr>\
1487 <th style=\"text-align:left;border-bottom:1px solid #d0d7de;padding:4px 2px\">file</th>\
1488 <th style=\"text-align:right;border-bottom:1px solid #d0d7de;padding:4px 2px\">added</th>\
1489 <th style=\"text-align:right;border-bottom:1px solid #d0d7de;padding:4px 2px\">removed\
1490 </th></tr></thead>\n<tbody>\n",
1491 );
1492 let mut total_added = 0u64;
1493 let mut total_removed = 0u64;
1494 for r in &rows {
1495 total_added += r.added.unwrap_or(0);
1496 total_removed += r.removed.unwrap_or(0);
1497 let cell = |n: Option<u64>| match n {
1498 Some(n) => n.to_string(),
1499 None => "bin".to_owned(),
1500 };
1501 let _ = writeln!(
1502 h,
1503 "<tr>\
1504 <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;\
1505 font-family:ui-monospace,monospace\">{}</td>\
1506 <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;text-align:right;\
1507 color:#0a3622\">{}</td>\
1508 <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;text-align:right;\
1509 color:#5c1a17\">{}</td></tr>",
1510 esc(&r.path),
1511 cell(r.added),
1512 cell(r.removed),
1513 );
1514 }
1515 let _ = writeln!(
1516 h,
1517 "</tbody>\n<tfoot><tr style=\"font-weight:600\">\
1518 <td style=\"padding:4px 2px\">total</td>\
1519 <td style=\"padding:4px 2px;text-align:right\">{total_added}</td>\
1520 <td style=\"padding:4px 2px;text-align:right\">{total_removed}</td>\
1521 </tr></tfoot>\n</table>"
1522 );
1523
1524 let _ = writeln!(
1526 h,
1527 "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1528 w.commits
1529 );
1530 if commits.is_empty() {
1531 h.push_str(&format!(
1532 "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>\n",
1533 w.no_commits
1534 ));
1535 } else {
1536 h.push_str("<ol style=\"margin:0;padding-left:20px;font-size:13px\">\n");
1537 for c in commits {
1538 let _ = writeln!(h, "<li>{}</li>", esc(c));
1539 }
1540 h.push_str("</ol>\n");
1541 }
1542 let _ = writeln!(
1543 h,
1544 "<p style=\"margin:8px 0 0;font-size:13px\">{} <strong>{}</strong>{}</p>",
1545 w.lands_as,
1546 esc(subject),
1547 w.lands_as_tail()
1548 );
1549
1550 let _ = writeln!(
1552 h,
1553 "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1554 w.comments
1555 );
1556 if pr.review_comments.is_empty() {
1557 h.push_str(&format!(
1558 "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>\n",
1559 w.no_comments
1560 ));
1561 } else {
1562 for c in &pr.review_comments {
1563 let anchor = match (&c.path, c.line) {
1564 (Some(p), Some(l)) => format!("{p}:{l}"),
1565 (Some(p), None) => p.clone(),
1566 _ => "pull request thread".to_owned(),
1567 };
1568 let _ = writeln!(
1569 h,
1570 "<div style=\"margin:0 0 8px;padding:8px;background:#f6f8fa;border-radius:6px\">\
1571 <div style=\"font-size:12px;color:#57606a\">{} · {}</div>\
1572 <div style=\"white-space:pre-wrap;font-size:13px\">{}</div></div>",
1573 esc(&c.author),
1574 esc(&anchor),
1575 esc(&tail(&c.body, 800)),
1576 );
1577 }
1578 }
1579
1580 let total = diff.lines().count();
1582 let shown = total.min(DIFF_MAX_LINES);
1583 let _ = writeln!(
1584 h,
1585 "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1586 w.diff
1587 );
1588 h.push_str(
1589 "<div style=\"font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;\
1590 border:1px solid #d0d7de;border-radius:6px;overflow-x:auto\">\n",
1591 );
1592 for line in diff.lines().take(shown) {
1593 let (gutter, style, body) = diff_row(line);
1594 let _ = writeln!(
1595 h,
1596 "<div style=\"display:flex;{style}\">\
1597 <span style=\"flex:0 0 1.4em;text-align:center;user-select:none;\
1598 border-right:1px solid #d0d7de\">{gutter}</span>\
1599 <span style=\"white-space:pre;padding-left:6px\">{}</span></div>",
1600 esc(body),
1601 );
1602 }
1603 h.push_str("</div>\n");
1604 if total > shown {
1605 let omitted = total - shown;
1606 let head = state.winner().map_or("HEAD", |w| w.branch.as_str());
1607 let where_ = state.winner().map_or_else(
1608 || state.repo.display().to_string(),
1609 |w| w.worktree.display().to_string(),
1610 );
1611 let _ = writeln!(
1612 h,
1613 "<p style=\"margin:8px 0 0;padding:8px;background:#fff8c5;border-radius:6px;\
1614 font-size:13px\">{}: {}</p>",
1615 w.truncated,
1616 w.truncated_note(
1617 omitted,
1618 total,
1619 shown,
1620 &esc(&where_),
1621 &esc(&state.base_branch),
1622 &esc(head),
1623 ),
1624 );
1625 }
1626
1627 h.push_str("</body>\n</html>\n");
1628 h
1629}
1630
1631fn contested_to_ask(state: &RunState) -> Option<ContestedHandoff> {
1634 if state.owner_hold(crate::config::OwnerHold::HoldContestedMerge) {
1635 state.contested_handoff.clone()
1636 } else {
1637 None
1638 }
1639}
1640
1641pub fn deputy_brief(q: &ask::Question, state: Option<&RunState>) -> String {
1649 let mut s = format!(
1650 "This is the merge approval for run {run} (`magi show {run}`). The question's \
1651 own text above names the pull request. Answering `{APPROVE}` squash-merges \
1652 it into the base branch; `{HOLD}` leaves the pull request open. Silence is a \
1653 hold: the owner not answering never merges. When the owner tells you to \
1654 merge, in whatever words, settle `{APPROVE}`; when they ask for what another \
1655 offered choice does, settle that one. If you cannot tell what they want, ask \
1656 with `magi ask --thread`.\n\n\
1657 This brief is a snapshot from when your turn started: check `magi show {run}` \
1658 and `gh pr view` (read-only) before telling the owner anything current. The \
1659 driver carries out the merge, repair, withdrawal or replacement: do not \
1660 change files, branches or the pull request yourself.",
1661 run = q.run
1662 );
1663 if let Some(target) = &q.merge_target {
1664 s.push_str(&format!("\n\nThis decision names PR {} at head `{}`. A settled `{APPROVE}` merges exactly that head; a newer head is never merged on this answer. Withdrawal explicitly closes the PR and ends the task. Replacement closes the old PR before dispatching a new attempt with the selected implementer; do not start a separate task for it yourself.", target.pr, target.head));
1665 }
1666 if q.choices.iter().any(|c| c == REPAIR) {
1667 s.push_str("\n\n`fix findings and re-review` requests one repair and bounded re-review on the existing PR. It never approves a merge. The driver performs the repair; do not edit or queue another task for it. Updated review and gate results require a fresh merge decision.");
1668 }
1669 if q.detail.contains("Approval required because:") || q.detail.contains("承認が必要な理由:")
1670 {
1671 s.push_str("\n\nSaved approval evidence (at question creation):\n");
1672 s.push_str(&q.detail);
1673 } else {
1674 s.push_str("\n\nApproval reasons and final review evidence were not recorded in this legacy question. Do not infer its original trigger from current settings; consult the saved panel and review history.");
1675 }
1676 let Some(state) = state else {
1677 s.push_str(
1678 "\n\nThe run's record could not be read, so the pull request, the panel \
1679 summary and any contested findings are not known to you beyond the \
1680 question's own text. Say so to the owner rather than guessing.",
1681 );
1682 return s;
1683 };
1684 if let Some(pr) = &state.pr {
1685 s.push_str(&format!(
1686 "\n\nPull request #{} {} (recorded state: {}, last seen).",
1687 pr.number, pr.url, pr.state
1688 ));
1689 }
1690 s.push_str(&format!("\nBase branch: `{}`.", state.base_branch));
1691 if let Some(w) = state.winner() {
1692 s.push_str(&format!("\nWinning branch: `{}`.", w.branch));
1693 }
1694
1695 s
1696}
1697
1698fn merge_consent_superseded(state: &RunState, question: &ask::Question) -> Result<bool> {
1702 if !question.status.open() && approval(question.resolution().as_deref()) != Approval::Merge {
1703 return Ok(false);
1704 }
1705 let Some(task_id) = state
1706 .origin
1707 .as_ref()
1708 .and_then(|origin| origin.task.as_ref())
1709 else {
1710 return Ok(false);
1711 };
1712 let task = crate::queue::Queue::open()
1713 .get(task_id)
1714 .context("cannot verify operator decisions for the merge approval")?;
1715 Ok(task
1716 .operator_decided_at
1717 .is_some_and(|at| at > question.answered_at.unwrap_or(question.asked_at)))
1718}
1719
1720async fn approval_gate(
1740 state: &mut RunState,
1741 pr: &PrState,
1742 subject: &str,
1743 contested: Option<&ContestedHandoff>,
1744 head: &str,
1745) -> Result<ApprovalGate> {
1746 let _chat_merge = crate::chat_merge::target_lock_wait(&crate::run::home(), &pr.url).await?;
1747 let store = ask::Questions::open();
1748 let reusable = state.land_approval.as_ref().and_then(|a| {
1753 store
1754 .list_for_effects()
1755 .into_iter()
1756 .find(|q| q.id == a.question)
1757 .filter(|q| {
1758 q.status != ask::QuestionStatus::Abandoned
1759 && state
1760 .repair_grants
1761 .last()
1762 .is_none_or(|g| q.asked_at > g.receipt.at)
1763 && (a.head.eq_ignore_ascii_case(head)
1764 || q.resolution()
1765 .as_deref()
1766 .is_some_and(crate::merge_decision::stops))
1767 })
1768 });
1769 let reusable = match reusable {
1770 Some(q) if merge_consent_superseded(state, &q)? => None,
1771 other => other,
1772 };
1773 if reusable.is_none() {
1774 for stale in store.list_for_effects().into_iter().filter(|q| {
1775 q.run == state.id
1776 && q.node == APPROVAL_NODE
1777 && q.status.open()
1778 && !store.held_reply(&q.id)
1779 }) {
1780 let why =
1781 "the pull request head or operator decision changed; asked again for approval";
1782 if let Err(e) = store.update(&stale.id, |q| {
1783 q.abandon(why);
1784 Ok(())
1785 }) {
1786 tracing::warn!("could not retire the superseded approval question: {e:#}");
1787 }
1788 }
1789 }
1790
1791 let q = match reusable {
1792 Some(mut q) => {
1793 if upgrade_repair_choice(&mut q, state) {
1794 q = store
1795 .update(&q.id, |current| {
1796 upgrade_repair_choice(current, state);
1797 Ok(())
1798 })?
1799 .0;
1800 }
1801 q
1802 }
1803 None => {
1804 let worktree = match state.winner() {
1805 Some(w) => w.worktree.clone(),
1806 None => state.repo.clone(),
1807 };
1808 let head = if head.is_empty() {
1811 state
1812 .winner()
1813 .map_or_else(|| "HEAD".to_owned(), |w| w.branch.clone())
1814 } else {
1815 head.to_owned()
1816 };
1817 let remote = &state.config.merge.remote;
1820 let tracking = format!("{remote}/{}", state.base_branch);
1821 let base = if git::rev_exists(&worktree, &tracking).await {
1822 tracking
1823 } else {
1824 String::new()
1825 };
1826 let range = format!("{base}...{head}");
1827 let numstat = if base.is_empty() {
1831 String::new()
1832 } else {
1833 git::git_raw(&worktree, &["diff", "--numstat", "-M", &range])
1834 .await
1835 .map(|o| o.stdout)
1836 .unwrap_or_default()
1837 };
1838 let diff = if base.is_empty() {
1839 String::new()
1840 } else {
1841 git::diff(&worktree, &base, &head).await.unwrap_or_default()
1842 };
1843 let commits: Vec<String> = if base.is_empty() {
1844 Vec::new()
1845 } else {
1846 git::git_raw(
1847 &worktree,
1848 &[
1849 "log",
1850 "--reverse",
1851 "--format=%s",
1852 &format!("{base}..{head}"),
1853 ],
1854 )
1855 .await
1856 .map(|o| o.stdout)
1857 .unwrap_or_default()
1858 .lines()
1859 .filter(|l| !l.trim().is_empty())
1860 .map(str::to_owned)
1861 .collect()
1862 };
1863
1864 let w = words(&state.config.graph.language);
1865 let html = approval_panel(state, pr, &numstat, &diff, &commits, subject);
1866 let mut fresh = ask::Question::new(
1867 state.id.clone(),
1868 APPROVAL_NODE.to_owned(),
1869 "land".to_owned(),
1870 w.approval_summary(pr.number, subject),
1871 format!(
1872 "{}\n\n{}",
1873 approval_evidence(state),
1874 w.approval_detail(&pr.url, &state.base_branch, subject, contested)
1875 ),
1876 approval_choices(state),
1877 );
1878 fresh.merge_target = Some(crate::merge_decision::Target {
1879 pr: pr.url.clone(),
1880 head: head.clone(),
1881 language: state.config.graph.language.clone(),
1882 });
1883 if fresh.choices.iter().any(|c| c == REPAIR) {
1884 fresh.actions.insert(
1885 REPAIR.to_owned(),
1886 ask::ChoiceAction::Resume {
1887 run: state.id.clone(),
1888 },
1889 );
1890 fresh.detail.push_str("\n\n`fix findings and re-review` runs one repair and bounded review on this PR; it does not approve a merge. A fresh decision follows the updated review and gate.");
1891 }
1892 for choice in fresh.choices.clone() {
1893 if crate::merge_decision::stops(&choice)
1894 && choice != HOLD
1895 && choice != crate::merge_decision::DISMISS
1896 {
1897 fresh.actions.insert(
1898 choice,
1899 ask::ChoiceAction::Resume {
1900 run: state.id.clone(),
1901 },
1902 );
1903 }
1904 }
1905 store
1906 .put_panel(&mut fresh, &html, &[])
1907 .context("write the merge approval panel")?;
1908 store
1909 .put_executable(&mut fresh)
1910 .context("file the merge approval question")?;
1911 state.land_approval = Some(LandApproval {
1912 question: fresh.id.clone(),
1913 head: head.clone(),
1914 });
1915 state.event(
1916 "land",
1917 format!("asking for merge approval ({})", fresh.short()),
1918 );
1919 state.save()?;
1920 if let Err(e) = ask::notify(&state.config.notify, &fresh).await {
1921 tracing::warn!(
1925 "could not notify about merge approval question {}: {e:#} - \
1926 the web UI is the only surface for it now",
1927 fresh.short()
1928 );
1929 }
1930 fresh
1931 }
1932 };
1933
1934 Ok(match q.status {
1935 ask::QuestionStatus::Open => ApprovalGate::Pending,
1936 ask::QuestionStatus::Abandoned => ApprovalGate::Held,
1940 ask::QuestionStatus::Answered => match approval(q.resolution().as_deref()) {
1944 Approval::Merge => ApprovalGate::Approved,
1945 Approval::Repair if !state.reviews.is_empty() => {
1946 if !state.merge_repairs.iter().any(|r| r.question == q.id) {
1947 state.merge_repairs.push(crate::run::MergeRepair {
1948 question: q.id.clone(),
1949 head: head.to_owned(),
1950 pr: pr.url.clone(),
1951 reviews: state.reviews.clone(),
1952 gate: state.gate.clone(),
1953 gate_head: state.gate_head.clone(),
1954 gate_fixes: state.gate_fixes.clone(),
1955 pre_gate: state.pre_gate.clone(),
1956 phase: crate::run::MergeRepairPhase::Requested,
1957 failure: None,
1958 });
1959 state.land_approval = None;
1960 state.event(
1961 "repair",
1962 "owner requested fix findings and re-review; merge is not approved",
1963 );
1964 state.save()?;
1965 }
1966 ApprovalGate::Repair
1967 }
1968 Approval::Repair | Approval::Hold => ApprovalGate::Held,
1969 },
1970 })
1971}
1972
1973fn rollup_verdict(rollup: &[GhCheck]) -> (Checks, Vec<String>) {
1976 let mut failing = Vec::new();
1977 let mut pending = false;
1978 let mut unknown = false;
1979 for check in rollup {
1980 match check.verdict() {
1981 Verdict::Pass => {}
1982 Verdict::Pending => pending = true,
1983 Verdict::Fail => failing.push(check.label()),
1984 Verdict::Unknown => unknown = true,
1985 }
1986 }
1987 let checks = if rollup.is_empty() {
1988 Checks::Unknown
1989 } else if pending {
1990 Checks::Pending
1991 } else if !failing.is_empty() {
1992 Checks::Red
1993 } else if unknown {
1994 Checks::Unknown
1995 } else {
1996 Checks::Green
1997 };
1998 (checks, failing)
1999}
2000
2001pub fn parse_pr(json: &str) -> Result<PrState> {
2004 let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2005 let state = match raw.state.to_ascii_uppercase().as_str() {
2006 "OPEN" => PrLifecycle::Open,
2007 "MERGED" => PrLifecycle::Merged,
2008 "CLOSED" => PrLifecycle::Closed,
2009 other => bail!("unknown pull request state `{other}`"),
2010 };
2011
2012 let (checks, failing) = rollup_verdict(&raw.status_check_rollup);
2013
2014 let mut review_comments = Vec::new();
2015 for r in raw.reviews {
2016 push_if_outstanding(
2017 &mut review_comments,
2018 ReviewComment {
2019 author: r.author.login,
2020 path: None,
2021 line: None,
2022 body: r.body,
2023 },
2024 );
2025 }
2026 for c in raw.comments {
2027 push_if_outstanding(
2028 &mut review_comments,
2029 ReviewComment {
2030 author: c.author.login,
2031 path: None,
2032 line: None,
2033 body: c.body,
2034 },
2035 );
2036 }
2037
2038 Ok(PrState {
2039 url: raw.url,
2040 number: raw.number,
2041 state,
2042 checks,
2043 failing,
2044 review_comments,
2045 blocking: Blocking::of(&raw.merge_state_status),
2046 })
2047}
2048
2049#[derive(Debug, Clone, PartialEq, Eq)]
2051pub(crate) struct CheckView {
2052 pub name: String,
2053 pub verdict: Verdict,
2054 pub run: Option<String>,
2056 pub url: Option<String>,
2057}
2058
2059#[derive(Debug, Clone, PartialEq, Eq)]
2063pub(crate) struct RollupView {
2064 pub url: String,
2065 pub number: u64,
2066 pub state: PrLifecycle,
2067 pub head: String,
2068 pub checks: Vec<CheckView>,
2069}
2070
2071pub(crate) fn parse_rollup(json: &str) -> Result<RollupView> {
2074 let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2075 let state = match raw.state.to_ascii_uppercase().as_str() {
2076 "OPEN" => PrLifecycle::Open,
2077 "MERGED" => PrLifecycle::Merged,
2078 "CLOSED" => PrLifecycle::Closed,
2079 other => bail!("unknown pull request state `{other}`"),
2080 };
2081 let checks = raw
2082 .status_check_rollup
2083 .iter()
2084 .map(|c| CheckView {
2085 name: c.label(),
2086 verdict: c.verdict(),
2087 run: c.url().and_then(run_of),
2088 url: c.url().map(str::to_owned),
2089 })
2090 .collect();
2091 Ok(RollupView {
2092 url: raw.url,
2093 number: raw.number,
2094 state,
2095 head: raw.head_ref_oid,
2096 checks,
2097 })
2098}
2099
2100pub async fn lifecycle(repo: &Path, pr_url: &str) -> Result<PrLifecycle> {
2110 let view = gh(
2111 repo,
2112 &[
2113 "pr".to_owned(),
2114 "view".to_owned(),
2115 pr_url.to_owned(),
2116 "--json".to_owned(),
2117 "state".to_owned(),
2118 ],
2119 )
2120 .await?;
2121 if !view.0 {
2122 bail!("gh pr view {pr_url}: {}", view.1);
2123 }
2124 Ok(parse_pr(&view.1)?.state)
2128}
2129
2130#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2134pub struct ExternalMerge {
2135 pub url: String,
2137 pub number: u64,
2139}
2140
2141#[derive(Debug, Deserialize)]
2142#[serde(rename_all = "camelCase")]
2143struct GhMergedPr {
2144 url: String,
2145 number: u64,
2146 merged_at: String,
2147 base_ref_name: String,
2148}
2149
2150fn pick_merged_pr(
2164 json: &str,
2165 base_branch: &str,
2166 created_at: Timestamp,
2167) -> Result<Option<ExternalMerge>> {
2168 pick_merged_pr_with(json, base_branch, created_at, false)
2169}
2170
2171fn pick_merged_pr_with(
2172 json: &str,
2173 base_branch: &str,
2174 created_at: Timestamp,
2175 reject_ambiguous: bool,
2176) -> Result<Option<ExternalMerge>> {
2177 let raw: Vec<GhMergedPr> =
2178 serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2179 let mut matches: Vec<ExternalMerge> = Vec::new();
2180 for pr in raw {
2181 if pr.base_ref_name != base_branch {
2182 continue;
2183 }
2184 let Ok(merged_at) = pr.merged_at.parse::<Timestamp>() else {
2185 continue;
2186 };
2187 if merged_at < created_at {
2188 continue;
2189 }
2190 matches.push(ExternalMerge {
2191 url: pr.url,
2192 number: pr.number,
2193 });
2194 }
2195 anyhow::ensure!(
2196 !reject_ambiguous || matches.len() <= 1,
2197 "multiple merged pull requests match this run; merge evidence is ambiguous"
2198 );
2199 if matches.len() == 1 {
2200 Ok(matches.pop())
2201 } else {
2202 Ok(None)
2203 }
2204}
2205
2206#[derive(Debug, Clone, PartialEq, Eq)]
2208pub enum OpenPr {
2209 None,
2211 One {
2213 url: String,
2215 title: String,
2217 },
2218 Many(Vec<String>),
2220}
2221
2222#[derive(Debug, Deserialize)]
2223#[serde(rename_all = "camelCase")]
2224struct GhOpenPr {
2225 url: String,
2229 #[serde(default)]
2230 title: String,
2231 base_ref_name: String,
2232 #[serde(default)]
2235 is_cross_repository: bool,
2236}
2237
2238pub fn pick_open_pr(json: &str, base: &str) -> Result<OpenPr> {
2244 let raw: Vec<GhOpenPr> =
2245 serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2246 let mut hits: Vec<GhOpenPr> = raw
2247 .into_iter()
2248 .filter(|p| p.base_ref_name == base && !p.is_cross_repository)
2249 .collect();
2250 Ok(match hits.len() {
2251 0 => OpenPr::None,
2252 1 => {
2253 let p = hits.remove(0);
2254 OpenPr::One {
2255 url: p.url,
2256 title: p.title,
2257 }
2258 }
2259 _ => OpenPr::Many(hits.into_iter().map(|p| p.url).collect()),
2260 })
2261}
2262
2263pub async fn find_open_pr(repo: &Path, branch: &str, base: &str) -> Result<OpenPr> {
2267 let (ok, out) = gh(
2268 repo,
2269 &[
2270 "pr".to_owned(),
2271 "list".to_owned(),
2272 "--head".to_owned(),
2273 branch.to_owned(),
2274 "--base".to_owned(),
2275 base.to_owned(),
2276 "--state".to_owned(),
2277 "open".to_owned(),
2278 "--json".to_owned(),
2279 "number,url,title,baseRefName,isCrossRepository".to_owned(),
2280 ],
2281 )
2282 .await?;
2283 if !ok {
2284 bail!("gh pr list failed: {out}");
2285 }
2286 pick_open_pr(&out, base)
2287}
2288
2289#[derive(Debug, Deserialize)]
2290#[serde(rename_all = "camelCase")]
2291struct GhPrHead {
2292 head_ref_name: String,
2293 base_ref_name: String,
2294 state: String,
2295 is_cross_repository: bool,
2298 head_ref_oid: String,
2301}
2302
2303#[derive(Debug, Clone, PartialEq, Eq)]
2305pub struct Refusal {
2306 pub retry: bool,
2309 pub why: String,
2311}
2312
2313impl Refusal {
2314 fn final_(why: String) -> Self {
2315 Self { retry: false, why }
2316 }
2317}
2318
2319pub fn closable(
2328 json: &str,
2329 branch: &str,
2330 base: &str,
2331 verified: &[String],
2332) -> std::result::Result<(), Refusal> {
2333 let pr: GhPrHead = serde_json::from_str(json).map_err(|e| Refusal {
2334 retry: true,
2335 why: format!("could not read the pull request ({e})"),
2336 })?;
2337 if pr.head_ref_name != branch {
2338 return Err(Refusal::final_(format!(
2339 "its head is `{}`, not this run's `{branch}`",
2340 pr.head_ref_name
2341 )));
2342 }
2343 if pr.is_cross_repository {
2344 return Err(Refusal::final_("its head lives in a fork".to_owned()));
2345 }
2346 if pr.base_ref_name != base {
2347 return Err(Refusal::final_(format!(
2348 "it targets `{}`, not `{base}`",
2349 pr.base_ref_name
2350 )));
2351 }
2352 if !pr.state.eq_ignore_ascii_case("open") {
2353 return Err(Refusal::final_(format!(
2354 "it is already {}",
2355 pr.state.to_ascii_lowercase()
2356 )));
2357 }
2358 if !verified.contains(&pr.head_ref_oid) {
2362 return Err(Refusal {
2363 retry: true,
2364 why: format!(
2365 "its head {} is not a commit this run checked against the base",
2366 crate::already::short_sha(&pr.head_ref_oid)
2367 ),
2368 });
2369 }
2370 Ok(())
2371}
2372
2373async fn remote_is_forge(repo: &Path, remote: &str) -> bool {
2378 let Ok(url) = git::git(repo, &["remote", "get-url", remote]).await else {
2379 return false;
2380 };
2381 is_forge_url(url.trim())
2382}
2383
2384fn is_forge_url(url: &str) -> bool {
2385 url.contains("://") && !url.starts_with("file://")
2386 || url
2387 .split_once(':')
2388 .is_some_and(|(host, _)| host.contains('@') && !host.contains(['/', '\\']))
2389}
2390
2391fn forge_unavailable(message: &str) -> bool {
2394 message.contains("known GitHub host") || message.contains("spawn gh")
2395}
2396
2397pub fn superseded_comment(base: &str, evidence: &crate::already::Evidence) -> String {
2400 let how = match evidence.proof {
2401 crate::already::Proof::PatchId => format!(
2402 "carried by commit {} on `{base}` with the same patch",
2403 evidence.names()
2404 ),
2405 crate::already::Proof::Ancestry => {
2406 format!("already in the history of `{base}` as {}", evidence.names())
2407 }
2408 crate::already::Proof::Tree => format!(
2409 "already part of `{base}` (merging this branch changes nothing at {})",
2410 crate::already::short_sha(&evidence.tip)
2411 ),
2412 };
2413 format!(
2414 "Closing: everything this branch adds is {how}, so there is nothing left to \
2415 land. This pull request was closed automatically after that was verified; \
2416 reopen it if you disagree."
2417 )
2418}
2419
2420pub async fn close_superseded_pr(
2432 state: &mut RunState,
2433 branch: &str,
2434 evidence: &crate::already::Evidence,
2435 verified: &[String],
2436) -> Result<std::result::Result<String, String>> {
2437 let repo = state.repo.clone();
2438 let base = state.base_branch.clone();
2439 let url = match state.pr.as_ref().filter(|p| p.state == "open") {
2440 Some(p) => p.url.clone(),
2441 None if !remote_is_forge(&repo, &state.config.merge.remote).await => {
2446 return Ok(Err(
2447 "the remote is not a forge, so there is no pull request".to_owned(),
2448 ));
2449 }
2450 None => match find_open_pr(&repo, branch, &base).await {
2451 Err(e) if forge_unavailable(&format!("{e:#}")) => {
2452 return Ok(Err(format!("no forge to ask: {e:#}")));
2453 }
2454 Err(e) => return Err(e),
2455 Ok(OpenPr::One { url, .. }) => url,
2456 Ok(OpenPr::None) => return Ok(Err("no open pull request".to_owned())),
2457 Ok(OpenPr::Many(urls)) => {
2458 return Ok(Err(format!(
2459 "{} open pull requests name it; not choosing between them",
2460 urls.len()
2461 )));
2462 }
2463 },
2464 };
2465 let (ok, view) = gh(
2466 &repo,
2467 &[
2468 "pr".to_owned(),
2469 "view".to_owned(),
2470 url.clone(),
2471 "--json".to_owned(),
2472 "headRefName,headRefOid,baseRefName,state,isCrossRepository".to_owned(),
2473 ],
2474 )
2475 .await?;
2476 if !ok {
2477 bail!("gh pr view {url} failed: {view}");
2478 }
2479 if let Err(refusal) = closable(&view, branch, &base, verified) {
2480 if refusal.retry {
2483 bail!("left {url} open: {}", refusal.why);
2484 }
2485 return Ok(Err(format!("left {url} open: {}", refusal.why)));
2486 }
2487 let (ok, out) = gh(
2488 &repo,
2489 &[
2490 "pr".to_owned(),
2491 "close".to_owned(),
2492 url.clone(),
2493 "--comment".to_owned(),
2494 superseded_comment(&base, evidence),
2495 ],
2496 )
2497 .await?;
2498 if !ok {
2499 bail!("gh pr close {url} failed: {out}");
2500 }
2501 if let Some(p) = state.pr.as_mut().filter(|p| p.url == url) {
2502 p.state = "closed".to_owned();
2503 }
2504 Ok(Ok(url))
2505}
2506
2507pub async fn set_pr_title(state: &mut RunState, repo: &Path, url: &str, title: &str) -> Result<()> {
2511 let (title, _) = crate::github_text::prepare(state, title, "");
2512 edit_pr_title(repo, url, &title).await
2513}
2514
2515pub async fn set_pr_title_verbatim(repo: &Path, url: &str, title: &str) -> Result<()> {
2519 edit_pr_title(repo, url, title).await
2520}
2521
2522pub async fn set_pr_text_verbatim(repo: &Path, url: &str, title: &str, body: &str) -> Result<()> {
2525 let (ok, _) = gh(
2526 repo,
2527 &[
2528 "pr".to_owned(),
2529 "edit".to_owned(),
2530 url.to_owned(),
2531 "--title".to_owned(),
2532 title.to_owned(),
2533 "--body".to_owned(),
2534 body.to_owned(),
2535 ],
2536 )
2537 .await
2538 .map_err(|_| anyhow::anyhow!("could not run gh pr edit for the chosen rewrite"))?;
2539 if !ok {
2540 bail!("gh pr edit failed while posting the chosen rewrite");
2542 }
2543 Ok(())
2544}
2545
2546async fn edit_pr_title(repo: &Path, url: &str, title: &str) -> Result<()> {
2547 let (ok, out) = gh(
2548 repo,
2549 &[
2550 "pr".to_owned(),
2551 "edit".to_owned(),
2552 url.to_owned(),
2553 "--title".to_owned(),
2554 title.to_owned(),
2555 ],
2556 )
2557 .await?;
2558 if !ok {
2559 bail!("gh pr edit failed: {out}");
2560 }
2561 Ok(())
2562}
2563
2564pub async fn find_external_merge(state: &RunState) -> Result<Option<ExternalMerge>> {
2577 let Some(winner) = state.winner() else {
2578 return Ok(None);
2579 };
2580 find_external_merge_with(
2581 state,
2582 state.pr_head.as_deref().unwrap_or(&winner.branch),
2583 false,
2584 )
2585 .await
2586}
2587
2588pub(crate) async fn find_external_merge_for_reopen(
2590 state: &RunState,
2591) -> Result<Option<ExternalMerge>> {
2592 let Some(branch) = state.pr_branch() else {
2593 anyhow::ensure!(
2594 state.pr.is_none() && state.pr_pushed_head.is_none(),
2595 "run has public PR evidence but no known branch to check"
2596 );
2597 return Ok(None);
2598 };
2599 find_external_merge_with(state, branch, true).await
2600}
2601
2602async fn find_external_merge_with(
2603 state: &RunState,
2604 branch: &str,
2605 reject_ambiguous: bool,
2606) -> Result<Option<ExternalMerge>> {
2607 let out = gh(
2608 &state.repo,
2609 &[
2610 "pr".to_owned(),
2611 "list".to_owned(),
2612 "--head".to_owned(),
2613 branch.to_owned(),
2614 "--state".to_owned(),
2615 "merged".to_owned(),
2616 "--json".to_owned(),
2617 "url,number,mergedAt,baseRefName".to_owned(),
2618 ],
2619 )
2620 .await?;
2621 if !out.0 {
2622 bail!("gh pr list --head {branch}: {}", out.1);
2623 }
2624 if reject_ambiguous {
2625 pick_merged_pr_with(&out.1, &state.base_branch, state.created_at, true)
2626 } else {
2627 pick_merged_pr(&out.1, &state.base_branch, state.created_at)
2628 }
2629}
2630
2631pub async fn branch_is_ancestor(repo: &Path, branch: &str, base_branch: &str) -> Result<bool> {
2643 let out = tokio::process::Command::new("git")
2644 .args(["merge-base", "--is-ancestor", branch, base_branch])
2645 .current_dir(repo)
2646 .quiet()
2647 .stdin(std::process::Stdio::null())
2648 .output()
2649 .await
2650 .context("spawn git merge-base --is-ancestor")?;
2651 Ok(out.status.success())
2652}
2653
2654fn forge_slug(url: &str) -> Option<(String, &str)> {
2662 let rest = url.rsplit("://").next()?;
2663 let (host, path) = rest.split_once('/')?;
2664 if host.is_empty() {
2665 return None;
2666 }
2667 Some((host.to_ascii_lowercase(), path))
2668}
2669
2670pub(crate) fn slug_of_pr_url(url: &str) -> Option<String> {
2678 let (host, path) = forge_slug(url)?;
2679 let mut segments = path.split('/');
2680 let owner = segments.next()?;
2681 let repo = segments.next()?;
2682 let kind = segments.next()?;
2683 if owner.is_empty() || repo.is_empty() || kind != "pull" {
2684 return None;
2685 }
2686 Some(format!("{host}/{owner}/{repo}"))
2687}
2688
2689fn slug_of_repo_url(url: &str) -> Option<String> {
2693 let (host, path) = forge_slug(url)?;
2694 let mut segments = path.split('/');
2695 let owner = segments.next()?;
2696 let repo = segments.next()?;
2697 if owner.is_empty() || repo.is_empty() {
2698 return None;
2699 }
2700 Some(format!("{host}/{owner}/{repo}"))
2701}
2702
2703pub(crate) fn ensure_same_repo(run_repo_slug: &str, pr_repo_slug: &str) -> Result<()> {
2724 if run_repo_slug.eq_ignore_ascii_case(pr_repo_slug) {
2725 return Ok(());
2726 }
2727 bail!(
2728 "refusing to correct this run: it is recorded against {run_repo_slug}, but the pull \
2729 request URL belongs to {pr_repo_slug} - pass the run id whose repository the URL \
2730 actually belongs to (or, if `origin` is a fork opened against a different upstream, \
2731 verify by hand before treating this as a false positive)"
2732 );
2733}
2734
2735async fn repo_slug(repo: &Path) -> Result<String> {
2746 let out = gh(
2747 repo,
2748 &[
2749 "repo".to_owned(),
2750 "view".to_owned(),
2751 "--json".to_owned(),
2752 "url".to_owned(),
2753 ],
2754 )
2755 .await?;
2756 if !out.0 {
2757 bail!("gh repo view --json url: {}", out.1);
2758 }
2759 #[derive(Debug, Deserialize)]
2760 struct GhRepo {
2761 url: String,
2762 }
2763 let parsed: GhRepo = serde_json::from_str(&out.1)
2764 .with_context(|| format!("parse `gh repo view` output: {}", out.1))?;
2765 slug_of_repo_url(&parsed.url)
2766 .with_context(|| format!("could not parse a host/owner/repo out of {}", parsed.url))
2767}
2768
2769pub async fn correct_manual_merge(
2817 state: &mut RunState,
2818 url: &str,
2819) -> Result<(RunStatus, RunStatus)> {
2820 let Some(pr_slug) = slug_of_pr_url(url) else {
2821 bail!(
2822 "could not parse an owner/repo out of {url}; refusing to guess which repository \
2823 this pull request belongs to"
2824 );
2825 };
2826 let run_slug = repo_slug(&state.repo).await?;
2827 ensure_same_repo(&run_slug, &pr_slug)?;
2828 correct_merge(state, url).await
2829}
2830
2831pub(crate) async fn correct_confirmed_external_merge(
2842 state: &mut RunState,
2843 url: &str,
2844) -> Result<(RunStatus, RunStatus)> {
2845 correct_merge(state, url).await
2846}
2847
2848fn names_same_pr(a: &RunState, url: &str, number: u64, repo: &Path) -> bool {
2850 let Some(pr) = a.pr.as_ref() else {
2851 return false;
2852 };
2853 if !url.is_empty()
2854 && pr
2855 .url
2856 .trim_end_matches('/')
2857 .eq_ignore_ascii_case(url.trim_end_matches('/'))
2858 {
2859 return true;
2860 }
2861 number > 0
2862 && pr.number == number
2863 && match (a.repo.canonicalize(), repo.canonicalize()) {
2864 (Ok(x), Ok(y)) => x == y,
2865 _ => a.repo == repo,
2866 }
2867}
2868
2869fn rewrite_open_prs(
2883 home: &Path,
2884 decide: &mut dyn FnMut(&RunState) -> Option<PrLifecycle>,
2885) -> usize {
2886 let now = Timestamp::now();
2887 let mut changed = 0;
2888 for id in crate::run::list_ids_in(&home.join("runs")) {
2889 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2890 continue;
2891 };
2892 let path = home.join("runs").join(&id).join("run.json");
2893 let Ok(body) = std::fs::read_to_string(&path) else {
2894 continue;
2895 };
2896 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2897 continue;
2898 };
2899 if !state.status.done()
2900 || state.pr.as_ref().is_none_or(|p| p.state != "open")
2901 || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2902 != crate::run::Liveness::Dead
2903 {
2904 continue;
2905 }
2906 let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2907 continue;
2908 };
2909 if let Some(pr) = state.pr.as_mut() {
2910 pr.state = to.as_str().to_owned();
2911 }
2912 let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2913 state.event(
2914 "land",
2915 format!("recorded {url} as {}: another run settled it", to.as_str()),
2916 );
2917 match state.save_under(home) {
2918 Ok(()) => changed += 1,
2919 Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2920 }
2921 }
2922 changed
2923}
2924
2925pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2930 if to == PrLifecycle::Open {
2931 return;
2932 }
2933 let Some(home) = crate::run::try_home() else {
2934 return;
2935 };
2936 write_pr_state_through_in(&home, run, to);
2937}
2938
2939pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2940 let Some(pr) = run.pr.as_ref() else {
2941 return 0;
2942 };
2943 let (url, number) = (pr.url.clone(), pr.number);
2944 rewrite_open_prs(home, &mut |other| {
2945 (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2946 })
2947}
2948
2949pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
2952 let now = Timestamp::now();
2953 let mut out = Vec::new();
2954 for id in crate::run::list_ids_in(&home.join("runs")) {
2955 let path = home.join("runs").join(&id).join("run.json");
2956 let Ok(body) = std::fs::read_to_string(&path) else {
2957 continue;
2958 };
2959 let Ok(state) = serde_json::from_str::<RunState>(&body) else {
2960 continue;
2961 };
2962 if let Some(pr) = state.pr.as_ref()
2963 && state.status.done()
2964 && pr.state == "open"
2965 && !pr.url.is_empty()
2966 && !crate::daemon::is_working_on(home, &id, now)
2967 {
2968 out.push((id, state.repo.clone(), pr.url.clone()));
2969 }
2970 }
2971 out
2972}
2973
2974pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
2977 rewrite_open_prs(home, &mut |s| {
2978 s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
2979 })
2980}
2981
2982pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
2989 let mut known = BTreeMap::new();
2990 let mut failed = 0;
2991 let mut seen = BTreeSet::new();
2992 for (_, repo, url) in stale_open_prs(home) {
2993 if known.len() + failed >= max_lookups || !seen.insert(url.clone()) {
2994 continue;
2995 }
2996 match lifecycle(&repo, &url).await {
2997 Ok(state) => {
2998 known.insert(url, state);
2999 }
3000 Err(e) => {
3001 tracing::warn!("repair pr state of {url}: {e:#}");
3002 failed += 1;
3003 }
3004 }
3005 }
3006 (apply_pr_states(home, &known), failed)
3007}
3008
3009async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
3010 match lifecycle(&state.repo, url).await? {
3011 PrLifecycle::Merged => {}
3012 other => bail!(
3013 "{url} is {}, not merged; refusing to record {} as merged on a guess",
3014 other.as_str(),
3015 state.id
3016 ),
3017 }
3018 let before = state.status;
3019 if let Err(e) = land(state, url).await {
3020 state.status = RunStatus::Blocked;
3027 state.event("fold", format!("manual-merge correction failed: {e:#}"));
3028 state.save()?;
3029 return Err(e).context(format!("confirming the merge of {url}"));
3030 }
3031 state.event(
3032 "fold",
3033 "operator recorded this pull request as a manual merge; this run never \
3034 re-entered `land`, so `bump::after_merge` did not run for it - a release \
3035 bump this change might warrant has to be filed by hand",
3036 );
3037 if state.status == RunStatus::Merged {
3040 crate::followup::after_merge(state, url).await;
3041 }
3042 state.save()?;
3043 Ok((before, state.status))
3044}
3045
3046pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3053 let raw: Vec<GhInline> =
3054 serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3055 let mut out = Vec::new();
3056 for c in raw {
3057 push_if_outstanding(
3058 &mut out,
3059 ReviewComment {
3060 author: c.user.login,
3061 path: c.path,
3062 line: c.line,
3063 body: c.body,
3064 },
3065 );
3066 }
3067 Ok(out)
3068}
3069
3070fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3076 if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3077 return;
3078 }
3079 if comment.path.is_none() && is_noise(&comment.body) {
3080 return;
3081 }
3082 out.push(comment);
3083}
3084
3085pub fn is_noise(body: &str) -> bool {
3103 if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3104 return true;
3105 }
3106 let mut content = false;
3107 for line in strip_blocks(body).lines() {
3108 let line = unquote(line);
3109 if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3110 continue;
3111 }
3112 content = true;
3113 break;
3114 }
3115 !content
3116}
3117
3118fn strip_blocks(body: &str) -> String {
3120 let mut out = String::with_capacity(body.len());
3121 let mut rest = body;
3122 loop {
3123 let open = ["<!--", "<details>"]
3124 .iter()
3125 .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3126 .min_by_key(|(i, _)| *i);
3127 let Some((at, tag)) = open else {
3128 out.push_str(rest);
3129 return out;
3130 };
3131 out.push_str(&rest[..at]);
3132 let after = &rest[at + tag.len()..];
3133 let close = if tag == "<!--" { "-->" } else { "</details>" };
3134 match after.find(close) {
3135 Some(end) => rest = &after[end + close.len()..],
3136 None => return out,
3138 }
3139 }
3140}
3141
3142fn unquote(line: &str) -> &str {
3144 let mut s = line.trim();
3145 while let Some(rest) = s.strip_prefix('>') {
3146 s = rest.trim_start();
3147 }
3148 s.trim()
3149}
3150
3151fn is_checklist(line: &str) -> bool {
3153 let rest = line
3154 .strip_prefix("- ")
3155 .or_else(|| line.strip_prefix("* "))
3156 .unwrap_or("");
3157 let rest = rest.trim_start();
3158 matches!(
3159 rest.get(..3),
3160 Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3161 )
3162}
3163
3164fn is_decoration(line: &str) -> bool {
3166 line.starts_with('#')
3167 || line.starts_with("[!")
3168 || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3169}
3170
3171fn is_banner(line: &str) -> bool {
3178 let plain = drop_spans(line, "**", "**");
3179 let plain = if plain.contains("](") {
3180 drop_spans(&plain, "[", ")")
3181 } else {
3182 plain
3183 };
3184 !plain.chars().any(char::is_alphanumeric)
3185}
3186
3187fn drop_spans(s: &str, open: &str, close: &str) -> String {
3191 let mut out = String::with_capacity(s.len());
3192 let mut rest = s;
3193 while let Some(at) = rest.find(open) {
3194 out.push_str(&rest[..at]);
3195 let after = &rest[at + open.len()..];
3196 match after.find(close) {
3197 Some(end) => rest = &after[end + close.len()..],
3198 None => return out,
3199 }
3200 }
3201 out.push_str(rest);
3202 out
3203}
3204
3205fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3223 static LOCKS: std::sync::LazyLock<
3224 std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3225 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3226 LOCKS
3227 .lock()
3228 .unwrap_or_else(std::sync::PoisonError::into_inner)
3229 .entry(repo.to_path_buf())
3230 .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3231 .clone()
3232}
3233
3234fn repo_label(repo: &Path, pr_url: &str) -> String {
3237 let parts: Vec<&str> = pr_url.split('/').collect();
3238 if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3239 && at >= 2
3240 && !parts[at - 1].is_empty()
3241 && !parts[at - 2].is_empty()
3242 {
3243 return format!("{}/{}", parts[at - 2], parts[at - 1]);
3244 }
3245 repo.file_name()
3246 .map(|n| n.to_string_lossy().into_owned())
3247 .unwrap_or_default()
3248}
3249
3250fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3254 (pr.checks == Checks::Red).then(|| {
3255 let details = crate::notices::format_list(&pr.failing)
3256 .map(|names| format!(": {names}"))
3257 .unwrap_or_default();
3258 format!(
3259 "Merged {repo_name} PR #{} with red checks{details} ({})",
3260 pr.number, pr.url
3261 )
3262 })
3263}
3264
3265async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3269 let repo_name = repo_label(&state.repo, &pr.url);
3270 let Some(summary) = red_merge_summary(&repo_name, pr) else {
3271 return;
3272 };
3273 if let Some(rec) = state.pr.as_mut() {
3274 rec.red_at_merge = pr.failing.clone();
3275 }
3276 state.event("land", summary.clone());
3277 crate::notices::raise_with(
3280 crate::notices::merged_red(&state.id, &summary),
3281 &state.config.notify,
3282 );
3283}
3284
3285pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3292 land_with(state, pr_url, &GhForge).await
3293}
3294
3295trait Forge {
3299 async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3300 let (ok, out) = gh(
3301 repo,
3302 &[
3303 "pr".into(),
3304 "close".into(),
3305 pr_url.into(),
3306 "--comment".into(),
3307 comment.into(),
3308 ],
3309 )
3310 .await?;
3311 if !ok {
3312 bail!("PR closure failed: {out}");
3313 }
3314 Ok(())
3315 }
3316 async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3317 None
3318 }
3319 async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3320 async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3321 async fn poll(&self);
3322 async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3324 fn now(&self) -> i64;
3326 async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3329 #[allow(clippy::too_many_arguments)]
3330 async fn fix(
3331 &self,
3332 state: &mut RunState,
3333 pr: &PrState,
3334 round: usize,
3335 budget: usize,
3336 reason: &str,
3337 logs: &str,
3338 ) -> Result<Fixed>;
3339}
3340
3341struct GhForge;
3342
3343impl Forge for GhForge {
3344 async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3345 collect_ci_evidence(state, seen).await
3346 }
3347 async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3348 observe(repo, pr_url).await
3349 }
3350 async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3351 gh(repo, argv).await
3352 }
3353 async fn poll(&self) {
3354 tokio::time::sleep(POLL).await;
3355 }
3356 async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3357 let args = [
3358 "run".to_owned(),
3359 "rerun".to_owned(),
3360 run.to_owned(),
3361 "--failed".to_owned(),
3362 ];
3363 let (ok, out) = gh(repo, &args).await?;
3364 if !ok {
3365 bail!("gh run rerun {run}: {out}");
3366 }
3367 Ok(())
3368 }
3369 fn now(&self) -> i64 {
3370 jiff::Timestamp::now().as_second()
3371 }
3372 async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3373 required_contexts_of(repo, base).await
3374 }
3375 async fn fix(
3376 &self,
3377 state: &mut RunState,
3378 pr: &PrState,
3379 round: usize,
3380 budget: usize,
3381 reason: &str,
3382 logs: &str,
3383 ) -> Result<Fixed> {
3384 fix_round(state, pr, round, budget, reason, logs).await
3385 }
3386}
3387
3388fn encode_path_segment(s: &str) -> String {
3390 let mut out = String::new();
3391 for b in s.bytes() {
3392 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3393 out.push(b as char);
3394 } else {
3395 let _ = write!(out, "%{b:02X}");
3396 }
3397 }
3398 out
3399}
3400
3401async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3406 let enc = encode_path_segment(base);
3407 let mut all = BTreeSet::new();
3408 let classic = gh(
3411 repo,
3412 &[
3413 "api".to_owned(),
3414 format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3415 ],
3416 )
3417 .await
3418 .ok()?;
3419 if classic.0 {
3420 all.extend(parse_classic_required(&classic.1)?);
3421 } else if !classic.1.contains("404") {
3422 return None;
3423 }
3424 let rules = gh(
3425 repo,
3426 &[
3427 "api".to_owned(),
3428 format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3429 ],
3430 )
3431 .await
3432 .ok()?;
3433 if !rules.0 {
3434 return None;
3435 }
3436 all.extend(parse_ruleset_required(&rules.1)?);
3437 Some(all)
3438}
3439
3440fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3443 let v: serde_json::Value = serde_json::from_str(json).ok()?;
3444 let mut out = BTreeSet::new();
3445 for c in v.get("contexts")?.as_array()? {
3446 out.insert(c.as_str()?.to_owned());
3447 }
3448 for c in v
3449 .get("checks")
3450 .and_then(|c| c.as_array())
3451 .into_iter()
3452 .flatten()
3453 {
3454 if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3455 out.insert(name.to_owned());
3456 }
3457 }
3458 Some(out)
3459}
3460
3461fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3463 let v: serde_json::Value = serde_json::from_str(json).ok()?;
3464 let mut out = BTreeSet::new();
3465 for rule in v.as_array()? {
3466 if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3467 continue;
3468 }
3469 let checks = rule
3470 .pointer("/parameters/required_status_checks")?
3471 .as_array()?;
3472 for c in checks {
3473 out.insert(c.get("context")?.as_str()?.to_owned());
3474 }
3475 }
3476 Some(out)
3477}
3478
3479fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3487 awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3488}
3489
3490fn bound_head<'a>(
3500 seen_head: &'a str,
3501 rollup_head: &str,
3502 awaiting: Option<&str>,
3503) -> Option<&'a str> {
3504 if seen_head.is_empty()
3505 || awaiting_new_head(awaiting, seen_head)
3506 || !rollup_head.eq_ignore_ascii_case(seen_head)
3507 {
3508 return None;
3509 }
3510 Some(seen_head)
3511}
3512
3513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3515enum Refused {
3516 Behind,
3518 Pending,
3520 Recheck,
3524 Final,
3527}
3528
3529fn classify_refusal(
3532 after: Option<&Seen>,
3533 rechecked: bool,
3534 observed_head: &str,
3535 ci: CiExpectation,
3536) -> Refused {
3537 let Some(after) = after else {
3538 return Refused::Pending;
3540 };
3541 if after.pr.state != PrLifecycle::Open {
3542 return Refused::Final;
3543 }
3544 if !after.head.eq_ignore_ascii_case(observed_head) {
3547 return Refused::Pending;
3548 }
3549 if Blocking::of(&after.merge_state) == Blocking::Behind {
3550 return Refused::Behind;
3551 }
3552 if bound_head(&after.head, &after.rollup_head, None).is_none() {
3554 return Refused::Pending;
3555 }
3556 let state = after.merge_state.to_ascii_uppercase();
3557 if (ci == CiExpectation::Expected
3558 && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3559 || state.is_empty()
3560 || state == "UNKNOWN"
3561 {
3562 return Refused::Pending;
3563 }
3564 if rechecked {
3565 Refused::Final
3566 } else {
3567 Refused::Recheck
3568 }
3569}
3570
3571async fn disarm<F: Forge>(
3576 forge: &F,
3577 state: &mut RunState,
3578 repo: &Path,
3579 number: u64,
3580) -> std::result::Result<(), String> {
3581 let argv = disable_automerge_argv(number);
3582 let out = {
3583 let merge_lock = repo_merge_lock(repo);
3584 let _merge_slot = merge_lock.lock().await;
3585 forge.merge(repo, &argv).await
3586 };
3587 match out {
3588 Ok((true, _)) => {
3589 state.land_armed_head = None;
3590 state.event("land", "auto-merge disabled");
3591 state.save().map_err(|e| format!("{e:#}"))?;
3592 Ok(())
3593 }
3594 Ok((false, msg)) => Err(msg),
3595 Err(e) => Err(format!("{e:#}")),
3596 }
3597}
3598
3599async fn stop_disarmed<F: Forge>(
3603 forge: &F,
3604 state: &mut RunState,
3605 repo: &Path,
3606 pr: &PrState,
3607 why: &str,
3608) -> Result<()> {
3609 if state.land_armed_head.is_none() {
3610 return stop(state, repo, pr, why).await;
3611 }
3612 match disarm(forge, state, repo, pr.number).await {
3613 Ok(()) => stop(state, repo, pr, why).await,
3614 Err(e) => {
3615 let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3616 stop(state, repo, pr, &why).await
3617 }
3618 }
3619}
3620
3621fn owner_requested_stop(state: &RunState) -> Result<bool> {
3623 let Some(binding) = &state.land_approval else {
3624 return Ok(false);
3625 };
3626 let q = ask::Questions::open().get_for_effects(&binding.question)?;
3627 Ok(q.run == state.id
3628 && q.node == APPROVAL_NODE
3629 && q.resolution()
3630 .as_deref()
3631 .is_some_and(crate::merge_decision::stops))
3632}
3633
3634async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3637 use crate::merge_decision as md;
3638 let Some(binding) = &state.land_approval else {
3639 return Ok(false);
3640 };
3641 let q = ask::Questions::open().get_for_effects(&binding.question)?;
3642 let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3643 return Ok(false);
3644 };
3645 if q.run != state.id || q.node != APPROVAL_NODE {
3646 bail!("stop decision names another run");
3647 }
3648 let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3649 pr: pr.url.clone(),
3650 head: binding.head.clone(),
3651 language: state.config.graph.language.clone(),
3652 });
3653 if target.pr != pr.url {
3654 bail!("stop decision names another PR");
3655 }
3656 if state.merge_decision.is_none() {
3657 state.merge_decision = Some(md::Decision {
3658 question: q.id.clone(),
3659 target,
3660 choice: choice.clone(),
3661 closed: false,
3662 replacement_run: None,
3663 replacement_pr: None,
3664 });
3665 state.save()?;
3666 }
3667 let repo = state.repo.clone();
3668 if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3670 stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3671 return Ok(true);
3672 }
3673 if choice.eq_ignore_ascii_case(HOLD) {
3674 stop(
3675 state,
3676 &repo,
3677 pr,
3678 "owner held the decision: PR left open; no further repair or merge work",
3679 )
3680 .await?;
3681 return Ok(true);
3682 }
3683 if md::selected_agent(&choice).is_some()
3684 || state
3685 .origin
3686 .as_ref()
3687 .and_then(|o| o.task.as_ref())
3688 .is_some()
3689 {
3690 let owners: Vec<_> = crate::queue::Queue::open()
3691 .list()
3692 .into_iter()
3693 .filter(|task| task.execution_runs().last() == Some(&state.id))
3694 .collect();
3695 let owner = (owners.len() == 1).then(|| &owners[0]);
3696 if !owner.is_some_and(|task| {
3697 task.execution_runs().last() == Some(&state.id)
3698 && (!task
3699 .operator_decided_at
3700 .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3701 || task.resumption.as_ref().is_some_and(|release| {
3702 release.question_id.as_deref() == Some(q.id.as_str())
3703 && task.operator_decided_at == Some(release.at)
3704 }))
3705 }) {
3706 stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3707 return Ok(true);
3708 }
3709 }
3710 if pr.state == PrLifecycle::Merged {
3711 stop(
3712 state,
3713 &repo,
3714 pr,
3715 "PR already merged; withdrawal/replacement cannot be applied",
3716 )
3717 .await?;
3718 return Ok(true);
3719 }
3720 let comment = format!(
3721 "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3722 q.id, choice, state.id
3723 );
3724 if pr.state == PrLifecycle::Open {
3725 if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3726 stop(
3727 state,
3728 &repo,
3729 pr,
3730 &format!(
3731 "owner requested closure but it failed: {e}; task held, no replacement started"
3732 ),
3733 )
3734 .await?;
3735 return Ok(true);
3736 }
3737 }
3738 let confirmed = forge.view(&repo, &pr.url).await?;
3739 if confirmed.pr.state != PrLifecycle::Closed {
3740 stop(
3741 state,
3742 &repo,
3743 pr,
3744 "PR closure was not confirmed; task held, no replacement started",
3745 )
3746 .await?;
3747 return Ok(true);
3748 }
3749 *pr = confirmed.pr;
3750 state.merge_decision.as_mut().unwrap().closed = true;
3751 if let Some(record) = &mut state.pr {
3752 record.state = "closed".into();
3753 }
3754 state.status = RunStatus::Superseded;
3755 state.merge = Some(MergeOutcome {
3756 mode: MergeMode::Pr,
3757 ok: false,
3758 detail: format!("owner decision: {choice}; PR closure confirmed"),
3759 empty: false,
3760 });
3761 state.event(
3762 "land",
3763 format!(
3764 "{} applied: PR closure confirmed; old execution retired",
3765 choice
3766 ),
3767 );
3768 state.save()?;
3769 Ok(true)
3770}
3771
3772fn check_landing_resources(
3774 state: &mut RunState,
3775 node: &str,
3776 outcomes: &[crate::run::CommandOutcome],
3777) -> Result<()> {
3778 if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
3779 let detail = format!("{}: {}", blocked.command, blocked.output_tail);
3780 state
3781 .resource_block
3782 .get_or_insert_with(|| crate::run::ResourceBlock {
3783 cause: crate::run::ResourceBlockCause::Other,
3784 node: node.into(),
3785 kind: "shared build cache".into(),
3786 detail: detail.clone(),
3787 at: jiff::Timestamp::now(),
3788 });
3789 state.event("resource", &detail);
3790 state.save()?;
3791 bail!("landing verification could not start: {detail}");
3792 }
3793 Ok(())
3794}
3795
3796async fn publish_landing_head<F: Forge>(
3799 state: &mut RunState,
3800 observed: &str,
3801 pr_url: &str,
3802 forge: &F,
3803) -> Result<String> {
3804 crate::pr_head::ensure_owner(state)?;
3805 let winner = state.winner().cloned().context("landing has no winner")?;
3806 let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3807 let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
3808 anyhow::ensure!(
3809 observed == expected
3810 || (observed == head
3811 && state.gate_head.as_deref() == Some(&head)
3812 && state.gate_allows_progress()),
3813 "public head moved outside this run; refusing to overwrite it"
3814 );
3815 anyhow::ensure!(
3816 git::is_clean(&winner.worktree).await?,
3817 "landing worktree is dirty"
3818 );
3819 if state.gate_head.as_deref() != Some(&head)
3820 || !state.gate_ran
3821 || !state.gate_commands_allow_progress()
3822 {
3823 state.reconcile_verification_head(&head);
3824 state.gate.clear();
3825 state.gate_head = None;
3826 state.gate_ran = false;
3827 state.pre_gate.clear();
3828 state.pre_gate_commit = None;
3829 state.save()?;
3830 let inherited = crate::repo_lock::WaitPolicy::current();
3831 let wait = crate::repo_lock::WaitPolicy::new(
3832 Duration::from_secs(state.config.graph.timeout_resource_wait),
3833 move || inherited.cancelled(),
3834 );
3835 let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3836 loop {
3837 if outcomes.iter().any(|outcome| outcome.resource_blocked) {
3838 state.gate = outcomes.clone();
3839 check_landing_resources(state, "gate", &outcomes)?;
3840 }
3841 if outcomes.iter().all(|o| o.ok()) {
3842 break;
3843 }
3844 match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
3845 crate::graph::GateFix::Retry => {
3846 outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3847 }
3848 crate::graph::GateFix::Stop => break,
3849 crate::graph::GateFix::Defer => {
3850 if let Some(e2e) = &state.gate_repair_e2e {
3854 let outcomes = e2e.outcomes.clone();
3855 check_landing_resources(state, "e2e", &outcomes)?;
3856 }
3857 bail!("landing gate repair deferred");
3858 }
3859 }
3860 }
3861 state.gate = outcomes;
3862 state.gate_ran = true;
3863 state.save()?;
3864 }
3865 let inherited = crate::repo_lock::WaitPolicy::current();
3866 let wait = crate::repo_lock::WaitPolicy::new(
3867 Duration::from_secs(state.config.graph.timeout_resource_wait),
3868 move || inherited.cancelled(),
3869 );
3870 let checked = state
3871 .gate_head
3872 .clone()
3873 .context("landing gate has no checked SHA")?;
3874 anyhow::ensure!(
3875 git::rev_parse(&winner.worktree, "HEAD").await? == checked
3876 && git::is_clean(&winner.worktree).await?,
3877 "landing tree changed after gate"
3878 );
3879 let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
3880 if matches!(e2e, crate::graph::GateFix::Defer) {
3881 let outcomes = state
3882 .gate_repair_e2e
3883 .as_ref()
3884 .context("deferred landing e2e has no outcomes")?
3885 .outcomes
3886 .clone();
3887 check_landing_resources(state, "e2e", &outcomes)?;
3888 }
3889 anyhow::ensure!(
3890 matches!(e2e, crate::graph::GateFix::Retry),
3891 "post-repair e2e has not passed on the landing head; nothing published"
3892 );
3893 anyhow::ensure!(
3894 git::rev_parse(&winner.worktree, "HEAD").await? == checked
3895 && git::is_clean(&winner.worktree).await?,
3896 "landing tree changed during post-repair e2e"
3897 );
3898 anyhow::ensure!(
3899 crate::graph::verify_current_head(state, &winner, &wait).await?,
3900 "current head e2e has not passed; nothing published"
3901 );
3902 anyhow::ensure!(
3903 state.gate_allows_progress(),
3904 "landing gate failed; nothing published"
3905 );
3906 crate::pr_head::ensure_owner(state)?;
3907 if owner_requested_stop(state)? {
3908 bail!("owner requested stop before publication");
3909 }
3910 let current = forge.view(&state.repo, pr_url).await?;
3911 anyhow::ensure!(
3912 current.pr.state == PrLifecycle::Open,
3913 "PR closed or merged while gating; nothing published"
3914 );
3915 anyhow::ensure!(
3916 current.head == observed || current.head == checked,
3917 "PR head changed while gating; nothing published"
3918 );
3919 anyhow::ensure!(
3920 crate::foreign_checkout::write_back(state, &checked).await?,
3921 "foreign checkout delivery is blocked; see the run events"
3922 );
3923 let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
3924 let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
3925 let refspec = format!("{checked}:refs/heads/{public}");
3926 let lock = repo_merge_lock(&state.repo);
3927 let _slot = lock.lock().await;
3928 let pushed = git::git_raw(
3929 &winner.worktree,
3930 &["push", &lease, &state.config.merge.remote, &refspec],
3931 )
3932 .await?;
3933 anyhow::ensure!(
3934 pushed.ok(),
3935 "publishing gated landing head failed: {}",
3936 pushed.stderr
3937 );
3938 state.pr_pushed_head = Some(checked.clone());
3939 state.land_sync_pending = false;
3940 state.save()?;
3941 Ok(checked)
3942}
3943
3944async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
3947 let winner = state.winner().cloned().context("landing has no winner")?;
3948 let inherited = crate::repo_lock::WaitPolicy::current();
3949 let wait = crate::repo_lock::WaitPolicy::new(
3950 Duration::from_secs(state.config.graph.timeout_resource_wait),
3951 move || inherited.cancelled(),
3952 );
3953 let _coordination = crate::repo_lock::SeatLease::operation_with(
3954 &winner.worktree,
3955 state.config.coordination.as_ref(),
3956 &wait,
3957 )
3958 .await?;
3959 if !git::is_clean(&winner.worktree).await? {
3960 let from = state
3961 .land_rebase_from
3962 .as_deref()
3963 .context("landing worktree is dirty")?;
3964 let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3965 anyhow::ensure!(head != from, "landing worktree is dirty");
3966 for args in [
3967 vec!["diff", "--cached", "--quiet", from],
3968 vec!["diff", "--quiet"],
3969 ] {
3970 anyhow::ensure!(
3971 git::git_raw(&winner.worktree, &args).await?.ok(),
3972 "landing worktree has edits beyond the interrupted rebase"
3973 );
3974 }
3975 let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
3979 let tracked = git::git(
3980 &winner.worktree,
3981 &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
3982 )
3983 .await?;
3984 for local in untracked.split('\0').filter(|p| !p.is_empty()) {
3985 anyhow::ensure!(
3986 !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
3987 path == local
3988 || path
3989 .strip_prefix(local)
3990 .is_some_and(|rest| rest.starts_with('/'))
3991 || local
3992 .strip_prefix(path)
3993 .is_some_and(|rest| rest.starts_with('/'))
3994 }),
3995 "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
3996 );
3997 }
3998 git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
3999 }
4000 if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
4001 anyhow::ensure!(
4002 git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
4003 "landing synchronization started outside the foreign checkout history"
4004 );
4005 if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
4006 git::git(
4012 &winner.worktree,
4013 &[
4014 "-c",
4015 "core.hooksPath=/dev/null",
4016 "merge",
4017 "--strategy=ours",
4018 "--no-ff",
4019 "--no-autostash",
4020 "--no-edit",
4021 "-m",
4022 "Merge pre-sync history into the repaired landing tree",
4023 from,
4024 ],
4025 )
4026 .await?;
4027 }
4028 }
4029 crate::worktree_setup::prepare_with(
4030 &state.config,
4031 &state.repo,
4032 &winner.worktree,
4033 crate::build_target::Coordination::Held(_coordination.as_ref()),
4034 )
4035 .await?;
4036 state.land_rebase_from = None;
4037 state.save()?;
4038 Ok(())
4039}
4040
4041async fn rebase_landing_worktree(
4042 state: &mut RunState,
4043 onto: &str,
4044) -> Result<crate::rebase::Rebased> {
4045 restore_landing_worktree(state).await?;
4046 let winner = state.winner().cloned().context("landing has no winner")?;
4047 let scratch = state.dir().join("rebase");
4048 let target = match state.land_sync_target.clone() {
4049 Some(target) => {
4050 crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4051 target
4052 }
4053 None if git::rebase_in_progress(&scratch).await => {
4056 crate::rebase::rebase_target(&scratch).await?
4057 }
4058 None => {
4059 anyhow::ensure!(
4060 state.land_sync_attempts < state.config.graph.land_rounds,
4061 "landing base synchronization budget exhausted"
4062 );
4063 let target = git::rev_parse(&state.repo, onto).await?;
4064 crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4065 state.land_sync_attempts += 1;
4066 state.land_sync_target = Some(target.clone());
4067 target
4068 }
4069 };
4070 state.land_sync_target = Some(target.clone());
4071 state.land_sync_pending = true;
4072 state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4073 state.save()?;
4074 let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4078 state.land_sync_target = None;
4079 state.save()?;
4080 if result == crate::rebase::Rebased::Applied {
4081 restore_landing_worktree(state).await?;
4082 }
4083 Ok(result)
4084}
4085
4086async fn resume_landing_head<F: Forge>(
4089 state: &mut RunState,
4090 observed: &str,
4091 pr_url: &str,
4092 forge: &F,
4093 reason: Option<Blocking>,
4094) -> Result<String> {
4095 crate::pr_head::ensure_owner(state)?;
4096 let winner = state.winner().cloned().context("landing has no winner")?;
4097 let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4098 let expected = state
4099 .pr_pushed_head
4100 .as_deref()
4101 .or(state.gate_head.as_deref())
4102 .context("missing public head lease")?;
4103 anyhow::ensure!(
4104 observed == expected
4105 || (observed == local
4106 && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4107 || git::is_ancestor(&winner.worktree, expected, &local).await)),
4108 "public head moved outside this run; refusing to sync"
4109 );
4110 state.pr_pushed_head = Some(observed.to_owned());
4117 state.save()?;
4118 restore_landing_worktree(state).await?;
4119 if let Some(target) = &state.land_sync_target
4122 && !git::rebase_in_progress(&state.dir().join("rebase")).await
4123 && git::ancestry(&winner.worktree, target, &local).await?
4124 {
4125 state.land_sync_target = None;
4126 state.save()?;
4127 }
4128 let remote = state.config.merge.remote.clone();
4129 let base = state.base_branch.clone();
4130 let fetched = git::fetch(&state.repo, &remote, &base).await?;
4131 anyhow::ensure!(
4132 fetched.ok(),
4133 "cannot fetch landing base: {}",
4134 fetched.stderr
4135 );
4136 anyhow::ensure!(
4137 !owner_requested_stop(state)?,
4138 "owner requested stop before base synchronization"
4139 );
4140 let onto = format!("{remote}/{base}");
4141 let tip = git::rev_parse(&state.repo, &onto).await?;
4142 let contains_base = git::ancestry(&state.repo, &tip, &local)
4143 .await
4144 .context("could not determine whether the landing head contains the fetched base")?;
4145 anyhow::ensure!(
4146 reason != Some(Blocking::Behind) || !contains_base,
4147 "BEHIND reported but the fetched base is already included; synchronization made no progress"
4148 );
4149 if !contains_base || reason == Some(Blocking::Conflict) {
4150 match rebase_landing_worktree(state, &onto).await? {
4151 crate::rebase::Rebased::Applied => {}
4152 crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4153 }
4154 }
4155 if reason == Some(Blocking::Behind) {
4156 anyhow::ensure!(
4157 git::rev_parse(&winner.worktree, "HEAD").await? != local,
4158 "BEHIND synchronization left the head unchanged"
4159 );
4160 }
4161 publish_landing_head(state, observed, pr_url, forge).await
4162}
4163
4164async fn synchronize_landing<F: Forge>(
4166 state: &mut RunState,
4167 pr: &mut PrState,
4168 observed: &str,
4169 pr_url: &str,
4170 forge: &F,
4171) -> Result<Option<String>> {
4172 if owner_stop(state, pr, forge).await? {
4173 return Ok(None);
4174 }
4175 state.event(
4176 "land",
4177 format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4178 );
4179 state.save()?;
4180 let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4181 if owner_stop(state, pr, forge).await? {
4182 return Ok(None);
4183 }
4184 match synced {
4185 Ok(head) => {
4186 if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4187 crate::graph::refresh_reviewed_commits(state, &branch).await;
4188 }
4189 Ok(Some(head))
4190 }
4191 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4192 Err(e) => {
4193 let repo = state.repo.clone();
4194 stop(
4195 state,
4196 &repo,
4197 pr,
4198 &format!("could not synchronize landing base: {e:#}"),
4199 )
4200 .await?;
4201 Ok(None)
4202 }
4203 }
4204}
4205
4206async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4207 crate::pr_head::ensure_owner(state)?;
4208 state.land_unrelated = None;
4209 let reopening_hold = crate::merge_decision::resumable_hold(state);
4210 let repo = state.repo.clone();
4211 let budget = state.config.graph.land_rounds;
4212 let mut round = 0usize;
4213 let ci = state.config.merge.ci.expectation();
4214 if ci == CiExpectation::Absent {
4215 state.event(
4216 "land",
4217 "CI not expected ([merge] ci = \"none\"); check status ignored",
4218 );
4219 }
4220 let mut waited = Duration::ZERO;
4221 let mut shown: BTreeSet<String> = BTreeSet::new();
4226 let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4228 let mut rechecked = false;
4230
4231 state.status = RunStatus::Landing;
4239 state.event("land", format!("watching {pr_url}"));
4240 state.save()?;
4241
4242 let mut resumed_armed = state.land_armed_head.is_some();
4246
4247 'landing: loop {
4248 let seen = forge.view(&repo, pr_url).await?;
4249 let mut pr = seen.pr.clone();
4250 pr.review_comments.retain(|c| !shown.contains(&c.body));
4251 state.pr = Some(crate::run::PrRecord {
4252 url: pr.url.clone(),
4253 number: pr.number,
4254 state: pr.state.as_str().to_owned(),
4255 checks: pr.checks.as_str().to_owned(),
4256 round,
4257 rounds: budget,
4258 red_at_merge: Vec::new(),
4259 });
4260 state.save()?;
4261
4262 if pr.state == PrLifecycle::Open {
4263 state.observe_branch_owner_holds(&seen.head).await;
4264 state.save()?;
4265 }
4266 crate::pr_head::ensure_owner(state)?;
4267 if reopening_hold {
4268 anyhow::ensure!(
4269 pr.state == PrLifecycle::Open,
4270 "held PR is no longer open; cannot request a fresh decision"
4271 );
4272 disarm(forge, state, &repo, pr.number)
4275 .await
4276 .map_err(anyhow::Error::msg)?;
4277 let previous = state.merge_decision.take();
4278 let binding = state.land_approval.take();
4279 state.config.graph.land_approval = true;
4280 let subject = merge_subject(
4281 crate::graph::landing_title(state, &seen.title),
4282 &crate::graph::landing_subject_source(state),
4283 );
4284 let contested = contested_to_ask(state);
4285 if let Err(error) =
4286 approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4287 {
4288 state.merge_decision = previous;
4289 state.land_approval = binding;
4290 return Err(error);
4291 }
4292 state.end_pass_parked(crate::run::ParkCause::Question);
4293 state.parked = true;
4294 state.event("land", format!("explicit resume reopened held decision {}; parked awaiting a fresh owner answer", previous.as_ref().map(|d| d.question.as_str()).unwrap_or_default()));
4295 state.save()?;
4296 return Ok(pr);
4297 }
4298 if owner_stop(state, &mut pr, forge).await? {
4299 return Ok(pr);
4300 }
4301
4302 if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4303 if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4308 let why = format!(
4309 "a previous pass may have armed auto-merge and it could not be disabled \
4310 on resume: {e}"
4311 );
4312 stop(state, &repo, &pr, &why).await?;
4313 return Ok(pr);
4314 }
4315 }
4316
4317 if pr.state == PrLifecycle::Open
4322 && !seen.head.is_empty()
4323 && state
4324 .land_armed_head
4325 .as_deref()
4326 .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4327 {
4328 if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4329 let why = format!(
4330 "the head moved while auto-merge was armed and it could not be disabled: {e}"
4331 );
4332 stop(state, &repo, &pr, &why).await?;
4333 return Ok(pr);
4334 }
4335 }
4336
4337 if state.land_sync_pending && pr.state == PrLifecycle::Open {
4338 if owner_stop(state, &mut pr, forge).await? {
4341 return Ok(pr);
4342 }
4343 let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4344 binding.head.eq_ignore_ascii_case(&seen.head)
4345 && ask::Questions::open()
4346 .get_for_effects(&binding.question)
4347 .is_ok_and(|q| {
4348 q.run == state.id
4349 && q.node == APPROVAL_NODE
4350 && q.status == ask::QuestionStatus::Answered
4351 && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4352 })
4353 });
4354 if repair_answer {
4355 let subject = merge_subject(
4356 crate::graph::landing_title(state, &seen.title),
4357 &crate::graph::landing_subject_source(state),
4358 );
4359 let contested = contested_to_ask(state);
4360 if matches!(
4361 approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4362 ApprovalGate::Repair
4363 ) {
4364 if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4365 state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4366 state.save()?;
4367 }
4368 return Ok(pr);
4369 }
4370 }
4371 let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4372 if owner_stop(state, &mut pr, forge).await? {
4375 return Ok(pr);
4376 }
4377 let head = synced?;
4378 awaiting_head = Some(head);
4379 waited = Duration::ZERO;
4380 rechecked = false;
4381 continue;
4383 }
4384
4385 if pr.state == PrLifecycle::Open
4388 && pr.blocking == Blocking::Behind
4389 && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4390 {
4391 let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4392 let Some(head) = synced else {
4393 return Ok(pr);
4394 };
4395 awaiting_head = Some(head);
4396 rechecked = false;
4397 waited = Duration::ZERO;
4398 continue;
4399 }
4400
4401 if pr.state == PrLifecycle::Open {
4402 if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4403 if waited >= WAIT_CEILING {
4404 let want = awaiting_head.as_deref().unwrap_or_default();
4405 let why = format!(
4406 "the pull request's checks were still not about one readable head after \
4407 {} minutes (expected {}, pull request points at {}, checks are for {}); \
4408 someone may have pushed over it",
4409 WAIT_CEILING.as_secs() / 60,
4410 if want.is_empty() { "any" } else { want },
4411 if seen.head.is_empty() {
4412 "nothing readable"
4413 } else {
4414 &seen.head
4415 },
4416 if seen.rollup_head.is_empty() {
4417 "nothing readable"
4418 } else {
4419 &seen.rollup_head
4420 },
4421 );
4422 stop_disarmed(forge, state, &repo, &pr, &why).await?;
4423 return Ok(pr);
4424 }
4425 waited += POLL;
4426 forge.poll().await;
4427 continue;
4428 }
4429 if awaiting_head.take().is_some() {
4432 waited = Duration::ZERO;
4435 }
4436 }
4437
4438 let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4441 let first = state
4442 .land_unsaid
4443 .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4444 if !first.0.eq_ignore_ascii_case(&seen.head) {
4445 *first = (seen.head.clone(), forge.now());
4446 }
4447 let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4448 state.save()?;
4449 elapsed
4450 } else {
4451 waited
4452 };
4453 let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4454 if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4455 if waited >= WAIT_CEILING {
4456 stop_disarmed(
4457 forge,
4458 state,
4459 &repo,
4460 &pr,
4461 "merge state remained unreadable; refusing to merge on a guess",
4462 )
4463 .await?;
4464 return Ok(pr);
4465 }
4466 waited += POLL;
4467 forge.poll().await;
4468 continue;
4469 }
4470
4471 if ci == CiExpectation::Expected
4476 && pr.state == PrLifecycle::Open
4477 && state.config.graph.rerun_flaky_checks
4478 {
4479 let include_optional = pr.checks == Checks::Red
4480 && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4481 let failing = rerunnable_with(&seen.contexts, include_optional);
4482 let now = forge.now();
4483 match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4484 RerunStep::Rerun(runs) => {
4485 let rec = state.land_reruns.get_or_insert_with(Default::default);
4486 if !rec.head.eq_ignore_ascii_case(&seen.head) {
4487 *rec = LandReruns {
4488 head: seen.head.clone(),
4489 runs: BTreeMap::new(),
4490 };
4491 }
4492 for run in &runs {
4493 rec.runs.insert(run.clone(), now);
4494 }
4495 state.save()?;
4499 let mut any = false;
4500 for run in &runs {
4501 let names = failing
4502 .iter()
4503 .filter(|(_, r)| r.as_deref() == Some(run))
4504 .map(|(l, _)| l.as_str())
4505 .collect::<Vec<_>>()
4506 .join(", ");
4507 match forge.rerun(&repo, run).await {
4508 Ok(()) => {
4509 any = true;
4510 state.event(
4511 "land",
4512 format!("reran failed check(s) {names} (run {run})"),
4513 );
4514 }
4515 Err(e) => state.event(
4517 "land",
4518 format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4519 ),
4520 }
4521 }
4522 state.save()?;
4523 if any {
4524 waited = Duration::ZERO;
4525 forge.poll().await;
4526 continue;
4527 }
4528 }
4529 RerunStep::Grace => {
4530 if waited >= WAIT_CEILING {
4531 let why = format!(
4532 "checks were still failing after a rerun and {} minutes",
4533 WAIT_CEILING.as_secs() / 60
4534 );
4535 stop(state, &repo, &pr, &why).await?;
4536 return Ok(pr);
4537 }
4538 waited += POLL;
4539 forge.poll().await;
4540 continue;
4541 }
4542 RerunStep::Fix => {}
4543 }
4544 }
4545
4546 let step = proposed;
4547 let armed_here = state
4552 .land_armed_head
4553 .as_deref()
4554 .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4555 if armed_here && matches!(step, Step::Merge | Step::Wait) {
4556 if waited >= WAIT_CEILING {
4557 let required = if seen.base.is_empty() {
4558 None
4559 } else {
4560 forge.required_contexts(&repo, &seen.base).await
4561 };
4562 let why = format!(
4563 "auto-merge was armed on {} but the pull request did not merge within {} \
4564 minutes ({})",
4565 seen.head,
4566 WAIT_CEILING.as_secs() / 60,
4567 waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4568 );
4569 stop_disarmed(forge, state, &repo, &pr, &why).await?;
4570 return Ok(pr);
4571 }
4572 waited += POLL;
4573 forge.poll().await;
4574 continue;
4575 }
4576 if armed_here && !matches!(step, Step::Done { .. }) {
4577 if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4580 let why = format!("auto-merge could not be disabled: {e}");
4581 stop(state, &repo, &pr, &why).await?;
4582 return Ok(pr);
4583 }
4584 }
4585 if pr.checks == Checks::Red
4586 && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4587 && pr.review_comments.is_empty()
4588 && let Some(evidence) = forge.attribution(state, &seen).await
4589 && evidence.unrelated(&seen.head, &pr.failing)
4590 {
4591 if owner_stop(state, &mut pr, forge).await? {
4592 return Ok(pr);
4593 }
4594 let fresh = forge.view(&repo, pr_url).await?;
4596 if fresh.head != seen.head
4597 || fresh.rollup_head != seen.rollup_head
4598 || fresh.pr.state != PrLifecycle::Open
4599 || fresh.pr.checks != Checks::Red
4600 || fresh.pr.failing != pr.failing
4601 || fresh
4602 .pr
4603 .review_comments
4604 .iter()
4605 .any(|c| !shown.contains(&c.body))
4606 {
4607 continue;
4608 }
4609 hold_unrelated(state, &pr, evidence).await?;
4610 return Ok(pr);
4611 }
4612 match step {
4613 Step::Wait => {
4614 if waited >= WAIT_CEILING {
4615 let why = format!(
4616 "checks were still running after {} minutes",
4617 WAIT_CEILING.as_secs() / 60
4618 );
4619 stop(state, &repo, &pr, &why).await?;
4620 return Ok(pr);
4621 }
4622 waited += POLL;
4623 forge.poll().await;
4624 }
4625 Step::Done { merged } => {
4626 if merged {
4627 state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
4628 }
4629 if let Some(armed) = state.land_armed_head.take() {
4634 if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
4635 let msg = format!(
4636 "{} merged on {} but the owner approved {armed}; review what landed",
4637 pr.url, seen.head
4638 );
4639 tracing::warn!("{msg}");
4640 state.event("land", msg);
4641 crate::notices::raise_with(
4645 crate::notices::Notice::warn(
4646 &format!("merged-unapproved-head:{}", state.id),
4647 "A pull request merged on a commit the owner did not approve; \
4648 review what landed",
4649 )
4650 .link(crate::notices::Link::Run {
4651 id: state.id.clone(),
4652 }),
4653 &state.config.notify,
4654 );
4655 }
4656 }
4657 state.status = if merged {
4658 RunStatus::Merged
4659 } else {
4660 RunStatus::Ready
4661 };
4662 let detail = if merged {
4663 format!("{} was merged", pr.url)
4664 } else {
4665 format!("{} was closed without merging", pr.url)
4666 };
4667 state.merge = Some(MergeOutcome {
4668 mode: MergeMode::Pr,
4669 ok: merged,
4670 detail: detail.clone(),
4671 empty: false,
4672 });
4673 state.event("land", detail);
4674 state.save()?;
4675 write_pr_state_through(state, pr.state);
4676 return Ok(pr);
4677 }
4678 Step::Merge => {
4679 state.check_delivery_evidence(&seen.head)?;
4680 let subject = merge_subject(
4681 crate::graph::landing_title(state, &seen.title),
4682 &crate::graph::landing_subject_source(state),
4683 );
4684 let contested = contested_to_ask(state);
4690 if !approval_reasons(state).is_empty() {
4691 match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
4692 .await?
4693 {
4694 ApprovalGate::Approved => {}
4695 ApprovalGate::Repair => {
4696 if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4699 state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4700 state.save()?;
4701 }
4702 return Ok(pr);
4703 }
4704 ApprovalGate::Held => {
4705 if owner_stop(state, &mut pr, forge).await? {
4708 return Ok(pr);
4709 }
4710 stop(
4711 state,
4712 &repo,
4713 &pr,
4714 "the owner did not approve the merge (held or unanswered)",
4715 )
4716 .await?;
4717 return Ok(pr);
4718 }
4719 ApprovalGate::Pending => {
4727 state.end_pass_parked(crate::run::ParkCause::Question);
4728 state.parked = true;
4729 state.event(
4730 "land",
4731 "parked awaiting merge approval - resumes once answered",
4732 );
4733 state.save()?;
4734 return Ok(pr);
4735 }
4736 }
4737 }
4738 let observed_head = seen.head.clone();
4749 {
4752 let fresh = forge.view(&repo, pr_url).await.ok();
4753 if fresh.as_ref().is_some_and(|current| {
4754 current.pr.state == PrLifecycle::Open
4755 && current.head.eq_ignore_ascii_case(&observed_head)
4756 && Blocking::of(¤t.merge_state) == Blocking::Behind
4757 }) {
4758 pr.blocking = Blocking::Behind;
4759 let synced =
4760 synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4761 .await?;
4762 let Some(head) = synced else {
4763 return Ok(pr);
4764 };
4765 awaiting_head = Some(head);
4766 rechecked = false;
4767 waited = Duration::ZERO;
4768 continue 'landing;
4769 }
4770 if !direct_merge_is_safe(
4771 fresh.as_ref(),
4772 &observed_head,
4773 &shown,
4774 round,
4775 budget,
4776 waited,
4777 ci,
4778 ) {
4779 if waited >= WAIT_CEILING {
4780 let why = "the pull request did not settle on the approved head \
4781 before it could be merged";
4782 stop(state, &repo, &pr, why).await?;
4783 return Ok(pr);
4784 }
4785 state.event(
4786 "land",
4787 "the pull request changed before merging; looking again",
4788 );
4789 waited += POLL;
4790 forge.poll().await;
4791 continue;
4792 }
4793 }
4794 let argv = merge_argv_at(pr.number, &subject, &observed_head);
4795 let out = {
4796 let merge_lock = repo_merge_lock(&repo);
4797 let _merge_slot = merge_lock.lock().await;
4798 crate::pr_head::ensure_owner(state)?;
4799 if let Some(task_id) = state
4800 .origin
4801 .as_ref()
4802 .and_then(|origin| origin.task.as_ref())
4803 {
4804 let task = crate::queue::Queue::open()
4805 .get(task_id)
4806 .context("cannot verify the task owner immediately before merge")?;
4807 if task.execution_runs().last() != Some(&state.id)
4808 || task.operator_held()
4809 || task.status == crate::queue::TaskStatus::Done
4810 {
4811 bail!(
4812 "task ownership or an operator hold superseded this merge approval"
4813 );
4814 }
4815 }
4816 if let Some(binding) = &state.land_approval {
4817 let current = ask::Questions::open().get_for_effects(&binding.question)?;
4818 if merge_consent_superseded(state, ¤t)?
4819 || current.run != state.id
4820 || !binding.head.eq_ignore_ascii_case(&observed_head)
4821 || approval(current.resolution().as_deref()) != Approval::Merge
4822 || current.merge_target.as_ref().is_some_and(|t| {
4823 t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
4824 })
4825 {
4826 bail!(
4827 "merge decision is stale or no longer authorizes the reviewed head"
4828 );
4829 }
4830 }
4831 forge.merge(&repo, &argv).await?
4832 };
4833 if out.0 {
4834 let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
4840 if c.pr.state == PrLifecycle::Merged {
4841 state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
4842 true
4843 } else {
4844 false
4845 }
4846 });
4847 if !confirmed {
4848 if waited >= WAIT_CEILING {
4849 let why = "the merge request succeeded but the pull request \
4850 could not be confirmed merged after waiting";
4851 stop(state, &repo, &pr, why).await?;
4852 return Ok(pr);
4853 }
4854 state.event(
4855 "land",
4856 "merge accepted but the pull request is not confirmed merged yet; waiting",
4857 );
4858 state.save()?;
4859 waited += POLL;
4860 forge.poll().await;
4861 continue;
4862 }
4863 pr.state = PrLifecycle::Merged;
4864 state.status = RunStatus::Merged;
4865 state.merge = Some(MergeOutcome {
4866 mode: MergeMode::Pr,
4867 ok: true,
4868 detail: format!("gh {}", argv.join(" ")),
4869 empty: false,
4870 });
4871 if let Some(pr_record) = state.pr.as_mut() {
4876 pr_record.state = pr.state.as_str().to_owned();
4877 }
4878 state.event("land", format!("merged {} as `{subject}`", pr.url));
4879 announce_red_merge(state, &pr).await;
4880 state.save()?;
4881 write_pr_state_through(state, pr.state);
4882 return Ok(pr);
4883 }
4884 let after_seen = forge.view(&repo, pr_url).await.ok();
4885 let after = after_seen.as_ref().map(|s| s.pr.state);
4886 if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
4887 state.pr_merged_head = after_seen
4888 .as_ref()
4889 .map(|s| s.head.clone())
4890 .filter(|h| !h.is_empty());
4891 pr.state = PrLifecycle::Merged;
4892 state.status = RunStatus::Merged;
4893 state.merge = Some(outcome);
4894 if let Some(pr_record) = state.pr.as_mut() {
4895 pr_record.state = pr.state.as_str().to_owned();
4896 }
4897 state.event("land", format!("merged {} as `{subject}`", pr.url));
4898 announce_red_merge(state, &pr).await;
4899 state.save()?;
4900 write_pr_state_through(state, pr.state);
4901 return Ok(pr);
4902 }
4903 let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
4904 match verdict {
4905 Refused::Behind => {
4906 pr.blocking = Blocking::Behind;
4907 let synced =
4908 synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4909 .await?;
4910 let Some(head) = synced else {
4911 return Ok(pr);
4912 };
4913 awaiting_head = Some(head);
4914 rechecked = false;
4915 waited = Duration::ZERO;
4916 continue 'landing;
4917 }
4918 Refused::Final => {
4919 let merge_state = after_seen
4920 .as_ref()
4921 .map(|s| s.merge_state.as_str())
4922 .filter(|m| !m.is_empty())
4923 .unwrap_or("unknown");
4924 let why = format!(
4928 "the merge was refused: {} (merge state: {merge_state})",
4929 out.1
4930 );
4931 stop(state, &repo, &pr, &why).await?;
4932 return Ok(pr);
4933 }
4934 verdict => {
4935 if waited >= WAIT_CEILING {
4940 let why = format!(
4941 "the merge was still refused after {} minutes: {}",
4942 WAIT_CEILING.as_secs() / 60,
4943 out.1
4944 );
4945 stop(state, &repo, &pr, &why).await?;
4946 return Ok(pr);
4947 }
4948 if verdict == Refused::Recheck {
4949 rechecked = true;
4950 }
4951 state.event(
4952 "land",
4953 "merge refused while the branch policy is not satisfied yet; waiting",
4954 );
4955 state.save()?;
4956 waited += POLL;
4957 forge.poll().await;
4958 }
4959 }
4960 }
4961 Step::Rebase => {
4962 let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4963 let Some(head) = synced else {
4964 return Ok(pr);
4965 };
4966 awaiting_head = Some(head);
4967 rechecked = false;
4968 waited = Duration::ZERO;
4969 continue 'landing;
4970 }
4971 Step::GiveUp { reason } => {
4972 stop(state, &repo, &pr, &reason).await?;
4973 return Ok(pr);
4974 }
4975 Step::Fix { reason } => {
4976 round += 1;
4977 waited = Duration::ZERO;
4978 for c in &pr.review_comments {
4979 shown.insert(c.body.clone());
4980 }
4981 state.event("land", format!("round {round}: {reason}"));
4982 state.save()?;
4983
4984 let logs = failing_logs(&repo, &seen.failing_urls).await;
4985 let was_red = pr.checks == Checks::Red;
4986 if owner_stop(state, &mut pr, forge).await? {
4987 return Ok(pr);
4988 }
4989 let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
4990 if owner_stop(state, &mut pr, forge).await? {
4991 return Ok(pr);
4992 }
4993 match fixed {
4994 Fixed::Committed { head } => {
4995 state.pr_pushed_head = Some(head.clone());
4998 awaiting_head = Some(head);
4999 rechecked = false;
5000 waited = Duration::ZERO;
5001 forge.poll().await;
5002 }
5003 Fixed::Declined if was_red => {
5004 if let Some(evidence) = forge.attribution(state, &seen).await
5009 && evidence.unrelated(&seen.head, &pr.failing)
5010 {
5011 let fresh = forge.view(&repo, pr_url).await?;
5012 if fresh.head != seen.head
5013 || fresh.rollup_head != seen.rollup_head
5014 || fresh.pr.state != PrLifecycle::Open
5015 || fresh.pr.checks != Checks::Red
5016 || fresh.pr.failing != pr.failing
5017 || fresh
5018 .pr
5019 .review_comments
5020 .iter()
5021 .any(|c| !shown.contains(&c.body))
5022 {
5023 continue;
5024 }
5025 if owner_stop(state, &mut pr, forge).await? {
5026 return Ok(pr);
5027 }
5028 hold_unrelated(state, &pr, evidence).await?;
5029 return Ok(pr);
5030 }
5031 let why = format!(
5032 "the fixer produced no commit while {} check(s) were failing \
5033 ({}); stopping instead of looping on an unchanged tree",
5034 pr.failing.len(),
5035 pr.failing.join(", ")
5036 );
5037 stop(state, &repo, &pr, &why).await?;
5038 return Ok(pr);
5039 }
5040 Fixed::Declined => state.event(
5045 "land",
5046 format!("round {round}: fixer declined the comments, nothing committed"),
5047 ),
5048 Fixed::Deferred => {
5049 state.status = RunStatus::Blocked;
5053 state.save()?;
5054 return Ok(pr);
5055 }
5056 Fixed::Failed(why) => {
5057 stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5058 return Ok(pr);
5059 }
5060 }
5061 state.save()?;
5062 }
5063 }
5064 }
5065}
5066
5067pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5069
5070#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5072pub struct CiHold {
5073 pub head: String,
5075 pub question: String,
5077 pub evidence: CiEvidence,
5079}
5080
5081#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5083struct CiFailure {
5084 path: String,
5085 start_line: u64,
5086 end_line: u64,
5087 title: String,
5088 message: String,
5089}
5090
5091#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5092struct CiCheckEvidence {
5093 label: String,
5094 head_check: u64,
5095 base_check: u64,
5096 app: u64,
5097 run: String,
5098 base_run: String,
5099 head_failures: Vec<CiFailure>,
5100 base_failures: Vec<CiFailure>,
5101 rerun_exhausted: bool,
5102}
5103
5104#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5106pub struct CiEvidence {
5107 head: String,
5108 base: String,
5109 changed: Vec<String>,
5110 checks: Vec<CiCheckEvidence>,
5111}
5112
5113impl CiEvidence {
5114 fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5117 if self.head != head
5118 || self.base.is_empty()
5119 || failing.is_empty()
5120 || self.changed.iter().any(|p| {
5121 p.starts_with(".github/")
5122 || p.starts_with(".config/")
5123 || p.starts_with(".cargo/")
5124 || matches!(
5125 p.rsplit('/').next().unwrap_or(p),
5126 "Cargo.toml"
5127 | "Cargo.lock"
5128 | "Makefile.toml"
5129 | "build.rs"
5130 | "rust-toolchain.toml"
5131 )
5132 })
5133 {
5134 return false;
5135 }
5136 failing.iter().all(|label| {
5137 let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5138 matches.len() == 1
5139 && matches[0].rerun_exhausted
5140 && !matches[0].head_failures.is_empty()
5141 && matches[0].head_failures.iter().all(|f| {
5142 !f.path.is_empty()
5145 && !f.path.starts_with('.')
5146 && !f.path.contains("..")
5147 && !f.path.starts_with('/')
5148 && !self.changed.contains(&f.path)
5149 && matches[0].base_failures.contains(f)
5150 })
5151 })
5152 }
5153}
5154
5155async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5156 let (ok, body) = gh(repo, &["api".into(), endpoint]).await.ok()?;
5157 if !ok {
5158 return None;
5159 }
5160 serde_json::from_str(&body).ok()
5161}
5162
5163async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5164 let count = check.pointer("/output/annotations_count")?.as_u64()?;
5165 if count == 0 || count >= 100 {
5166 return None;
5167 }
5168 let id = check.get("id")?.as_u64()?;
5169 let value = ci_json(
5170 repo,
5171 format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5172 )
5173 .await?;
5174 let annotations = value.as_array()?;
5175 if annotations.len() != count as usize {
5176 return None;
5177 }
5178 annotations
5179 .iter()
5180 .filter(|a| a["annotation_level"] == "failure")
5181 .map(|a| {
5182 Some(CiFailure {
5183 path: a["path"].as_str()?.into(),
5184 start_line: a["start_line"].as_u64()?,
5185 end_line: a["end_line"].as_u64()?,
5186 title: a["title"].as_str()?.into(),
5187 message: a["message"].as_str()?.into(),
5188 })
5189 })
5190 .collect()
5191}
5192
5193async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5194 let value = ci_json(
5195 repo,
5196 format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5197 )
5198 .await?;
5199 let runs = value["check_runs"].as_array()?;
5200 if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5201 return None;
5202 }
5203 Some(runs.clone())
5204}
5205
5206async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5207 let repo = &state.repo;
5208 let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5209 let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5210 .await
5211 .ok()?;
5212 if !base.ok() {
5213 return None;
5214 }
5215 let range = format!("{}...{}", base.stdout, seen.head);
5216 let diff = git::git_raw(
5218 repo,
5219 &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5220 )
5221 .await
5222 .ok()?;
5223 if !diff.ok() {
5224 return None;
5225 }
5226 let head_runs = ci_runs(repo, &seen.head).await?;
5227 let base_runs = ci_runs(repo, &base.stdout).await?;
5228 let mut checks = Vec::new();
5229 for label in &seen.pr.failing {
5230 let matching = |runs: &[serde_json::Value]| {
5231 runs.iter()
5232 .filter(|r| r["name"].as_str() == Some(label))
5233 .cloned()
5234 .collect::<Vec<_>>()
5235 };
5236 let heads = matching(&head_runs);
5237 let bases = matching(&base_runs);
5238 if heads.len() != 1 || bases.len() != 1 {
5239 return None;
5240 }
5241 let h = &heads[0];
5242 let b = &bases[0];
5243 if h["conclusion"] != "failure"
5244 || b["conclusion"] != "failure"
5245 || h["status"] != "completed"
5246 || b["status"] != "completed"
5247 || h["head_sha"].as_str()? != seen.head
5248 || b["head_sha"].as_str()? != base.stdout
5249 || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5250 {
5251 return None;
5252 }
5253 let run = run_of(h["details_url"].as_str()?)?;
5254 let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5255 if contexts.len() != 1
5256 || contexts[0].run.as_ref() != Some(&run)
5257 || contexts[0].verdict != Verdict::Fail
5258 {
5259 return None;
5260 }
5261 let workflow =
5264 ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5265 let base_run = run_of(b["details_url"].as_str()?)?;
5266 let base_workflow = ci_json(
5267 repo,
5268 format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5269 )
5270 .await?;
5271 if base_workflow["head_sha"].as_str()? != base.stdout
5272 || base_workflow["head_branch"].as_str()? != seen.base
5273 || base_workflow["status"] != "completed"
5274 || base_workflow["conclusion"] != "failure"
5275 || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5276 {
5277 return None;
5278 }
5279 let exhausted = state
5280 .land_reruns
5281 .as_ref()
5282 .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5283 && workflow["head_sha"].as_str()? == seen.head
5284 && workflow["run_attempt"].as_u64()? > 1
5285 && workflow["status"] == "completed";
5286 checks.push(CiCheckEvidence {
5287 label: label.clone(),
5288 head_check: h["id"].as_u64()?,
5289 base_check: b["id"].as_u64()?,
5290 app: h.pointer("/app/id")?.as_u64()?,
5291 run,
5292 base_run,
5293 head_failures: ci_annotations(repo, h).await?,
5294 base_failures: ci_annotations(repo, b).await?,
5295 rerun_exhausted: exhausted,
5296 });
5297 }
5298 Some(CiEvidence {
5299 head: seen.head.clone(),
5300 base: base.stdout,
5301 changed: diff
5302 .stdout
5303 .split('\0')
5304 .filter(|p| !p.is_empty())
5305 .map(str::to_owned)
5306 .collect(),
5307 checks,
5308 })
5309}
5310
5311async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5312 let detail = serde_json::to_string(&evidence)?;
5313 let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5314 let hold = "operator: 保留して後で判断する".to_owned();
5315 let mut q = ask::Question::new(
5316 state.id.clone(),
5317 CI_HOLD_NODE.into(),
5318 "land".into(),
5319 "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5320 format!(
5321 "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5322 ),
5323 vec![resume.clone(), hold.clone()],
5324 );
5325 q.actions.insert(
5326 resume,
5327 ask::ChoiceAction::Resume {
5328 run: state.id.clone(),
5329 },
5330 );
5331 q.actions.insert(hold, ask::ChoiceAction::Hold);
5332 ask::Questions::open().put_executable(&mut q)?;
5333 state.land_unrelated = Some(CiHold {
5334 head: evidence.head.clone(),
5335 question: q.id.clone(),
5336 evidence,
5337 });
5338 state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5339 state.end_pass_parked(crate::run::ParkCause::Question);
5340 state.parked = true;
5341 state.save()?;
5342 if let Err(e) = ask::notify(&state.config.notify, &q).await {
5343 tracing::warn!("could not notify about CI hold: {e:#}");
5344 }
5345 let body = stop_comment(
5347 &state.id,
5348 "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5349 );
5350 let (_, body) = crate::github_text::prepare(state, "", &body);
5351 gh(
5352 &state.repo,
5353 &[
5354 "pr".into(),
5355 "comment".into(),
5356 pr.number.to_string(),
5357 "--body".into(),
5358 body,
5359 ],
5360 )
5361 .await
5362 .ok();
5363 Ok(())
5364}
5365
5366#[derive(Clone)]
5370struct Seen {
5371 pr: PrState,
5372 title: String,
5373 failing_urls: Vec<(String, String)>,
5374 head: String,
5376 rollup_head: String,
5379 merge_state: String,
5382 contexts: Vec<CheckInfo>,
5384 base: String,
5386}
5387
5388#[derive(Clone)]
5390struct CheckInfo {
5391 label: String,
5392 verdict: Verdict,
5393 required: Option<bool>,
5394 run: Option<String>,
5396}
5397
5398#[derive(Debug, Clone, PartialEq, Eq)]
5400enum RerunStep {
5401 Rerun(Vec<String>),
5403 Grace,
5405 Fix,
5407}
5408
5409#[cfg(test)]
5413fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5414 rerunnable_with(contexts, false)
5415}
5416
5417fn rerunnable_with(
5418 contexts: &[CheckInfo],
5419 include_optional: bool,
5420) -> Vec<(String, Option<String>)> {
5421 contexts
5422 .iter()
5423 .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5424 .filter(|c| {
5426 c.run.as_ref().is_none_or(|r| {
5427 !contexts.iter().any(|o| {
5428 matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5429 && o.run.as_ref() == Some(r)
5430 })
5431 })
5432 })
5433 .map(|c| (c.label.clone(), c.run.clone()))
5434 .collect()
5435}
5436
5437fn rerun_step(
5439 failing: &[(String, Option<String>)],
5440 record: Option<&LandReruns>,
5441 head: &str,
5442 now: i64,
5443) -> RerunStep {
5444 if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5447 return RerunStep::Fix;
5448 }
5449 let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5451 let mut fresh: Vec<String> = Vec::new();
5452 let mut recent = false;
5453 for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5454 match record.and_then(|r| r.runs.get(run)) {
5455 None => {
5456 if !fresh.iter().any(|f| f == run) {
5457 fresh.push(run.to_owned());
5458 }
5459 }
5460 Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5461 Some(_) => {}
5462 }
5463 }
5464 if !fresh.is_empty() {
5465 RerunStep::Rerun(fresh)
5466 } else if recent {
5467 RerunStep::Grace
5468 } else {
5469 RerunStep::Fix
5470 }
5471}
5472
5473async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5477 let view = gh(
5478 repo,
5479 &[
5480 "pr".to_owned(),
5481 "view".to_owned(),
5482 pr_url.to_owned(),
5483 "--json".to_owned(),
5484 "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5485 .to_owned(),
5486 ],
5487 )
5488 .await?;
5489 if !view.0 {
5490 bail!("gh pr view {pr_url}: {}", view.1);
5491 }
5492 let number = parse_pr(&view.1)?.number;
5493 let node = last_commit_node(repo, number).await;
5494 let mut seen = seen_from(&view.1, node.as_deref())?;
5495
5496 let inline = gh(
5497 repo,
5498 &[
5499 "api".to_owned(),
5500 format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5501 ],
5502 )
5503 .await?;
5504 if inline.0 {
5505 match parse_inline_comments(&inline.1) {
5506 Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5507 Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5510 }
5511 } else {
5512 tracing::warn!("gh api pulls/{}/comments: {}", seen.pr.number, inline.1);
5513 }
5514 Ok(seen)
5515}
5516
5517fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5528 let mut pr = parse_pr(view_json)?;
5529 let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5530
5531 let mut rollup_head = String::new();
5532 let mut failing_urls = Vec::new();
5533 let mut contexts = Vec::new();
5534 let mut checks = Checks::Unknown;
5535 let mut failing = Vec::new();
5536 if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5537 (checks, failing) = rollup_verdict(&rollup);
5538 failing_urls = rollup
5539 .iter()
5540 .filter(|c| c.verdict() == Verdict::Fail)
5541 .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5542 .collect();
5543 contexts = rollup
5544 .iter()
5545 .map(|c| CheckInfo {
5546 label: c.label(),
5547 verdict: c.verdict(),
5548 required: c.is_required,
5549 run: c.url().and_then(run_of),
5550 })
5551 .collect();
5552 rollup_head = oid;
5553 }
5554 pr.checks = checks;
5555 pr.failing = failing;
5556
5557 Ok(Seen {
5558 pr,
5559 title: raw.title,
5560 failing_urls,
5561 head: raw.head_ref_oid,
5562 rollup_head,
5563 merge_state: raw.merge_state_status,
5564 contexts,
5565 base: raw.base_ref_name,
5566 })
5567}
5568
5569fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
5572 let v: serde_json::Value = serde_json::from_str(json).ok()?;
5573 if v.get("errors").is_some_and(|e| !e.is_null()) {
5574 return None;
5575 }
5576 let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
5577 let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
5578 let contexts = commit.pointer("/statusCheckRollup/contexts");
5579 let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
5580 return Some((oid.to_owned(), Vec::new()));
5582 };
5583 if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
5584 return None;
5585 }
5586 let nodes = contexts.get("nodes")?.as_array()?;
5587 let rollup = nodes
5588 .iter()
5589 .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
5590 .collect::<Result<Vec<_>, _>>()
5591 .ok()?;
5592 Some((oid.to_owned(), rollup))
5593}
5594
5595async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
5598 let out = gh(
5599 repo,
5600 &[
5601 "api".to_owned(),
5602 "graphql".to_owned(),
5603 "-F".to_owned(),
5604 "owner={owner}".to_owned(),
5605 "-F".to_owned(),
5606 "repo={repo}".to_owned(),
5607 "-F".to_owned(),
5608 format!("number={number}"),
5609 "-f".to_owned(),
5610 "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
5611 name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
5612 statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
5613 ... on CheckRun{name status conclusion detailsUrl \
5614 isRequired(pullRequestNumber:$number)} \
5615 ... on StatusContext{context state targetUrl \
5616 isRequired(pullRequestNumber:$number)}}}}}}}}}}"
5617 .to_owned(),
5618 ],
5619 )
5620 .await
5621 .ok()?;
5622 out.0.then_some(out.1)
5623}
5624
5625#[doc(hidden)]
5627#[derive(Debug, PartialEq)]
5628pub enum Fixed {
5629 Committed {
5631 head: String,
5633 },
5634 Declined,
5636 Deferred,
5638 Failed(String),
5640}
5641
5642#[doc(hidden)]
5648pub async fn fix_round(
5649 state: &mut RunState,
5650 pr: &PrState,
5651 round: usize,
5652 budget: usize,
5653 reason: &str,
5654 logs: &str,
5655) -> Result<Fixed> {
5656 let winner = state
5657 .winner()
5658 .cloned()
5659 .context("landing needs a winning candidate; none is recorded on this run")?;
5660 let roles = state
5661 .config
5662 .resolve_roles()
5663 .context("resolve the roster for the fix round")?;
5664 let attempts = crate::fixer::attempts(state, &roles, &winner);
5668 let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
5669
5670 let prompt = fix_prompt(state, pr, round, budget, reason, logs);
5671 let mut artifacts = agent::artifacts_dir(&state.dir());
5672 if let Some(request) = state
5673 .merge_repairs
5674 .last()
5675 .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
5676 {
5677 artifacts = artifacts.join(format!("merge-repair-{}", request.question));
5678 }
5679 let prompt =
5680 if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
5681 format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
5682 } else {
5683 prompt
5684 };
5685 let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5689 let mut last = None;
5693 for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
5694 if owner_requested_stop(state)? {
5695 return Ok(Fixed::Declined);
5696 }
5697 let mut seat = seat_of(state, &seat_key, &spec.id);
5698 let stem = if i == 0 {
5699 format!("land-{round}")
5700 } else {
5701 format!("land-{round}-{}", spec.id)
5702 };
5703 let out = agent::invoke(
5704 &spec,
5705 &mut seat,
5706 &Invocation {
5707 coordination: state.config.coordination.as_ref(),
5708 fetched_base: state.fetched_base.as_ref(),
5709 cwd: &winner.worktree,
5710 prompt: &prompt,
5711 timeout: Duration::from_secs(state.config.graph.timeout_fix),
5712 allow_write: true,
5713 sessions: state.config.graph.sessions,
5714 artifacts: &artifacts,
5715 stem: &stem,
5716 run: &state.id,
5717 node: "land",
5718 cache_dir: state.config.cache_dir().as_deref(),
5719 attachments: &[],
5720 writable: &[],
5721 },
5722 )
5723 .await;
5724 state.seats.insert(seat.key.clone(), seat);
5725 if let Some(next) = ids.get(i + 1)
5726 && agent::chain_advances(&out)
5727 {
5728 let (class, why) = crate::fixer::failure_of(&out);
5729 crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
5730 continue;
5731 }
5732 last = Some((seat_key, out));
5733 break;
5734 }
5735 let (seat_key, out) = last.expect("the fixer chain always has an entry");
5736
5737 match out {
5738 Ok(o) if o.quota_exhausted() => {
5739 let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
5740 crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
5741 state.quota.push(loss);
5742 state.status = RunStatus::Blocked;
5743 state.save()?;
5744 let inherited = crate::repo_lock::WaitPolicy::current();
5748 let wait = crate::repo_lock::WaitPolicy::new(
5749 Duration::from_secs(state.config.graph.timeout_resource_wait),
5750 move || inherited.cancelled(),
5751 );
5752 let _coordination = crate::repo_lock::SeatLease::operation_with(
5753 &winner.worktree,
5754 state.config.coordination.as_ref(),
5755 &wait,
5756 )
5757 .await?;
5758 let rescue = git::rescue_commit(
5759 &winner.worktree,
5760 &format!("magi: deferred land round {round} (uncommitted work)"),
5761 )
5762 .await?;
5763 state.note_withheld("land", &rescue.withheld);
5764 state.save()?;
5765 return Ok(Fixed::Deferred);
5766 }
5767 Ok(o) if !o.usable() => {
5768 return Ok(Fixed::Failed(format!(
5769 "the fixer produced nothing usable ({})",
5770 crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
5771 )));
5772 }
5773 Ok(_) => {}
5774 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
5775 Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
5776 }
5777
5778 if owner_requested_stop(state)? {
5779 return Ok(Fixed::Declined);
5780 }
5781
5782 let wait = crate::repo_lock::WaitPolicy::new(
5785 Duration::from_secs(state.config.graph.timeout_resource_wait),
5786 || false,
5787 );
5788 let coordination = crate::repo_lock::SeatLease::operation_with(
5789 &winner.worktree,
5790 state.config.coordination.as_ref(),
5791 &wait,
5792 )
5793 .await?;
5794 match git::rescue_commit(
5795 &winner.worktree,
5796 &format!("magi: land round {round} fixes (uncommitted work)"),
5797 )
5798 .await
5799 {
5800 Ok(r) => state.note_withheld("land", &r.withheld),
5801 Err(e)
5802 if state
5803 .merge_repairs
5804 .last()
5805 .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
5806 {
5807 return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
5808 }
5809 Err(_) => {}
5810 }
5811 let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5812 drop(coordination);
5813 if after == before {
5814 return Ok(Fixed::Declined);
5815 }
5816
5817 if owner_requested_stop(state)? {
5818 return Ok(Fixed::Declined);
5819 }
5820 crate::pr_head::ensure_owner(state)?;
5821 let remote = state.config.merge.remote.clone();
5822 anyhow::ensure!(
5823 crate::foreign_checkout::write_back(state, &after).await?,
5824 "foreign checkout delivery is blocked; see the run events"
5825 );
5826 let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
5827 let push = if state.pr_head.is_some() {
5828 let expected = state
5829 .pr_pushed_head
5830 .as_deref()
5831 .context("missing public head lease")?;
5832 git::push_as(
5833 &winner.worktree,
5834 &remote,
5835 &winner.branch,
5836 &public_head,
5837 expected,
5838 )
5839 .await?
5840 } else {
5841 git::push(&winner.worktree, &remote, &winner.branch).await?
5842 };
5843 if !push.ok() {
5844 return Ok(Fixed::Failed(format!(
5845 "pushing {} to {remote} failed: {}",
5846 public_head, push.stderr
5847 )));
5848 }
5849 state.event(
5850 "land",
5851 format!("round {round}: pushed a fix to {public_head}"),
5852 );
5853 state.pr_pushed_head = Some(after.clone());
5854 state.save()?;
5855 Ok(Fixed::Committed { head: after })
5856}
5857
5858pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
5860 crate::fixer::seat_for(state, key, agent)
5861}
5862
5863pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
5866 let seen = observe(&state.repo, url).await?;
5867 let winner = state.winner().context("no winning branch to repair")?;
5868 if seen.pr.state != PrLifecycle::Open || seen.head != head {
5869 anyhow::bail!(
5870 "PR is closed or its head changed; review the current head before requesting repair again"
5871 );
5872 }
5873 if git::rev_parse(&winner.worktree, "HEAD").await? != head
5874 || !git::is_clean(&winner.worktree).await?
5875 {
5876 anyhow::bail!(
5877 "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
5878 );
5879 }
5880 let view = gh(
5883 &state.repo,
5884 &[
5885 "pr".into(),
5886 "view".into(),
5887 url.into(),
5888 "--json".into(),
5889 "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
5890 ],
5891 )
5892 .await?;
5893 if !view.0 {
5894 bail!("cannot check auto-merge: {}", view.1);
5895 }
5896 let live: serde_json::Value = serde_json::from_str(&view.1)?;
5897 let public = state.pr_branch().unwrap_or(&winner.branch);
5898 if live["state"] != "OPEN"
5899 || live["headRefOid"] != head
5900 || live["headRefName"] != public
5901 || live["baseRefName"] != state.base_branch
5902 || live["isCrossRepository"] != false
5903 {
5904 bail!("PR changed during repair preflight; review its current head explicitly");
5905 }
5906 let auto_merge = live
5907 .get("autoMergeRequest")
5908 .context("cannot read the PR auto-merge reservation; repair held")?;
5909 if !auto_merge.is_null() {
5910 let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
5911 if !out.0 {
5912 bail!("cannot disable auto-merge; repair held: {}", out.1);
5913 }
5914 }
5915 Ok(seen.pr)
5916}
5917
5918fn fix_prompt(
5920 state: &RunState,
5921 pr: &PrState,
5922 round: usize,
5923 budget: usize,
5924 reason: &str,
5925 logs: &str,
5926) -> String {
5927 let mut s = format!(
5928 "Your patch is open as a pull request and it is not landing. Land round \
5929 {round} of {budget}.\n\n\
5930 Pull request: {}\n\n\
5931 What is holding it: {reason}\n\n\
5932 # The task\n\n{}\n",
5933 pr.url, state.instruction
5934 );
5935
5936 if pr.failing.is_empty() {
5937 s.push_str("\n# Failing checks\n\n(none)\n");
5938 } else {
5939 let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
5940 if logs.trim().is_empty() {
5941 s.push_str(
5942 "\nNo log could be read; investigate the failure with necessary focused checks.\n",
5943 );
5944 } else {
5945 let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
5946 }
5947 }
5948
5949 if pr.review_comments.is_empty() {
5950 s.push_str("\n# Review comments\n\n(none)\n");
5951 } else {
5952 s.push_str("\n# Review comments\n");
5953 for c in &pr.review_comments {
5954 let where_ = match (&c.path, c.line) {
5955 (Some(p), Some(l)) => format!(" ({p}:{l})"),
5956 (Some(p), None) => format!(" ({p})"),
5957 _ => String::new(),
5958 };
5959 let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
5960 }
5961 }
5962
5963 s.push_str(
5964 "\n# Rules\n\n\
5965 1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
5966 failing test; do not silence a lint with an allow attribute; do not \
5967 stretch a timeout to hide a race. If the check is right, the code is \
5968 wrong.\n\
5969 2. Change nothing the checks and the comments did not raise. A \
5970 drive-by refactor turns a one-line fix into a pull request that \
5971 needs reviewing again.\n\
5972 3. If a comment is wrong, say so with a checkable argument and change \
5973 nothing for it. A declined comment with a reason is a correct \
5974 outcome; a change made to appease a reviewer is not.\n\
5975 4. Commit in this worktree. magi pushes to the pull request's branch \
5976 for you; do not push, merge, or close anything yourself.\n\
5977 5. Never name yourself, your vendor, or your model, anywhere.\n\n\
5978 # Output\n\n\
5979 Say what you changed and why, and what you declined and why.",
5980 );
5981
5982 let language = &state.config.graph.language;
5983 if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
5984 let _ = write!(s, "\n\nWrite all prose in {language}.");
5985 }
5986 s.push_str(&crate::prompt::github_rule(
5988 language,
5989 &state.config.graph.github_language,
5990 ));
5991 if let Some(overlay) = state.config.prompts.overlay("fix") {
5992 let _ = write!(s, "\n\n{overlay}");
5993 }
5994 s.push('\n');
5995 s.push_str(crate::prompt::child_run_ownership());
5996 s
5997}
5998
5999async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6002 let mut out = String::new();
6003 for (name, url) in failing.iter().take(MAX_LOGS) {
6004 let args = match (job_of(url), run_of(url)) {
6005 (Some(job), _) => vec![
6006 "run".to_owned(),
6007 "view".to_owned(),
6008 "--log-failed".to_owned(),
6009 "--job".to_owned(),
6010 job,
6011 ],
6012 (None, Some(run)) => vec![
6013 "run".to_owned(),
6014 "view".to_owned(),
6015 run,
6016 "--log-failed".to_owned(),
6017 ],
6018 (None, None) => continue,
6020 };
6021 let (ok, body) = match gh(repo, &args).await {
6022 Ok(v) => v,
6023 Err(e) => (false, format!("{e:#}")),
6024 };
6025 if !ok && body.trim().is_empty() {
6026 continue;
6027 }
6028 let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6029 }
6030 out
6031}
6032
6033fn job_of(details_url: &str) -> Option<String> {
6036 let after = details_url.split("/job/").nth(1)?;
6037 let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6038 (!id.is_empty()).then_some(id)
6039}
6040
6041pub(crate) fn run_of(details_url: &str) -> Option<String> {
6043 let after = details_url.split("/actions/runs/").nth(1)?;
6044 let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6045 (!id.is_empty()).then_some(id)
6046}
6047
6048fn stop_comment(run_id: &str, why: &str) -> String {
6052 format!(
6053 "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6054 The branch is untouched and the run is `{run_id}`. Nothing was merged."
6055 )
6056}
6057
6058async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6063 let body = stop_comment(&state.id, why);
6064 let (_, mut body) = crate::github_text::prepare(state, "", &body);
6065 if !body.contains(MARKER) {
6066 body = format!("{MARKER}\n{body}");
6067 }
6068 let posted = gh(
6069 repo,
6070 &[
6071 "pr".to_owned(),
6072 "comment".to_owned(),
6073 pr.number.to_string(),
6074 "--body".to_owned(),
6075 body,
6076 ],
6077 )
6078 .await;
6079 match posted {
6080 Ok((true, _)) => {}
6081 Ok((false, out)) => tracing::warn!("could not comment on {}: {out}", pr.url),
6082 Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6083 }
6084 state.status = RunStatus::Blocked;
6085 state.merge = Some(MergeOutcome {
6086 mode: MergeMode::Pr,
6087 ok: false,
6088 detail: why.to_owned(),
6089 empty: false,
6090 });
6091 state.event("land", format!("stopped: {why}"));
6092 state.save()?;
6093 Ok(())
6094}
6095
6096pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<(bool, String)> {
6112 let out = tokio::process::Command::new("gh")
6113 .args(args)
6114 .current_dir(cwd)
6115 .env_remove("GH_REPO")
6116 .quiet()
6117 .stdin(std::process::Stdio::null())
6118 .output()
6119 .await
6120 .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6121 let mut body = String::from_utf8_lossy(&out.stdout).into_owned();
6122 let err = String::from_utf8_lossy(&out.stderr);
6123 if body.trim().is_empty() {
6124 body = err.into_owned();
6125 } else if !err.trim().is_empty() {
6126 body.push_str(&err);
6127 }
6128 Ok((out.status.success(), body.trim().to_owned()))
6129}
6130
6131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6133pub(crate) enum Verdict {
6134 Pass,
6135 Fail,
6136 Pending,
6137 Unknown,
6138}
6139
6140impl Verdict {
6141 pub(crate) fn label(self) -> &'static str {
6143 match self {
6144 Self::Pass => "passed",
6145 Self::Fail => "failed",
6146 Self::Pending => "pending",
6147 Self::Unknown => "unknown",
6148 }
6149 }
6150}
6151
6152#[derive(Debug, Deserialize)]
6153#[serde(rename_all = "camelCase")]
6154struct GhPr {
6155 #[serde(default)]
6156 url: String,
6157 #[serde(default)]
6158 number: u64,
6159 #[serde(default)]
6160 state: String,
6161 #[serde(default)]
6162 title: String,
6163 #[serde(default)]
6164 status_check_rollup: Vec<GhCheck>,
6165 #[serde(default)]
6172 merge_state_status: String,
6173 #[serde(default)]
6177 head_ref_oid: String,
6178 #[serde(default)]
6179 base_ref_name: String,
6180 #[serde(default)]
6181 reviews: Vec<GhReview>,
6182 #[serde(default)]
6183 comments: Vec<GhComment>,
6184}
6185
6186#[derive(Debug, Deserialize)]
6191#[serde(rename_all = "camelCase")]
6192struct GhCheck {
6193 #[serde(default)]
6194 name: Option<String>,
6195 #[serde(default)]
6196 context: Option<String>,
6197 #[serde(default)]
6198 status: Option<String>,
6199 #[serde(default)]
6200 conclusion: Option<String>,
6201 #[serde(default)]
6202 state: Option<String>,
6203 #[serde(default)]
6204 details_url: Option<String>,
6205 #[serde(default)]
6206 target_url: Option<String>,
6207 #[serde(default)]
6210 is_required: Option<bool>,
6211}
6212
6213impl GhCheck {
6214 fn label(&self) -> String {
6216 self.name
6217 .clone()
6218 .or_else(|| self.context.clone())
6219 .unwrap_or_else(|| "(unnamed check)".to_owned())
6220 }
6221
6222 fn url(&self) -> Option<&str> {
6224 self.details_url
6225 .as_deref()
6226 .or(self.target_url.as_deref())
6227 .filter(|u| !u.is_empty())
6228 }
6229
6230 fn verdict(&self) -> Verdict {
6238 if let Some(status) = self.status.as_deref() {
6239 if !status.eq_ignore_ascii_case("COMPLETED") {
6240 return Verdict::Pending;
6241 }
6242 }
6243 let outcome = self
6244 .conclusion
6245 .as_deref()
6246 .or(self.state.as_deref())
6247 .unwrap_or("");
6248 match outcome.to_ascii_uppercase().as_str() {
6249 "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6250 "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6251 | "ACTION_REQUIRED" => Verdict::Fail,
6252 "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6253 Verdict::Pending
6254 }
6255 _ => Verdict::Unknown,
6256 }
6257 }
6258}
6259
6260#[derive(Debug, Deserialize)]
6261struct GhAuthor {
6262 #[serde(default)]
6263 login: String,
6264}
6265
6266#[derive(Debug, Deserialize)]
6267struct GhReview {
6268 #[serde(default)]
6269 author: GhAuthor,
6270 #[serde(default)]
6271 body: String,
6272}
6273
6274#[derive(Debug, Deserialize)]
6275struct GhComment {
6276 #[serde(default)]
6277 author: GhAuthor,
6278 #[serde(default)]
6279 body: String,
6280}
6281
6282#[derive(Debug, Deserialize)]
6283struct GhUser {
6284 #[serde(default)]
6285 login: String,
6286}
6287
6288#[derive(Debug, Deserialize)]
6289struct GhInline {
6290 #[serde(default)]
6291 user: GhUser,
6292 #[serde(default)]
6293 path: Option<String>,
6294 #[serde(default)]
6295 line: Option<u64>,
6296 #[serde(default)]
6297 body: String,
6298}
6299
6300impl Default for GhAuthor {
6301 fn default() -> Self {
6302 Self {
6303 login: "(unknown)".to_owned(),
6304 }
6305 }
6306}
6307
6308impl Default for GhUser {
6309 fn default() -> Self {
6310 Self {
6311 login: "(unknown)".to_owned(),
6312 }
6313 }
6314}
6315
6316#[cfg(test)]
6317pub(crate) mod tests {
6318 use super::*;
6319 use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6320
6321 fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6322 format!(
6323 r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6324 )
6325 }
6326
6327 #[test]
6328 fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6329 let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6330 assert_eq!(
6331 closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6332 Ok(())
6333 );
6334 for (json, why) in [
6335 (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6336 (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6337 (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6338 (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6339 (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6340 (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6341 ] {
6342 let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6343 .unwrap_err()
6344 .why;
6345 assert!(err.contains(why), "{json}: {err}");
6346 }
6347 let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6349 let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6350 assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6351 assert!(
6352 !closable(
6353 &head_json("x", "main", "OPEN", false),
6354 "magi/27b2/A",
6355 "main",
6356 &[]
6357 )
6358 .unwrap_err()
6359 .retry
6360 );
6361 assert!(is_forge_url("https://github.com/o/r.git"));
6362 assert!(is_forge_url("git@github.com:o/r.git"));
6363 assert!(!is_forge_url("/tmp/origin.git"));
6364 assert!(!is_forge_url("C:\\work\\origin.git"));
6365 assert!(!is_forge_url("file:///tmp/origin.git"));
6366 assert!(forge_unavailable(
6367 "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6368 ));
6369 assert!(!forge_unavailable(
6370 "gh pr list failed: error connecting to api.github.com"
6371 ));
6372 assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6373 assert!(
6375 closable(
6376 r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6377 "b",
6378 "main",
6379 &["aaa".to_owned()]
6380 )
6381 .is_err()
6382 );
6383 }
6384
6385 #[test]
6386 fn the_close_comment_names_the_commit_on_the_base() {
6387 let e = crate::already::Evidence {
6388 proof: crate::already::Proof::PatchId,
6389 tip: "1234567890".to_owned(),
6390 commits: vec!["0e368de0000".to_owned()],
6391 };
6392 let c = superseded_comment("main", &e);
6393 assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6394 }
6395
6396 const GREEN_OPEN: &str = r####"{
6398 "url": "https://github.com/yukimemi/magi/pull/10",
6399 "number": 10,
6400 "state": "OPEN",
6401 "mergeStateStatus": "CLEAN",
6402 "statusCheckRollup": [
6403 {
6404 "__typename": "CheckRun",
6405 "conclusion": "SKIPPED",
6406 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6407 "name": "review",
6408 "status": "COMPLETED",
6409 "workflowName": "claude-review"
6410 },
6411 {
6412 "__typename": "CheckRun",
6413 "conclusion": "SUCCESS",
6414 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6415 "name": "check (ubuntu-latest)",
6416 "status": "COMPLETED",
6417 "workflowName": "CI"
6418 },
6419 {
6420 "__typename": "CheckRun",
6421 "conclusion": "SUCCESS",
6422 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6423 "name": "rustfmt",
6424 "status": "COMPLETED",
6425 "workflowName": "CI"
6426 },
6427 {
6428 "__typename": "StatusContext",
6429 "context": "CodeRabbit",
6430 "state": "SUCCESS",
6431 "targetUrl": ""
6432 }
6433 ],
6434 "reviews": [],
6435 "comments": [
6436 {
6437 "author": {
6438 "login": "coderabbitai"
6439 },
6440 "authorAssociation": "NONE",
6441 "body": "<!-- This is an auto-generated comment: summarize by coderabbit.ai -->\n<!-- This is an auto-generated comment: skip review by coderabbit.ai -->\n\n> [!IMPORTANT]\n> - [ ] <!-- {\"checkboxId\":\"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe\"} --> 🔍 Trigger review\n> \n> This repository does not receive automatic reviews because it has fewer than 10 stars.\n> \n> <details>\n> <summary>⚙️ Run configuration</summary>\n> \n> **Configuration used**: defaults\n> \n> **Review profile**: CHILL\n> \n> **Plan**: Pro Plus\n> \n> **Run ID**: `78e70bf3-c5a0-4269-a96c-2afb2dba7eff`\n> \n> </details>\n\n<!-- end of auto-generated comment: skip review by coderabbit.ai -->\n\n<!-- tips_start -->\n\n---\n\nThanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=yukimemi/magi&utm_content=10)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.\n\n<details>\n<summary>❤️ Share</summary>\n\n- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%2"
6442 }
6443 ]
6444}"####;
6445
6446 const RED_OPEN: &str = r####"{
6448 "url": "https://github.com/yukimemi/magi/pull/9",
6449 "number": 9,
6450 "state": "OPEN",
6451 "mergeStateStatus": "UNSTABLE",
6452 "statusCheckRollup": [
6453 {
6454 "__typename": "CheckRun",
6455 "conclusion": "SUCCESS",
6456 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6457 "name": "check (ubuntu-latest)",
6458 "status": "COMPLETED",
6459 "workflowName": "CI"
6460 },
6461 {
6462 "__typename": "CheckRun",
6463 "conclusion": "SUCCESS",
6464 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6465 "name": "rustfmt",
6466 "status": "COMPLETED",
6467 "workflowName": "CI"
6468 },
6469 {
6470 "__typename": "CheckRun",
6471 "conclusion": "FAILURE",
6472 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6473 "name": "editorconfig",
6474 "status": "COMPLETED",
6475 "workflowName": "CI"
6476 },
6477 {
6478 "__typename": "StatusContext",
6479 "context": "CodeRabbit",
6480 "state": "SUCCESS",
6481 "targetUrl": ""
6482 }
6483 ],
6484 "reviews": [],
6485 "comments": [
6486 {
6487 "author": {
6488 "login": "coderabbitai"
6489 },
6490 "authorAssociation": "NONE",
6491 "body": "<!-- This is an auto-generated comment: summarize by coderabbit.ai -->\n<!-- This is an auto-generated comment: skip review by coderabbit.ai -->\n\n> [!IMPORTANT]\n> - [ ] <!-- {\"checkboxId\":\"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe\"} --> 🔍 Trigger review\n> \n> This repository does not receive automatic reviews because it has fewer than 10 stars.\n> \n> <details>\n> <summary>⚙️ Run configuration</summary>\n> \n> **Configuration used**: defaults\n> \n> **Review profile**: CHILL\n> \n> **Plan**: Team\n> \n> **Run ID**: `91e0dc24-6040-4c3d-92c6-f7d2b542523d`\n> \n> </details>\n\n<!-- end of auto-generated comment: skip review by coderabbit.ai -->\n\n<!-- tips_start -->\n\n---\n\nThanks for using [CodeRabbit](https://coderab"
6492 }
6493 ]
6494}"####;
6495
6496 const PENDING_OPEN: &str = r####"{
6498 "url": "https://github.com/yukimemi/magi/pull/9",
6499 "number": 9,
6500 "state": "OPEN",
6501 "statusCheckRollup": [
6502 {
6503 "__typename": "CheckRun",
6504 "conclusion": "SUCCESS",
6505 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6506 "name": "check (ubuntu-latest)",
6507 "status": "COMPLETED",
6508 "workflowName": "CI"
6509 },
6510 {
6511 "__typename": "CheckRun",
6512 "conclusion": "SUCCESS",
6513 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6514 "name": "rustfmt",
6515 "status": "COMPLETED",
6516 "workflowName": "CI"
6517 },
6518 {
6519 "__typename": "CheckRun",
6520 "conclusion": null,
6521 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6522 "name": "editorconfig",
6523 "status": "IN_PROGRESS",
6524 "workflowName": "CI"
6525 },
6526 {
6527 "__typename": "StatusContext",
6528 "context": "CodeRabbit",
6529 "state": "SUCCESS",
6530 "targetUrl": ""
6531 }
6532 ],
6533 "reviews": [],
6534 "comments": []
6535}"####;
6536
6537 const MERGED: &str = r####"{
6539 "url": "https://github.com/yukimemi/magi/pull/16",
6540 "number": 16,
6541 "state": "MERGED",
6542 "statusCheckRollup": [
6543 {
6544 "__typename": "CheckRun",
6545 "conclusion": "SUCCESS",
6546 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
6547 "name": "check (ubuntu-latest)",
6548 "status": "COMPLETED",
6549 "workflowName": "CI"
6550 },
6551 {
6552 "__typename": "CheckRun",
6553 "conclusion": "SUCCESS",
6554 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
6555 "name": "review",
6556 "status": "COMPLETED",
6557 "workflowName": "claude-review"
6558 }
6559 ],
6560 "reviews": [],
6561 "comments": []
6562}"####;
6563
6564 const REVIEWED_OPEN: &str = r####"{
6566 "url": "https://github.com/yukimemi/magi/pull/12",
6567 "number": 12,
6568 "state": "OPEN",
6569 "statusCheckRollup": [
6570 {
6571 "__typename": "CheckRun",
6572 "conclusion": "SUCCESS",
6573 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
6574 "name": "check (ubuntu-latest)",
6575 "status": "COMPLETED",
6576 "workflowName": "CI"
6577 },
6578 {
6579 "__typename": "CheckRun",
6580 "conclusion": "SUCCESS",
6581 "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
6582 "name": "review",
6583 "status": "COMPLETED",
6584 "workflowName": "claude-review"
6585 }
6586 ],
6587 "reviews": [
6588 {
6589 "author": {
6590 "login": "claude"
6591 },
6592 "state": "COMMENTED",
6593 "body": ""
6594 }
6595 ],
6596 "comments": [
6597 {
6598 "author": {
6599 "login": "coderabbitai"
6600 },
6601 "authorAssociation": "NONE",
6602 "body": "<!-- This is an auto-generated comment: summarize by coderabbit.ai -->\n<!-- This is an auto-generated comment: skip review by coderabbit.ai -->\n\n> [!IMPORTANT]\n> - [ ] <!-- {\"checkboxId\":\"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe\"} --> 🔍 Trigger review\n> \n> This repository does not receive automatic reviews because it has fewer than 10 stars.\n> \n> <details>\n> <summary>⚙️ Run configuration</summary>\n> \n> **Configuration used**: defaults\n> \n> **Review profile**: CHILL\n> \n> **Plan**: Team\n> \n> **Run ID**: `72058bf3-b7df-41d9-8e4d-a06a31be4a26`\n> \n> </details>\n\n<!-- end of auto-generated comment: skip review by coderabbit.ai -->\n\n<!-- tips_start -->\n\n---\n\nThanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=yukimemi/magi&utm_content=12)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.\n\n<details>\n<summa"
6603 },
6604 {
6605 "author": {
6606 "login": "claude"
6607 },
6608 "authorAssociation": "NONE",
6609 "body": "**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)\n\n---\n### Review: `magi review <branch>` — cheap-half-only graph\n\nRead through `src/graph.rs`, `src/main.rs`, `src/prompt.rs`, and the new/edited tests, and traced the claimed degeneration (`prep` short-circuits on a non-empty candidate list, `implement` skips because `commits != 0`, `judge`/`vote` skip on `viable().len() == 1`, `tally` skips because it's pre-set, `fold_losers` has no losers) against the actual code — it holds up. CI (`cargo make check`) is green on this PR.\n\n**Correctness**\n\n- One real bug, flagged inline on `src/graph.rs:1255`: the fixer-agent fallback (`self.roles.implementers[winner.index].clone()`) is unreachable in the normal graph (a real candidate's `winner.agent` always resolves via `config.agent(...)`), but a review-only run's `winner.agent` is always the `\"(existing branch)\"` sentinel, so this fallback now runs on *every* review-only fix that has no dedicated `[roles] fixer`. `graph.candidates` has no lower-bound validation, so a `magi.toml` tuned for review-only use (`candidates = 0`, plausible given this PR's own cost rationale) would panic with an out-of-bounds index the first time a"
6610 }
6611 ]
6612}"####;
6613
6614 const INLINE: &str = r####"[
6616 {
6617 "user": {
6618 "login": "claude[bot]"
6619 },
6620 "path": "src/graph.rs",
6621 "line": 231,
6622 "body": "Minor edge case: unlike `implement()` (which sets `c.empty = commits == 0 || patch.trim().is_empty()`, `src/graph.rs:472`), the seeded review-only candidate always sets `empty: false` once `commits > 0` is confirmed, without checking whether the diff itself is actually empty (e.g. a commit immediately followed by a revert nets zero file changes). Such a branch would pass `Runner::review`'s validation and proceed into a review round with an empty patch, where `implement()`'s equivalent path would"
6623 }
6624]"####;
6625
6626 const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
6628<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
6629
6630> [!IMPORTANT]
6631> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
6632>
6633> This repository does not receive automatic reviews because it has fewer than 10 stars.
6634>
6635> <details>
6636> <summary>⚙️ Run configuration</summary>
6637>
6638> **Configuration used**: defaults
6639>
6640> **Review profile**: CHILL
6641>
6642> **Plan**: Team
6643>
6644> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
6645>
6646> </details>
6647
6648<!-- end of auto-generated comment: skip review by coderabbit.ai -->
6649
6650<!-- tips_start -->
6651
6652---
6653
6654Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=yukimemi/magi&utm_content=16)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
6655
6656<details>
6657<summary>❤️ Share</summary>
6658
6659- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20off"####;
6660
6661 const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
6663
6664---
6665### Reviewing PR #16
6666
6667- [x] Read AGENTS.md conventions
6668- [x] Review `src/daemon.rs` changes
6669- [x] Review `src/main.rs` changes (new `doctor` reporting)
6670- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
6671- [x] Check test coverage for new behavior
6672- [x] Run verification commands (blocked — see note)
6673- [x] Post findings"####;
6674
6675 const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
6677
6678---
6679### Review: `magi review <branch>` — cheap-half-only graph
6680
6681Read through `src/graph.rs`, `src/main.rs`, `src/prompt.rs`, and the new/edited tests, and traced the claimed degeneration (`prep` short-circuits on a non-empty candidate list, `implement` skips because `commits != 0`, `judge`/`vote` skip on `viable().len() == 1`, `tally` skips because it's pre-set, `fold_losers` has no losers) against the actual code — it holds up. CI (`cargo make check`) is green on this PR.
6682
6683**Correctness**
6684
6685- One real bug, flagged inline on `src/graph.rs:1255`: the fixer-agent fallback (`self.roles.implementers[winner.index].clone()`) is unreachable in the normal graph (a real candidate's `winner.agent` always resolves via `config.agent(...)`), but a review-only run's `winner.agent` is always the `"(existing branch)"` sentinel, so this fallback now runs on *every* review-only fix that has no dedicated `[roles] fixer`. `graph.candidates` has no lower-bound validation, so a `magi.toml` tuned for review-only use (`candidates = 0`, plausible given this PR's own cost rationale) would panic with an out-of-bounds index the first time a"####;
6686
6687 fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
6688 PrState {
6689 url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
6690 number: 16,
6691 state: PrLifecycle::Open,
6692 checks,
6693 blocking: if matches!(checks, Checks::Red) {
6697 Blocking::Yes
6698 } else {
6699 Blocking::No
6700 },
6701 failing: failing.iter().map(|s| (*s).to_owned()).collect(),
6702 review_comments: (0..comments)
6703 .map(|i| ReviewComment {
6704 author: "coderabbitai".to_owned(),
6705 path: Some("src/graph.rs".to_owned()),
6706 line: Some(231),
6707 body: format!("finding {i}"),
6708 })
6709 .collect(),
6710 }
6711 }
6712
6713 #[test]
6714 fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
6715 use CiExpectation::{Absent, Expected};
6716 for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
6717 let p = pr(checks, &["x"], 0);
6718 for waited in [Duration::ZERO, CHECKS_GRACE] {
6719 assert_eq!(
6720 decide_with(&p, 0, 4, waited, Expected),
6721 decide(&p, 0, 4, waited)
6722 );
6723 }
6724 }
6725 for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
6727 let p = pr(checks, &["x"], 0);
6728 assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
6729 assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
6730 }
6731 for comments in [0, 1] {
6733 for round in [0, 4] {
6734 let absent = decide_with(
6735 &pr(Checks::Unknown, &[], comments),
6736 round,
6737 4,
6738 CHECKS_GRACE,
6739 Absent,
6740 );
6741 for checks in [Checks::Green, Checks::Red, Checks::Pending] {
6742 assert_eq!(
6743 decide_with(
6744 &pr(checks, &["third-party"], comments),
6745 round,
6746 4,
6747 Duration::ZERO,
6748 Absent
6749 ),
6750 absent
6751 );
6752 }
6753 if comments != 0 {
6754 assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
6755 assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
6756 }
6757 }
6758 }
6759 let empty = pr(Checks::Unknown, &[], 0);
6760 for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
6761 assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
6762 }
6763 assert_eq!(
6764 decide_with(&empty, 0, 4, Duration::ZERO, Expected),
6765 Step::Wait
6766 );
6767 assert_eq!(
6768 decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
6769 Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
6770 );
6771 let mut p = pr(Checks::Unknown, &[], 0);
6773 p.blocking = Blocking::Conflict;
6774 assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
6775 p.state = PrLifecycle::Merged;
6777 assert_eq!(
6778 decide_with(&p, 0, 4, Duration::ZERO, Absent),
6779 Step::Done { merged: true }
6780 );
6781 }
6782
6783 #[test]
6784 fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
6785 let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
6786 assert_eq!(state.number, 10);
6787 assert_eq!(state.state, PrLifecycle::Open);
6788 assert_eq!(state.checks, Checks::Green);
6789 assert!(state.failing.is_empty());
6790 assert!(
6791 state.review_comments.is_empty(),
6792 "the only comment is CodeRabbit's trigger notice: {:?}",
6793 state.review_comments
6794 );
6795 assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
6796 }
6797
6798 #[test]
6799 fn a_failing_check_parses_as_red_and_is_named() {
6800 let state = parse_pr(RED_OPEN).expect("red fixture parses");
6801 assert_eq!(state.checks, Checks::Red);
6802 assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
6803 let mut blocking = state.clone();
6810 blocking.blocking = Blocking::Yes;
6811 match decide(&blocking, 0, 4, Duration::ZERO) {
6812 Step::Fix { reason } => {
6813 assert!(reason.contains("editorconfig"), "reason: {reason}");
6814 assert!(reason.contains("failing"), "reason: {reason}");
6815 }
6816 other => panic!("expected a fix round, got {other:?}"),
6817 }
6818 }
6819
6820 #[test]
6821 fn a_check_still_running_parses_as_pending_and_is_waited_for() {
6822 let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
6823 assert_eq!(state.checks, Checks::Pending);
6824 assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
6825 }
6826
6827 #[test]
6828 fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
6829 let state = parse_pr(MERGED).expect("merged fixture parses");
6830 assert_eq!(state.state, PrLifecycle::Merged);
6831 assert_eq!(
6832 decide(&state, 0, 4, Duration::ZERO),
6833 Step::Done { merged: true }
6834 );
6835 }
6836
6837 #[test]
6838 fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
6839 let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
6840 assert_eq!(state.checks, Checks::Green);
6841 let authors: Vec<&str> = state
6842 .review_comments
6843 .iter()
6844 .map(|c| c.author.as_str())
6845 .collect();
6846 assert_eq!(
6847 authors,
6848 vec!["claude"],
6849 "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
6850 );
6851 match decide(&state, 0, 4, Duration::ZERO) {
6852 Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
6853 other => panic!("expected a fix round, got {other:?}"),
6854 }
6855 }
6856
6857 #[test]
6858 fn inline_review_comments_keep_their_file_and_line() {
6859 let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
6860 assert_eq!(comments.len(), 1);
6861 assert_eq!(comments[0].author, "claude[bot]");
6862 assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
6863 assert_eq!(comments[0].line, Some(231));
6864 assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
6865 }
6866
6867 #[test]
6868 fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
6869 assert!(
6870 is_noise(CODERABBIT_TRIGGER),
6871 "CodeRabbit's trigger notice declares itself not a review"
6872 );
6873 assert!(
6874 is_noise(CLAUDE_CHECKLIST),
6875 "a progress checklist asks for nothing"
6876 );
6877 assert!(
6878 !is_noise(CLAUDE_FINDING),
6879 "a review that names a bug is input, not noise"
6880 );
6881
6882 let mut clean = pr(Checks::Green, &[], 0);
6883 clean.review_comments.push(ReviewComment {
6884 author: "coderabbitai".to_owned(),
6885 path: None,
6886 line: None,
6887 body: CODERABBIT_TRIGGER.to_owned(),
6888 });
6889 clean.review_comments.retain(|c| !is_noise(&c.body));
6890 assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
6891
6892 let mut found = pr(Checks::Green, &[], 0);
6893 found.review_comments.push(ReviewComment {
6894 author: "claude".to_owned(),
6895 path: None,
6896 line: None,
6897 body: CLAUDE_FINDING.to_owned(),
6898 });
6899 found.review_comments.retain(|c| !is_noise(&c.body));
6900 assert!(matches!(
6901 decide(&found, 0, 4, Duration::ZERO),
6902 Step::Fix { .. }
6903 ));
6904 }
6905
6906 #[test]
6907 fn the_policy_table_holds_for_every_combination_that_matters() {
6908 let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
6909 (
6910 "pending checks are waited for, even on the last round",
6911 pr(Checks::Pending, &[], 0),
6912 4,
6913 4,
6914 Duration::ZERO,
6915 Step::Wait,
6916 ),
6917 (
6918 "red checks are fixed",
6919 pr(Checks::Red, &["editorconfig"], 0),
6920 0,
6921 4,
6922 Duration::ZERO,
6923 Step::Fix {
6924 reason: "1 check(s) failing: editorconfig".to_owned(),
6925 },
6926 ),
6927 (
6928 "green with comments is fixed, not merged",
6929 pr(Checks::Green, &[], 2),
6930 1,
6931 4,
6932 Duration::ZERO,
6933 Step::Fix {
6934 reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
6935 .to_owned(),
6936 },
6937 ),
6938 (
6939 "green and clean merges",
6940 pr(Checks::Green, &[], 0),
6941 3,
6942 4,
6943 Duration::ZERO,
6944 Step::Merge,
6945 ),
6946 (
6947 "an unreadable rollup is waited on while the grace lasts",
6948 pr(Checks::Unknown, &[], 0),
6949 0,
6950 4,
6951 Duration::ZERO,
6952 Step::Wait,
6953 ),
6954 (
6955 "an unreadable rollup is never merged once the grace is spent",
6956 pr(Checks::Unknown, &[], 0),
6957 0,
6958 4,
6959 CHECKS_GRACE,
6960 Step::GiveUp {
6961 reason: "no check status is readable on the pull request after 3 minute(s); \
6962 refusing to merge on a guess"
6963 .to_owned(),
6964 },
6965 ),
6966 ];
6967 for (what, state, round, budget, waited, want) in cases {
6968 assert_eq!(decide(&state, round, budget, waited), want, "{what}");
6969 }
6970 }
6971
6972 #[test]
6973 fn the_forge_verdict_survives_the_round_trip_from_gh() {
6974 let green = parse_pr(GREEN_OPEN).expect("parse");
6978 assert_eq!(green.blocking, Blocking::No);
6979 let red = parse_pr(RED_OPEN).expect("parse");
6980 assert_eq!(
6981 red.blocking,
6982 Blocking::No,
6983 "`UNSTABLE` is mergeable: the red check is one nobody requires"
6984 );
6985 assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
6986 let quiet =
6988 parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
6989 assert_eq!(quiet.blocking, Blocking::Unsaid);
6990 }
6991
6992 #[test]
6993 fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
6994 let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7000 nonblocking.blocking = Blocking::No;
7001 assert_eq!(
7002 decide(&nonblocking, 0, 4, Duration::ZERO),
7003 Step::Merge,
7004 "the forge says nothing is in the way, so nothing is"
7005 );
7006
7007 let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7009 blocking.blocking = Blocking::Yes;
7010 assert!(matches!(
7011 decide(&blocking, 0, 4, Duration::ZERO),
7012 Step::Fix { .. }
7013 ));
7014
7015 let mut commented = pr(Checks::Red, &["coverage"], 1);
7018 commented.blocking = Blocking::No;
7019 assert!(matches!(
7020 decide(&commented, 0, 4, Duration::ZERO),
7021 Step::Fix { .. }
7022 ));
7023
7024 let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7026 unsaid.blocking = Blocking::Unsaid;
7027 assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7028 assert!(matches!(
7029 decide(&unsaid, 0, 4, CHECKS_GRACE),
7030 Step::Fix { .. }
7031 ));
7032 }
7033
7034 #[test]
7035 fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7036 let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7037 red.blocking = Blocking::No;
7038 assert_eq!(
7039 decide(&red, 0, 4, Duration::ZERO),
7040 Step::Merge,
7041 "announcing must not change the decision"
7042 );
7043 let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7044 assert!(said.contains("yukimemi/magi"), "{said}");
7045 assert!(said.contains("#16"), "{said}");
7046 assert!(
7047 said.contains("https://github.com/yukimemi/magi/pull/16"),
7048 "{said}"
7049 );
7050 assert!(
7051 said.contains("test (windows-latest)") && said.contains("coverage"),
7052 "{said}"
7053 );
7054
7055 let green = pr(Checks::Green, &["stale"], 0);
7057 assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7058 }
7059
7060 #[test]
7061 fn red_merge_notices_omit_empty_check_details() {
7062 for checks in [vec![], vec!["", " "]] {
7063 let red = pr(Checks::Red, &checks, 0);
7064 let summary = red_merge_summary("owner/repo", &red).unwrap();
7065 let notice = crate::notices::merged_red("run-1", &summary);
7066 assert_eq!(
7067 notice.message,
7068 format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7069 );
7070 assert_eq!(notice.severity, crate::notices::Severity::Warn);
7071 }
7072 let red = pr(Checks::Red, &["", " test ", " "], 0);
7073 let summary = red_merge_summary("owner/repo", &red).unwrap();
7074 assert!(summary.contains("with red checks: test ("), "{summary}");
7075 }
7076
7077 #[test]
7078 fn the_repo_label_comes_from_the_pull_request_url() {
7079 let p = Path::new("/tmp/checkout");
7080 assert_eq!(
7081 repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7082 "yukimemi/magi"
7083 );
7084 assert_eq!(repo_label(p, "not a url"), "checkout");
7085 }
7086
7087 #[test]
7088 fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7089 let mut conflicted = pr(Checks::Green, &[], 0);
7094 conflicted.blocking = Blocking::Conflict;
7095 assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7096
7097 let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7101 red.blocking = Blocking::Conflict;
7102 assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7103
7104 let mut merged = pr(Checks::Red, &[], 0);
7106 merged.blocking = Blocking::Conflict;
7107 merged.state = PrLifecycle::Merged;
7108 assert_eq!(
7109 decide(&merged, 0, 4, Duration::ZERO),
7110 Step::Done { merged: true }
7111 );
7112 }
7113
7114 #[test]
7115 fn the_forge_verdict_is_read_off_merge_state_status() {
7116 for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7119 assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7120 assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7121 }
7122 assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7123 assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7124 assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7125 for quiet in ["", "UNKNOWN"] {
7128 assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7129 assert!(Blocking::of(quiet).stops_a_merge());
7130 }
7131 }
7132
7133 #[test]
7134 fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7135 let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7136 let jj = "could not determine current branch: failed to run git: not on any branch";
7138
7139 let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7140 .expect("the forge says merged, so it merged");
7141 assert!(landed.ok);
7142 assert!(
7143 landed.detail.contains("but the pull request is merged"),
7144 "the record must not read as a clean success: {}",
7145 landed.detail
7146 );
7147 assert!(
7148 landed.detail.contains("not on any branch"),
7149 "and it must keep what the command actually said: {}",
7150 landed.detail
7151 );
7152
7153 assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7155 assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7156 assert!(merged_after_all(&argv, jj, None).is_none());
7158 }
7159
7160 #[test]
7161 fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7162 let mut state = pr(Checks::Red, &["editorconfig"], 3);
7163 state.state = PrLifecycle::Closed;
7164 assert_eq!(
7165 decide(&state, 0, 4, Duration::ZERO),
7166 Step::Done { merged: false },
7167 "a human closing the pull request ends the loop, whatever CI says"
7168 );
7169 }
7170
7171 #[test]
7172 fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7173 let red = decide(
7174 &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7175 4,
7176 4,
7177 Duration::ZERO,
7178 );
7179 match red {
7180 Step::GiveUp { reason } => {
7181 assert!(reason.contains("editorconfig"), "reason: {reason}");
7182 assert!(reason.contains("test (macos)"), "reason: {reason}");
7183 assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7184 }
7185 other => panic!("expected a give-up, got {other:?}"),
7186 }
7187
7188 let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7189 match commented {
7190 Step::GiveUp { reason } => {
7191 assert!(reason.contains("unresolved"), "reason: {reason}");
7192 assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7193 }
7194 other => panic!("expected a give-up, got {other:?}"),
7195 }
7196 }
7197
7198 #[test]
7199 fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7200 let candidate_commit = "magi: candidate A (uncommitted work)";
7201 let subject = merge_subject(candidate_commit, "add retries to the uploader");
7202 let argv = merge_argv(16, &subject);
7203
7204 assert!(argv.contains(&"--squash".to_owned()));
7205 assert!(argv.contains(&"--delete-branch".to_owned()));
7206 assert!(argv.contains(&"--subject".to_owned()));
7207 assert_eq!(
7208 argv.last().map(String::as_str),
7209 Some("add retries to the uploader"),
7210 "the subject must not be the candidate commit message"
7211 );
7212 assert_ne!(subject, candidate_commit);
7213 }
7214
7215 #[test]
7216 fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7217 assert_eq!(
7218 merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7219 "feat: a queue, an unattended loop, and a phone UI"
7220 );
7221 assert_eq!(
7222 merge_subject("", "# port the retry logic\n\ndetails"),
7223 "port the retry logic",
7224 "an empty title falls back to the task's first line, heading marks stripped"
7225 );
7226 }
7227
7228 #[test]
7229 fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7230 let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7231 assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7232 assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7233 assert_eq!(job_of("https://coderabbit.ai/status"), None);
7234 assert_eq!(run_of(""), None);
7235 }
7236
7237 #[test]
7238 fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7239 let mut out = Vec::new();
7240 push_if_outstanding(
7241 &mut out,
7242 ReviewComment {
7243 author: "yukimemi".to_owned(),
7244 path: None,
7245 line: None,
7246 body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7247 },
7248 );
7249 assert!(out.is_empty());
7250 }
7251
7252 fn run_state() -> RunState {
7256 let mut state = RunState::new(
7257 std::path::PathBuf::from("/repo/magi"),
7258 "main".to_owned(),
7259 "abcdef1234".to_owned(),
7260 "add retries to the uploader".to_owned(),
7261 crate::config::Config::default(),
7262 );
7263 state.config.disk.min_free_bytes = 0;
7265 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7270 let nanos = std::time::SystemTime::now()
7271 .duration_since(std::time::UNIX_EPOCH)
7272 .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7273 state.id = format!(
7274 "20261004-{nanos:06}-{:04x}",
7275 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7276 );
7277 state
7278 }
7279
7280 fn green_pr() -> PrState {
7281 PrState {
7282 url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7283 number: 42,
7284 state: PrLifecycle::Open,
7285 checks: Checks::Green,
7286 blocking: Blocking::No,
7288 failing: Vec::new(),
7289 review_comments: vec![ReviewComment {
7290 author: "coderabbitai".to_owned(),
7291 path: Some("src/land.rs".to_owned()),
7292 line: Some(212),
7293 body: "this branch never checks the exit code".to_owned(),
7294 }],
7295 }
7296 }
7297
7298 #[test]
7299 fn land_fixer_defers_review_and_verification_without_a_cache() {
7300 let state = run_state();
7301 let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7302 assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7303 assert!(p.contains("Commit in this worktree"), "{p}");
7304 }
7305
7306 #[test]
7307 fn github_facing_land_text_is_english_whatever_the_language() {
7308 let mut state = run_state();
7309 state.config.graph.language = "ja".to_owned();
7310 let comment = stop_comment(&state.id, "checks are still red");
7311 assert!(crate::github_text::check("", &comment).is_empty());
7312 assert!(comment.is_ascii(), "{comment}");
7313 assert!(comment.starts_with(MARKER));
7314
7315 let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7316 let ja_at = p.find("Write all prose in ja").unwrap();
7317 let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7318 assert!(ja_at < rule_at, "{p}");
7319 assert!(p.contains("stays in Japanese"), "{p}");
7320
7321 state.config.graph.language = "en".to_owned();
7322 let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7323 assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7324 assert!(!p.contains("does not apply"), "{p}");
7325 }
7326
7327 const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7328
7329 fn panel() -> String {
7330 approval_panel(
7331 &run_state(),
7332 &green_pr(),
7333 NUMSTAT,
7334 "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7335 &[
7336 "land: ask before merging".to_owned(),
7337 "land: colour the diff".to_owned(),
7338 ],
7339 "feat: merge approval from the phone",
7340 )
7341 }
7342
7343 #[test]
7344 fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7345 let html = panel();
7346 for needle in [
7347 "42",
7348 "main",
7349 "src/land.rs",
7350 "src/web.rs",
7351 "assets/logo.png",
7352 "feat: merge approval from the phone",
7353 "land: ask before merging",
7354 "land: colour the diff",
7355 "coderabbitai",
7356 "this branch never checks the exit code",
7357 "green",
7358 ] {
7359 assert!(html.contains(needle), "the panel must state `{needle}`");
7360 }
7361 }
7362
7363 async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7364 crate::run::pin_test_home();
7365 let tmp = tempfile::tempdir().unwrap();
7366 let repo = tmp.path().join("repo");
7367 let remote = tmp.path().join("remote.git");
7368 std::fs::create_dir(&repo).unwrap();
7369 git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7370 .await
7371 .unwrap();
7372 git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7373 git::git(&repo, &["config", "user.name", "Test"])
7374 .await
7375 .unwrap();
7376 git::git(&repo, &["config", "user.email", "test@example.test"])
7377 .await
7378 .unwrap();
7379 std::fs::write(repo.join("base"), "base").unwrap();
7380 git::git(&repo, &["add", "."]).await.unwrap();
7381 git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7382 git::git(
7383 &repo,
7384 &["remote", "add", "origin", remote.to_str().unwrap()],
7385 )
7386 .await
7387 .unwrap();
7388 git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7389 git::git(&repo, &["checkout", "-b", "winner"])
7390 .await
7391 .unwrap();
7392 std::fs::write(repo.join("change"), "change").unwrap();
7393 git::git(&repo, &["add", "."]).await.unwrap();
7394 git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7395 let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7396 git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7397 .await
7398 .unwrap();
7399 let mut state = run_state();
7400 state.repo = repo.clone();
7401 state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7402 state.config.graph.land = true;
7403 state.config.graph.land_approval = true;
7404 state.pr_head = Some("task-head".into());
7405 state.pr_pushed_head = Some(head.clone());
7406 state.candidates = vec![winning_candidate("change")];
7407 state.candidates[0].worktree = repo;
7408 state.candidates[0].branch = "winner".into();
7409 state.tally = Some(uncontested_tally());
7410 state.gate_ran = true;
7411 state.gate_head = Some(head.clone());
7412 state.land_sync_pending = true;
7413 state.save().unwrap();
7414 (tmp, state, head)
7415 }
7416
7417 async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7418 let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7419 resume_landing_head(state, head, &green_pr().url, &forge, None).await
7420 }
7421
7422 async fn advance_landing_base(state: &RunState) {
7423 git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7424 std::fs::write(state.repo.join("advance"), "advance").unwrap();
7425 git::git(&state.repo, &["add", "."]).await.unwrap();
7426 git::git(&state.repo, &["commit", "-m", "advance base"])
7427 .await
7428 .unwrap();
7429 git::git(&state.repo, &["push", "origin", "main"])
7430 .await
7431 .unwrap();
7432 git::git(&state.repo, &["checkout", "winner"])
7433 .await
7434 .unwrap();
7435 }
7436
7437 #[tokio::test]
7438 async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
7439 let (_tmp, mut state, head) = landing_git_fixture().await;
7440 advance_landing_base(&state).await;
7441 let scratch = state.dir().join("rebase");
7442 std::fs::create_dir_all(&scratch).unwrap();
7443 std::fs::write(scratch.join("obstruction"), "keep").unwrap();
7444 let attempts = state.land_sync_attempts;
7445 let error = rebase_landing_worktree(&mut state, "origin/main")
7446 .await
7447 .unwrap_err();
7448 assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
7449 assert_eq!(state.land_sync_attempts, attempts);
7450 assert!(state.land_sync_target.is_none());
7451 assert!(state.rebase_fixes.is_empty());
7452 assert!(
7453 state
7454 .base_sync
7455 .as_ref()
7456 .is_none_or(|sync| sync.conflict.is_none())
7457 );
7458 assert!(
7459 state
7460 .resource_block
7461 .as_ref()
7462 .unwrap()
7463 .detail
7464 .contains("worktree add")
7465 );
7466 assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
7467 std::fs::remove_dir_all(&scratch).unwrap();
7468 state.resource_block = None;
7469 assert_eq!(
7470 rebase_landing_worktree(&mut state, "origin/main")
7471 .await
7472 .unwrap(),
7473 crate::rebase::Rebased::Applied
7474 );
7475 assert_eq!(state.land_sync_attempts, attempts + 1);
7476 assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
7477 assert!(git::is_clean(&state.repo).await.unwrap());
7478 assert!(state.rebase_fixes.is_empty());
7479 }
7480
7481 async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7482 {
7483 let (tmp, mut state, old) = landing_git_fixture().await;
7484 let path = tmp.path().join("foreign");
7485 git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7486 .await
7487 .unwrap();
7488 state.foreign_checkout = Some(
7489 crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7490 .await
7491 .unwrap(),
7492 );
7493 state.config.merge.mode = crate::config::MergeMode::Pr;
7494 state.save().unwrap();
7495 (tmp, state, old, path)
7496 }
7497
7498 #[tokio::test]
7499 async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
7500 for phase in 0..4 {
7501 let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7502 advance_landing_base(&state).await;
7503 state.config.verify.gate = vec!["test -f advance && test -f change".into()];
7504 if phase == 0 {
7505 assert_eq!(
7508 rebase_landing_worktree(&mut state, "origin/main")
7509 .await
7510 .unwrap(),
7511 crate::rebase::Rebased::Applied
7512 );
7513 } else {
7514 interrupt_landing_rebase(&mut state).await;
7515 let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
7516 if phase == 2 {
7517 git::sync_to_head(&state.repo).await.unwrap();
7518 } else if phase == 3 {
7519 restore_landing_worktree(&mut state).await.unwrap();
7522 let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7523 state.land_rebase_from = Some(old.clone());
7524 state.save().unwrap();
7525 restore_landing_worktree(&mut state).await.unwrap();
7526 assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
7527 }
7528 state.save().unwrap();
7529 state = RunState::load(&state.id).unwrap();
7530 restore_landing_worktree(&mut state).await.unwrap();
7531 assert_eq!(
7532 git::tree_of(&state.repo, "HEAD").await.unwrap(),
7533 repaired_tree
7534 );
7535 }
7536 let head = if phase == 0 {
7537 let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
7538 publish_landing_head(&mut state, &old, &green_pr().url, &forge)
7539 .await
7540 .unwrap()
7541 } else {
7542 resume_observed_head(&mut state, &old).await.unwrap()
7543 };
7544 assert!(git::is_ancestor(&state.repo, &old, &head).await);
7545 assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7546 assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7547 assert_eq!(
7548 git::remote_head(&state.repo, "origin", "task-head")
7549 .await
7550 .unwrap(),
7551 Some(head.clone())
7552 );
7553 assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7554 assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
7555 assert!(state.gate_allows_progress());
7556 assert!(state.land_rebase_from.is_none());
7557 assert!(!state.land_sync_pending);
7558 assert!(git::is_clean(&path).await.unwrap());
7559 }
7560 }
7561
7562 #[tokio::test]
7563 async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
7564 let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7565 git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7566 std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7567 git::commit_all(&state.repo, "conflicting base")
7568 .await
7569 .unwrap();
7570 git::git(&state.repo, &["push", "origin", "main"])
7571 .await
7572 .unwrap();
7573 git::git(&state.repo, &["checkout", "winner"])
7574 .await
7575 .unwrap();
7576 landing_gate_fixer(
7577 &mut state,
7578 "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7579 );
7580 state.config.graph.gate_fix_rounds = 0;
7581 state.config.verify.gate = vec!["exit 1".into()];
7582 assert!(resume_observed_head(&mut state, &old).await.is_err());
7583 assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
7584 let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7585 assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
7586 assert_eq!(
7587 std::fs::read_to_string(state.repo.join("change")).unwrap(),
7588 "resolved"
7589 );
7590 assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
7592 assert_eq!(
7593 git::remote_head(&state.repo, "origin", "task-head")
7594 .await
7595 .unwrap(),
7596 Some(old.clone())
7597 );
7598 state = RunState::load(&state.id).unwrap();
7599 state.config.verify.gate = vec!["grep -q resolved change".into()];
7600 let head = resume_observed_head(&mut state, &old).await.unwrap();
7601 assert_eq!(head, repaired);
7602 assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7603 assert_eq!(
7604 std::fs::read_to_string(path.join("change")).unwrap(),
7605 "resolved"
7606 );
7607 assert_eq!(
7608 git::remote_head(&state.repo, "origin", "task-head")
7609 .await
7610 .unwrap(),
7611 Some(head.clone())
7612 );
7613 assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7614 assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7615 assert!(git::is_clean(&path).await.unwrap());
7616 }
7617
7618 #[tokio::test]
7619 async fn landing_resume_completes_the_last_charged_sync_attempt() {
7620 for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
7621 let (_tmp, mut state, old) = landing_git_fixture().await;
7622 git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7623 std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7624 git::commit_all(&state.repo, "conflicting base")
7625 .await
7626 .unwrap();
7627 git::git(&state.repo, &["push", "origin", "main"])
7628 .await
7629 .unwrap();
7630 git::git(&state.repo, &["checkout", "winner"])
7631 .await
7632 .unwrap();
7633 let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
7634 state.config.graph.land_rounds = 1;
7635 state.land_sync_attempts = 1;
7636 state.land_sync_target = saved_target.then(|| target.clone());
7637 state.land_rebase_from = Some(old.clone());
7638 landing_gate_fixer(
7639 &mut state,
7640 "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7641 );
7642 state.config.verify.gate = vec!["grep -q resolved change".into()];
7643 state.save().unwrap();
7644 if scratch_started {
7646 assert!(matches!(
7647 git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
7648 .await
7649 .unwrap(),
7650 git::RebaseStart::Conflicted(_)
7651 ));
7652 }
7653 state = RunState::load(&state.id).unwrap();
7654 let head = resume_observed_head(&mut state, &old).await.unwrap();
7655 assert_ne!(head, old);
7656 assert_eq!(state.land_sync_attempts, 1);
7657 assert!(state.land_sync_target.is_none());
7658 assert!(state.land_rebase_from.is_none());
7659 assert!(!state.land_sync_pending);
7660 assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7661 assert!(state.gate_allows_progress());
7662 assert_eq!(
7663 git::remote_head(&state.repo, "origin", "task-head")
7664 .await
7665 .unwrap(),
7666 Some(head)
7667 );
7668 assert!(
7669 rebase_landing_worktree(&mut state, "origin/main")
7670 .await
7671 .unwrap_err()
7672 .to_string()
7673 .contains("budget exhausted")
7674 );
7675 }
7676 }
7677
7678 #[tokio::test]
7679 async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
7680 let (_tmp, mut state, old) = landing_git_fixture().await;
7681 advance_landing_base(&state).await;
7682 state.config.verify.gate = vec!["test -f advance".into()];
7683 let head = resume_observed_head(&mut state, &old).await.unwrap();
7684 assert_ne!(head, old);
7685 assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7686 assert!(state.gate_allows_progress());
7687 assert_eq!(
7688 git::remote_head(&state.repo, "origin", "task-head")
7689 .await
7690 .unwrap(),
7691 Some(head.clone())
7692 );
7693 assert_eq!(state.pr_pushed_head, Some(head));
7694 assert!(!state.land_sync_pending);
7695 assert!(state.config.graph.land_approval);
7696 }
7697
7698 fn landing_gate_fixer(state: &mut RunState, script: &str) {
7699 state.config.disk.min_free_bytes = 0;
7700 state.config.graph.gate_fix_rounds = 1;
7701 state.config.agents = vec![crate::config::AgentSpec {
7702 id: "mock".into(),
7703 kind: crate::config::AgentKind::Command,
7704 model: None,
7705 command: vec!["sh".into(), "-c".into(), script.into()],
7706 extra_args: Vec::new(),
7707 env: Default::default(),
7708 prompt_delivery: None,
7709 max_turn_secs: None,
7710 }];
7711 state.candidates[0].agent = "mock".into();
7712 }
7713
7714 #[tokio::test]
7715 async fn landing_resume_revalidates_an_operator_published_winner_extension() {
7716 let (_tmp, mut state, old) = landing_git_fixture().await;
7717 std::fs::write(state.repo.join("change"), "operator update").unwrap();
7718 git::commit_all(&state.repo, "extend winner").await.unwrap();
7719 let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7720 git::git(
7721 &state.repo,
7722 &["push", "origin", "HEAD:refs/heads/task-head"],
7723 )
7724 .await
7725 .unwrap();
7726 state.config.verify.gate = vec!["exit 1".into()];
7727 state.config.graph.gate_fix_rounds = 0;
7728 assert!(resume_observed_head(&mut state, &updated).await.is_err());
7729 assert_ne!(old, updated);
7730 assert_eq!(state.gate_head.as_ref(), Some(&updated));
7731 assert!(!state.gate_allows_progress());
7732 assert!(state.land_sync_pending);
7733 state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
7734 let head = resume_observed_head(&mut state, &updated).await.unwrap();
7735 assert_eq!(head, updated);
7736 assert!(state.gate_allows_progress());
7737 assert!(!state.land_sync_pending);
7738 let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7739 land_with(&mut state, &green_pr().url, &forge)
7740 .await
7741 .unwrap();
7742 assert!(state.parked);
7743 assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7744 assert!(forge.argvs().is_empty());
7745 }
7746
7747 #[tokio::test]
7748 async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
7749 for divergent in [false, true] {
7750 let (_tmp, mut state, old) = landing_git_fixture().await;
7751 if divergent {
7752 git::git(&state.repo, &["reset", "--hard", "origin/main"])
7753 .await
7754 .unwrap();
7755 }
7756 std::fs::write(state.repo.join("external"), "external").unwrap();
7757 git::commit_all(&state.repo, "external update")
7758 .await
7759 .unwrap();
7760 let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7761 git::git(
7762 &state.repo,
7763 &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
7764 )
7765 .await
7766 .unwrap();
7767 if !divergent {
7768 git::git(&state.repo, &["reset", "--hard", &old])
7769 .await
7770 .unwrap();
7771 }
7772 let error = resume_observed_head(&mut state, &external)
7773 .await
7774 .unwrap_err();
7775 assert!(
7776 error
7777 .to_string()
7778 .contains("public head moved outside this run")
7779 );
7780 assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
7781 assert_eq!(
7782 git::remote_head(&state.repo, "origin", "task-head")
7783 .await
7784 .unwrap(),
7785 Some(external)
7786 );
7787 }
7788 }
7789
7790 #[tokio::test]
7791 async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
7792 let (_tmp, mut state, old) = landing_git_fixture().await;
7793 advance_landing_base(&state).await;
7794 landing_gate_fixer(
7795 &mut state,
7796 "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7797 );
7798 state.config.verify.gate =
7799 vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7800 state.config.verify.e2e = vec!["test -f advance".into()];
7801 state.config.graph.gate_fix_rounds = 0;
7804 assert!(resume_observed_head(&mut state, &old).await.is_err());
7805 assert_eq!(
7806 git::remote_head(&state.repo, "origin", "task-head")
7807 .await
7808 .unwrap(),
7809 Some(old.clone())
7810 );
7811 state.config.graph.gate_fix_rounds = 1;
7812 let head = resume_observed_head(&mut state, &old).await.unwrap();
7813 assert_eq!(state.gate_fixes.len(), 1);
7814 assert!(state.gate_fixes[0].committed);
7815 assert!(state.gate_allows_progress());
7816 assert_eq!(state.gate_head.as_ref(), Some(&head));
7817 assert_eq!(
7818 git::remote_head(&state.repo, "origin", "task-head")
7819 .await
7820 .unwrap(),
7821 Some(head.clone())
7822 );
7823 let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7824 land_with(&mut state, &green_pr().url, &forge)
7825 .await
7826 .unwrap();
7827 assert!(state.parked);
7828 assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7829 assert!(forge.argvs().is_empty());
7830 }
7831
7832 #[tokio::test]
7833 async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
7834 let (_tmp, mut state, old) = landing_git_fixture().await;
7835 advance_landing_base(&state).await;
7836 landing_gate_fixer(
7837 &mut state,
7838 "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7839 );
7840 state.config.verify.gate = vec!["echo still red; exit 1".into()];
7841 for _ in 0..2 {
7842 assert!(resume_observed_head(&mut state, &old).await.is_err());
7843 assert_eq!(state.gate_fixes.len(), 1);
7844 assert_eq!(
7845 git::remote_head(&state.repo, "origin", "task-head")
7846 .await
7847 .unwrap(),
7848 Some(old.clone())
7849 );
7850 }
7851 }
7852
7853 #[tokio::test]
7854 async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
7855 let (_tmp, mut state, old) = landing_git_fixture().await;
7856 advance_landing_base(&state).await;
7857 landing_gate_fixer(
7858 &mut state,
7859 "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7860 );
7861 state.config.verify.gate =
7862 vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7863 state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
7865 let mut saved_comparison = None;
7866 for resume in 0..3 {
7867 assert!(resume_observed_head(&mut state, &old).await.is_err());
7868 state = RunState::load(&state.id).unwrap();
7869 let evidence = state.gate_repair_e2e.as_ref().unwrap();
7870 let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7871 assert_eq!(evidence.head, head);
7872 assert!(!evidence.passed);
7873 assert!(evidence.outcomes.iter().any(|o| !o.ok()));
7874 let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
7875 if let Some(saved) = &saved_comparison {
7876 assert_eq!(comparison, saved);
7877 } else {
7878 saved_comparison = Some(comparison.clone());
7879 }
7880 assert_eq!(state.gate_fixes.len(), 1);
7881 assert_eq!(
7882 git::remote_head(&state.repo, "origin", "task-head")
7883 .await
7884 .unwrap(),
7885 Some(old.clone())
7886 );
7887 if resume > 0 {
7888 assert!(
7889 state.gate_allows_progress(),
7890 "a green gate must not bypass red e2e"
7891 );
7892 }
7893 }
7894 state.config.verify.e2e = vec!["grep -q fixed change".into()];
7896 assert!(resume_observed_head(&mut state, &old).await.is_err());
7897 assert_eq!(
7898 state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
7899 saved_comparison
7900 );
7901 }
7902
7903 #[tokio::test]
7904 async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
7905 for phase in 0..3 {
7906 let (_tmp, mut state, old) = landing_git_fixture().await;
7907 advance_landing_base(&state).await;
7908 let head = resume_observed_head(&mut state, &old).await.unwrap();
7909 state.land_sync_pending = true;
7912 state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
7913 state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
7914 head: if phase == 2 {
7915 old.clone()
7916 } else {
7917 head.clone()
7918 },
7919 passed: phase == 2,
7920 outcomes: if phase == 1 {
7921 vec![crate::run::CommandOutcome {
7922 command: state.config.verify.e2e[0].clone(),
7923 code: None,
7924 output_tail: "verification resource unavailable".into(),
7925 duration_ms: 0,
7926 resource_blocked: true,
7927 ..Default::default()
7928 }]
7929 } else {
7930 Vec::new()
7931 },
7932 });
7933 state.save().unwrap();
7934 for _ in 0..2 {
7935 state = RunState::load(&state.id).unwrap();
7936 assert!(resume_observed_head(&mut state, &head).await.is_err());
7937 let evidence = state.gate_repair_e2e.as_ref().unwrap();
7938 assert_eq!(evidence.head, head);
7939 assert!(!evidence.passed);
7940 assert!(!evidence.outcomes.is_empty());
7941 assert_eq!(
7942 git::remote_head(&state.repo, "origin", "task-head")
7943 .await
7944 .unwrap(),
7945 Some(head.clone())
7946 );
7947 assert!(state.land_sync_pending);
7948 }
7949 }
7950 }
7951
7952 #[tokio::test]
7953 async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
7954 for code in [None, Some(126), Some(127)] {
7955 let (_tmp, mut state, old) = landing_git_fixture().await;
7956 advance_landing_base(&state).await;
7957 let head = resume_observed_head(&mut state, &old).await.unwrap();
7958 state.land_sync_pending = true;
7959 state.config.verify.e2e = vec!["true".into()];
7960 state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
7961 head: head.clone(),
7962 passed: false,
7963 outcomes: vec![crate::run::CommandOutcome {
7964 command: state.config.verify.e2e[0].clone(),
7965 code,
7966 output_tail: "verification command did not complete".into(),
7967 ..Default::default()
7968 }],
7969 });
7970 state.save().unwrap();
7971 state = RunState::load(&state.id).unwrap();
7972 assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
7973 let evidence = state.gate_repair_e2e.as_ref().unwrap();
7974 assert_eq!(evidence.head, head);
7975 assert!(evidence.passed);
7976 assert_eq!(evidence.outcomes[0].code, Some(0));
7977 }
7978 }
7979
7980 async fn interrupt_landing_rebase(state: &mut RunState) {
7981 state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
7982 state.save().unwrap();
7983 let scratch = state.dir().join("rebase");
7984 assert_eq!(
7985 crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
7986 .await
7987 .unwrap(),
7988 crate::rebase::Rebased::Applied
7989 );
7990 assert!(!git::is_clean(&state.repo).await.unwrap());
7991 }
7992
7993 async fn landing_setup(state: &mut RunState) {
7994 git::git(
7995 &state.repo,
7996 &["config", "extensions.worktreeConfig", "true"],
7997 )
7998 .await
7999 .unwrap();
8000 state.config.worktree.setup =
8001 vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8002 crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8003 .await
8004 .unwrap();
8005 state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8006 }
8007
8008 #[tokio::test]
8009 async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8010 let (tmp, mut state, head) = landing_git_fixture().await;
8011 git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8012 git::acquire_worktree_config(&state.repo).await.unwrap();
8013 let winner = tmp.path().join("landing");
8014 git::worktree_add_existing(&state.repo, &winner, "winner", false)
8015 .await
8016 .unwrap();
8017 state.candidates[0].worktree = winner.clone();
8018 state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8019 state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8020 state.config.disk.min_free_bytes = 0;
8021 state.config.worktree.setup = vec![crate::config::SetupStep {
8022 run: Some("touch setup-completed".into()),
8023 ..Default::default()
8024 }];
8025 #[cfg(unix)]
8026 {
8027 std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8028 state.config.coordination = Some(crate::config::Coordination {
8029 contract_file: "fixture-contract".into(),
8030 contract_token: "fixture-v1".into(),
8031 lock_file: "fixture-lock".into(),
8032 });
8033 }
8034 state.land_rebase_from = Some(head);
8035 let restore = restore_landing_worktree(&mut state);
8036 #[cfg(unix)]
8039 let restore = async {
8040 tokio::time::timeout(Duration::from_secs(15), restore)
8041 .await
8042 .expect("landing setup must not wait for its own repository operation")
8043 };
8044 restore.await.unwrap();
8045 assert!(winner.join("setup-completed").is_file());
8046 assert!(git::is_clean(&winner).await.unwrap());
8047 assert!(state.land_rebase_from.is_none());
8048 }
8049
8050 #[tokio::test]
8051 async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8052 for phase in 0..3 {
8053 let (_tmp, mut state, old) = landing_git_fixture().await;
8054 advance_landing_base(&state).await;
8055 landing_setup(&mut state).await;
8056 if phase > 0 {
8057 interrupt_landing_rebase(&mut state).await;
8058 if phase == 2 {
8059 git::sync_to_head(&state.repo).await.unwrap();
8061 assert!(!state.repo.join(".env").exists());
8062 }
8063 state = RunState::load(&state.id).unwrap();
8064 }
8065 let head = resume_observed_head(&mut state, &old).await.unwrap();
8066 assert_ne!(head, old);
8067 assert!(state.gate_allows_progress());
8068 assert!(state.land_rebase_from.is_none());
8069 assert_eq!(
8070 std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8071 "secret"
8072 );
8073 assert!(git::is_clean(&state.repo).await.unwrap());
8074 assert!(
8075 !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8076 .await
8077 .unwrap()
8078 .contains(".env")
8079 );
8080 }
8081 }
8082
8083 #[tokio::test]
8084 async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8085 let (_tmp, mut state, _) = landing_git_fixture().await;
8086 advance_landing_base(&state).await;
8087 landing_setup(&mut state).await;
8088 interrupt_landing_rebase(&mut state).await;
8089 let locals = [
8092 "local notes",
8093 #[cfg(unix)]
8094 "local\nnotes",
8095 ];
8096 let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8097 .await
8098 .unwrap();
8099 std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8100 for local in locals {
8101 std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8102 assert!(
8103 git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8104 .await
8105 .unwrap()
8106 .ok()
8107 );
8108 }
8109 restore_landing_worktree(&mut state).await.unwrap();
8110 for local in locals {
8111 assert_eq!(
8112 std::fs::read_to_string(state.repo.join(local)).unwrap(),
8113 "keep these notes"
8114 );
8115 }
8116 assert_eq!(
8117 std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8118 "secret"
8119 );
8120 assert!(git::is_clean(&state.repo).await.unwrap());
8121 assert!(state.land_rebase_from.is_none());
8122 }
8123
8124 #[tokio::test]
8125 async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8126 for local in ["advance", "advance/notes", "new-directory"] {
8127 let (_tmp, mut state, _) = landing_git_fixture().await;
8128 advance_landing_base(&state).await;
8129 git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8131 std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8132 std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8133 git::git(&state.repo, &["add", "."]).await.unwrap();
8134 git::git(&state.repo, &["commit", "-m", "add directory"])
8135 .await
8136 .unwrap();
8137 git::git(&state.repo, &["push", "origin", "main"])
8138 .await
8139 .unwrap();
8140 git::git(&state.repo, &["checkout", "winner"])
8141 .await
8142 .unwrap();
8143 let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8144 .await
8145 .unwrap();
8146 std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8147 let path = state.repo.join(local);
8148 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8149 std::fs::write(&path, "local notes").unwrap();
8150 interrupt_landing_rebase(&mut state).await;
8151 let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8152 let checkpoint = state.land_rebase_from.clone();
8153 let error = restore_landing_worktree(&mut state).await.unwrap_err();
8154 assert!(
8155 error.to_string().contains("conflicting with HEAD"),
8156 "{error:#}"
8157 );
8158 assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8159 assert_eq!(
8160 git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8161 before
8162 );
8163 assert_eq!(state.land_rebase_from, checkpoint);
8164 }
8165 }
8166
8167 #[tokio::test]
8168 async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8169 for interrupted in [false, true] {
8170 let (_tmp, mut state, old) = landing_git_fixture().await;
8171 assert!(state.config.worktree.setup.is_empty());
8172 let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8174 .await
8175 .unwrap();
8176 std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8177 state.config.verify.gate =
8178 vec!["mkdir -p target && printf artifact > target/probe".into()];
8179 state.gate_ran = false;
8180 resume_observed_head(&mut state, &old).await.unwrap();
8181 assert_eq!(
8182 std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8183 "artifact"
8184 );
8185 advance_landing_base(&state).await;
8186 if interrupted {
8187 interrupt_landing_rebase(&mut state).await;
8188 state = RunState::load(&state.id).unwrap();
8189 }
8190 state.config.verify.gate =
8191 vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8192 let head = resume_observed_head(&mut state, &old).await.unwrap();
8193 assert_ne!(head, old);
8194 assert!(state.gate_allows_progress());
8195 assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8196 assert_eq!(
8197 std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8198 "artifact"
8199 );
8200 assert!(state.land_rebase_from.is_none());
8201 assert_eq!(
8202 git::remote_head(&state.repo, "origin", "task-head")
8203 .await
8204 .unwrap(),
8205 Some(head.clone())
8206 );
8207 let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8208 land_with(&mut state, &green_pr().url, &forge)
8209 .await
8210 .unwrap();
8211 assert!(state.parked);
8212 assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8213 assert!(forge.argvs().is_empty());
8214 }
8215 }
8216
8217 #[tokio::test]
8218 #[cfg(unix)]
8219 async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8220 use std::os::fd::AsRawFd as _;
8221
8222 for interrupted in [false, true] {
8223 let (_tmp, mut state, _) = landing_git_fixture().await;
8224 advance_landing_base(&state).await;
8225 landing_setup(&mut state).await;
8226 if interrupted {
8227 interrupt_landing_rebase(&mut state).await;
8228 }
8229 state.config.worktree.setup =
8230 vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8231 let common = crate::repo_lock::common_dir(&state.repo)
8232 .await
8233 .unwrap()
8234 .unwrap();
8235 std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8236 state.config.coordination = crate::config::test_coordination();
8237 state.config.graph.timeout_resource_wait = 0;
8238 let external = std::fs::OpenOptions::new()
8239 .read(true)
8240 .write(true)
8241 .create(true)
8242 .truncate(false)
8243 .open(common.join("updater.lock"))
8244 .unwrap();
8245 let locked =
8247 unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8248 assert_eq!(locked, 0);
8249 let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8250 let checkpoint = state.land_rebase_from.clone();
8251 let error = restore_landing_worktree(&mut state).await.unwrap_err();
8252 assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8253 assert_eq!(
8254 git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8255 before
8256 );
8257 assert_eq!(state.land_rebase_from, checkpoint);
8258 assert_eq!(
8259 std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8260 "secret"
8261 );
8262
8263 drop(external);
8264 state.config.graph.timeout_resource_wait = 2;
8265 restore_landing_worktree(&mut state).await.unwrap();
8266 assert!(git::is_clean(&state.repo).await.unwrap());
8267 assert!(state.land_rebase_from.is_none());
8268 assert_eq!(
8269 std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8270 "restored"
8271 );
8272 }
8273 }
8274
8275 #[tokio::test]
8276 #[cfg(unix)]
8277 async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8278 use std::sync::atomic::{AtomicBool, Ordering};
8279
8280 let (_tmp, mut state, _) = landing_git_fixture().await;
8281 advance_landing_base(&state).await;
8282 landing_setup(&mut state).await;
8283 interrupt_landing_rebase(&mut state).await;
8284 let common = crate::repo_lock::common_dir(&state.repo)
8285 .await
8286 .unwrap()
8287 .unwrap();
8288 std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8289 state.config.coordination = crate::config::test_coordination();
8290 let holder = crate::repo_lock::SeatLease::for_checkout(
8291 &state.repo,
8292 true,
8293 state.config.coordination.as_ref(),
8294 )
8295 .await
8296 .unwrap();
8297 assert!(holder.is_some());
8298 let cancelled = Arc::new(AtomicBool::new(false));
8299 let signal = cancelled.clone();
8300 let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8301 signal.load(Ordering::SeqCst)
8302 });
8303 let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8304 let checkpoint = state.land_rebase_from.clone();
8305 let (result, ()) = tokio::join!(
8306 tokio::time::timeout(
8307 Duration::from_secs(2),
8308 wait.scope(restore_landing_worktree(&mut state)),
8309 ),
8310 async {
8311 tokio::time::sleep(Duration::from_millis(100)).await;
8312 cancelled.store(true, Ordering::SeqCst);
8313 }
8314 );
8315 let error = result
8316 .expect("cancellation must release the waiting driver")
8317 .unwrap_err();
8318 assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8319 assert_eq!(
8320 git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8321 before
8322 );
8323 assert_eq!(state.land_rebase_from, checkpoint);
8324 assert_eq!(
8325 std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8326 "secret"
8327 );
8328 drop(holder);
8329 restore_landing_worktree(&mut state).await.unwrap();
8330 assert!(state.land_rebase_from.is_none());
8331 assert!(git::is_clean(&state.repo).await.unwrap());
8332 }
8333
8334 #[tokio::test]
8335 #[cfg(unix)]
8336 async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8337 use std::sync::atomic::{AtomicBool, Ordering};
8338
8339 for e2e in [false, true] {
8340 let (_tmp, mut state, head) = landing_git_fixture().await;
8341 let common = crate::repo_lock::common_dir(&state.repo)
8342 .await
8343 .unwrap()
8344 .unwrap();
8345 std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8346 state.config.coordination = crate::config::test_coordination();
8347 if e2e {
8348 state.config.verify.e2e = vec!["true".into()];
8349 state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
8350 head: head.clone(),
8351 passed: false,
8352 outcomes: Vec::new(),
8353 });
8354 } else {
8355 state.config.verify.gate = vec!["true".into()];
8356 state.gate_ran = false;
8357 }
8358 let holder = crate::repo_lock::SeatLease::for_checkout(
8359 &state.repo,
8360 true,
8361 state.config.coordination.as_ref(),
8362 )
8363 .await
8364 .unwrap();
8365 assert!(holder.is_some());
8366 let cancelled = Arc::new(AtomicBool::new(false));
8367 let signal = cancelled.clone();
8368 let waiting = Arc::new(tokio::sync::Notify::new());
8369 let observed = waiting.clone();
8370 let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8371 observed.notify_one();
8372 signal.load(Ordering::SeqCst)
8373 });
8374 let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8375 let url = green_pr().url;
8376 let result = {
8377 let mut publishing =
8378 Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8379 tokio::time::timeout(Duration::from_secs(30), async {
8383 tokio::select! {
8384 result = &mut publishing => panic!(
8385 "verification must wait behind the held seat: {result:?}"
8386 ),
8387 () = waiting.notified() => {}
8388 }
8389 })
8390 .await
8391 .expect("verification must reach the inherited coordination wait");
8392 cancelled.store(true, Ordering::SeqCst);
8393 tokio::time::timeout(Duration::from_secs(2), publishing).await
8394 };
8395 let error = result
8396 .expect("cancellation must release the verification waiter")
8397 .unwrap_err();
8398 assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8399 assert!(error.to_string().contains("cancelled"), "{error:#}");
8400 assert!(forge.argvs().is_empty());
8401 assert_eq!(
8402 git::remote_head(&state.repo, "origin", "task-head")
8403 .await
8404 .unwrap(),
8405 Some(head.clone())
8406 );
8407 drop(holder);
8408 assert_eq!(
8410 publish_landing_head(&mut state, &head, &url, &forge)
8411 .await
8412 .unwrap(),
8413 head
8414 );
8415 }
8416 }
8417
8418 #[tokio::test]
8419 async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
8420 for staged in [false, true] {
8421 let (_tmp, mut state, old) = landing_git_fixture().await;
8422 advance_landing_base(&state).await;
8423 interrupt_landing_rebase(&mut state).await;
8424 std::fs::write(state.repo.join("change"), "user edit").unwrap();
8425 if staged {
8426 git::git(&state.repo, &["add", "change"]).await.unwrap();
8427 }
8428 assert!(resume_observed_head(&mut state, &old).await.is_err());
8429 assert_eq!(
8430 std::fs::read_to_string(state.repo.join("change")).unwrap(),
8431 "user edit"
8432 );
8433 assert_eq!(
8434 git::remote_head(&state.repo, "origin", "task-head")
8435 .await
8436 .unwrap(),
8437 Some(old)
8438 );
8439 }
8440 }
8441
8442 #[tokio::test]
8443 async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
8444 let (_tmp, mut state, head) = landing_git_fixture().await;
8445 let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8446 let id = state.id.clone();
8447 let pr = land_with(&mut state, &green_pr().url, &forge)
8448 .await
8449 .unwrap();
8450 assert_eq!(pr.state, PrLifecycle::Open);
8451 assert_eq!(state.id, id);
8452 assert!(state.parked);
8453 assert_eq!(state.status, RunStatus::Landing);
8454 assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8455 assert!(forge.argvs().is_empty());
8456
8457 state.land_sync_pending = true;
8458 std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
8459 let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
8460 closed.pr.state = PrLifecycle::Closed;
8461 let forge = Scripted::new(vec![closed], vec![]);
8462 assert_eq!(
8463 land_with(&mut state, &green_pr().url, &forge)
8464 .await
8465 .unwrap()
8466 .state,
8467 PrLifecycle::Closed
8468 );
8469 assert_eq!(
8470 std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
8471 "do not touch"
8472 );
8473 assert!(forge.argvs().is_empty());
8474 }
8475
8476 #[tokio::test]
8477 async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
8478 let (_tmp, mut state, old) = landing_git_fixture().await;
8479 advance_landing_base(&state).await;
8480 state.config.verify.gate = vec!["exit 1".into()];
8481 assert!(resume_observed_head(&mut state, &old).await.is_err());
8482 assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
8483 assert!(!state.gate_allows_progress());
8484 assert_eq!(
8485 git::remote_head(&state.repo, "origin", "task-head")
8486 .await
8487 .unwrap(),
8488 Some(old)
8489 );
8490 assert!(state.land_sync_pending);
8491 }
8492
8493 #[tokio::test]
8494 async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
8495 let (_tmp, mut state, old) = landing_git_fixture().await;
8496 advance_landing_base(&state).await;
8497 let pushed = resume_observed_head(&mut state, &old).await.unwrap();
8498 state.pr_pushed_head = Some(old.clone());
8500 state.land_sync_pending = true;
8501 assert_eq!(
8502 resume_observed_head(&mut state, &pushed).await.unwrap(),
8503 pushed
8504 );
8505 git::git(
8508 &state.repo,
8509 &["push", "--force", "origin", "main:refs/heads/task-head"],
8510 )
8511 .await
8512 .unwrap();
8513 assert!(
8514 publish_landing_head(
8515 &mut state,
8516 &pushed,
8517 &green_pr().url,
8518 &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
8519 )
8520 .await
8521 .unwrap_err()
8522 .to_string()
8523 .contains("publishing gated")
8524 );
8525 assert!(
8526 resume_observed_head(&mut state, "foreign-head")
8527 .await
8528 .is_err()
8529 );
8530 }
8531 #[tokio::test]
8532 async fn landing_publication_refuses_a_pr_closed_during_gate() {
8533 let (_tmp, mut state, head) = landing_git_fixture().await;
8534 let mut closed = seen(&head, Checks::Green, "CLEAN", false);
8535 closed.pr.state = PrLifecycle::Closed;
8536 let forge = Scripted::new(vec![closed], vec![]);
8537 assert!(
8538 publish_landing_head(&mut state, &head, &green_pr().url, &forge)
8539 .await
8540 .unwrap_err()
8541 .to_string()
8542 .contains("PR closed or merged")
8543 );
8544 }
8545
8546 fn winning_candidate(summary: &str) -> Candidate {
8548 Candidate {
8549 index: 0,
8550 label: 'A',
8551 agent: "opus".to_owned(),
8552 branch: "magi/x/A".to_owned(),
8553 worktree: PathBuf::from("/wt/A"),
8554 summary: summary.to_owned(),
8555 stat: String::new(),
8556 files: 1,
8557 commits: 1,
8558 empty: false,
8559 failed: None,
8560 verified_noop: None,
8561 duration_ms: 0,
8562 folded: false,
8563 }
8564 }
8565
8566 fn uncontested_tally() -> Tally {
8567 Tally {
8568 first_choice: BTreeMap::from([('A', 1)]),
8569 borda: BTreeMap::new(),
8570 winner: 'A',
8571 rankings: 1,
8572 unanimous_initial: true,
8573 deliberated: false,
8574 changed_votes: 0,
8575 unanimous_final: true,
8576 tie_break: None,
8577 judges: 1,
8578 present: 1,
8579 quorum: 1,
8580 met_quorum: true,
8581 uncontested: None,
8582 }
8583 }
8584
8585 fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
8586 ReviewRecord {
8587 attempts: 0,
8588 reviewer,
8589 agent: agent.to_owned(),
8590 summary: summary.to_owned(),
8591 findings: Vec::new(),
8592 vote: None,
8593 failed: None,
8594 duration_ms: 0,
8595 }
8596 }
8597
8598 fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
8599 let answered = reviews.len();
8600 ReviewRound {
8601 round,
8602 head: "abc1234".to_owned(),
8603 verified_head: None,
8604 verified_at: None,
8605 reviews,
8606 e2e: Vec::new(),
8607 verify_retried: false,
8608 e2e_deferred: false,
8609 e2e_defer_reason: None,
8610 fix: None,
8611 blocking: 0,
8612 answered,
8613 expected: answered,
8614 clean: true,
8615 progressed: false,
8616 vote_split: false,
8617 reconsideration: Vec::new(),
8618 verdict: None,
8619 }
8620 }
8621
8622 #[test]
8623 fn the_approval_panel_states_the_task_verbatim_in_either_language() {
8624 let en = panel();
8625 assert!(en.contains("Task"), "{en}");
8626 assert!(en.contains("add retries to the uploader"), "{en}");
8627
8628 let mut state = run_state();
8629 state.config.graph.language = "ja".to_owned();
8630 let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8631 assert!(ja.contains("タスク"), "{ja}");
8632 assert!(
8633 ja.contains("add retries to the uploader"),
8634 "the task itself is not translated: {ja}"
8635 );
8636 }
8637
8638 #[test]
8639 fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
8640 let html = panel();
8644 assert!(!html.contains("What changed"), "{html}");
8645 assert!(!html.contains("Review verdict"), "{html}");
8646 }
8647
8648 #[test]
8649 fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
8650 let mut state = run_state();
8651 state.candidates = vec![winning_candidate("")];
8652 state.tally = Some(uncontested_tally());
8653 let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8654 assert!(
8655 !html.contains("What changed"),
8656 "an empty summary must not render an empty box: {html}"
8657 );
8658 }
8659
8660 #[test]
8661 fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
8662 let mut state = run_state();
8663 state.candidates = vec![winning_candidate(
8664 "Added a retry loop around the uploader PUT call.",
8665 )];
8666 state.tally = Some(uncontested_tally());
8667 let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8668 assert!(en.contains("What changed"), "{en}");
8669 assert!(
8670 en.contains("Added a retry loop around the uploader PUT call."),
8671 "{en}"
8672 );
8673
8674 state.config.graph.language = "ja".to_owned();
8675 let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8676 assert!(ja.contains("変更内容"), "{ja}");
8677 assert!(
8678 ja.contains("Added a retry loop around the uploader PUT call."),
8679 "{ja}"
8680 );
8681 }
8682
8683 #[test]
8684 fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
8685 let mut state = run_state();
8686 state.reviews = vec![
8687 review_round(
8688 1,
8689 vec![review_record(1, "alpha", "found a race, sent back")],
8690 ),
8691 review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
8692 ];
8693 let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8694 assert!(en.contains("Review verdict"), "{en}");
8695 assert!(en.contains("race is fixed, clean"), "{en}");
8696 assert!(
8697 !en.contains("found a race, sent back"),
8698 "only the round that actually cleared the merge should show: {en}"
8699 );
8700
8701 state.config.graph.language = "ja".to_owned();
8702 let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8703 assert!(ja.contains("レビューの結論"), "{ja}");
8704 assert!(ja.contains("レビュアー"), "{ja}");
8705 assert!(ja.contains("race is fixed, clean"), "{ja}");
8706 }
8707
8708 fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
8714 ReviewRecord {
8715 attempts: 0,
8716 reviewer,
8717 agent: agent.to_owned(),
8718 summary: String::new(),
8719 findings: Vec::new(),
8720 vote: None,
8721 failed: Some(reason.to_owned()),
8722 duration_ms: 0,
8723 }
8724 }
8725
8726 #[test]
8727 fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
8728 let mut state = run_state();
8729 state.reviews = vec![review_round(
8730 1,
8731 vec![
8732 review_record(1, "alpha", "clean, nothing to add"),
8733 unanswered_review_record(2, "beta", "timed out"),
8734 ],
8735 )];
8736 let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8737 assert!(en.contains("clean, nothing to add"), "{en}");
8738 assert!(
8739 en.contains("produced no answer: timed out"),
8740 "a seat that never answered must say so, not render a blank box: {en}"
8741 );
8742 assert!(
8743 !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
8744 "no reviewer box may be left empty: {en}"
8745 );
8746
8747 state.config.graph.language = "ja".to_owned();
8748 let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8749 assert!(ja.contains("回答なし: timed out"), "{ja}");
8750 }
8751
8752 #[test]
8753 fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
8754 let html = panel();
8755 assert!(!html.contains("<script"), "no script survives the csp");
8756 assert!(!html.contains("<form"), "form-action is 'none'");
8757 let pr = green_pr();
8758 assert_eq!(
8759 html.matches("http").count(),
8760 html.matches(pr.url.as_str()).count(),
8761 "the only http url in the panel is the pull request's own link"
8762 );
8763 assert!(
8764 html.contains("target=\"_blank\""),
8765 "the PR link must open in a new tab so it escapes the iframe"
8766 );
8767 assert!(
8768 html.contains("rel=\"noopener noreferrer\""),
8769 "external links opening in new tabs must carry noopener noreferrer"
8770 );
8771 }
8772
8773 #[test]
8774 fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
8775 let html = panel();
8776 assert!(
8777 html.contains(">+</span>"),
8778 "an added line carries a `+` in the gutter, not only a background"
8779 );
8780 assert!(
8781 html.contains(">-</span>"),
8782 "a removed line carries a `-` in the gutter, not only a background"
8783 );
8784 assert!(
8785 html.contains(">new line</span>"),
8786 "the marker is moved to the gutter, so the body is printed once without it"
8787 );
8788 }
8789
8790 #[test]
8791 fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
8792 let total = DIFF_MAX_LINES + 100;
8793 let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
8794 let html = approval_panel(
8795 &run_state(),
8796 &green_pr(),
8797 NUMSTAT,
8798 &diff,
8799 &[],
8800 "feat: something long",
8801 );
8802 assert!(
8803 html.contains(&format!("100 of {total} diff lines omitted")),
8804 "the note must say exactly how much was cut"
8805 );
8806 assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
8807 assert!(
8808 !html.contains(&format!("line {DIFF_MAX_LINES}")),
8809 "nothing past the threshold is rendered"
8810 );
8811 assert!(
8812 html.contains("/repo/magi"),
8813 "the note says where the rest is"
8814 );
8815 }
8816
8817 #[test]
8818 fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
8819 let html = approval_panel(
8820 &run_state(),
8821 &green_pr(),
8822 "1\t2\tsrc/<b>&\"x\"'.rs",
8823 "",
8824 &[],
8825 "subject",
8826 );
8827 assert!(html.contains("src/<b>&"x"'.rs"));
8828 assert!(
8829 !html.contains("<b>"),
8830 "an agent-influenced path must never become markup"
8831 );
8832 }
8833
8834 #[tokio::test]
8835 async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
8836 let a = std::path::PathBuf::from("/repo/a");
8837 let b = std::path::PathBuf::from("/repo/b");
8838
8839 let held = repo_merge_lock(&a).lock_owned().await;
8840
8841 assert!(
8844 repo_merge_lock(&a).try_lock().is_err(),
8845 "a second merge into the same repository must not proceed concurrently"
8846 );
8847
8848 assert!(
8852 repo_merge_lock(&b).try_lock().is_ok(),
8853 "a different repository's merge lock must be independent"
8854 );
8855
8856 drop(held);
8857 assert!(
8858 repo_merge_lock(&a).try_lock().is_ok(),
8859 "the lock is released once the holder is done"
8860 );
8861 }
8862
8863 pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
8864 let mut state = landing_state();
8865 let mut rec = review_record(1, "alpha", "precise rejection reason");
8866 rec.vote = Some(if reject {
8867 crate::verdict::ReviewVote::Reject
8868 } else {
8869 crate::verdict::ReviewVote::Approve
8870 });
8871 if major {
8872 rec.findings = contested().findings;
8873 }
8874 let mut round = review_round(1, vec![rec]);
8875 round.clean = false;
8876 round.blocking = usize::from(major);
8877 state.reviews.push(round);
8878 state.config.graph.review_rounds = 1;
8879 state
8880 }
8881
8882 #[test]
8883 fn approval_policy_controls_are_independent_and_keep_all_reasons() {
8884 for every in [false, true] {
8885 for contested in [false, true] {
8886 for major in [false, true] {
8887 for reject in [false, true] {
8888 let mut state = repair_state(major, reject);
8889 state.config.graph.land_approval = every;
8890 state.config.graph.hold_contested_merge = contested;
8891 let reasons = approval_reasons(&state);
8892 assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
8893 assert_eq!(
8894 reasons.contains(&ApprovalReason::OpenBlockingFindings),
8895 contested && major
8896 );
8897 assert_eq!(
8898 reasons.contains(&ApprovalReason::FinalReject),
8899 contested && reject
8900 );
8901 assert_eq!(
8902 reasons.len(),
8903 usize::from(every)
8904 + usize::from(contested && major)
8905 + usize::from(contested && reject)
8906 );
8907 }
8908 }
8909 }
8910 }
8911 }
8912
8913 #[test]
8914 fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
8915 use crate::verdict::ReviewVote::{Approve, Reject};
8916 for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
8917 let mut state = repair_state(false, initial_reject);
8918 state.reviews[0]
8919 .reconsideration
8920 .push(crate::run::ReviewRevoteRecord {
8921 reviewer: 1,
8922 agent: "alpha".into(),
8923 vote: Some(final_vote),
8924 reason: "changed after reading the panel <evidence>".into(),
8925 failed: None,
8926 });
8927 assert_eq!(
8928 approval_reasons(&state).contains(&ApprovalReason::FinalReject),
8929 final_vote == Reject
8930 );
8931 for language in ["en", "ja"] {
8932 state.config.graph.language = language.into();
8933 let evidence = approval_evidence(&state);
8934 assert!(evidence.contains(&format!("→ {}", final_vote.label())));
8935 assert!(evidence.contains("changed after reading the panel <evidence>"));
8936 let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
8937 assert!(html.contains("changed after reading the panel <evidence>"));
8938 assert!(!html.contains("<evidence>"));
8939 }
8940 state.reviews[0].reconsideration[0].vote = None;
8941 state.reviews[0].reconsideration[0].failed = Some("timed out".into());
8942 assert_eq!(
8943 approval_reasons(&state).contains(&ApprovalReason::FinalReject),
8944 initial_reject
8945 );
8946 assert!(approval_evidence(&state).contains("timed out"));
8947 }
8948 }
8949
8950 #[tokio::test]
8951 async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
8952 for every in [false, true] {
8953 for contested in [false, true] {
8954 for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
8955 {
8956 let mut state = repair_state(major, reject);
8957 state.config.graph.land_approval = every;
8958 state.config.graph.hold_contested_merge = contested;
8959 let forge = Scripted::new(
8960 vec![seen("abc", Checks::Green, "CLEAN", false)],
8961 vec![(true, "")],
8962 );
8963 land_with(&mut state, URL, &forge).await.unwrap();
8964 let expected = every || (contested && (major || reject));
8965 assert_eq!(state.land_approval.is_some(), expected);
8966 assert_eq!(forge.calls().contains(&"merge"), !expected);
8967 if expected {
8968 assert!(state.parked);
8969 }
8970 }
8971 }
8972 }
8973 }
8974
8975 #[tokio::test]
8976 async fn reviewed_branch_hold_is_read_before_landing_decision() {
8977 for (base, control) in [
8978 (false, "land_approval"),
8979 (true, "land_approval"),
8980 (false, "hold_contested_merge"),
8981 ] {
8982 let (_tmp, mut state, _) = landing_git_fixture().await;
8983 state.config.graph.land_approval = base;
8984 state.config.graph.hold_contested_merge = false;
8985 state.reviewed_commits = Some(Vec::new());
8986 if control == "hold_contested_merge" {
8987 state.reviews = repair_state(false, true).reviews;
8988 }
8989 std::fs::write(
8990 state.repo.join("magi.toml"),
8991 format!("[graph]\n{control} = {}\n", !base),
8992 )
8993 .unwrap();
8994 git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
8995 git::git(&state.repo, &["commit", "-m", "approval policy"])
8996 .await
8997 .unwrap();
8998 let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8999 state.land_sync_pending = false;
9000 state.pr_pushed_head = Some(head.clone());
9001 state.gate_head = Some(head.clone());
9002 let forge = Scripted::new(
9003 vec![seen(&head, Checks::Green, "CLEAN", false)],
9004 vec![(true, "")],
9005 );
9006 land_with(&mut state, URL, &forge).await.unwrap();
9007 assert!(
9008 state.land_approval.is_some(),
9009 "base={base}, control={control}"
9010 );
9011 assert!(!forge.calls().contains(&"merge"));
9012 if !base {
9013 let question = ask::Questions::open()
9014 .get(&state.land_approval.as_ref().unwrap().question)
9015 .unwrap();
9016 assert!(question.detail.contains(&format!(
9017 "{control}=true from the reviewed branch's magi.toml"
9018 )));
9019 }
9020 }
9021 }
9022
9023 #[tokio::test]
9024 async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9025 for file in ["magi.toml", ".magi/config.toml"] {
9026 for control in crate::config::OwnerHold::ALL {
9027 let (_tmp, mut state, _) = landing_git_fixture().await;
9028 state.config.graph.land_approval = false;
9029 state.config.graph.hold_contested_merge = false;
9030 state.reviewed_commits = Some(Vec::new());
9031 if control == crate::config::OwnerHold::HoldContestedMerge {
9032 state.reviews = repair_state(false, true).reviews;
9033 }
9034 let config = state.repo.join(file);
9035 std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9036 std::fs::write(
9037 &config,
9038 format!(
9039 "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9040 control.key()
9041 ),
9042 )
9043 .unwrap();
9044 git::git(&state.repo, &["add", file]).await.unwrap();
9045 git::git(&state.repo, &["commit", "-m", "require approval"])
9046 .await
9047 .unwrap();
9048 let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9049 let gate = state.config.verify.gate.clone();
9050 state.observe_branch_owner_holds(&head).await;
9051 assert_eq!(state.config.verify.gate, gate);
9052 assert!(state.owner_hold(control));
9053 let holds = state.branch_owner_holds.clone();
9054 git::git(&state.repo, &["rm", file]).await.unwrap();
9055 git::git(&state.repo, &["commit", "-m", "remove config"])
9056 .await
9057 .unwrap();
9058 let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9059 state.save().unwrap();
9060 state = RunState::load(&state.id).unwrap();
9061 state.observe_branch_owner_holds(&later).await;
9062 assert_eq!(state.branch_owner_holds, holds);
9063 assert_eq!(state.branch_owner_holds[0].head, head);
9064 state.land_sync_pending = false;
9065 state.pr_pushed_head = Some(later.clone());
9066 state.gate_head = Some(later.clone());
9067 let forge = Scripted::new(
9068 vec![seen(&later, Checks::Green, "CLEAN", false)],
9069 vec![(true, "")],
9070 );
9071 land_with(&mut state, URL, &forge).await.unwrap();
9072 assert!(!forge.calls().contains(&"merge"));
9073 assert!(state.parked);
9074 let question = ask::Questions::open()
9075 .get(&state.land_approval.as_ref().unwrap().question)
9076 .unwrap();
9077 assert!(question.detail.contains("Approval required because:"));
9078 assert!(question.detail.contains(&format!(
9079 "{}=true from the reviewed branch's {file}",
9080 control.key()
9081 )));
9082 assert_eq!(state.branch_owner_holds, holds);
9083 state.save().unwrap();
9084 let resumed = RunState::load(&state.id).unwrap();
9085 assert!(resumed.owner_hold(control));
9086 assert_eq!(resumed.branch_owner_holds, holds);
9087 assert_eq!(
9088 resumed.land_approval.unwrap().question,
9089 state.land_approval.unwrap().question
9090 );
9091 }
9092 }
9093 }
9094
9095 #[tokio::test]
9096 async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9097 let mut state = repair_state(false, true);
9098 state.reviews[0].clean = true;
9099 let mut finding = contested().findings.remove(0);
9100 finding.severity = crate::verdict::Severity::Minor;
9101 state.reviews[0].reviews[0].findings.push(finding);
9102 assert!(state.open_findings().is_empty());
9103 let mut pr = green_pr();
9104 pr.review_comments.clear();
9105 for language in ["en", "ja"] {
9106 state.config.graph.language = language.into();
9107 let html = approval_panel(&state, &pr, "", "", &[], "subject");
9108 assert!(html.contains("[R3-1-1] minor"));
9109 assert!(html.contains(if language == "ja" {
9110 "内部指摘の解決を意味するものではありません"
9111 } else {
9112 "This does not mean internal findings are resolved"
9113 }));
9114 assert!(
9115 html.find(if language == "ja" {
9116 "承認が必要な理由:"
9117 } else {
9118 "Approval required because:"
9119 })
9120 .unwrap()
9121 < html.find("[R3-1-1]").unwrap()
9122 );
9123 }
9124 state.config.graph.language = "en".into();
9125 let observed = seen("abc", Checks::Green, "CLEAN", false);
9126 assert_eq!(
9127 approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9128 .await
9129 .unwrap(),
9130 ApprovalGate::Pending
9131 );
9132 let id = state.land_approval.as_ref().unwrap().question.clone();
9133 let q = ask::Questions::open().get(&id).unwrap();
9134 assert!(q.detail.starts_with("Approval required because:"));
9135 assert!(q.detail.contains("final reviewer reject"));
9136 assert!(q.detail.contains("[R3-1-1] minor"));
9137 assert!(
9138 q.detail
9139 .contains("No adoption or resolution evidence recorded")
9140 );
9141 state.config.graph.land_approval = false;
9142 state.config.graph.hold_contested_merge = false;
9143 state.reviews.clear();
9144 assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9145 assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9146 assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9147 let forge = Scripted::new(vec![observed], vec![]);
9148 land_with(&mut state, URL, &forge).await.unwrap();
9149 assert!(!forge.calls().contains(&"merge"));
9150 assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9151 assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9152 }
9153
9154 #[tokio::test]
9155 async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9156 let mut state = repair_state(false, true);
9157 state.config.graph.land_approval = false;
9158 let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9159 let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9160 let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9161 state.reviews[0].reviews[0].summary = long_reason.clone();
9162 for i in 1..=10 {
9163 let mut finding = contested().findings.remove(0);
9164 finding.id = format!("R1-1-{i}");
9165 finding.severity = if i == 9 {
9166 crate::verdict::Severity::Major
9167 } else {
9168 crate::verdict::Severity::Minor
9169 };
9170 finding.title = long_title.clone();
9171 finding.detail = long_detail.clone();
9172 state.reviews[0].reviews[0].findings.push(finding);
9173 }
9174 state.reviews[0].fix = Some(crate::run::FixRecord {
9175 agent: "fixer".into(),
9176 addressed: vec!["R1-1-9".into()],
9177 rejected: vec![crate::verdict::Rejection {
9178 id: "R1-1-10".into(),
9179 why: long_reason.clone(),
9180 }],
9181 notes: long_detail.clone(),
9182 committed: false,
9183 failed: None,
9184 duration_ms: 0,
9185 continuation: None,
9186 });
9187 assert_eq!(
9188 approval_reasons(&state),
9189 [
9190 ApprovalReason::OpenBlockingFindings,
9191 ApprovalReason::FinalReject
9192 ]
9193 );
9194 let excerpt = approval_excerpt(&long_reason, 300);
9195 assert_eq!(excerpt.chars().count(), 300);
9196 assert!(excerpt.ends_with('…'));
9197 let boundary = "拒".repeat(300);
9198 assert_eq!(approval_excerpt(&boundary, 300), boundary);
9199 for language in ["en", "ja"] {
9200 state.config.graph.language = language.into();
9201 for revote in [
9202 None,
9203 Some(crate::verdict::ReviewVote::Reject),
9204 Some(crate::verdict::ReviewVote::Approve),
9205 ] {
9206 state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9207 state.reviews[0].reconsideration.clear();
9208 if let Some(vote) = revote {
9209 state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9210 state.reviews[0]
9211 .reconsideration
9212 .push(crate::run::ReviewRevoteRecord {
9213 reviewer: 1,
9214 agent: "alpha".into(),
9215 vote: Some(vote),
9216 reason: long_reason.clone(),
9217 failed: None,
9218 });
9219 }
9220 let evidence = approval_evidence(&state);
9221 let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9222 assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9223 assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9224 assert_eq!(
9225 approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9226 final_vote == crate::verdict::ReviewVote::Reject
9227 );
9228 assert!(evidence.contains(&excerpt));
9229 assert!(evidence.contains("[R1-1-8] minor"));
9230 assert!(evidence.contains("[R1-1-9] major"));
9231 assert!(evidence.contains("[R1-1-10] minor"));
9232 for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9233 assert!(!evidence.contains(tail));
9234 }
9235 assert!(evidence.contains(if language == "ja" {
9236 "採用申告(解決未確認)"
9237 } else {
9238 "claimed addressed (resolution unconfirmed)"
9239 }));
9240 assert!(evidence.contains(if language == "ja" {
9241 "不採用理由"
9242 } else {
9243 "declined"
9244 }));
9245 let major_evidence = evidence
9246 .split("[R1-1-9] major")
9247 .nth(1)
9248 .unwrap()
9249 .split("[R1-1-10]")
9250 .next()
9251 .unwrap();
9252 assert!(major_evidence.contains(if language == "ja" {
9253 "採用申告(解決未確認)"
9254 } else {
9255 "claimed addressed (resolution unconfirmed)"
9256 }));
9257 let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9258 assert!(last_evidence.contains(if language == "ja" {
9259 "不採用理由"
9260 } else {
9261 "declined"
9262 }));
9263 let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9264 assert!(html.contains(&esc(&evidence)));
9265 assert_eq!(
9266 approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9267 .await
9268 .unwrap(),
9269 ApprovalGate::Pending
9270 );
9271 let id = &state.land_approval.take().unwrap().question;
9272 let q = ask::Questions::open().get(id).unwrap();
9273 assert!(q.detail.starts_with(&evidence));
9274 }
9275 state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9276 }
9277 }
9278
9279 #[test]
9280 fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9281 for (major, reject) in [(true, false), (false, true), (true, true)] {
9282 let state = repair_state(major, reject);
9283 assert!(repair_available(&state));
9284 assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9285 }
9286 assert!(!repair_available(&repair_state(false, false)));
9287 let mut clean = repair_state(true, false);
9288 clean.reviews[0].clean = true;
9289 assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9290 assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9291 }
9292
9293 #[tokio::test]
9294 async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9295 let mut state = repair_state(true, false);
9296 let pr = green_pr();
9297 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9298 .await
9299 .unwrap();
9300 let store = ask::Questions::open();
9301 let id = state.land_approval.as_ref().unwrap().question.clone();
9302 store
9304 .update(&id, |q| {
9305 q.choices = vec![APPROVE.into(), HOLD.into()];
9306 Ok(())
9307 })
9308 .unwrap();
9309 let upgraded = store.get(&id).unwrap();
9310 assert_eq!(upgraded.choices, approval_choices(&state));
9311 assert!(!upgraded.actions.contains_key(HOLD));
9312 assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9313 assert!(
9314 store
9315 .list()
9316 .iter()
9317 .any(|q| q.id == id && q.choices == upgraded.choices)
9318 );
9319 assert!(
9320 crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9321 );
9322 assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9323 store
9324 .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9325 .unwrap();
9326 store
9329 .update(&id, |q| {
9330 q.actions.clear();
9331 Ok(())
9332 })
9333 .unwrap();
9334 assert_eq!(
9335 store.get(&id).unwrap().chosen_action(),
9336 Some(&ask::ChoiceAction::Resume {
9337 run: state.id.clone()
9338 })
9339 );
9340 let binding = state.land_approval.clone();
9341 assert_eq!(
9342 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9343 .await
9344 .unwrap(),
9345 ApprovalGate::Repair
9346 );
9347 assert!(state.land_approval.is_none());
9348 assert_eq!(state.merge_repairs.len(), 1);
9349 let request = &state.merge_repairs[0];
9350 assert_eq!(request.question, id);
9351 assert_eq!(request.head, "abc");
9352 assert_eq!(request.pr, pr.url);
9353 assert_eq!(
9354 request.reviews[0].reviews[0].summary,
9355 "precise rejection reason"
9356 );
9357 assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9358 assert_eq!(
9359 request.reviews[0].reviews[0].findings[0].detail,
9360 state.reviews[0].reviews[0].findings[0].detail
9361 );
9362 state.land_approval = binding;
9364 assert_eq!(
9365 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9366 .await
9367 .unwrap(),
9368 ApprovalGate::Repair
9369 );
9370 assert_eq!(state.merge_repairs.len(), 1);
9371 state.land_approval = None;
9372 state.config.graph.land_approval = false;
9373 state.config.graph.hold_contested_merge = false;
9374 state.reviews.clear();
9375 assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9376 assert_eq!(
9377 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9378 .await
9379 .unwrap(),
9380 ApprovalGate::Pending
9381 );
9382 let fresh_id = &state.land_approval.as_ref().unwrap().question;
9383 assert_ne!(fresh_id, &id);
9384 let fresh = store.get(fresh_id).unwrap();
9385 assert!(
9386 fresh
9387 .detail
9388 .contains("fresh owner approval after merge repair")
9389 );
9390 assert!(fresh.detail.contains("No review recorded"));
9391 assert!(!fresh.detail.contains("precise rejection reason"));
9392 }
9393
9394 #[tokio::test]
9395 async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9396 for choice in [REPAIR, HOLD] {
9397 let mut state = repair_state(false, true);
9398 let observed = seen("abc", Checks::Green, "CLEAN", false);
9399 approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9400 .await
9401 .unwrap();
9402 let id = state.land_approval.as_ref().unwrap().question.clone();
9403 ask::Questions::open()
9404 .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9405 .unwrap();
9406 let forge = Scripted::new(vec![observed], vec![(true, "")]);
9407 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9408 .await
9409 .unwrap();
9410 assert!(
9411 forge
9412 .argvs()
9413 .iter()
9414 .all(|a| a.iter().any(|s| s == "--disable-auto"))
9415 );
9416 assert!(!forge.calls().contains(&"fix"));
9417 assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
9418 assert_ne!(state.status, RunStatus::Merged);
9419 }
9420 }
9421
9422 #[test]
9423 fn only_the_merge_choice_merges_and_silence_holds() {
9424 let table = [
9425 (None, Approval::Hold),
9426 (Some("merge"), Approval::Merge),
9427 (Some(" merge\n"), Approval::Merge),
9428 (Some("hold"), Approval::Hold),
9429 (Some(""), Approval::Hold),
9430 (Some("yes"), Approval::Hold),
9431 ];
9432 for (answer, want) in table {
9433 assert_eq!(
9434 approval(answer),
9435 want,
9436 "answer {answer:?} must resolve to {want:?}"
9437 );
9438 }
9439 }
9440
9441 #[tokio::test]
9442 async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
9443 let mut state = landing_state();
9444 state.config.graph.land_approval = true;
9445 let pr = green_pr();
9446
9447 let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9448 .await
9449 .unwrap();
9450 assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
9451 assert!(
9452 !state.parked,
9453 "approval_gate itself never sets `parked`; only its caller does"
9454 );
9455
9456 let store = ask::Questions::open();
9457 let filed: Vec<_> = store
9458 .list()
9459 .into_iter()
9460 .filter(|q| q.run == state.id)
9461 .collect();
9462 assert_eq!(filed.len(), 1, "exactly one question is filed");
9463 assert_eq!(filed[0].node, APPROVAL_NODE);
9464 assert_eq!(filed[0].choices, approval_choices(&state));
9465 assert!(filed[0].status.open());
9466
9467 let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9471 .await
9472 .unwrap();
9473 assert_eq!(again, ApprovalGate::Pending);
9474 let still_one = store
9475 .list()
9476 .into_iter()
9477 .filter(|q| q.run == state.id)
9478 .count();
9479 assert_eq!(
9480 still_one, 1,
9481 "asking twice must not double-file the question"
9482 );
9483 }
9484
9485 #[tokio::test]
9486 async fn approving_the_existing_question_is_read_back_as_approved() {
9487 crate::run::pin_test_home();
9488 let mut state = run_state();
9489 state.config.graph.land_approval = true;
9490 let pr = green_pr();
9491 assert_eq!(
9492 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9493 .await
9494 .unwrap(),
9495 ApprovalGate::Pending
9496 );
9497
9498 let store = ask::Questions::open();
9499 let mut q = store
9500 .list()
9501 .into_iter()
9502 .find(|q| q.run == state.id)
9503 .expect("filed above");
9504 let talks = crate::talk::Talks::open();
9505 let cfg = crate::config::Config {
9506 agents: vec![crate::config::AgentSpec {
9507 id: "mock".into(),
9508 kind: crate::config::AgentKind::Command,
9509 model: None,
9510 command: vec!["true".into()],
9511 extra_args: Vec::new(),
9512 env: Default::default(),
9513 prompt_delivery: None,
9514 max_turn_secs: None,
9515 }],
9516 ..crate::config::Config::default()
9517 };
9518 let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
9519 crate::consult::begin(&store, &talks, &q, &talk).unwrap();
9520 crate::talk::drain(&mut talk, &talks).unwrap();
9521 assert_eq!(
9522 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9523 .await
9524 .unwrap(),
9525 ApprovalGate::Pending,
9526 "consultation cannot approve or hold the merge"
9527 );
9528 q = store.get(&q.id).unwrap();
9529 assert!(q.answer.is_none());
9530 q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9532 store.put(&mut q).unwrap();
9533
9534 assert_eq!(
9535 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9536 .await
9537 .unwrap(),
9538 ApprovalGate::Approved
9539 );
9540 }
9541
9542 #[tokio::test]
9543 async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
9544 crate::run::pin_test_home();
9545 let store = ask::Questions::open();
9546 for via_list in [false, true] {
9547 let mut state = repair_state(false, true);
9548 let pr = green_pr();
9549 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9550 .await
9551 .unwrap();
9552 let id = state.land_approval.as_ref().unwrap().question.clone();
9553 store
9554 .update(&id, |q| {
9555 q.actions.insert(
9556 HOLD.to_owned(),
9557 ask::ChoiceAction::Resume {
9558 run: state.id.clone(),
9559 },
9560 );
9561 Ok(())
9562 })
9563 .unwrap();
9564 let q = if via_list {
9565 store.list().into_iter().find(|q| q.id == id).unwrap()
9566 } else {
9567 store.get(&id).unwrap()
9568 };
9569 assert!(!q.actions.contains_key(HOLD));
9570 store
9571 .update(&id, |q| {
9572 assert!(!q.actions.contains_key(HOLD));
9574 assert!(!upgrade_repair_choice(q, &state));
9575 q.answer(ask::Answer::Choice(HOLD.to_owned()))
9576 })
9577 .unwrap();
9578 assert!(store.get(&id).unwrap().chosen_action().is_none());
9579 assert_eq!(
9580 approval_gate(&mut state, &pr, "feat: x", None, "abc")
9581 .await
9582 .unwrap(),
9583 ApprovalGate::Held
9584 );
9585 }
9586 }
9587
9588 #[tokio::test]
9589 async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
9590 crate::run::pin_test_home();
9591 let store = ask::Questions::open();
9592
9593 let mut held_state = run_state();
9594 held_state.config.graph.land_approval = true;
9595 let pr = green_pr();
9596 approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9597 .await
9598 .unwrap();
9599 let mut q = store
9600 .list()
9601 .into_iter()
9602 .find(|q| q.run == held_state.id)
9603 .expect("filed above");
9604 q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
9605 store.put(&mut q).unwrap();
9606 assert_eq!(
9607 approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9608 .await
9609 .unwrap(),
9610 ApprovalGate::Held
9611 );
9612
9613 let mut abandoned_state = run_state();
9614 abandoned_state.config.graph.land_approval = true;
9615 approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9616 .await
9617 .unwrap();
9618 let mut q = store
9619 .list()
9620 .into_iter()
9621 .find(|q| q.run == abandoned_state.id)
9622 .expect("filed above");
9623 q.abandon("no answer within the timeout");
9624 store.put(&mut q).unwrap();
9625 assert_eq!(
9626 approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9627 .await
9628 .unwrap(),
9629 ApprovalGate::Pending,
9630 "an expired approval must ask again without merging"
9631 );
9632 assert_eq!(
9633 store.get(&q.id).unwrap().status,
9634 ask::QuestionStatus::Abandoned
9635 );
9636 assert_ne!(
9637 abandoned_state.land_approval.as_ref().unwrap().question,
9638 q.id
9639 );
9640 }
9641
9642 fn contested() -> ContestedHandoff {
9643 let finding = |id: &str, n: u32| crate::verdict::Finding {
9644 id: id.to_owned(),
9645 severity: crate::verdict::Severity::Major,
9646 file: Some("src/a.rs".to_owned()),
9647 line: Some(n),
9648 title: format!("problem {id}"),
9649 detail: String::new(),
9650 };
9651 ContestedHandoff {
9652 findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
9653 rejecters: vec![(1, "alpha".to_owned())],
9654 }
9655 }
9656
9657 #[test]
9658 fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
9659 let mut state = run_state();
9660 assert!(contested_to_ask(&state).is_none(), "nothing recorded");
9661 state.contested_handoff = Some(contested());
9662 assert!(contested_to_ask(&state).is_some());
9663 state.config.graph.hold_contested_merge = false;
9664 assert!(
9665 contested_to_ask(&state).is_none(),
9666 "the switch restores today"
9667 );
9668 }
9669
9670 #[test]
9671 fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
9672 let q = ask::Question::new(
9673 "run-1".to_owned(),
9674 APPROVAL_NODE.to_owned(),
9675 "land".to_owned(),
9676 "Merge?".to_owned(),
9677 String::new(),
9678 vec![APPROVE.to_owned(), HOLD.to_owned()],
9679 );
9680 let none = deputy_brief(&q, None);
9681 assert!(none.contains("could not be read"), "{none}");
9682 assert!(none.contains("Silence is a hold"), "{none}");
9683
9684 let mut state = run_state();
9685 state.pr = Some(crate::run::PrRecord {
9686 url: "https://example.test/pull/7".to_owned(),
9687 number: 7,
9688 state: "open".to_owned(),
9689 checks: "green".to_owned(),
9690 round: 0,
9691 rounds: 3,
9692 red_at_merge: Vec::new(),
9693 });
9694 state.contested_handoff = Some(contested());
9695 let b = deputy_brief(&q, Some(&state));
9696 assert!(b.contains("https://example.test/pull/7"), "{b}");
9697 assert!(b.contains("not recorded in this legacy question"), "{b}");
9698 assert!(!b.contains("This question was filed although"));
9699 state.contested_handoff = None;
9700 assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
9701 }
9702
9703 #[test]
9704 fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
9705 for lang in ["en", "ja"] {
9706 let mut cfg = crate::config::Config::default();
9707 cfg.graph.language = lang.to_owned();
9708 let w = words(&cfg.graph.language);
9709 let text = w.approval_detail(
9710 "https://github.com/yukimemi/magi/pull/42",
9711 "main",
9712 "feat: x",
9713 Some(&contested()),
9714 );
9715 assert!(text.contains("pull/42"), "{text}");
9716 assert!(
9717 text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
9718 "{text}"
9719 );
9720 assert!(text.contains("R3-1-5"), "{text}");
9721 assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
9722 assert!(text.contains("2"), "the rest are counted: {text}");
9723 assert!(text.contains("#1 (alpha)"), "{text}");
9724 }
9725 let plain = words("en").approval_detail("u", "main", "s", None);
9726 assert!(!plain.contains("reject"), "{plain}");
9727 }
9728
9729 #[tokio::test]
9730 async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
9731 crate::run::pin_test_home();
9732 let mut state = run_state();
9733 state.config.graph.land_approval = false;
9734 state.contested_handoff = Some(contested());
9735 let pr = green_pr();
9736 let c = contested_to_ask(&state);
9737 assert_eq!(
9738 approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9739 .await
9740 .unwrap(),
9741 ApprovalGate::Pending,
9742 "silence is a hold"
9743 );
9744 let store = ask::Questions::open();
9745 let filed: Vec<_> = store
9746 .list()
9747 .into_iter()
9748 .filter(|q| q.run == state.id)
9749 .collect();
9750 assert_eq!(filed.len(), 1);
9751 assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
9752
9753 assert_eq!(
9754 approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9755 .await
9756 .unwrap(),
9757 ApprovalGate::Pending
9758 );
9759 let mut q = store
9760 .list()
9761 .into_iter()
9762 .find(|q| q.run == state.id)
9763 .unwrap();
9764 assert_eq!(q.id, filed[0].id, "the same question after a resume");
9765 q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9766 store.put(&mut q).unwrap();
9767 assert_eq!(
9768 approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9769 .await
9770 .unwrap(),
9771 ApprovalGate::Approved
9772 );
9773 }
9774
9775 #[test]
9776 fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
9777 let rows = parse_numstat(NUMSTAT);
9778 assert_eq!(
9779 rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
9780 ["src/web.rs", "src/land.rs", "assets/logo.png"]
9781 );
9782 assert_eq!(rows[2].added, None, "a binary file has no line counts");
9783 }
9784 #[test]
9785 fn the_approval_speaks_the_language_the_repository_is_configured_for() {
9786 let mut state = run_state();
9790 state.config.graph.language = "ja".to_owned();
9791 let pr = green_pr();
9792 let commits = ["c1".to_owned()];
9793
9794 let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9795 assert!(ja.contains("lang=\"ja\""), "the document must declare it");
9796 assert!(ja.contains("squash されるコミット"), "{ja}");
9797 assert!(ja.contains("レビューコメント"), "{ja}");
9798 assert!(ja.contains("差分"), "{ja}");
9799 assert!(
9800 !ja.contains("Commits being squashed"),
9801 "no English left over"
9802 );
9803
9804 let w = words("ja");
9805 assert!(w.approval_summary(17, "feat: x").contains("マージ"));
9806 assert!(
9807 w.approval_detail("http://x/1", "main", "feat: x", None)
9808 .contains("パネル")
9809 );
9810
9811 assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
9813 assert!(ja.contains("feat: x"), "nor is the merge subject");
9814
9815 state.config.graph.language = "en".to_owned();
9818 let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9819 assert!(en.contains("Commits being squashed"), "{en}");
9820 assert_eq!(words("Klingon").html_lang, "en");
9821 }
9822
9823 #[test]
9827 fn pick_open_pr_classifies_by_count_and_base() {
9828 let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
9829 assert_eq!(
9830 pick_open_pr(one, "main").unwrap(),
9831 OpenPr::One {
9832 url: "https://x/pull/58".into(),
9833 title: "t".into()
9834 }
9835 );
9836 assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
9837 assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
9838 let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
9839 {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
9840 assert_eq!(
9841 pick_open_pr(two, "main").unwrap(),
9842 OpenPr::Many(vec!["u1".into(), "u2".into()])
9843 );
9844 let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
9846 assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
9847 assert!(pick_open_pr("not json", "main").is_err());
9848 assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
9850 assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
9851 }
9852
9853 #[test]
9854 fn pick_merged_pr_picks_the_unique_match() {
9855 let json = r#"[
9856 {"url": "https://github.com/o/r/pull/42", "number": 42,
9857 "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
9858 ]"#;
9859 let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9860 let found = pick_merged_pr(json, "main", created_at)
9861 .expect("valid json")
9862 .expect("one unambiguous match");
9863 assert_eq!(found.url, "https://github.com/o/r/pull/42");
9864 assert_eq!(found.number, 42);
9865 }
9866
9867 #[test]
9871 fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
9872 let json = r#"[
9873 {"url": "https://github.com/o/r/pull/42", "number": 42,
9874 "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
9875 {"url": "https://github.com/o/r/pull/43", "number": 43,
9876 "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
9877 ]"#;
9878 let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9879 assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9880 let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
9881 assert!(error.to_string().contains("ambiguous"), "{error:#}");
9882 }
9883
9884 #[test]
9888 fn pick_merged_pr_ignores_a_different_base_branch() {
9889 let json = r#"[
9890 {"url": "https://github.com/o/r/pull/42", "number": 42,
9891 "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
9892 ]"#;
9893 let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9894 assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9895 }
9896
9897 #[test]
9900 fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
9901 let json = r#"[
9902 {"url": "https://github.com/o/r/pull/42", "number": 42,
9903 "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
9904 ]"#;
9905 let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9906 assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9907 }
9908
9909 #[test]
9910 fn slug_of_pr_url_reads_host_owner_and_repo() {
9911 assert_eq!(
9912 slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
9913 Some("github.com/yukimemi/shun")
9914 );
9915 }
9916
9917 #[test]
9918 fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
9919 assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
9920 assert_eq!(slug_of_pr_url("not a url at all"), None);
9921 assert_eq!(slug_of_pr_url("https://github.com"), None);
9922 }
9923
9924 #[test]
9925 fn slug_of_repo_url_reads_host_owner_and_repo() {
9926 assert_eq!(
9927 slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
9928 Some("github.com/yukimemi/magi")
9929 );
9930 assert_eq!(slug_of_repo_url("https://github.com"), None);
9931 }
9932
9933 #[test]
9934 fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
9935 ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
9936 .expect("same repo, different case");
9937 }
9938
9939 #[test]
9944 fn ensure_same_repo_refuses_a_different_repo() {
9945 let err =
9946 ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
9947 let msg = format!("{err:#}");
9948 assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
9949 assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
9950 }
9951
9952 #[test]
9957 fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
9958 let err = ensure_same_repo(
9959 "github.com/yukimemi/magi",
9960 "github.example.com/yukimemi/magi",
9961 )
9962 .unwrap_err();
9963 let msg = format!("{err:#}");
9964 assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
9965 assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
9966 }
9967
9968 #[tokio::test]
9973 async fn find_external_merge_returns_none_without_a_winner() {
9974 let state = RunState::new(
9975 PathBuf::from("/no/such/repo"),
9976 "main".to_owned(),
9977 "0000000000000000000000000000000000000000".to_owned(),
9978 "irrelevant".to_owned(),
9979 crate::config::Config::default(),
9980 );
9981 assert_eq!(find_external_merge(&state).await.unwrap(), None);
9982 }
9983
9984 fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
9985 let mut run = RunState::new(
9986 PathBuf::from(repo),
9987 "main".to_owned(),
9988 "abcdef1234".to_owned(),
9989 "x".to_owned(),
9990 crate::config::Config::default(),
9991 );
9992 run.id = id.to_owned();
9993 run.status = status;
9994 run.driver_exited = true;
9995 run.pr = Some(crate::run::PrRecord {
9996 number: url.rsplit('/').next().unwrap().parse().unwrap(),
9997 url: url.to_owned(),
9998 state: state.to_owned(),
9999 checks: "red".to_owned(),
10000 round: 0,
10001 rounds: 2,
10002 red_at_merge: Vec::new(),
10003 });
10004 run.save_under(home).unwrap();
10005 }
10006
10007 fn recorded(home: &Path, id: &str) -> String {
10008 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10009 serde_json::from_str::<RunState>(&body)
10010 .unwrap()
10011 .pr
10012 .unwrap()
10013 .state
10014 }
10015
10016 const PR: &str = "https://github.com/o/r/pull/7";
10017
10018 #[test]
10019 fn write_through_updates_predecessors_and_siblings_only() {
10020 let tmp = tempfile::tempdir().unwrap();
10021 let h = tmp.path();
10022 pr_run(
10023 h,
10024 "20261004-100000-aaaa",
10025 "/repo/r",
10026 RunStatus::Superseded,
10027 PR,
10028 "open",
10029 );
10030 pr_run(
10031 h,
10032 "20261004-100100-bbbb",
10033 "/repo/r",
10034 RunStatus::Blocked,
10035 PR,
10036 "open",
10037 );
10038 pr_run(
10040 h,
10041 "20261004-100200-cccc",
10042 "/repo/r",
10043 RunStatus::Landing,
10044 PR,
10045 "open",
10046 );
10047 pr_run(
10049 h,
10050 "20261004-100300-dddd",
10051 "/repo/other",
10052 RunStatus::Blocked,
10053 "https://github.com/o/other/pull/7",
10054 "open",
10055 );
10056 pr_run(
10058 h,
10059 "20261004-100400-eeee",
10060 "/repo/r",
10061 RunStatus::Blocked,
10062 "https://github.com/o/r/pull/8",
10063 "open",
10064 );
10065 pr_run(
10066 h,
10067 "20261004-100500-ffff",
10068 "/repo/r",
10069 RunStatus::Merged,
10070 PR,
10071 "open",
10072 );
10073 let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10074
10075 assert_eq!(
10076 write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10077 2
10078 );
10079 assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10080 assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10081 assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10082 assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10083 assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10084 assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10086 assert_eq!(
10088 write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10089 0
10090 );
10091 let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10092 assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10093 }
10094
10095 #[test]
10096 fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10097 let home = tempfile::tempdir().unwrap();
10098 let live_id = "20261004-100000-aaaa";
10099 let unknown_id = "20261004-100100-bbbb";
10100 for id in [live_id, unknown_id] {
10101 pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10102 let mut s = RunState::load_under(id, home.path()).unwrap();
10103 s.driver_exited = false;
10104 s.driver_claimed = None;
10106 if id == live_id {
10107 s.driver_pid = Some(std::process::id());
10108 s.driver_started_at = crate::proc::process_started_at(std::process::id());
10109 }
10110 s.save_under(home.path()).unwrap();
10111 if id == unknown_id {
10112 assert_eq!(
10113 s.liveness_under(home.path(), false),
10114 crate::run::Liveness::Unknown
10115 );
10116 }
10117 }
10118 let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10119 assert_eq!(apply_pr_states(home.path(), &known), 0);
10120 for id in [live_id, unknown_id] {
10121 assert_eq!(recorded(home.path(), id), "open");
10122 }
10123 }
10124
10125 #[test]
10126 fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10127 let tmp = tempfile::tempdir().unwrap();
10128 let h = tmp.path();
10129 let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10130 pr_run(
10131 h,
10132 "20261004-100000-aaaa",
10133 "/repo/r",
10134 RunStatus::Superseded,
10135 &url(1),
10136 "open",
10137 );
10138 pr_run(
10139 h,
10140 "20261004-100100-bbbb",
10141 "/repo/r",
10142 RunStatus::Blocked,
10143 &url(2),
10144 "open",
10145 );
10146 pr_run(
10147 h,
10148 "20261004-100200-cccc",
10149 "/repo/r",
10150 RunStatus::Ready,
10151 &url(3),
10152 "open",
10153 );
10154 pr_run(
10155 h,
10156 "20261004-100300-dddd",
10157 "/repo/r",
10158 RunStatus::Ready,
10159 &url(4),
10160 "open",
10161 );
10162 pr_run(
10163 h,
10164 "20261004-100400-eeee",
10165 "/repo/r",
10166 RunStatus::Implementing,
10167 &url(1),
10168 "open",
10169 );
10170 assert_eq!(stale_open_prs(h).len(), 4);
10171
10172 let mut known = BTreeMap::new();
10173 known.insert(url(1), PrLifecycle::Merged);
10174 known.insert(url(2), PrLifecycle::Closed);
10175 known.insert(url(3), PrLifecycle::Open);
10176 assert_eq!(apply_pr_states(h, &known), 2);
10178 assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10179 assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10180 assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10181 assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10182 assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10183 assert_eq!(apply_pr_states(h, &known), 0);
10184 }
10185
10186 use std::collections::VecDeque;
10189 use std::sync::Mutex;
10190
10191 struct Scripted {
10194 public_repo: Option<PathBuf>,
10195 evidence: Mutex<Option<CiEvidence>>,
10196 views: Mutex<VecDeque<Seen>>,
10197 merges: Mutex<VecDeque<(bool, String)>>,
10198 fix: Mutex<Option<Fixed>>,
10199 log: Mutex<Vec<&'static str>>,
10200 argvs: Mutex<Vec<Vec<String>>>,
10201 required: Mutex<Option<BTreeSet<String>>>,
10202 merged: Mutex<bool>,
10205 queued: Mutex<bool>,
10206 unreadable_after_merge: Mutex<bool>,
10208 reruns: Mutex<Vec<String>>,
10210 rerun_fails: Mutex<bool>,
10211 clock: Mutex<i64>,
10213 }
10214
10215 impl Scripted {
10216 fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10217 Self {
10218 public_repo: None,
10219 evidence: Mutex::new(None),
10220 views: Mutex::new(views.into()),
10221 merges: Mutex::new(
10222 merges
10223 .into_iter()
10224 .map(|(ok, m)| (ok, m.to_owned()))
10225 .collect(),
10226 ),
10227 fix: Mutex::new(None),
10228 log: Mutex::new(Vec::new()),
10229 argvs: Mutex::new(Vec::new()),
10230 required: Mutex::new(None),
10231 merged: Mutex::new(false),
10232 queued: Mutex::new(false),
10233 unreadable_after_merge: Mutex::new(false),
10234 reruns: Mutex::new(Vec::new()),
10235 rerun_fails: Mutex::new(false),
10236 clock: Mutex::new(1_000),
10237 }
10238 }
10239 fn argvs(&self) -> Vec<Vec<String>> {
10240 self.argvs.lock().unwrap().clone()
10241 }
10242 fn calls(&self) -> Vec<&'static str> {
10243 self.log.lock().unwrap().clone()
10244 }
10245 }
10246
10247 impl Forge for Scripted {
10248 async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10249 self.evidence.lock().unwrap().clone()
10250 }
10251 async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10252 self.log.lock().unwrap().push("view");
10253 if *self.unreadable_after_merge.lock().unwrap()
10254 && !self.argvs.lock().unwrap().is_empty()
10255 {
10256 anyhow::bail!("forge unreachable");
10257 }
10258 let mut seen = {
10259 let mut v = self.views.lock().unwrap();
10260 if v.len() > 1 {
10261 v.pop_front().unwrap()
10262 } else {
10263 v[0].clone()
10264 }
10265 };
10266 if seen.head == "@published" {
10267 let head =
10268 git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10269 .await?
10270 .context("missing published head")?;
10271 seen.head.clone_from(&head);
10272 seen.rollup_head = head;
10273 }
10274 if *self.merged.lock().unwrap() {
10275 seen.pr.state = PrLifecycle::Merged;
10276 }
10277 Ok(seen)
10278 }
10279 async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10280 self.log.lock().unwrap().push("merge");
10281 self.argvs.lock().unwrap().push(argv.to_vec());
10282 let out = self
10283 .merges
10284 .lock()
10285 .unwrap()
10286 .pop_front()
10287 .expect("unscripted merge");
10288 if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10289 {
10290 *self.merged.lock().unwrap() = true;
10291 }
10292 Ok(out)
10293 }
10294 async fn poll(&self) {
10295 self.log.lock().unwrap().push("poll");
10296 *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10297 }
10298 async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10299 self.log.lock().unwrap().push("rerun");
10300 self.reruns.lock().unwrap().push(run.to_owned());
10301 if *self.rerun_fails.lock().unwrap() {
10302 anyhow::bail!("gh run rerun: no");
10303 }
10304 Ok(())
10305 }
10306 fn now(&self) -> i64 {
10307 *self.clock.lock().unwrap()
10308 }
10309 async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10310 self.required.lock().unwrap().clone()
10311 }
10312 async fn fix(
10313 &self,
10314 _state: &mut RunState,
10315 _pr: &PrState,
10316 _round: usize,
10317 _budget: usize,
10318 _reason: &str,
10319 _logs: &str,
10320 ) -> Result<Fixed> {
10321 self.log.lock().unwrap().push("fix");
10322 Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10323 }
10324 }
10325
10326 const REFUSED: &str =
10327 "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10328
10329 fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10330 let mut pr = green_pr();
10331 pr.checks = checks;
10332 pr.blocking = Blocking::of(merge_state);
10333 if !comments {
10334 pr.review_comments.clear();
10335 }
10336 Seen {
10337 pr,
10338 title: "feat: x".to_owned(),
10339 failing_urls: Vec::new(),
10340 head: head.to_owned(),
10341 rollup_head: head.to_owned(),
10342 merge_state: merge_state.to_owned(),
10343 contexts: Vec::new(),
10344 base: "main".to_owned(),
10345 }
10346 }
10347
10348 fn landing_state() -> RunState {
10349 crate::run::pin_test_home();
10350 let mut state = run_state();
10351 state.config.graph.land_approval = false;
10352 state
10353 }
10354
10355 #[test]
10356 fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10357 assert!(!awaiting_new_head(None, "aaa"));
10358 assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10359 assert!(awaiting_new_head(Some("abc123"), "def456"));
10360 assert!(awaiting_new_head(Some("abc123"), ""));
10361 }
10362
10363 #[test]
10364 fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10365 let open = |c, m: &str| seen("a", c, m, false);
10366 let table = [
10367 (None, false, Refused::Pending),
10368 (
10369 Some(open(Checks::Pending, "BLOCKED")),
10370 false,
10371 Refused::Pending,
10372 ),
10373 (
10374 Some(open(Checks::Unknown, "BLOCKED")),
10375 false,
10376 Refused::Pending,
10377 ),
10378 (
10379 Some(open(Checks::Green, "UNKNOWN")),
10380 false,
10381 Refused::Pending,
10382 ),
10383 (Some(open(Checks::Green, "")), false, Refused::Pending),
10384 (
10385 Some(open(Checks::Green, "BLOCKED")),
10386 false,
10387 Refused::Recheck,
10388 ),
10389 (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10390 ];
10391 for (after, rechecked, want) in table {
10392 assert_eq!(
10393 classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10394 want
10395 );
10396 }
10397 let mut closed = open(Checks::Green, "CLEAN");
10398 closed.pr.state = PrLifecycle::Closed;
10399 assert_eq!(
10400 classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10401 Refused::Final
10402 );
10403 }
10404
10405 #[test]
10406 fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10407 for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10408 let pr = seen("a", checks, "BEHIND", false).pr;
10409 assert_eq!(
10410 decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10411 Step::Rebase
10412 );
10413 }
10414 for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
10415 let current = seen("a", Checks::Green, status, false);
10416 assert_ne!(
10417 decide_with(¤t.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10418 Step::Rebase
10419 );
10420 assert_ne!(
10421 classify_refusal(Some(¤t), false, "a", CiExpectation::Expected),
10422 Refused::Behind
10423 );
10424 }
10425 let mut current = seen("a", Checks::Pending, "BEHIND", false);
10426 current.rollup_head = "old".into();
10427 assert_eq!(
10428 classify_refusal(Some(¤t), true, "a", CiExpectation::Expected),
10429 Refused::Behind
10430 );
10431 assert_eq!(
10432 classify_refusal(Some(¤t), true, "other", CiExpectation::Expected),
10433 Refused::Pending
10434 );
10435 current.pr.state = PrLifecycle::Closed;
10436 assert_eq!(
10437 classify_refusal(Some(¤t), true, "a", CiExpectation::Expected),
10438 Refused::Final
10439 );
10440 }
10441
10442 #[tokio::test]
10443 async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
10444 for boundary in ["initial", "premerge", "refusal"] {
10445 let (_tmp, mut state, old) = landing_git_fixture().await;
10446 state.land_sync_pending = false;
10447 advance_landing_base(&state).await;
10448 state.config.verify.gate = vec!["test -f advance".into()];
10449 state.config.verify.e2e = vec!["test -f advance".into()];
10450 approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
10451 .await
10452 .unwrap();
10453 let old_binding = state.land_approval.clone().unwrap();
10454 let store = ask::Questions::open();
10455 let mut question = store.get(&old_binding.question).unwrap();
10456 question
10457 .answer(ask::Answer::Choice(APPROVE.to_owned()))
10458 .unwrap();
10459 store.put(&mut question).unwrap();
10460 let mut views = Vec::new();
10461 if boundary != "initial" {
10462 views.push(seen(&old, Checks::Green, "CLEAN", false));
10463 }
10464 if boundary == "refusal" {
10465 views.push(seen(&old, Checks::Green, "CLEAN", false));
10466 }
10467 let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
10468 behind.rollup_head = "old-ci-head".into();
10469 views.push(behind);
10470 views.push(seen(&old, Checks::Green, "CLEAN", false));
10472 views.push(seen("@published", Checks::Pending, "CLEAN", false));
10473 views.push(seen("@published", Checks::Green, "CLEAN", false));
10474 let merges = if boundary == "refusal" {
10475 vec![(false, REFUSED)]
10476 } else {
10477 vec![]
10478 };
10479 let mut forge = Scripted::new(views, merges);
10480 forge.public_repo = Some(state.repo.clone());
10481 let run = state.id.clone();
10482 land_with(&mut state, URL, &forge).await.unwrap();
10483 let head = state.pr_pushed_head.clone().unwrap();
10484 assert_ne!(head, old, "{boundary}");
10485 assert_eq!(state.id, run);
10486 assert_eq!(state.pr_branch(), Some("task-head"));
10487 assert_eq!(state.winner().unwrap().branch, "winner");
10488 assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
10489 assert!(state.gate_allows_progress());
10490 let e2e = state.head_e2e.as_ref().unwrap();
10491 assert_eq!(e2e.head, head);
10492 assert!(e2e.passed);
10493 assert_eq!(state.land_sync_attempts, 1);
10494 assert!(!state.land_sync_pending);
10495 assert!(state.parked);
10496 let binding = state.land_approval.as_ref().unwrap();
10497 assert_eq!(binding.head, head);
10498 assert_ne!(binding.question, old_binding.question);
10499 assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
10500 let mut question = store.get(&binding.question).unwrap();
10502 question
10503 .answer(ask::Answer::Choice(APPROVE.to_owned()))
10504 .unwrap();
10505 store.put(&mut question).unwrap();
10506 let forge = Scripted::new(
10507 vec![seen(&head, Checks::Green, "CLEAN", false)],
10508 vec![(true, "")],
10509 );
10510 land_with(&mut state, URL, &forge).await.unwrap();
10511 assert_eq!(state.status, RunStatus::Merged);
10512 assert_eq!(
10513 value_of(&forge.argvs()[0], "--match-head-commit"),
10514 Some(head.as_str())
10515 );
10516 }
10517 }
10518
10519 #[tokio::test]
10520 async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
10521 let (_tmp, mut state, old) = landing_git_fixture().await;
10522 state.land_sync_pending = false;
10523 state.config.graph.land_approval = false;
10524 state.config.verify.gate = vec!["test -f advance && test -f change".into()];
10525 advance_landing_base(&state).await;
10526 let mut forge = Scripted::new(
10527 vec![
10528 seen(&old, Checks::Green, "CLEAN", false),
10529 seen(&old, Checks::Green, "CLEAN", false),
10530 seen(&old, Checks::Green, "BEHIND", false),
10531 seen(&old, Checks::Green, "CLEAN", false),
10534 seen("@published", Checks::Green, "CLEAN", false),
10535 ],
10536 vec![(false, REFUSED), (true, "")],
10537 );
10538 forge.public_repo = Some(state.repo.clone());
10539 land_with(&mut state, URL, &forge).await.unwrap();
10540 let head = state.pr_pushed_head.as_deref().unwrap();
10541 assert_ne!(head, old);
10542 assert_eq!(state.land_sync_attempts, 1);
10543 assert_eq!(state.gate_head.as_deref(), Some(head));
10544 assert_eq!(state.status, RunStatus::Merged);
10545 let requests = forge.argvs();
10546 assert_eq!(requests.len(), 2);
10547 assert_eq!(
10548 value_of(&requests[0], "--match-head-commit"),
10549 Some(old.as_str())
10550 );
10551 assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
10552 }
10553
10554 #[tokio::test]
10555 async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
10556 let (tmp, mut state, old) = landing_git_fixture().await;
10557 state.land_sync_pending = false;
10558 let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
10561 let commit = tmp.path().join("broken-commit");
10562 std::fs::write(
10563 &commit,
10564 format!(
10565 "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
10566 "f".repeat(40)
10567 ),
10568 )
10569 .unwrap();
10570 let replacement = git::git(
10571 &state.repo,
10572 &[
10573 "hash-object",
10574 "-t",
10575 "commit",
10576 "-w",
10577 commit.to_str().unwrap(),
10578 ],
10579 )
10580 .await
10581 .unwrap();
10582 git::git(&state.repo, &["replace", &old, replacement.trim()])
10583 .await
10584 .unwrap();
10585 let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10586 land_with(&mut state, URL, &forge).await.unwrap();
10587 assert_eq!(state.land_sync_attempts, 0);
10588 assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10589 assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10590 assert!(forge.argvs().is_empty());
10591 assert!(
10592 state.events.iter().any(|e| e.message.contains(
10593 "could not determine whether the landing head contains the fetched base"
10594 ))
10595 );
10596 }
10597
10598 #[tokio::test]
10599 async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
10600 let (_tmp, mut state, old) = landing_git_fixture().await;
10601 state.land_sync_pending = false;
10602 git::git(
10603 &state.repo,
10604 &["remote", "set-url", "origin", "missing-remote"],
10605 )
10606 .await
10607 .unwrap();
10608 let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10609 land_with(&mut state, URL, &forge).await.unwrap();
10610 assert_eq!(state.land_sync_attempts, 0);
10611 assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10612 assert!(
10613 state
10614 .events
10615 .iter()
10616 .any(|e| e.message.contains("cannot fetch landing base"))
10617 );
10618 assert!(forge.argvs().is_empty());
10619 }
10620
10621 #[tokio::test]
10622 async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
10623 let (_tmp, mut state, old) = landing_git_fixture().await;
10624 state.land_sync_pending = false;
10625 let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10626 land_with(&mut state, URL, &forge).await.unwrap();
10627 assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10628 assert_eq!(state.land_sync_attempts, 0);
10629 assert!(
10630 state
10631 .events
10632 .iter()
10633 .any(|e| e.message.contains("already included"))
10634 );
10635 advance_landing_base(&state).await;
10636 state.land_sync_attempts = state.config.graph.land_rounds;
10637 state.land_sync_pending = true;
10638 state.save().unwrap();
10639 let mut restored = RunState::load(&state.id).unwrap();
10640 assert!(
10641 resume_observed_head(&mut restored, &old)
10642 .await
10643 .unwrap_err()
10644 .to_string()
10645 .contains("budget exhausted")
10646 );
10647 assert_eq!(
10648 git::remote_head(&state.repo, "origin", "task-head")
10649 .await
10650 .unwrap(),
10651 Some(old)
10652 );
10653 }
10654
10655 #[tokio::test]
10656 async fn a_normal_landing_merges_on_the_first_look() {
10657 let mut state = landing_state();
10658 let forge = Scripted::new(
10659 vec![seen("a", Checks::Green, "CLEAN", false)],
10660 vec![(true, "")],
10661 );
10662 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10663 .await
10664 .unwrap();
10665 assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10667 assert_eq!(state.status, RunStatus::Merged);
10668 }
10669
10670 #[tokio::test]
10671 async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
10672 let mut state = landing_state();
10673 let forge = Scripted::new(
10674 vec![seen("a", Checks::Green, "CLEAN", false)],
10675 std::iter::repeat_n((true, ""), 100).collect(),
10676 );
10677 *forge.queued.lock().unwrap() = true;
10678 let task = async {
10679 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10680 .await
10681 .unwrap();
10682 };
10683 task.await;
10686 assert_ne!(state.status, RunStatus::Merged);
10687 }
10688
10689 #[tokio::test]
10690 async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
10691 let mut state = landing_state();
10692 let forge = Scripted::new(
10693 vec![seen("a", Checks::Green, "CLEAN", false)],
10694 std::iter::repeat_n((true, ""), 100).collect(),
10695 );
10696 *forge.unreadable_after_merge.lock().unwrap() = true;
10697 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10698 .await
10699 .ok();
10700 assert_ne!(state.status, RunStatus::Merged);
10701 }
10702
10703 #[tokio::test]
10704 async fn a_task_public_head_is_awaited_on_land_entry() {
10705 let mut state = landing_state();
10706 state.pr_head = Some("magi/task-abcd-1234".into());
10707 state.pr_pushed_head = Some("new".into());
10708 let forge = Scripted::new(
10709 vec![
10710 seen("old", Checks::Green, "CLEAN", false),
10711 seen("new", Checks::Green, "CLEAN", false),
10712 ],
10713 vec![(true, "")],
10714 );
10715 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10716 .await
10717 .unwrap();
10718 assert_eq!(
10719 forge.calls(),
10720 ["view", "poll", "view", "view", "merge", "view"]
10721 );
10722 assert_eq!(state.status, RunStatus::Merged);
10723 }
10724
10725 #[tokio::test]
10726 async fn a_superseded_public_head_owner_cannot_reenter_land() {
10727 let mut state = landing_state();
10728 state.pr_taken_over_by = Some("next".into());
10729 let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
10730 assert!(
10731 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10732 .await
10733 .is_err()
10734 );
10735 assert!(forge.calls().is_empty());
10736 }
10737
10738 #[tokio::test]
10739 async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
10740 let mut state = landing_state();
10741 let forge = Scripted::new(
10742 vec![
10743 seen("old", Checks::Green, "CLEAN", true),
10744 seen("old", Checks::Green, "CLEAN", true),
10746 seen("new", Checks::Pending, "BLOCKED", true),
10747 seen("new", Checks::Green, "CLEAN", true),
10748 ],
10749 vec![(true, "")],
10750 );
10751 *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10752 head: "NEW".to_owned(),
10753 });
10754 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10755 .await
10756 .unwrap();
10757 assert_eq!(
10758 forge.calls(),
10759 [
10760 "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
10761 "view"
10762 ]
10763 );
10764 assert_eq!(state.status, RunStatus::Merged);
10765 }
10766
10767 #[tokio::test]
10768 async fn a_head_that_never_arrives_stops_naming_both_commits() {
10769 let mut state = landing_state();
10770 let forge = Scripted::new(
10771 vec![
10772 seen("old", Checks::Green, "CLEAN", true),
10773 seen("someone-elses", Checks::Green, "CLEAN", true),
10774 ],
10775 vec![],
10776 );
10777 *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10778 head: "mine".to_owned(),
10779 });
10780 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10781 .await
10782 .unwrap();
10783 assert!(!forge.calls().contains(&"merge"));
10784 let why = state.merge.as_ref().unwrap().detail.clone();
10785 assert!(
10786 why.contains("mine") && why.contains("someone-elses"),
10787 "{why}"
10788 );
10789 assert_eq!(state.status, RunStatus::Blocked);
10790 }
10791
10792 #[tokio::test]
10793 async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
10794 let mut state = landing_state();
10795 let forge = Scripted::new(
10796 vec![
10797 seen("a", Checks::Green, "CLEAN", false),
10798 seen("a", Checks::Green, "CLEAN", false),
10799 seen("a", Checks::Pending, "BLOCKED", false),
10800 seen("a", Checks::Pending, "BLOCKED", false),
10801 seen("a", Checks::Green, "CLEAN", false),
10802 ],
10803 vec![(false, REFUSED), (true, "")],
10804 );
10805 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10806 .await
10807 .unwrap();
10808 assert_eq!(
10809 forge.calls(),
10810 [
10811 "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
10812 "view"
10813 ]
10814 );
10815 assert_eq!(state.status, RunStatus::Merged);
10816 }
10817
10818 #[tokio::test]
10819 async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
10820 let mut state = landing_state();
10821 let forge = Scripted::new(
10822 vec![
10823 seen("a", Checks::Green, "CLEAN", false),
10824 seen("a", Checks::Green, "BLOCKED", false),
10825 ],
10826 vec![(false, REFUSED), (false, REFUSED)],
10827 );
10828 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10829 .await
10830 .unwrap();
10831 assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
10833 let why = state.merge.as_ref().unwrap().detail.clone();
10834 assert!(
10835 why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
10836 "{why}"
10837 );
10838 assert_eq!(state.status, RunStatus::Blocked);
10839 }
10840
10841 #[test]
10842 fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
10843 assert_eq!(bound_head("abc", "abc", None), Some("abc"));
10844 assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
10845 assert_eq!(bound_head("old", "old", Some("new")), None);
10847 assert_eq!(bound_head("new", "old", Some("new")), None);
10849 assert_eq!(bound_head("new", "old", None), None);
10850 assert_eq!(bound_head("", "", None), None);
10852 assert_eq!(bound_head("", "", Some("new")), None);
10853 assert_eq!(bound_head("abc", "", None), None);
10854 }
10855
10856 fn view_json(head: &str) -> String {
10857 format!(
10858 r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
10859 "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
10860 "reviews":[],"comments":[]}}"#
10861 )
10862 }
10863
10864 fn node_json(oid: &str, check: &str, has_next: bool) -> String {
10865 format!(
10866 r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
10867 {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
10868 "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
10869 "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
10870 )
10871 }
10872
10873 #[test]
10874 fn rollup_is_bound_to_the_commit_in_the_same_node() {
10875 let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
10878 assert_eq!(s.rollup_head, "old");
10879 assert_eq!(s.pr.checks, Checks::Red);
10880 assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
10881 assert_eq!(s.failing_urls.len(), 1);
10882 }
10883
10884 #[test]
10885 fn checks_come_from_the_node_not_the_view() {
10886 let view = view_json("new").replace(
10887 r#""reviews""#,
10888 r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
10889 );
10890 let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
10891 assert_eq!(s.pr.checks, Checks::Green);
10892 assert!(s.pr.failing.is_empty());
10893 assert_eq!(
10894 bound_head(&s.head, &s.rollup_head, Some("new")),
10895 Some("new")
10896 );
10897 }
10898
10899 #[test]
10900 fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
10901 for node in [
10902 None,
10903 Some("not json".to_owned()),
10904 Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
10905 Some(node_json("new", "SUCCESS", true)),
10906 ] {
10907 let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
10908 assert!(s.rollup_head.is_empty());
10909 assert_eq!(s.pr.checks, Checks::Unknown);
10910 assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
10911 }
10912 }
10913
10914 #[test]
10915 fn the_merge_command_is_pinned_to_the_observed_head() {
10916 let argv = merge_argv_at(7, "feat: x", "deadbeef");
10917 let at = argv
10918 .iter()
10919 .position(|a| a == "--match-head-commit")
10920 .unwrap();
10921 assert_eq!(argv[at + 1], "deadbeef");
10922 }
10923
10924 #[tokio::test]
10925 async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
10926 let mut state = landing_state();
10927 let mut stale = seen("new", Checks::Red, "CLEAN", false);
10930 stale.rollup_head = "old".to_owned();
10931 let forge = Scripted::new(
10932 vec![seen("old", Checks::Green, "CLEAN", true), stale],
10933 vec![],
10934 );
10935 *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10936 head: "new".to_owned(),
10937 });
10938 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10939 .await
10940 .unwrap();
10941 assert!(!forge.calls().contains(&"merge"));
10942 assert_eq!(state.status, RunStatus::Blocked);
10943 let why = state.merge.as_ref().unwrap().detail.clone();
10944 assert!(why.contains("new") && why.contains("old"), "{why}");
10945 }
10946
10947 #[test]
10948 fn a_refusal_read_against_another_commits_checks_is_pending() {
10949 let mut after = seen("a", Checks::Green, "BLOCKED", false);
10950 after.rollup_head = "old".to_owned();
10951 assert_eq!(
10952 classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
10953 Refused::Pending
10954 );
10955 }
10956
10957 #[tokio::test]
10958 async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
10959 let mut state = landing_state();
10960 state.config.merge.ci = crate::config::MergeCi::None;
10961 state.config.graph.land_approval = true;
10962 let forge = Scripted::new(
10963 vec![seen("a", Checks::Unknown, "CLEAN", false)],
10964 vec![(true, "")],
10965 );
10966 land_with(&mut state, URL, &forge).await.unwrap();
10967 assert!(state.parked);
10968 assert_eq!(forge.calls(), ["view"]);
10969 let store = ask::Questions::open();
10970 let mut q = store
10971 .get(&state.land_approval.as_ref().unwrap().question)
10972 .unwrap();
10973 q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10974 store.put(&mut q).unwrap();
10975
10976 land_with(&mut state, URL, &forge).await.unwrap();
10977 assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
10978 assert_eq!(state.status, RunStatus::Merged);
10979 assert_eq!(
10980 value_of(&forge.argvs()[0], "--match-head-commit"),
10981 Some("a")
10982 );
10983 }
10984
10985 #[tokio::test]
10986 async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
10987 let mut state = landing_state();
10988 state.config.merge.ci = crate::config::MergeCi::None;
10989 let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
10990 land_with(&mut state, URL, &forge).await.unwrap();
10991 assert!(forge.reruns.lock().unwrap().is_empty());
10992 assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10993 assert_eq!(state.status, RunStatus::Merged);
10994 }
10995
10996 #[test]
10997 fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
10998 let shown = BTreeSet::new();
10999 let guard = |s: Option<&Seen>| {
11000 direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11001 };
11002 let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11003 assert!(guard(Some(&fresh)));
11004 assert!(!guard(None));
11005 fresh.rollup_head = "old".to_owned();
11006 assert!(!guard(Some(&fresh)));
11007 fresh.rollup_head = "a".to_owned();
11008 fresh.head = "b".to_owned();
11009 assert!(!guard(Some(&fresh)));
11010 assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11011 assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11012 }
11013
11014 #[test]
11015 fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11016 for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11017 let after = seen("a", checks, "BLOCKED", false);
11018 assert_eq!(
11019 classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11020 Refused::Recheck
11021 );
11022 assert_eq!(
11023 classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11024 Refused::Final
11025 );
11026 }
11027 }
11028
11029 #[tokio::test]
11030 async fn a_matching_head_with_red_non_required_checks_still_merges() {
11031 let mut state = landing_state();
11032 let forge = Scripted::new(
11033 vec![seen("a", Checks::Red, "CLEAN", false)],
11034 vec![(true, "")],
11035 );
11036 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11037 .await
11038 .unwrap();
11039 assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11040 assert_eq!(state.status, RunStatus::Merged);
11041 }
11042
11043 #[tokio::test]
11044 async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11045 let mut state = landing_state();
11046 let forge = Scripted::new(
11047 vec![
11048 seen("a", Checks::Green, "CLEAN", false),
11049 seen("a", Checks::Green, "CLEAN", false),
11050 seen("b", Checks::Green, "BLOCKED", false),
11052 seen("b", Checks::Green, "CLEAN", false),
11053 ],
11054 vec![(false, REFUSED), (true, "")],
11055 );
11056 land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11057 .await
11058 .unwrap();
11059 assert_eq!(
11060 forge.calls(),
11061 [
11062 "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
11063 ]
11064 );
11065 assert_eq!(state.status, RunStatus::Merged);
11066 }
11067
11068 fn merged_view(head: &str) -> Seen {
11069 let mut m = seen(head, Checks::Green, "CLEAN", false);
11070 m.pr.state = PrLifecycle::Merged;
11071 m
11072 }
11073
11074 fn has(argv: &[String], flag: &str) -> bool {
11075 argv.iter().any(|a| a == flag)
11076 }
11077
11078 fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11079 let at = argv.iter().position(|a| a == flag)?;
11080 argv.get(at + 1).map(String::as_str)
11081 }
11082
11083 const URL: &str = "https://github.com/o/r/pull/42";
11084
11085 #[tokio::test]
11086 async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11087 let mut state = landing_state();
11088 let forge = Scripted::new(
11089 vec![
11090 seen("abc", Checks::Green, "CLEAN", false),
11091 seen("abc", Checks::Green, "CLEAN", false),
11092 ],
11093 vec![(true, "")],
11094 );
11095 land_with(&mut state, URL, &forge).await.unwrap();
11096 assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11097 let argv = &forge.argvs()[0];
11098 assert!(has(argv, "--squash") && has(argv, "--subject"));
11099 assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11100 assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11101 assert_eq!(state.status, RunStatus::Merged);
11102 assert!(state.land_armed_head.is_none());
11103 }
11104
11105 #[tokio::test]
11106 async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11107 let mut state = landing_state();
11108 state.land_armed_head = Some("a".to_owned());
11109 let forge = Scripted::new(
11110 vec![seen("a", Checks::Green, "CLEAN", false)],
11111 vec![(true, ""), (true, "")],
11112 );
11113 land_with(&mut state, URL, &forge).await.unwrap();
11114 let argvs = forge.argvs();
11115 assert!(has(&argvs[0], "--disable-auto"));
11116 assert!(!has(&argvs[1], "--auto"));
11117 assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11118 assert_eq!(state.status, RunStatus::Merged);
11119 assert!(state.land_armed_head.is_none());
11120 }
11121
11122 #[tokio::test]
11123 async fn an_approval_never_carries_over_to_a_new_head() {
11124 crate::run::pin_test_home();
11125 let mut state = run_state();
11126 state.config.graph.land_approval = true;
11127 let pr = green_pr();
11128 let store = ask::Questions::open();
11129
11130 approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11131 .await
11132 .unwrap();
11133 let mut q = store
11134 .list()
11135 .into_iter()
11136 .find(|q| q.run == state.id)
11137 .unwrap();
11138 q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11139 store.put(&mut q).unwrap();
11140 assert_eq!(
11141 approval_gate(&mut state, &pr, "feat: x", None, "AAA")
11142 .await
11143 .unwrap(),
11144 ApprovalGate::Approved,
11145 "the same head keeps its approval"
11146 );
11147
11148 assert_eq!(
11150 approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11151 .await
11152 .unwrap(),
11153 ApprovalGate::Pending
11154 );
11155 let all: Vec<_> = store
11156 .list()
11157 .into_iter()
11158 .filter(|q| q.run == state.id)
11159 .collect();
11160 assert_eq!(all.len(), 2);
11161
11162 state.land_approval = None;
11164 assert_eq!(
11165 approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11166 .await
11167 .unwrap(),
11168 ApprovalGate::Pending
11169 );
11170 let open = store
11171 .list()
11172 .into_iter()
11173 .filter(|q| q.run == state.id && q.status.open())
11174 .count();
11175 assert_eq!(open, 1, "the superseded question was retired");
11176 }
11177
11178 #[tokio::test]
11179 async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11180 let mut state = landing_state();
11181 let forge = Scripted::new(
11182 vec![
11183 seen("a", Checks::Green, "CLEAN", false),
11184 seen("b", Checks::Green, "CLEAN", false),
11186 ],
11187 vec![(true, "")],
11188 );
11189 land_with(&mut state, URL, &forge).await.unwrap();
11190 let argvs = forge.argvs();
11191 assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11192 assert!(!has(&argvs[0], "--auto"));
11193 assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11194 assert_eq!(state.status, RunStatus::Merged);
11195 }
11196
11197 fn passing(label: &str) -> CheckInfo {
11198 CheckInfo {
11199 label: label.to_owned(),
11200 verdict: Verdict::Pass,
11201 required: Some(false),
11202 run: None,
11203 }
11204 }
11205
11206 fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11207 (label.to_owned(), run.map(str::to_owned))
11208 }
11209
11210 fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11211 LandReruns {
11212 head: head.to_owned(),
11213 runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11214 }
11215 }
11216
11217 #[test]
11218 fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11219 let f = [failing("test (macos)", Some("7"))];
11220 assert_eq!(
11221 rerun_step(&f, None, "h", 100),
11222 RerunStep::Rerun(vec!["7".to_owned()])
11223 );
11224 let rec = reran("h", &[("7", 100)]);
11225 let grace = crate::release_watch::RERUN_GRACE;
11226 assert_eq!(
11227 rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11228 RerunStep::Grace
11229 );
11230 assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11231 }
11232
11233 #[test]
11234 fn a_failure_without_a_run_id_goes_to_the_fixer() {
11235 let f = [failing("a", Some("7")), failing("ci/external", None)];
11236 assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11237 assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11238 }
11239
11240 #[test]
11241 fn a_moved_head_forgets_the_reruns() {
11242 let f = [failing("a", Some("7"))];
11243 let rec = reran("old", &[("7", 100)]);
11244 assert_eq!(
11245 rerun_step(&f, Some(&rec), "new", 101),
11246 RerunStep::Rerun(vec!["7".to_owned()])
11247 );
11248 }
11249
11250 #[test]
11251 fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11252 let f = [
11253 failing("a", Some("7")),
11254 failing("b", Some("7")),
11255 failing("c", Some("8")),
11256 ];
11257 assert_eq!(
11258 rerun_step(&f, None, "h", 0),
11259 RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11260 );
11261 let rec = reran("h", &[("7", 0)]);
11262 assert_eq!(
11263 rerun_step(&f, Some(&rec), "h", 1),
11264 RerunStep::Rerun(vec!["8".to_owned()])
11265 );
11266 }
11267
11268 #[test]
11269 fn only_blocking_failures_are_candidates_for_a_rerun() {
11270 let check = |label: &str, verdict, required, run: &str| CheckInfo {
11271 label: label.to_owned(),
11272 verdict,
11273 required,
11274 run: Some(run.to_owned()),
11275 };
11276 let got = rerunnable(&[
11277 check("passed", Verdict::Pass, Some(true), "1"),
11278 check("optional", Verdict::Fail, Some(false), "2"),
11279 check("required", Verdict::Fail, Some(true), "3"),
11280 check("unknown", Verdict::Fail, None, "4"),
11281 ]);
11282 let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11283 assert_eq!(labels, ["required", "unknown"]);
11284 }
11285
11286 fn unrelated_ci_fixture() -> CiEvidence {
11287 let failure = CiFailure {
11288 path: "tests/web_render.rs".into(),
11289 start_line: 42,
11290 end_line: 42,
11291 title: "question_identity_disclosure_copy_and_live_updates".into(),
11292 message: "assertion failed".into(),
11293 };
11294 CiEvidence {
11295 head: "a".into(),
11296 base: "base-sha".into(),
11297 changed: vec![
11298 "AGENTS.md".into(),
11299 "src/talk.rs".into(),
11300 "tests/consult_investigation.rs".into(),
11301 ],
11302 checks: vec![CiCheckEvidence {
11303 label: "coverage".into(),
11304 head_check: 70,
11305 base_check: 60,
11306 app: 1,
11307 run: "7".into(),
11308 base_run: "6".into(),
11309 head_failures: vec![failure.clone()],
11310 base_failures: vec![failure],
11311 rerun_exhausted: true,
11312 }],
11313 }
11314 }
11315
11316 #[test]
11317 fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11318 let good = unrelated_ci_fixture();
11319 let red = vec!["coverage".into()];
11320 assert!(good.unrelated("a", &red));
11321 assert!(!good.unrelated("another-head", &red));
11322 assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11323 assert!(!good.unrelated("a", &[]));
11324 for mutation in 0..8 {
11325 let mut bad = good.clone();
11326 match mutation {
11327 0 => bad.checks[0].rerun_exhausted = false,
11328 1 => bad.checks[0].base_failures.clear(),
11329 2 => bad.checks[0].head_failures.clear(),
11330 3 => bad.changed.push("tests/web_render.rs".into()),
11331 4 => bad.changed.push(".github/workflows/ci.yml".into()),
11332 5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11333 6 => bad.checks.push(bad.checks[0].clone()),
11334 _ => bad.base.clear(),
11335 }
11336 assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11337 }
11338 }
11339
11340 #[test]
11341 fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11342 let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11343 assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11344 assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11345 assert!(matches!(
11346 decide(&pr, 2, 2, CHECKS_GRACE),
11347 Step::GiveUp { .. }
11348 ));
11349 let optional = CheckInfo {
11350 label: "coverage".into(),
11351 verdict: Verdict::Fail,
11352 required: Some(false),
11353 run: Some("7".into()),
11354 };
11355 assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11356 assert_eq!(
11357 rerunnable_with(&[optional], true),
11358 vec![("coverage".into(), Some("7".into()))]
11359 );
11360 }
11361
11362 #[tokio::test]
11363 async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11364 let mut state = landing_state();
11365 let mut red = coverage_unknown();
11366 red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11367 red.pr.failing = vec!["coverage".into()];
11368 let forge = Scripted::new(vec![red], vec![]);
11369 *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11370 *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11371 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11372 assert!(forge.calls().contains(&"fix"));
11373 assert!(state.land_unrelated.is_some());
11374 assert!(state.parked);
11375 assert!(
11376 !state
11377 .events
11378 .iter()
11379 .any(|e| e.message.contains("fixer produced no commit"))
11380 );
11381 }
11382
11383 fn coverage_unknown() -> Seen {
11384 let mut s = red("a", Some("7"));
11385 s.pr.blocking = Blocking::Unsaid;
11386 s.merge_state = "UNKNOWN".into();
11387 s.pr.failing = vec!["coverage".into()];
11388 s.contexts[0].label = "coverage".into();
11389 s.contexts[0].required = Some(false);
11390 s
11391 }
11392
11393 #[tokio::test]
11394 async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11395 let mut state = landing_state();
11396 let unknown = coverage_unknown();
11397 let mut unstable = unknown.clone();
11398 unstable.pr.blocking = Blocking::of("UNSTABLE");
11399 unstable.merge_state = "UNSTABLE".into();
11400 let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11401 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11402 assert!(!forge.calls().contains(&"fix"));
11403 assert!(!forge.calls().contains(&"rerun"));
11404 assert_eq!(state.status, RunStatus::Merged);
11405 assert_eq!(state.pr.unwrap().round, 0);
11406 }
11407
11408 #[tokio::test]
11409 async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11410 let mut state = landing_state();
11411 let forge = Scripted::new(vec![coverage_unknown()], vec![]);
11412 *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11413 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11414 assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11415 assert!(!forge.calls().contains(&"fix"));
11416 assert!(state.parked);
11417 assert_eq!(state.status, RunStatus::Landing);
11418 assert_eq!(state.pr.as_ref().unwrap().round, 0);
11419 let hold = state.land_unrelated.as_ref().unwrap();
11420 let q = ask::Questions::open().get(&hold.question).unwrap();
11421 assert!(
11422 q.actions
11423 .values()
11424 .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
11425 );
11426 assert!(
11427 state
11428 .events
11429 .iter()
11430 .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
11431 );
11432 let first = state.land_unsaid.clone();
11433 state.parked = false;
11435 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11436 assert_eq!(state.land_unsaid, first);
11437 assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11438 }
11439
11440 fn red(head: &str, run: Option<&str>) -> Seen {
11441 let mut s = seen(head, Checks::Red, "BLOCKED", false);
11442 s.pr.failing = vec!["test (macos)".to_owned()];
11443 s.contexts = vec![CheckInfo {
11444 label: "test (macos)".to_owned(),
11445 verdict: Verdict::Fail,
11446 required: Some(true),
11447 run: run.map(str::to_owned),
11448 }];
11449 s
11450 }
11451
11452 const RERUN_PR: &str = "https://github.com/o/r/pull/42";
11453
11454 #[tokio::test]
11455 async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
11456 let mut state = landing_state();
11457 let forge = Scripted::new(
11458 vec![
11459 red("a", Some("7")),
11460 seen("a", Checks::Pending, "BLOCKED", false),
11461 seen("a", Checks::Green, "CLEAN", false),
11462 ],
11463 vec![(true, "")],
11464 );
11465 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11466 assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11467 assert!(!forge.calls().contains(&"fix"));
11468 assert_eq!(state.status, RunStatus::Merged);
11469 assert_eq!(state.pr.as_ref().unwrap().round, 0);
11470 let argvs = forge.argvs();
11471 assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
11472 assert!(
11473 state
11474 .events
11475 .iter()
11476 .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
11477 );
11478 }
11479
11480 #[tokio::test]
11481 async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
11482 let mut state = landing_state();
11483 let forge = Scripted::new(
11484 vec![
11485 red("a", Some("7")),
11486 seen("a", Checks::Green, "CLEAN", false),
11487 ],
11488 vec![(true, "")],
11489 );
11490 *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11491 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11493 assert_eq!(forge.reruns.lock().unwrap().len(), 1);
11494 let calls = forge.calls();
11495 let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
11496 let fix_at = calls.iter().position(|c| *c == "fix");
11497 assert!(fix_at.is_none_or(|f| f > rerun_at));
11498 }
11499
11500 #[tokio::test]
11501 async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
11502 let mut state = landing_state();
11503 let mut v = red("a", Some("7"));
11504 v.pr.checks = Checks::Pending;
11505 v.contexts.push(CheckInfo {
11506 label: "slow".to_owned(),
11507 verdict: Verdict::Pending,
11508 required: Some(true),
11509 run: Some("8".to_owned()),
11510 });
11511 let forge = Scripted::new(
11512 vec![v, seen("a", Checks::Green, "CLEAN", false)],
11513 vec![(true, "")],
11514 );
11515 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11516 assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11517 assert_eq!(state.status, RunStatus::Merged);
11518 }
11519
11520 #[test]
11521 fn a_run_with_a_job_still_going_is_not_rerun_yet() {
11522 let mut v = red("a", Some("7"));
11523 v.contexts.push(CheckInfo {
11524 label: "same run, still going".to_owned(),
11525 verdict: Verdict::Pending,
11526 required: Some(true),
11527 run: Some("7".to_owned()),
11528 });
11529 assert!(rerunnable(&v.contexts).is_empty());
11530 }
11531
11532 #[tokio::test]
11533 async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
11534 let mut state = landing_state();
11535 state.config.graph.land_rounds = 0;
11536 let forge = Scripted::new(
11537 vec![
11538 red("a", Some("7")),
11539 seen("a", Checks::Green, "CLEAN", false),
11540 ],
11541 vec![(true, "")],
11542 );
11543 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11544 assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11545 assert_eq!(state.status, RunStatus::Merged);
11546 assert!(!forge.calls().contains(&"fix"));
11547 assert_eq!(state.pr.as_ref().unwrap().round, 0);
11548 }
11549
11550 #[tokio::test]
11551 async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
11552 let mut state = landing_state();
11553 state.config.graph.land_rounds = 1;
11554 let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
11555 *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
11556 let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11557 assert_eq!(pr.state, PrLifecycle::Open);
11558 assert_eq!(state.status, RunStatus::Blocked);
11559 assert_eq!(state.pr.as_ref().unwrap().round, 0);
11560 assert!(
11561 state.merge_decision.is_none(),
11562 "no ordinary failure handoff"
11563 );
11564 assert!(forge.argvs().is_empty(), "no merge on outage");
11565
11566 let recovered = Scripted::new(
11567 vec![
11568 seen("a", Checks::Green, "CLEAN", true),
11569 seen("b", Checks::Green, "CLEAN", false),
11570 ],
11571 vec![(true, "")],
11572 );
11573 *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
11574 land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
11575 assert_eq!(state.status, RunStatus::Merged);
11576 assert_eq!(state.pr.as_ref().unwrap().round, 1);
11577 assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
11578 }
11579
11580 #[tokio::test]
11581 async fn the_last_fix_rounds_new_head_gets_its_rerun() {
11582 let mut state = landing_state();
11583 state.config.graph.land_rounds = 1;
11584 let forge = Scripted::new(
11585 vec![
11586 seen("a", Checks::Green, "CLEAN", true),
11587 red("b", Some("7")),
11588 seen("b", Checks::Green, "CLEAN", false),
11589 ],
11590 vec![(true, "")],
11591 );
11592 *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11593 head: "b".to_owned(),
11594 });
11595 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11596 assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11597 assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
11598 assert_eq!(state.pr.as_ref().unwrap().round, 1);
11599 assert_eq!(state.status, RunStatus::Merged);
11600 assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
11601 assert_eq!(
11602 value_of(&forge.argvs()[0], "--match-head-commit"),
11603 Some("b")
11604 );
11605 }
11606
11607 #[tokio::test]
11608 async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
11609 let mut state = landing_state();
11610 let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11611 *forge.rerun_fails.lock().unwrap() = true;
11612 *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11613 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11614 assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
11615 assert_eq!(
11616 forge.calls().iter().filter(|c| **c == "fix").count(),
11617 1,
11618 "{:?}",
11619 forge.calls()
11620 );
11621 }
11622
11623 #[tokio::test]
11624 async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
11625 let mut state = landing_state();
11626 let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11627 state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
11629 *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11630 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11631 assert!(forge.reruns.lock().unwrap().is_empty());
11632 }
11633
11634 #[tokio::test]
11635 async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
11636 let mut state = landing_state();
11637 state.config.graph.rerun_flaky_checks = false;
11638 let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11639 *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11640 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11641 assert!(forge.reruns.lock().unwrap().is_empty());
11642 assert!(forge.calls().contains(&"fix"));
11643
11644 let mut state = landing_state();
11645 let forge = Scripted::new(vec![red("a", None)], vec![]);
11646 *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11647 land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11648 assert!(forge.reruns.lock().unwrap().is_empty());
11649 assert!(forge.calls().contains(&"fix"));
11650 }
11651
11652 fn names(xs: &[&str]) -> BTreeSet<String> {
11653 xs.iter().map(|x| (*x).to_owned()).collect()
11654 }
11655
11656 #[test]
11657 fn a_required_check_the_rollup_never_listed_is_named() {
11658 let req = names(&["build"]);
11659 let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
11660 assert!(why.contains("never reported: build"), "{why}");
11661 assert!(!why.contains("probably waiting for a review"), "{why}");
11662 }
11663
11664 #[test]
11665 fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
11666 let why = waiting_on("BLOCKED", &[passing("review")], None);
11667 assert!(why.contains("could not be read"), "{why}");
11668 assert!(!why.contains("probably waiting for a review"), "{why}");
11669 }
11670
11671 #[test]
11672 fn all_required_reported_keeps_the_review_guess() {
11673 let req = names(&["build"]);
11674 let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11675 assert!(why.contains("probably waiting for a review"), "{why}");
11676 assert!(!why.contains("never reported"), "{why}");
11677 }
11678
11679 #[test]
11680 fn required_names_match_the_rollup_ignoring_case_only() {
11681 let req = names(&["Build"]);
11682 let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11683 assert!(!why.contains("never reported"), "{why}");
11684 }
11685
11686 #[test]
11687 fn required_contexts_are_read_from_protection_and_rulesets() {
11688 let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
11689 assert_eq!(
11690 parse_classic_required(classic),
11691 Some(names(&["build", "lint"]))
11692 );
11693 let rules = r#"[{"type":"pull_request","parameters":{}},
11694 {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
11695 assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
11696 assert_eq!(parse_ruleset_required("nope"), None);
11697 assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
11698 }
11699
11700 #[test]
11701 fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
11702 let shown = BTreeSet::new();
11703 let ok = seen("a", Checks::Green, "CLEAN", false);
11704 let guard = |s: Option<&Seen>| {
11705 direct_merge_is_safe(
11706 s,
11707 "A",
11708 &shown,
11709 0,
11710 4,
11711 Duration::ZERO,
11712 CiExpectation::Expected,
11713 )
11714 };
11715 assert!(guard(Some(&ok)));
11716 assert!(!guard(None));
11717 assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
11718 let mut stale = ok.clone();
11719 stale.rollup_head = "old".to_owned();
11720 assert!(!guard(Some(&stale)));
11721 assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
11722 assert!(!guard(Some(&merged_view("a"))));
11723 }
11724
11725 #[test]
11726 fn the_rollup_node_carries_whether_each_check_is_required() {
11727 let node = node_json("new", "SUCCESS", false)
11728 .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
11729 let s = seen_from(&view_json("new"), Some(&node)).unwrap();
11730 assert_eq!(s.contexts.len(), 1);
11731 assert_eq!(s.contexts[0].required, Some(true));
11732 let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
11733 assert_eq!(s.contexts[0].required, None);
11734 }
11735
11736 #[tokio::test]
11737 async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
11738 let mut state = landing_state();
11739 state.land_armed_head = Some("a".to_owned());
11740 let forge = Scripted::new(
11741 vec![seen("a", Checks::Green, "CLEAN", true)],
11742 vec![(false, "disable exploded")],
11743 );
11744 land_with(&mut state, URL, &forge).await.unwrap();
11745 assert!(!forge.calls().contains(&"fix"));
11746 assert_eq!(state.status, RunStatus::Blocked);
11747 assert_eq!(state.land_armed_head.as_deref(), Some("a"));
11748 let why = state.merge.as_ref().unwrap().detail.clone();
11749 assert!(why.contains("disable exploded"), "{why}");
11750 }
11751}