Skip to main content

magi/
land.rs

1//! Landing the winner: watch the pull request, fix what it complains about,
2//! and merge it.
3//!
4//! Opening the pull request used to be where magi stopped and the operator
5//! started: watch the checks, read what the review bots found, push a fix,
6//! wait again, merge. That loop is mechanical, it takes an hour of wall-clock
7//! time per pull request, and doing it by hand six times in one session is how
8//! a queue that drains unattended stops being unattended. So it lives here.
9//!
10//! # Shape
11//!
12//! [`PrState`] is one observation of a pull request and [`decide`] is the whole
13//! policy as a *pure* function of it. Nothing in [`decide`] talks to `gh`,
14//! which is what makes "green with an unresolved comment is a fix, not a merge"
15//! an assertion in a test rather than a claim in a comment. [`land`] is the
16//! only part that performs I/O: observe, decide, act, repeat.
17//!
18//! # What it refuses to do
19//!
20//! Merging is the one irreversible thing magi can do to a repository, so the
21//! loop is built to stop rather than to guess:
22//!
23//! * A red pull request is never merged. When the budget runs out the pull
24//!   request is left open with a comment naming what is still failing, because
25//!   a magi that force-merges a red pull request is worse than one that stops.
26//! * A pull request whose checks cannot be read at all (`gh` reported no
27//!   rollup) is not merged either. Landing is for repositories with CI; with no
28//!   signal there is nothing to be green.
29//! * A pull request a human merged or closed underneath us is
30//!   [`Step::Done`] - the person won, and their decision is not an error.
31//!
32//! # Why `--subject` is not optional
33//!
34//! A candidate branch holds one commit whose subject is
35//! `magi: candidate A (uncommitted work)`, and `gh pr merge --squash` prefers a
36//! single commit's message over the pull request title. Merging without
37//! [`merge_argv`]'s explicit `--subject` therefore writes a `main` history that
38//! says nothing about what landed. `AGENTS.md` records the trap; this module is
39//! where it is prevented.
40
41use 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
61/// How often the pull request is re-read while its checks are still running.
62///
63/// Thirty seconds: a CI matrix takes minutes, so anything shorter is spent
64/// entirely on `gh` invocations, and anything much longer adds latency to every
65/// single round of a loop that already waits for agents.
66pub const POLL: Duration = Duration::from_secs(30);
67
68/// How long one wait may last before landing gives up on the checks finishing.
69///
70/// A workflow that has not settled in forty-five minutes is stuck on a runner
71/// queue, a missing approval, or a hung job - none of which more polling fixes,
72/// and all of which a person needs to see.
73pub const WAIT_CEILING: Duration = Duration::from_secs(45 * 60);
74
75/// How long the checks may stay unreadable before landing gives up on them.
76///
77/// GitHub registers a workflow run some seconds after the branch is pushed, so
78/// immediately after a pull request is opened "no checks" and "no CI in this
79/// repository" look identical. Measured on run 01c2: magi opened pull request
80/// 22, read `unknown` four seconds later, refused to merge on a guess and
81/// marked the run blocked - and every check on that pull request was green
82/// minutes afterwards, with the whole competition then re-run from scratch for
83/// a task that was already finished. Three minutes is well past the observed
84/// registration delay and still bounded, so a repository that genuinely has no
85/// checks costs one three-minute wait and then says so.
86pub const CHECKS_GRACE: Duration = Duration::from_secs(3 * 60);
87
88/// Bytes of failing log kept per check. The fixer needs the assertion and the
89/// frame around it, not the forty thousand lines of `cargo` output above it.
90const LOG_TAIL: usize = 4_000;
91
92/// Failing checks whose logs are fetched. Beyond a handful the failures share a
93/// cause, and fetching each one costs a `gh` round trip.
94const MAX_LOGS: usize = 3;
95
96/// Marker carried by every comment magi posts on a pull request.
97///
98/// Without it magi's own "still failing" comment is indistinguishable from a
99/// reviewer's, and the next observation would hand magi's own prose to the
100/// fixer as a finding.
101pub const MARKER: &str = "<!-- magi:land -->";
102
103/// Markers a bot puts in a comment to say that the comment is not a review.
104///
105/// CodeRabbit labels its own machinery in HTML comments - the trigger notice,
106/// the walkthrough summary, the "thanks for using" footer - and its actual
107/// findings arrive as *inline* review comments with a path and a line. Taking
108/// the bot at its word is more honest than guessing from prose, and it is the
109/// difference between a fix round that has something to fix and one that asks
110/// an agent to act on a quota notice.
111const NOT_A_REVIEW: [&str; 3] = [
112    "skip review by coderabbit.ai",
113    "summarize by coderabbit.ai",
114    "<!-- tips_start -->",
115];
116
117/// Where a pull request is in its life.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum PrLifecycle {
120    /// Still ours to land.
121    Open,
122    /// Already merged, by us or by a person.
123    Merged,
124    /// Closed without merging.
125    Closed,
126}
127
128/// The aggregate verdict of a pull request's checks.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum Checks {
131    /// At least one check has not finished.
132    Pending,
133    /// Every check passed (a skipped check counts as passed: the review
134    /// workflow skips release and bot pull requests by design).
135    Green,
136    /// At least one check finished without passing.
137    Red,
138    /// Nothing readable - no rollup at all, or a status magi does not know.
139    Unknown,
140}
141
142impl PrLifecycle {
143    /// Stable lower-case name, as the API and the reports spell it.
144    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    /// Stable lower-case name, as the API and the reports spell it.
155    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/// One outstanding review comment, human or bot.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct ReviewComment {
168    /// Login of whoever wrote it.
169    pub author: String,
170    /// File it was left on, for inline review comments.
171    pub path: Option<String>,
172    /// Line it was left on, when the comment is inline and still anchored.
173    pub line: Option<u64>,
174    /// The comment itself, as written.
175    pub body: String,
176}
177
178/// One observation of a pull request.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct PrState {
181    /// Pull request url, as `gh` reports it.
182    pub url: String,
183    /// Pull request number.
184    pub number: u64,
185    /// Open, merged, or closed.
186    pub state: PrLifecycle,
187    /// Aggregate check verdict.
188    pub checks: Checks,
189    /// Names of the checks that finished without passing.
190    pub failing: Vec<String>,
191    /// Comments that still want an answer, human and bot.
192    pub review_comments: Vec<ReviewComment>,
193    /// Whether the forge itself considers the failures blocking.
194    pub blocking: Blocking,
195}
196
197/// Whether a failing check actually stands between the pull request and
198/// `main`, according to the forge.
199///
200/// The rollup lists every check equally, so `coverage` going red on a
201/// repository that deliberately does not require it looked exactly like a
202/// broken build - and magi answered by spending a fix round on a change that
203/// was fine. Pull request 37 had to be merged by hand for that reason: the
204/// only red check was `editorconfig`, which was failing because the *action*
205/// could not fetch its own binary, and which the repository does not require.
206///
207/// `mergeStateStatus` is where GitHub applies the required-check set, so it
208/// is the one field that can tell the difference.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Blocking {
211    /// Required checks are satisfied and the branch merges cleanly.
212    No,
213    /// Something required is failing or missing.
214    Yes,
215    /// The branch no longer merges: the base moved under it.
216    Conflict,
217    /// The forge requires the head to include the current base.
218    Behind,
219    /// The forge did not say - an older `gh`, or a token without the scope.
220    /// Treated as `Yes`, because refusing to guess is the rule everywhere
221    /// else in this module.
222    Unsaid,
223}
224
225impl Blocking {
226    /// Read `mergeStateStatus`, which is upper-case in `gh`'s output.
227    fn of(raw: &str) -> Self {
228        match raw.to_ascii_uppercase().as_str() {
229            // Mergeable. `UNSTABLE` is the interesting one: mergeable, with a
230            // non-required check failing or still running.
231            "CLEAN" | "UNSTABLE" | "HAS_HOOKS" => Self::No,
232            "DIRTY" => Self::Conflict,
233            "BEHIND" => Self::Behind,
234            "" | "UNKNOWN" => Self::Unsaid,
235            // BLOCKED, DRAFT: something has to change first.
236            _ => Self::Yes,
237        }
238    }
239
240    /// Does this stand between the pull request and the base branch?
241    #[must_use]
242    pub fn stops_a_merge(self) -> bool {
243        !matches!(self, Self::No)
244    }
245}
246
247/// What the loop decided to do next. Pure, so the policy is testable.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum Step {
250    /// Checks are still running; re-read the pull request after [`POLL`].
251    Wait,
252    /// The base moved and the branch no longer merges: rebase it.
253    ///
254    /// Not a fix round. Nothing is wrong with the change - a competition
255    /// that runs for two hours against a repository merging pull requests
256    /// all day conflicts on the way in, and that is arithmetic rather than a
257    /// defect. Pull requests 35 and 37 were both rebased by hand for exactly
258    /// this.
259    Rebase,
260    /// Red checks or unresolved comments; run a fix round.
261    Fix {
262        /// What is unhappy, in one line, for the run log and the fix prompt.
263        reason: String,
264    },
265    /// Green and nothing outstanding; merge it.
266    Merge,
267    /// The pull request left our hands.
268    Done {
269        /// Did it land, or was it closed?
270        merged: bool,
271    },
272    /// Stop and leave the pull request to a person.
273    GiveUp {
274        /// Why magi stopped, in one line.
275        reason: String,
276    },
277}
278
279/// The outcome to record when `gh pr merge` exits non-zero, given what the
280/// pull request looked like immediately afterwards.
281///
282/// `gh pr merge` merges server-side first and only then does local work -
283/// deleting the branch, switching back to a base branch - so a non-zero exit
284/// does not mean the merge did not happen. In a jj-colocated repository it
285/// reliably does not mean that: git HEAD is detached, and `--delete-branch`
286/// ends with "could not determine current branch: not on any branch" *after*
287/// the merge has landed. Run ec12 merged pull request 28 into `main` and
288/// recorded `ok: false`, and its task was held waiting for a merge that was
289/// already done.
290///
291/// So the forge is asked, and its answer wins - the same authority [`decide`]
292/// gives the pull request's own state over everything else. The recorded
293/// detail carries both facts, because "the command failed and the merge
294/// happened anyway" is exactly what someone reading the run later needs to
295/// know.
296///
297/// `None` means the merge really did not happen, including when the pull
298/// request could not be read at all: an unreadable answer is not evidence of
299/// success.
300pub(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
320/// Decide the next step. No I/O.
321///
322/// `round` counts the fix rounds already spent, so `round == budget` means the
323/// budget is gone. A wait never spends a round: waiting is free, and a slow CI
324/// must not consume the allowance meant for actual fixes.
325///
326/// The order of the tests is the policy:
327///
328/// 1. **The pull request's own state wins.** A merge or a close that happened
329///    underneath us is the end of the story regardless of what the checks say.
330/// 2. **Pending beats red.** A check that is still running may yet fail, and one
331///    fix round that addresses every failure is cheaper than two that each
332///    address half - the fix pushes and restarts the whole suite anyway.
333/// 3. **Comments outrank green.** An unresolved comment holds the merge even
334///    when CI is happy; that is what a review is for.
335/// 4. **Unreadable is not absent.** Checks that cannot be read yet are waited
336///    on for [`CHECKS_GRACE`], because a pull request opened a moment ago has
337///    not been given its workflow runs yet. Past the grace they are treated as
338///    genuinely missing and magi stops rather than merge on a guess.
339pub fn decide(pr: &PrState, round: usize, budget: usize, waited: Duration) -> Step {
340    decide_with(pr, round, budget, waited, CiExpectation::Expected)
341}
342
343/// Whether the repository's CI is expected to report on this pull request.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub enum CiExpectation {
346    /// Checks will come: wait for them, judge them (the default, and what
347    /// [`decide`] always uses).
348    Expected,
349    /// The repository explicitly disables CI expectations with `[merge] ci = "none"`.
350    /// Ignore all check statuses while retaining conflicts and review comments.
351    Absent,
352}
353
354/// [`decide`] with the CI expectation made explicit. `Absent` ignores the
355/// rollup, but still requires conflicts and review comments to be resolved.
356pub 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    // Before the checks: every check on a branch that cannot land is an
370    // answer about a state that cannot land.
371    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        // Red, but the forge says it does not stand in the way: the failing
391        // checks are ones this repository chose not to require. Spending a fix
392        // round on them asks an agent to repair something nobody is gating on
393        // - and pull request 37's only red check was an *action* that could
394        // not fetch its own binary. Merge, and name them so the record is
395        // honest about what was red when it landed.
396        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
435/// Distinct comment authors, in the order they first appear.
436fn 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
446/// The argv magi merges with, minus the program name.
447///
448/// `--subject` is the point of this function existing: see the module docs.
449pub 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
461/// [`merge_argv`] pinned to the commit the decision was made about.
462///
463/// `--match-head-commit` makes the forge refuse the merge if the branch moved
464/// after it was observed, so a push landing between the look and the merge is
465/// never merged unseen.
466pub 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
473/// Take auto-merge back. magi no longer arms auto-merge, but a run recorded by
474/// an older build may still have one standing on the forge, so the disarm
475/// paths (and `RunState::land_armed_head`) stay. Run before anything that changes the head, so an
476/// armed merge never outlives the commit that was approved for it.
477pub 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
483/// May the direct merge go ahead, judged from a fresh read?
484///
485/// The pull request must still be open on the approved head, the checks must
486/// have been read for that very head, and the policy must still say merge.
487/// Pure, so the head guard is asserted without a forge.
488fn 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
514/// What GitHub is still waiting for, for the stop reason when an armed merge
515/// does not happen in time. No I/O.
516///
517/// Required checks that are pending or failing are named. A check whose
518/// required-ness could not be read is never assumed optional: every unsettled
519/// check is listed and the reason says so.
520fn 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    // Required contexts the rollup never listed: nothing reported them, so no
549    // pending/failing entry exists to name. Matched case-insensitively against
550    // the labels as the rollup spells them, and no further.
551    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
597/// The squash subject to merge under.
598///
599/// The pull request title, unless it is empty or is a candidate branch's commit
600/// subject that leaked into the title - in which case the task's own first line
601/// is used, because `magi: candidate A (uncommitted work)` in `main` tells a
602/// reader nothing about what landed.
603pub 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
616/// The choice that lets the merge happen, verbatim as the owner taps it.
617pub const APPROVE: &str = "merge";
618
619/// The choice that leaves the pull request open.
620pub const HOLD: &str = "hold";
621
622/// A bounded repair followed by a new review and a fresh owner decision.
623pub const REPAIR: &str = "fix findings and re-review";
624
625/// Whether review evidence offers a meaningful repair choice. This does not
626/// decide whether owner approval is required.
627pub 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/// All applicable reasons for consulting the owner, independent of repair choices.
637#[derive(Debug, Clone, Copy, PartialEq, Eq)]
638pub enum ApprovalReason {
639    /// Universal owner approval is enabled for every merge.
640    EveryMerge,
641    /// Contested-merge approval is enabled and blocking findings remain open.
642    OpenBlockingFindings,
643    /// Contested-merge approval is enabled and a final reviewer vote rejects.
644    FinalReject,
645    /// An existing owner decision must be honored even if controls change.
646    ExistingDecision,
647    /// Merge repair requires a fresh owner decision, even on the same head.
648    AfterRepair,
649}
650
651/// Disabling fresh approval controls never bypasses an existing owner decision
652/// or the fresh decision owed after repair, even if repair kept the same head.
653pub 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
679/// Bound free-form approval evidence by characters, including an explicit
680/// ellipsis when abbreviated. Keep UTF-8 text intact in questions and panels.
681fn 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
691/// Persisted verbatim in the question and panel at creation. Deputies and
692/// resumed questions use that snapshot, never reconstruct past policy from
693/// today's settings. Fixer claims and successful gates are not resolutions.
694fn 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
914/// Shared choices for web, CLI and consultation questions.
915pub 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
933/// Extend unanswered legacy cards in place. Answered cards keep their choices;
934/// a legacy repair answer gains only its missing dispatch action.
935pub 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        // Older cards attached Resume to hold; a hold must remain answerable
947        // without dispatching a question action.
948        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
980/// Graph node recorded on the approval question.
981///
982/// The phone keys its high-stakes card off this rather than off the choice
983/// strings, so renaming a button cannot silently downgrade the card that
984/// guards the one irreversible action magi takes.
985pub const APPROVAL_NODE: &str = "land-approval";
986
987/// Unified diff lines carried in the panel before it is truncated.
988///
989/// Four hundred: the panel is read on a 390px phone, where a diff line often
990/// wraps to two rows, so this is already a few thousand rows of scrolling -
991/// past that nobody is reading, and the bytes still count against the panel's
992/// 8 MiB cap. A larger diff is not hidden: the note says how many lines were
993/// cut and which worktree holds the whole patch.
994pub const DIFF_MAX_LINES: usize = 400;
995
996/// What the owner's answer to the approval question means.
997#[derive(Debug, Clone, Copy, PartialEq, Eq)]
998pub enum Approval {
999    /// The owner said [`APPROVE`]. Merge.
1000    Merge,
1001    /// Repair the existing PR, then ask again; never approval to merge.
1002    Repair,
1003    /// Anything else, including silence. Leave the pull request open.
1004    Hold,
1005}
1006
1007/// Read the owner's answer, where `None` is an unanswered question.
1008///
1009/// Silence is a hold. A timed-out question means the owner never saw it or
1010/// never decided, and defaulting an irreversible merge to "yes" would make this
1011/// gate worse than no gate at all: it would merge unattended while claiming to
1012/// have asked. Only the exact [`APPROVE`] choice merges, so an answer this
1013/// function does not recognise holds too.
1014pub 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/// What [`approval_gate`] found on one check of the owner's merge decision.
1023#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1024enum ApprovalGate {
1025    /// The owner said [`APPROVE`]. Merge.
1026    Approved,
1027    /// The owner explicitly requested repair, without authorizing a merge.
1028    Repair,
1029    /// The owner said anything else, the question timed out, or it was
1030    /// closed with no decision recorded.
1031    Held,
1032    /// Filed and still waiting - the caller parks rather than blocking on it.
1033    Pending,
1034}
1035
1036/// Escape text for HTML, including both quote characters.
1037///
1038/// Every string in the panel is agent-influenced: a branch name, a file path, a
1039/// commit subject, a review comment. The sandboxed frame stops such text from
1040/// *running*, but it does not stop a `<` from ending the document early or a
1041/// `"` from ending an attribute and inventing a new one - the panel would then
1042/// render a lie, or not render at all. Both quotes are escaped because the same
1043/// function is used inside attributes, where remembering which quote style the
1044/// caller used is one mistake away from an injected attribute.
1045fn 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("&amp;"),
1050            '<' => out.push_str("&lt;"),
1051            '>' => out.push_str("&gt;"),
1052            '"' => out.push_str("&quot;"),
1053            '\'' => out.push_str("&#39;"),
1054            _ => out.push(c),
1055        }
1056    }
1057    out
1058}
1059
1060/// One row of the diffstat table.
1061#[derive(Debug, Clone, PartialEq, Eq)]
1062struct StatRow {
1063    path: String,
1064    /// `None` for a binary file, which `git` reports as `-`.
1065    added: Option<u64>,
1066    removed: Option<u64>,
1067}
1068
1069impl StatRow {
1070    /// Lines touched, for sorting. A binary file counts as zero rather than as
1071    /// unknown, which puts it at the bottom where it needs no attention.
1072    fn churn(&self) -> u64 {
1073        self.added.unwrap_or(0) + self.removed.unwrap_or(0)
1074    }
1075}
1076
1077/// Parse `git diff --numstat` into rows, biggest churn first.
1078///
1079/// `--numstat` and not `--stat`: the `+++---` bar in `--stat` is *scaled* to the
1080/// terminal width, so counting its characters would print fabricated numbers in
1081/// the one table an operator approves an irreversible action from.
1082fn 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    // Path breaks the tie so the same change always renders the same table; an
1101    // operator comparing two panels should not see rows shuffle.
1102    rows.sort_by(|a, b| b.churn().cmp(&a.churn()).then_with(|| a.path.cmp(&b.path)));
1103    rows
1104}
1105
1106/// How one diff line is shown: a gutter character, a style, and the body to
1107/// print - which is the line minus its marker, so the marker appears exactly
1108/// once, in the gutter.
1109///
1110/// The gutter is why this exists at all. The operator may be colour blind, or
1111/// reading in sunlight with the screen dimmed, so an added line is never
1112/// distinguished by its background alone: `+` and `-` sit in a fixed column,
1113/// the same mark they already read in a terminal.
1114fn 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
1130/// The handful of words the approval panel says in its own voice.
1131///
1132/// magi's own text, not an agent's, so `[graph] language` has to reach it too:
1133/// the operator asked why the merge question spoke English on a repository
1134/// configured for Japanese, and "because that string is a literal in Rust" is
1135/// not an answer. Only the languages magi can actually check are translated;
1136/// anything else falls back to English rather than shipping a guess, and that
1137/// fallback is deliberate.
1138struct 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    /// The clause after the merge subject. Split out because word order moves:
1197    /// Japanese puts the subject before the verb, so a shared template with a
1198    /// hole in the middle would read as machine translation.
1199    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    /// The question's own one-line summary, which is what a phone shows first.
1208    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    /// The body under the summary, above the panel.
1217    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    /// Why this question exists although merge approvals are off: the open
1243    /// blocking findings and who rejected. Short enough for a phone.
1244    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    /// The truncation note, written whole in each language for the same reason.
1300    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
1325/// Pick the panel's language. Codes and names both, because `[graph] language`
1326/// has always accepted either.
1327fn words(language: &str) -> &'static Words {
1328    if crate::lang::is_japanese(language) {
1329        &JA
1330    } else {
1331        &EN
1332    }
1333}
1334
1335/// The approval panel's html: what is about to land, and the evidence for it.
1336///
1337/// Pure, so the whole document is asserted in tests without `gh`, without a
1338/// network and without a repository. The caller gathers `diffstat`
1339/// (`git diff --numstat`), `diff` (the unified patch), `commits` (the subjects
1340/// being squashed) and `subject` (what the squash will be called) from the
1341/// winner's worktree.
1342///
1343/// It emits no `<script>`, no `<form>` and no remote url, because the frame's
1344/// content security policy blocks all three: anything of the sort here would be
1345/// dead markup that misleads the next reader into thinking it works.
1346pub 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    // The decision, in the words the operator is approving.
1377    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    // The task, verbatim: the operator's own words for what was asked, so the
1399    // panel does not make them reconstruct the request from a diffstat.
1400    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    // The winner's own account of what it did and why, when there is one.
1409    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    // Only the last round's reviewer prose is current. Its votes and
1424    // remaining findings are shown explicitly in the evidence above.
1425    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            // A seat the review loop counted as answered has real prose in
1433            // `summary`; one it counted against `incomplete` (see
1434            // `graph::Runner::review_loop`) never produced any and left it
1435            // empty - which must not be read back as a blank verdict, since
1436            // an empty box here looks like "nothing to say" rather than
1437            // "never answered".
1438            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    // Diffstat as a real table, so a phone reads what moved without scrolling
1477    // sideways through a terminal bar chart.
1478    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    // The commits being squashed, and the subject that replaces them.
1525    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    // The review comments that shaped this branch, and who asked for them.
1551    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    // The patch itself.
1581    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
1631/// Historical contested hand-off evidence for the question detail. Approval
1632/// itself is decided by `approval_reasons`, including reject-only cases.
1633fn 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
1641/// What a merge-approval question's deputy is told: the pull request, the run,
1642/// what each answer does, and the evidence saved when the question was filed.
1643///
1644/// Rebuilt for every deputy turn, it is still a snapshot of that moment, so it
1645/// says so and points at `magi show` / `gh pr view` for anything current.
1646/// `state` is `None` for a run that cannot be read; what is missing is named as
1647/// missing, and no past approval basis is rebuilt from today's state.
1648pub 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
1698// Releasing a task permits work to resume; it does not renew merge consent.
1699// Check the persisted operator decision both when reusing a card and at the
1700// final merge boundary, since a hold/release can arrive between those reads.
1701fn 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
1720/// Ask the owner before merging, with the whole case attached as a panel.
1721///
1722/// The evidence is gathered from the winner's own worktree with the `git` CLI,
1723/// never from the network, so a phone on a slow link gets the diff magi is
1724/// looking at rather than a link it has to go and open.
1725///
1726/// Never blocks. `land` used to sit inside [`ask::ask_and_wait`]'s poll loop
1727/// for up to a day right here, which held the whole run's task claim - and
1728/// the daemon's one slot with it - for exactly as long as the owner took to
1729/// notice their phone. [`ApprovalGate::Pending`] is the answer that lets the
1730/// caller park the run and hand the slot back instead: the question is on
1731/// disk either way, so nothing about the wait itself changes, only who is
1732/// blocked on it.
1733///
1734/// Idempotent across resumes: called again for a run already waiting on its
1735/// own question, this finds that question by [`crate::ask::Questions::list`]
1736/// rather than filing a second one - asking twice would double the
1737/// notification for one decision, and leave the first question's panel an
1738/// orphan nobody's answer ever reaches.
1739async 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    // An answer belongs to the commit its panel showed. A question recorded
1749    // for another head - or none recorded at all, as for a question filed
1750    // before heads were tracked - is never reused: a fix or rebase push made
1751    // a commit the owner has not seen, and their word does not carry over.
1752    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            // The diff is built from the commit being approved, not from the
1809            // branch name, which may already point somewhere else.
1810            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            // The diff is against what the remote's base holds, never the
1818            // local branch of that name; unreadable means less evidence.
1819            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            // A failed `git` must not decide the merge: the panel degrades to
1828            // less evidence and the owner still chooses. Merging because the
1829            // diff could not be read would be the worst of both.
1830            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                // A broken webhook is not a reason to lose the merge: the
1922                // question is already on disk and the web UI already shows
1923                // it, so the operator still has a way in.
1924                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        // Nobody answered before `state.config.graph.answer_timeout` passed,
1937        // or the question was closed with no decision recorded underneath
1938        // this run - either way there is nothing left to wait on.
1939        ask::QuestionStatus::Abandoned => ApprovalGate::Held,
1940        // The merge gate does not speak `--thread`: an owner who talked back
1941        // instead of choosing never reaches `Answered`, so this arm only
1942        // ever sees an actual decision.
1943        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
1973/// Fold a rollup's entries into one verdict plus the failing checks' labels.
1974/// No I/O. An empty rollup is `Unknown`, never green.
1975fn 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
2001/// Parse `gh pr view --json url,number,state,statusCheckRollup,reviews,comments`
2002/// output into a [`PrState`]. No I/O.
2003pub 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/// One rollup entry as the release watcher reads it.
2050#[derive(Debug, Clone, PartialEq, Eq)]
2051pub(crate) struct CheckView {
2052    pub name: String,
2053    pub verdict: Verdict,
2054    /// Workflow run behind the check, when its url names one.
2055    pub run: Option<String>,
2056    pub url: Option<String>,
2057}
2058
2059/// A pull request's lifecycle, head commit and per-check verdicts, without
2060/// [`rollup_verdict`]'s aggregation (a pending check anywhere hides a failure
2061/// from it, which is exactly what the release watcher must not inherit).
2062#[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
2071/// Parse `gh pr view --json url,number,state,headRefOid,statusCheckRollup`
2072/// output. No I/O.
2073pub(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
2100/// Read just a pull request's lifecycle state - open, merged, or closed -
2101/// with none of the checks/reviews/comments [`land`] itself needs to decide
2102/// what to do next.
2103///
2104/// For a caller that only ever wants one fact and must not risk anything
2105/// else: `magi fold --merged` uses this to confirm a URL the operator hands
2106/// it is actually a merged pull request *before* touching a run's state, so a
2107/// typo or a still-open PR fails loudly instead of quietly recording a merge
2108/// that never happened.
2109pub 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    // `parse_pr` reads every other field of `GhPr` as its serde default
2125    // (empty string, empty vec, zero) when this narrower `--json` selection
2126    // does not carry them - harmless, since only `.state` is read back.
2127    Ok(parse_pr(&view.1)?.state)
2128}
2129
2130/// A pull request the operator merged outside of `land::land`'s own loop,
2131/// found by asking GitHub about the run's own winning branch rather than
2132/// requiring the operator to go and find the URL themselves.
2133#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2134pub struct ExternalMerge {
2135    /// The pull request's URL, ready to hand to [`correct_manual_merge`].
2136    pub url: String,
2137    /// The pull request's number.
2138    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
2150/// Pure half of [`find_external_merge`]: given the raw `gh pr list --head
2151/// <branch> --state merged --json url,number,mergedAt,baseRefName` output,
2152/// decide whether exactly one of the pull requests it lists could actually
2153/// be *this* run's.
2154///
2155/// A branch name alone does not prove it: [`RunState::branch_for`] derives it
2156/// from the run's own short id, so a collision with some other, unrelated
2157/// task's merged pull request from a same-named branch is rare but not
2158/// impossible once branches are deleted and ids run out. Filtering on
2159/// `base_ref_name` (the branch this run actually targets) and `merged_at`
2160/// (which cannot predate the run itself) rules that case out. More than one
2161/// survivor is exactly as uninformative as zero — something this run cannot
2162/// tell apart from another — so only a unique survivor is returned.
2163fn pick_merged_pr(
2164    json: &str,
2165    base_branch: &str,
2166    created_at: Timestamp,
2167) -> Result<Option<ExternalMerge>> {
2168    let raw: Vec<GhMergedPr> =
2169        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2170    let mut matches: Vec<ExternalMerge> = Vec::new();
2171    for pr in raw {
2172        if pr.base_ref_name != base_branch {
2173            continue;
2174        }
2175        let Ok(merged_at) = pr.merged_at.parse::<Timestamp>() else {
2176            continue;
2177        };
2178        if merged_at < created_at {
2179            continue;
2180        }
2181        matches.push(ExternalMerge {
2182            url: pr.url,
2183            number: pr.number,
2184        });
2185    }
2186    if matches.len() == 1 {
2187        Ok(matches.pop())
2188    } else {
2189        Ok(None)
2190    }
2191}
2192
2193/// What `gh pr list --head <branch> --base <base> --state open` found.
2194#[derive(Debug, Clone, PartialEq, Eq)]
2195pub enum OpenPr {
2196    /// Nothing open: the caller creates one.
2197    None,
2198    /// Exactly one: the caller adopts it instead of creating a second.
2199    One {
2200        /// The pull request's URL.
2201        url: String,
2202        /// Its current title.
2203        title: String,
2204    },
2205    /// More than one: magi does not pick between them.
2206    Many(Vec<String>),
2207}
2208
2209#[derive(Debug, Deserialize)]
2210#[serde(rename_all = "camelCase")]
2211struct GhOpenPr {
2212    // `url` and `baseRefName` are required: a record missing either must be a
2213    // parse error, not a pull request that silently fails the base filter and
2214    // reads as "none open" (which would go on to create a duplicate).
2215    url: String,
2216    #[serde(default)]
2217    title: String,
2218    base_ref_name: String,
2219    // A fork's branch of the same name is not the task head; `gh pr list --head`
2220    // matches by branch name alone, so the filter has to be ours.
2221    #[serde(default)]
2222    is_cross_repository: bool,
2223}
2224
2225/// Pure half of [`find_open_pr`]: classify the raw `--json
2226/// number,url,title,baseRefName` output. Entries whose base is not `base` are
2227/// dropped even though the query already filtered on it, so a stub or an old
2228/// `gh` that ignores `--base` cannot get a pull request into the wrong branch
2229/// adopted.
2230pub fn pick_open_pr(json: &str, base: &str) -> Result<OpenPr> {
2231    let raw: Vec<GhOpenPr> =
2232        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2233    let mut hits: Vec<GhOpenPr> = raw
2234        .into_iter()
2235        .filter(|p| p.base_ref_name == base && !p.is_cross_repository)
2236        .collect();
2237    Ok(match hits.len() {
2238        0 => OpenPr::None,
2239        1 => {
2240            let p = hits.remove(0);
2241            OpenPr::One {
2242                url: p.url,
2243                title: p.title,
2244            }
2245        }
2246        _ => OpenPr::Many(hits.into_iter().map(|p| p.url).collect()),
2247    })
2248}
2249
2250/// Open pull requests whose head is `branch` and whose base is `base`. A
2251/// failing `gh` is an error carrying its own output, never "none": guessing
2252/// there is how a duplicate gets created.
2253pub async fn find_open_pr(repo: &Path, branch: &str, base: &str) -> Result<OpenPr> {
2254    let (ok, out) = gh(
2255        repo,
2256        &[
2257            "pr".to_owned(),
2258            "list".to_owned(),
2259            "--head".to_owned(),
2260            branch.to_owned(),
2261            "--base".to_owned(),
2262            base.to_owned(),
2263            "--state".to_owned(),
2264            "open".to_owned(),
2265            "--json".to_owned(),
2266            "number,url,title,baseRefName,isCrossRepository".to_owned(),
2267        ],
2268    )
2269    .await?;
2270    if !ok {
2271        bail!("gh pr list failed: {out}");
2272    }
2273    pick_open_pr(&out, base)
2274}
2275
2276#[derive(Debug, Deserialize)]
2277#[serde(rename_all = "camelCase")]
2278struct GhPrHead {
2279    head_ref_name: String,
2280    base_ref_name: String,
2281    state: String,
2282    // Required, like `GhOpenPr`'s fields: a record that cannot say whether the
2283    // head lives in a fork must be a parse error, never "same repository".
2284    is_cross_repository: bool,
2285    // Required too: it is what ties the pull request to the commits that were
2286    // actually proven to be on the base.
2287    head_ref_oid: String,
2288}
2289
2290/// Why [`closable`] said no, and whether asking again later could say yes.
2291#[derive(Debug, Clone, PartialEq, Eq)]
2292pub struct Refusal {
2293    /// A later attempt may succeed (the head moved, the view was unreadable);
2294    /// `false` means this pull request is simply not the run's to close.
2295    pub retry: bool,
2296    /// What was wrong.
2297    pub why: String,
2298}
2299
2300impl Refusal {
2301    fn final_(why: String) -> Self {
2302        Self { retry: false, why }
2303    }
2304}
2305
2306/// Pure half of [`close_superseded_pr`]: read `gh pr view --json
2307/// headRefName,baseRefName,state,isCrossRepository` and say whether closing
2308/// is safe, `Err` carrying the reason when it is not.
2309///
2310/// Closing is outward-facing, so every property is checked on what the forge
2311/// says now, not on what magi recorded: the head must be exactly `branch` in
2312/// this repository (a fork's branch of the same name is somebody else's), the
2313/// base must be `base`, and the pull request must still be open.
2314pub fn closable(
2315    json: &str,
2316    branch: &str,
2317    base: &str,
2318    verified: &[String],
2319) -> std::result::Result<(), Refusal> {
2320    let pr: GhPrHead = serde_json::from_str(json).map_err(|e| Refusal {
2321        retry: true,
2322        why: format!("could not read the pull request ({e})"),
2323    })?;
2324    if pr.head_ref_name != branch {
2325        return Err(Refusal::final_(format!(
2326            "its head is `{}`, not this run's `{branch}`",
2327            pr.head_ref_name
2328        )));
2329    }
2330    if pr.is_cross_repository {
2331        return Err(Refusal::final_("its head lives in a fork".to_owned()));
2332    }
2333    if pr.base_ref_name != base {
2334        return Err(Refusal::final_(format!(
2335            "it targets `{}`, not `{base}`",
2336            pr.base_ref_name
2337        )));
2338    }
2339    if !pr.state.eq_ignore_ascii_case("open") {
2340        return Err(Refusal::final_(format!(
2341            "it is already {}",
2342            pr.state.to_ascii_lowercase()
2343        )));
2344    }
2345    // Last, so a pull request that is not this run's at all is reported as
2346    // such. A head that is this branch but not a commit checked against the
2347    // base (somebody pushed since) may well get checked next time: retry.
2348    if !verified.contains(&pr.head_ref_oid) {
2349        return Err(Refusal {
2350            retry: true,
2351            why: format!(
2352                "its head {} is not a commit this run checked against the base",
2353                crate::already::short_sha(&pr.head_ref_oid)
2354            ),
2355        });
2356    }
2357    Ok(())
2358}
2359
2360/// Does `remote` point at something a forge could host - a URL or an scp-style
2361/// `user@host:path` - rather than a filesystem path or nothing at all? Judged
2362/// from the URL alone, so it answers the same on every machine, whatever `gh`
2363/// happens to be installed or logged in to.
2364async fn remote_is_forge(repo: &Path, remote: &str) -> bool {
2365    let Ok(url) = git::git(repo, &["remote", "get-url", remote]).await else {
2366        return false;
2367    };
2368    is_forge_url(url.trim())
2369}
2370
2371fn is_forge_url(url: &str) -> bool {
2372    url.contains("://") && !url.starts_with("file://")
2373        || url
2374            .split_once(':')
2375            .is_some_and(|(host, _)| host.contains('@') && !host.contains(['/', '\\']))
2376}
2377
2378/// Does this `gh` failure mean there is no GitHub to ask, as opposed to a
2379/// request that failed?
2380fn forge_unavailable(message: &str) -> bool {
2381    message.contains("known GitHub host") || message.contains("spawn gh")
2382}
2383
2384/// The comment left on a pull request closed because its change is already on
2385/// the base.
2386pub fn superseded_comment(base: &str, evidence: &crate::already::Evidence) -> String {
2387    let how = match evidence.proof {
2388        crate::already::Proof::PatchId => format!(
2389            "carried by commit {} on `{base}` with the same patch",
2390            evidence.names()
2391        ),
2392        crate::already::Proof::Ancestry => {
2393            format!("already in the history of `{base}` as {}", evidence.names())
2394        }
2395        crate::already::Proof::Tree => format!(
2396            "already part of `{base}` (merging this branch changes nothing at {})",
2397            crate::already::short_sha(&evidence.tip)
2398        ),
2399    };
2400    format!(
2401        "Closing: everything this branch adds is {how}, so there is nothing left to \
2402         land. This pull request was closed automatically after that was verified; \
2403         reopen it if you disagree."
2404    )
2405}
2406
2407/// Close the open pull request for `branch`, if there is one and it is
2408/// provably this run's, with a comment naming what supersedes it. `Ok(Ok(url))` is
2409/// the URL closed; `Ok(Err(why))` is a final "nothing to close" (no pull request,
2410/// not this run's, no forge); `Err` is anything a later attempt could resolve (a
2411/// failed `gh` call, a head that moved since it was checked), which the caller
2412/// must not treat as settled.
2413///
2414/// The recorded `state.pr` is preferred, else the forge is asked for an open
2415/// pull request on `branch`; either way the candidate is re-read and passed
2416/// through [`closable`] before anything is written; `verified` lists the
2417/// commits proven to be on the base, and the pull request's head must be one.
2418pub async fn close_superseded_pr(
2419    state: &mut RunState,
2420    branch: &str,
2421    evidence: &crate::already::Evidence,
2422    verified: &[String],
2423) -> Result<std::result::Result<String, String>> {
2424    let repo = state.repo.clone();
2425    let base = state.base_branch.clone();
2426    let url = match state.pr.as_ref().filter(|p| p.state == "open") {
2427        Some(p) => p.url.clone(),
2428        // No recorded pull request. A forge that cannot be asked at all (no
2429        // GitHub remote, no `gh`) says nothing about this run, so that is
2430        // "none found"; any other lookup failure is an error, because "could
2431        // not look" is not "nothing there" and the caller must retry.
2432        None if !remote_is_forge(&repo, &state.config.merge.remote).await => {
2433            return Ok(Err(
2434                "the remote is not a forge, so there is no pull request".to_owned(),
2435            ));
2436        }
2437        None => match find_open_pr(&repo, branch, &base).await {
2438            Err(e) if forge_unavailable(&format!("{e:#}")) => {
2439                return Ok(Err(format!("no forge to ask: {e:#}")));
2440            }
2441            Err(e) => return Err(e),
2442            Ok(OpenPr::One { url, .. }) => url,
2443            Ok(OpenPr::None) => return Ok(Err("no open pull request".to_owned())),
2444            Ok(OpenPr::Many(urls)) => {
2445                return Ok(Err(format!(
2446                    "{} open pull requests name it; not choosing between them",
2447                    urls.len()
2448                )));
2449            }
2450        },
2451    };
2452    let (ok, view) = gh(
2453        &repo,
2454        &[
2455            "pr".to_owned(),
2456            "view".to_owned(),
2457            url.clone(),
2458            "--json".to_owned(),
2459            "headRefName,headRefOid,baseRefName,state,isCrossRepository".to_owned(),
2460        ],
2461    )
2462    .await?;
2463    if !ok {
2464        bail!("gh pr view {url} failed: {view}");
2465    }
2466    if let Err(refusal) = closable(&view, branch, &base, verified) {
2467        // A pull request whose head cannot be tied to what was proven is not
2468        // one to walk away from: the caller keeps the run resumable.
2469        if refusal.retry {
2470            bail!("left {url} open: {}", refusal.why);
2471        }
2472        return Ok(Err(format!("left {url} open: {}", refusal.why)));
2473    }
2474    let (ok, out) = gh(
2475        &repo,
2476        &[
2477            "pr".to_owned(),
2478            "close".to_owned(),
2479            url.clone(),
2480            "--comment".to_owned(),
2481            superseded_comment(&base, evidence),
2482        ],
2483    )
2484    .await?;
2485    if !ok {
2486        bail!("gh pr close {url} failed: {out}");
2487    }
2488    if let Some(p) = state.pr.as_mut().filter(|p| p.url == url) {
2489        p.state = "closed".to_owned();
2490    }
2491    Ok(Ok(url))
2492}
2493
2494/// `gh pr edit <url> --title <title>`, for an adopted pull request whose title
2495/// differs from the one this run computed. Only the title: the body may have
2496/// been edited by the owner and cannot be compared.
2497pub async fn set_pr_title(state: &mut RunState, repo: &Path, url: &str, title: &str) -> Result<()> {
2498    let (title, _) = crate::github_text::prepare(state, title, "");
2499    edit_pr_title(repo, url, &title).await
2500}
2501
2502/// [`set_pr_title`] for a title the owner explicitly chose to post unmodified
2503/// (`github_text::POST_ORIGINAL` or `github_text::USE_REWRITE`): the posting
2504/// gate is skipped on purpose.
2505pub async fn set_pr_title_verbatim(repo: &Path, url: &str, title: &str) -> Result<()> {
2506    edit_pr_title(repo, url, title).await
2507}
2508
2509/// Post both fields of the owner's chosen rewrite to an adopted pull request,
2510/// unmodified and without the posting gate.
2511pub async fn set_pr_text_verbatim(repo: &Path, url: &str, title: &str, body: &str) -> Result<()> {
2512    let (ok, _) = gh(
2513        repo,
2514        &[
2515            "pr".to_owned(),
2516            "edit".to_owned(),
2517            url.to_owned(),
2518            "--title".to_owned(),
2519            title.to_owned(),
2520            "--body".to_owned(),
2521            body.to_owned(),
2522        ],
2523    )
2524    .await
2525    .map_err(|_| anyhow::anyhow!("could not run gh pr edit for the chosen rewrite"))?;
2526    if !ok {
2527        // Command output may echo the chosen text; keep it out of run events.
2528        bail!("gh pr edit failed while posting the chosen rewrite");
2529    }
2530    Ok(())
2531}
2532
2533async fn edit_pr_title(repo: &Path, url: &str, title: &str) -> Result<()> {
2534    let (ok, out) = gh(
2535        repo,
2536        &[
2537            "pr".to_owned(),
2538            "edit".to_owned(),
2539            url.to_owned(),
2540            "--title".to_owned(),
2541            title.to_owned(),
2542        ],
2543    )
2544    .await?;
2545    if !ok {
2546        bail!("gh pr edit failed: {out}");
2547    }
2548    Ok(())
2549}
2550
2551/// Ask GitHub whether this run's winning candidate branch was actually merged
2552/// somewhere `land::land`'s own loop never saw — the gap `magi fold
2553/// --merged` exists to close, minus the operator having to find the URL by
2554/// hand.
2555///
2556/// `Ok(None)` covers every case where nothing can be said with confidence: no
2557/// winner decided yet (nothing to check a branch for), no merged pull request
2558/// found, or [`pick_merged_pr`] found more than one candidate and would not
2559/// guess between them. Never wired to a weaker, URL-less signal like
2560/// [`branch_is_ancestor`] — a caller wanting that has to ask for it
2561/// separately, precisely because it cannot drive an automatic correction on
2562/// its own (see that function's own doc).
2563pub async fn find_external_merge(state: &RunState) -> Result<Option<ExternalMerge>> {
2564    let Some(winner) = state.winner() else {
2565        return Ok(None);
2566    };
2567    let branch = state.pr_branch().unwrap_or(&winner.branch).to_owned();
2568    let out = gh(
2569        &state.repo,
2570        &[
2571            "pr".to_owned(),
2572            "list".to_owned(),
2573            "--head".to_owned(),
2574            branch.clone(),
2575            "--state".to_owned(),
2576            "merged".to_owned(),
2577            "--json".to_owned(),
2578            "url,number,mergedAt,baseRefName".to_owned(),
2579        ],
2580    )
2581    .await?;
2582    if !out.0 {
2583        bail!("gh pr list --head {branch}: {}", out.1);
2584    }
2585    pick_merged_pr(&out.1, &state.base_branch, state.created_at)
2586}
2587
2588/// Whether `branch` is, right now, an ancestor of `base_branch` in the local
2589/// git graph — the weaker, URL-less signal that a branch landed somewhere.
2590///
2591/// Deliberately never consulted by [`find_external_merge`]: a base branch
2592/// that has moved since the run started can make an old, abandoned branch
2593/// look like an ancestor of the *current* base for reasons that have nothing
2594/// to do with a merge (a later commit that happens to supersede it, an
2595/// unrelated squash), and there is no pull request URL here to confirm
2596/// against or to land through anyway. Its only honest use is a weaker
2597/// notice — "this looks merged, go check" — never an automatic rewrite of
2598/// `status`/`merge`.
2599pub async fn branch_is_ancestor(repo: &Path, branch: &str, base_branch: &str) -> Result<bool> {
2600    let out = tokio::process::Command::new("git")
2601        .args(["merge-base", "--is-ancestor", branch, base_branch])
2602        .current_dir(repo)
2603        .quiet()
2604        .stdin(std::process::Stdio::null())
2605        .output()
2606        .await
2607        .context("spawn git merge-base --is-ancestor")?;
2608    Ok(out.status.success())
2609}
2610
2611/// Parse `host/owner/repo` out of a forge URL, with no network access.
2612///
2613/// The host is part of the slug, not discarded: `owner/repo` alone would
2614/// treat `github.example.com/o/r` and `github.com/o/r` as the same
2615/// repository, which is exactly the mix-up the same-repo guard exists to
2616/// catch. Returns `None` for anything that doesn't have a `<host>/<path>`
2617/// shape at all.
2618fn forge_slug(url: &str) -> Option<(String, &str)> {
2619    let rest = url.rsplit("://").next()?;
2620    let (host, path) = rest.split_once('/')?;
2621    if host.is_empty() {
2622        return None;
2623    }
2624    Some((host.to_ascii_lowercase(), path))
2625}
2626
2627/// Parse `host/owner/repo` out of a GitHub pull request URL, with no network
2628/// access - the first half of the same-repo guard [`correct_manual_merge`]
2629/// applies before it writes anything.
2630///
2631/// Returns `None` for anything that does not look like
2632/// `https://<host>/<owner>/<repo>/pull/<n>`, which the caller treats as
2633/// fail-closed: a URL this cannot make sense of refuses rather than guesses.
2634pub(crate) fn slug_of_pr_url(url: &str) -> Option<String> {
2635    let (host, path) = forge_slug(url)?;
2636    let mut segments = path.split('/');
2637    let owner = segments.next()?;
2638    let repo = segments.next()?;
2639    let kind = segments.next()?;
2640    if owner.is_empty() || repo.is_empty() || kind != "pull" {
2641        return None;
2642    }
2643    Some(format!("{host}/{owner}/{repo}"))
2644}
2645
2646/// Parse `host/owner/repo` out of a plain repository URL (no `/pull/<n>`
2647/// suffix), the shape `gh repo view --json url` returns - the other half of
2648/// the same-repo guard, matched against [`slug_of_pr_url`]'s output.
2649fn slug_of_repo_url(url: &str) -> Option<String> {
2650    let (host, path) = forge_slug(url)?;
2651    let mut segments = path.split('/');
2652    let owner = segments.next()?;
2653    let repo = segments.next()?;
2654    if owner.is_empty() || repo.is_empty() {
2655        return None;
2656    }
2657    Some(format!("{host}/{owner}/{repo}"))
2658}
2659
2660/// Refuse to correct a run against a pull request from a different
2661/// repository than the one it is recorded against.
2662///
2663/// This is the guard the shun/8c75 incident argued for: an operator ran
2664/// `magi fold --merged <shun PR url>` meaning to correct an old `Blocked` run
2665/// in a different repository, omitted the run id, and the id defaulted to
2666/// this machine's most recently created run - an unrelated, still-in-progress
2667/// run in a completely different repository - which then had its `status`
2668/// rewritten to `merged` from a pull request it had nothing to do with.
2669/// `correct_manual_merge` now requires an explicit id (see `magi fold`'s own
2670/// CLI help), but a mistyped or stale id could still name a run in a
2671/// different repository than the one the URL belongs to, so this checks that
2672/// independently rather than trusting the id alone.
2673///
2674/// Comparison is case-insensitive - GitHub owner/repo names are - and a
2675/// mismatch names both slugs rather than just refusing, so an operator whose
2676/// local checkout's `origin` is a fork of the repository the pull request was
2677/// opened against (a legitimate setup this cannot tell apart from a genuine
2678/// mix-up) can judge for themselves rather than being blocked with no way to
2679/// see why.
2680pub(crate) fn ensure_same_repo(run_repo_slug: &str, pr_repo_slug: &str) -> Result<()> {
2681    if run_repo_slug.eq_ignore_ascii_case(pr_repo_slug) {
2682        return Ok(());
2683    }
2684    bail!(
2685        "refusing to correct this run: it is recorded against {run_repo_slug}, but the pull \
2686         request URL belongs to {pr_repo_slug} - pass the run id whose repository the URL \
2687         actually belongs to (or, if `origin` is a fork opened against a different upstream, \
2688         verify by hand before treating this as a false positive)"
2689    );
2690}
2691
2692/// Ask the forge which `host/owner/repo` a local checkout's `origin` remote
2693/// actually resolves to, for the same-repo guard in [`correct_manual_merge`].
2694///
2695/// Asking `gh` rather than parsing `git remote -v` locally is deliberate: it
2696/// normalizes case, SSH vs. HTTPS remotes, and a renamed or transferred
2697/// repository the same way GitHub itself would recognize it, so the
2698/// comparison in [`ensure_same_repo`] is against the same canonical slug on
2699/// both sides. Reads `url` rather than `nameWithOwner` so the host is part of
2700/// the answer too - `nameWithOwner` alone cannot tell a `github.com` repo from
2701/// a same-named one on a GitHub Enterprise host.
2702async fn repo_slug(repo: &Path) -> Result<String> {
2703    let out = gh(
2704        repo,
2705        &[
2706            "repo".to_owned(),
2707            "view".to_owned(),
2708            "--json".to_owned(),
2709            "url".to_owned(),
2710        ],
2711    )
2712    .await?;
2713    if !out.0 {
2714        bail!("gh repo view --json url: {}", out.1);
2715    }
2716    #[derive(Debug, Deserialize)]
2717    struct GhRepo {
2718        url: String,
2719    }
2720    let parsed: GhRepo = serde_json::from_str(&out.1)
2721        .with_context(|| format!("parse `gh repo view` output: {}", out.1))?;
2722    slug_of_repo_url(&parsed.url)
2723        .with_context(|| format!("could not parse a host/owner/repo out of {}", parsed.url))
2724}
2725
2726/// Confirm `url` is actually a merged pull request, then rewrite `state`'s
2727/// `status` and `merge` exactly as the automatic land loop (`land::land`)
2728/// would have written them had magi opened and merged this pull request
2729/// itself.
2730///
2731/// This is `magi fold --merged`'s whole implementation, and also what the
2732/// web `fold-merged` route calls once it has a URL in hand — an operator
2733/// recovery path for a merge magi could not finish on its own: a PR title too
2734/// long for the GraphQL mutation, `gh pr create` unreachable, a stale token -
2735/// closed by hand with a pull request magi never opened and so never
2736/// recorded. Reusing `land::land` rather than writing `status`/`merge`
2737/// directly keeps this one authoritative: a merged pull request decides
2738/// `Step::Done { merged: true }` on the very first read, before any of
2739/// `land`'s own checks/fix/rebase machinery can run, which is what makes it
2740/// safe to call here even though this pull request was never magi's own.
2741///
2742/// [`ensure_same_repo`] is checked before anything else: a pull request from
2743/// a different repository than the one `state` is recorded against is
2744/// refused outright, regardless of its lifecycle. This is the guard for a
2745/// URL an *operator* hands in - the CLI or the web route - where a stale or
2746/// mistyped run id could otherwise get corrected from an unrelated
2747/// repository's pull request (see the shun/8c75 incident in `magi fold`'s own
2748/// CLI help). The automatic janitor sweep (`clean::reconcile_external_merges`)
2749/// goes through [`correct_confirmed_external_merge`] instead, which skips
2750/// this check: its `url` was never operator-supplied, it comes from
2751/// [`find_external_merge`] querying `gh` from inside `state.repo` itself, so
2752/// it is already guaranteed to name a pull request in that same repository -
2753/// re-deriving and re-checking the repository here would only be a second
2754/// `gh repo view` call that can fail for reasons that have nothing to do with
2755/// correctness (a rate limit, a network blip), turning a self-heal that would
2756/// otherwise have succeeded into a run left `Blocked` for another pass.
2757///
2758/// [`lifecycle`] is checked next and separately so a mistyped or still-open
2759/// URL fails loudly without writing anything, rather than handing an open
2760/// pull request to the full autonomous loop by accident.
2761///
2762/// Correcting `status` this way does not run `bump::after_merge`
2763/// (`src/bump.rs`): that call is made only from `graph::Runner::run_land`,
2764/// which this path never goes through. A release version bump the change
2765/// might have earned is therefore not filed automatically and has to be
2766/// requested by hand - recorded as an event on the run so the gap is visible
2767/// to whoever reads it later, not just wherever this was called from. Follow-up
2768/// tasks for findings the merge left open (`crate::followup`) *are* filed here.
2769///
2770/// Returns the status before and after, so every caller (CLI, janitor, web
2771/// route) can build its own log line or response from the same pair rather
2772/// than each re-deriving it.
2773pub async fn correct_manual_merge(
2774    state: &mut RunState,
2775    url: &str,
2776) -> Result<(RunStatus, RunStatus)> {
2777    let Some(pr_slug) = slug_of_pr_url(url) else {
2778        bail!(
2779            "could not parse an owner/repo out of {url}; refusing to guess which repository \
2780             this pull request belongs to"
2781        );
2782    };
2783    let run_slug = repo_slug(&state.repo).await?;
2784    ensure_same_repo(&run_slug, &pr_slug)?;
2785    correct_merge(state, url).await
2786}
2787
2788/// The janitor's own entry point into the same correction
2789/// [`correct_manual_merge`] performs for an operator-supplied URL, minus the
2790/// same-repo guard - see that function's own doc for why skipping it here is
2791/// safe rather than a hole: [`clean::reconcile_external_merges`] only ever
2792/// calls this with a `url` [`find_external_merge`] already found by querying
2793/// `state.repo`'s own remote, so the guard could never do anything here but
2794/// fail on its own transient errors.
2795///
2796/// [`crate::clean`] is the only caller; `pub(crate)` rather than private only
2797/// because it lives in a different module.
2798pub(crate) async fn correct_confirmed_external_merge(
2799    state: &mut RunState,
2800    url: &str,
2801) -> Result<(RunStatus, RunStatus)> {
2802    correct_merge(state, url).await
2803}
2804
2805/// Same pull request, same repository: the url, or the number within one repo.
2806fn names_same_pr(a: &RunState, url: &str, number: u64, repo: &Path) -> bool {
2807    let Some(pr) = a.pr.as_ref() else {
2808        return false;
2809    };
2810    if !url.is_empty()
2811        && pr
2812            .url
2813            .trim_end_matches('/')
2814            .eq_ignore_ascii_case(url.trim_end_matches('/'))
2815    {
2816        return true;
2817    }
2818    number > 0
2819        && pr.number == number
2820        && match (a.repo.canonicalize(), repo.canonicalize()) {
2821            (Ok(x), Ok(y)) => x == y,
2822            _ => a.repo == repo,
2823        }
2824}
2825
2826/// Rewrite `pr.state` to a final state on every run record under `home` that
2827/// `decide` picks, and report how many were rewritten.
2828///
2829/// Lifecycle writes through to other runs are deliberately narrow (task-head
2830/// ownership is recorded separately): only a **terminal** run (never one a
2831/// driver may still be writing), only a proven-stopped driver with no daemon
2832/// claim (the shared liveness judge), only a record
2833/// whose `pr.state` is still `open`, and only `merged` / `closed` ever goes in.
2834/// The record is read as folding reads it (no schema check: every bump so far
2835/// only added fields, and the whole struct round-trips) and written through
2836/// [`RunState::save_under`], the path every record uses, so nothing but
2837/// `pr.state` and an event line changes (and `updated_at`, as for any save).
2838/// A run that cannot be read or written is skipped with a warning.
2839fn rewrite_open_prs(
2840    home: &Path,
2841    decide: &mut dyn FnMut(&RunState) -> Option<PrLifecycle>,
2842) -> usize {
2843    let now = Timestamp::now();
2844    let mut changed = 0;
2845    for id in crate::run::list_ids_in(&home.join("runs")) {
2846        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2847            continue;
2848        };
2849        let path = home.join("runs").join(&id).join("run.json");
2850        let Ok(body) = std::fs::read_to_string(&path) else {
2851            continue;
2852        };
2853        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2854            continue;
2855        };
2856        if !state.status.done()
2857            || state.pr.as_ref().is_none_or(|p| p.state != "open")
2858            || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2859                != crate::run::Liveness::Dead
2860        {
2861            continue;
2862        }
2863        let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2864            continue;
2865        };
2866        if let Some(pr) = state.pr.as_mut() {
2867            pr.state = to.as_str().to_owned();
2868        }
2869        let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2870        state.event(
2871            "land",
2872            format!("recorded {url} as {}: another run settled it", to.as_str()),
2873        );
2874        match state.save_under(home) {
2875            Ok(()) => changed += 1,
2876            Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2877        }
2878    }
2879    changed
2880}
2881
2882/// A run reached a final state for its pull request: tell every other terminal
2883/// run in the same repository that names the same pull request (handed-over
2884/// predecessors, blocked attempts, anything), so their records stop saying
2885/// `open`. Best effort; `run`'s own record is the caller's.
2886pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2887    if to == PrLifecycle::Open {
2888        return;
2889    }
2890    let Some(home) = crate::run::try_home() else {
2891        return;
2892    };
2893    write_pr_state_through_in(&home, run, to);
2894}
2895
2896pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2897    let Some(pr) = run.pr.as_ref() else {
2898        return 0;
2899    };
2900    let (url, number) = (pr.url.clone(), pr.number);
2901    rewrite_open_prs(home, &mut |other| {
2902        (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2903    })
2904}
2905
2906/// Terminal runs whose record still says their pull request is open, as
2907/// `(run id, repo, url)`, for [`repair_stale_pr_states`].
2908pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
2909    let now = Timestamp::now();
2910    let mut out = Vec::new();
2911    for id in crate::run::list_ids_in(&home.join("runs")) {
2912        let path = home.join("runs").join(&id).join("run.json");
2913        let Ok(body) = std::fs::read_to_string(&path) else {
2914            continue;
2915        };
2916        let Ok(state) = serde_json::from_str::<RunState>(&body) else {
2917            continue;
2918        };
2919        if let Some(pr) = state.pr.as_ref()
2920            && state.status.done()
2921            && pr.state == "open"
2922            && !pr.url.is_empty()
2923            && !crate::daemon::is_working_on(home, &id, now)
2924        {
2925            out.push((id, state.repo.clone(), pr.url.clone()));
2926        }
2927    }
2928    out
2929}
2930
2931/// Apply forge answers (`pr url -> state`) to every stale terminal record.
2932/// A url with no answer (the forge was unreadable) changes nothing.
2933pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
2934    rewrite_open_prs(home, &mut |s| {
2935        s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
2936    })
2937}
2938
2939/// One-time (and idempotent) repair of records that froze an `open` pull
2940/// request: ask the forge about each distinct pull request that a terminal run
2941/// still calls open - at most `max_lookups` of them - and rewrite the merged
2942/// and closed ones. A genuinely open pull request is left alone, and a lookup
2943/// that fails is "unknown, change nothing". Returns `(records rewritten,
2944/// lookups that failed)`.
2945pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
2946    let mut known = BTreeMap::new();
2947    let mut failed = 0;
2948    let mut seen = BTreeSet::new();
2949    for (_, repo, url) in stale_open_prs(home) {
2950        if known.len() + failed >= max_lookups || !seen.insert(url.clone()) {
2951            continue;
2952        }
2953        match lifecycle(&repo, &url).await {
2954            Ok(state) => {
2955                known.insert(url, state);
2956            }
2957            Err(e) => {
2958                tracing::warn!("repair pr state of {url}: {e:#}");
2959                failed += 1;
2960            }
2961        }
2962    }
2963    (apply_pr_states(home, &known), failed)
2964}
2965
2966async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
2967    match lifecycle(&state.repo, url).await? {
2968        PrLifecycle::Merged => {}
2969        other => bail!(
2970            "{url} is {}, not merged; refusing to record {} as merged on a guess",
2971            other.as_str(),
2972            state.id
2973        ),
2974    }
2975    let before = state.status;
2976    if let Err(e) = land(state, url).await {
2977        // `land` sets `status` to `Landing` and saves before its first read
2978        // of the pull request — see its own doc — so a failure here (a
2979        // transient `gh` hiccup between the two forge reads this function
2980        // makes) can leave the run stuck on that in-between value with
2981        // nothing left driving it. Land it on the same terminal shape an
2982        // automated `land` failure lands on instead of leaving it stuck.
2983        state.status = RunStatus::Blocked;
2984        state.event("fold", format!("manual-merge correction failed: {e:#}"));
2985        state.save()?;
2986        return Err(e).context(format!("confirming the merge of {url}"));
2987    }
2988    state.event(
2989        "fold",
2990        "operator recorded this pull request as a manual merge; this run never \
2991         re-entered `land`, so `bump::after_merge` did not run for it - a release \
2992         bump this change might warrant has to be filed by hand",
2993    );
2994    // Unlike the bump, the findings the merge left open are filed on this
2995    // path too: nothing else would ever carry them forward.
2996    if state.status == RunStatus::Merged {
2997        crate::followup::after_merge(state, url).await;
2998    }
2999    state.save()?;
3000    Ok((before, state.status))
3001}
3002
3003/// Parse `gh api repos/{owner}/{repo}/pulls/<n>/comments` into inline review
3004/// comments. No I/O.
3005///
3006/// `gh pr view` does not surface inline comments, and inline is exactly where
3007/// both review bots put their findings - a landing loop that read only the
3008/// top-level thread would never see the thing it is supposed to fix.
3009pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3010    let raw: Vec<GhInline> =
3011        serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3012    let mut out = Vec::new();
3013    for c in raw {
3014        push_if_outstanding(
3015            &mut out,
3016            ReviewComment {
3017                author: c.user.login,
3018                path: c.path,
3019                line: c.line,
3020                body: c.body,
3021            },
3022        );
3023    }
3024    Ok(out)
3025}
3026
3027/// Keep a comment only when it asks for something.
3028///
3029/// An inline comment always does: it names a file and a line. A top-level
3030/// comment is dropped when it is empty, when it is magi's own, or when it is
3031/// [noise](is_noise).
3032fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3033    if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3034        return;
3035    }
3036    if comment.path.is_none() && is_noise(&comment.body) {
3037        return;
3038    }
3039    out.push(comment);
3040}
3041
3042/// Is this comment body machinery rather than a finding?
3043///
3044/// Two tests, both structural, because guessing from prose is how a "looks
3045/// good to me" turns into a fix round:
3046///
3047/// 1. The bot said so - the body carries one of the [`NOT_A_REVIEW`] markers
3048///    with which CodeRabbit labels its trigger notice, its walkthrough, and its
3049///    footer.
3050/// 2. It asks for nothing - once HTML comments, `<details>` blocks, headings,
3051///    horizontal rules, and the bot's own status banner are removed, every
3052///    remaining line is a task-list item. That is exactly the shape of the
3053///    comment the Claude review job posts while it is still working.
3054///
3055/// Anything else is input, including bot prose. A bot that writes a paragraph
3056/// has said something, and the fix prompt tells the fixer it may decline a
3057/// comment with an argument - a wasted sentence in a prompt is cheaper than a
3058/// missed finding.
3059pub fn is_noise(body: &str) -> bool {
3060    if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3061        return true;
3062    }
3063    let mut content = false;
3064    for line in strip_blocks(body).lines() {
3065        let line = unquote(line);
3066        if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3067            continue;
3068        }
3069        content = true;
3070        break;
3071    }
3072    !content
3073}
3074
3075/// Remove HTML comments and collapsed `<details>` blocks.
3076fn strip_blocks(body: &str) -> String {
3077    let mut out = String::with_capacity(body.len());
3078    let mut rest = body;
3079    loop {
3080        let open = ["<!--", "<details>"]
3081            .iter()
3082            .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3083            .min_by_key(|(i, _)| *i);
3084        let Some((at, tag)) = open else {
3085            out.push_str(rest);
3086            return out;
3087        };
3088        out.push_str(&rest[..at]);
3089        let after = &rest[at + tag.len()..];
3090        let close = if tag == "<!--" { "-->" } else { "</details>" };
3091        match after.find(close) {
3092            Some(end) => rest = &after[end + close.len()..],
3093            // Unterminated: the rest of the body is inside the block.
3094            None => return out,
3095        }
3096    }
3097}
3098
3099/// Strip blockquote markers, which both bots wrap their callouts in.
3100fn unquote(line: &str) -> &str {
3101    let mut s = line.trim();
3102    while let Some(rest) = s.strip_prefix('>') {
3103        s = rest.trim_start();
3104    }
3105    s.trim()
3106}
3107
3108/// `- [ ]` / `- [x]`, in any of the bullet styles GitHub renders.
3109fn is_checklist(line: &str) -> bool {
3110    let rest = line
3111        .strip_prefix("- ")
3112        .or_else(|| line.strip_prefix("* "))
3113        .unwrap_or("");
3114    let rest = rest.trim_start();
3115    matches!(
3116        rest.get(..3),
3117        Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3118    )
3119}
3120
3121/// A heading, a horizontal rule, or a callout tag - shape, never content.
3122fn is_decoration(line: &str) -> bool {
3123    line.starts_with('#')
3124        || line.starts_with("[!")
3125        || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3126}
3127
3128/// A line that is nothing but emphasis and links.
3129///
3130/// Both review jobs open with a status banner
3131/// (`**Claude finished ... in 4m 14s** —— [View job](url)`). It reads as prose
3132/// to a line-based test and asks for nothing, so it is measured the same way a
3133/// heading is: strip the markup, and if no word survives, it was decoration.
3134fn is_banner(line: &str) -> bool {
3135    let plain = drop_spans(line, "**", "**");
3136    let plain = if plain.contains("](") {
3137        drop_spans(&plain, "[", ")")
3138    } else {
3139        plain
3140    };
3141    !plain.chars().any(char::is_alphanumeric)
3142}
3143
3144/// Remove every `open` .. `close` span, including the delimiters. An
3145/// unterminated span swallows the rest of the input, which is what a reader
3146/// sees too.
3147fn drop_spans(s: &str, open: &str, close: &str) -> String {
3148    let mut out = String::with_capacity(s.len());
3149    let mut rest = s;
3150    while let Some(at) = rest.find(open) {
3151        out.push_str(&rest[..at]);
3152        let after = &rest[at + open.len()..];
3153        match after.find(close) {
3154            Some(end) => rest = &after[end + close.len()..],
3155            None => return out,
3156        }
3157    }
3158    out.push_str(rest);
3159    out
3160}
3161
3162/// The lock that keeps at most one run per repository actually moving the
3163/// base branch at a time: a rebase push, or `gh pr merge`.
3164///
3165/// Deliberately narrow. Everything else in [`land`]'s loop - watching CI,
3166/// running a fix round in the winner's own worktree, waiting on the owner's
3167/// approval - touches nothing a *different* run in the same repository could
3168/// collide with, and holding a lock across any of that would serialise one
3169/// run's CI wait (up to [`WAIT_CEILING`]) against another run's land-approval
3170/// resume, which is precisely the "must not wait on another task" property
3171/// the daemon's slot-freeing exists to give a resume. Only the two moments
3172/// that actually write to the shared base branch need mutual exclusion, and
3173/// both are brief.
3174///
3175/// One entry per repository, each its own `tokio::sync::Mutex`, so two
3176/// different repositories' runs never wait on each other. The outer
3177/// `std::sync::Mutex` guards only the map itself, held long enough to find or
3178/// insert an entry and clone its `Arc`, never across an `.await`.
3179fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3180    static LOCKS: std::sync::LazyLock<
3181        std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3182    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3183    LOCKS
3184        .lock()
3185        .unwrap_or_else(std::sync::PoisonError::into_inner)
3186        .entry(repo.to_path_buf())
3187        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3188        .clone()
3189}
3190
3191/// `owner/repo` out of a pull request url, falling back to the checkout's
3192/// directory name when the url is not the usual `host/owner/repo/pull/N`.
3193fn repo_label(repo: &Path, pr_url: &str) -> String {
3194    let parts: Vec<&str> = pr_url.split('/').collect();
3195    if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3196        && at >= 2
3197        && !parts[at - 1].is_empty()
3198        && !parts[at - 2].is_empty()
3199    {
3200        return format!("{}/{}", parts[at - 2], parts[at - 1]);
3201    }
3202    repo.file_name()
3203        .map(|n| n.to_string_lossy().into_owned())
3204        .unwrap_or_default()
3205}
3206
3207/// The operator-facing sentence for a merge that went ahead with red checks,
3208/// or `None` when the checks were not red. Judged on `checks`, not on
3209/// `failing`, which can be non-empty on a green observation.
3210fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3211    (pr.checks == Checks::Red).then(|| {
3212        let details = crate::notices::format_list(&pr.failing)
3213            .map(|names| format!(": {names}"))
3214            .unwrap_or_default();
3215        format!(
3216            "Merged {repo_name} PR #{} with red checks{details} ({})",
3217            pr.number, pr.url
3218        )
3219    })
3220}
3221
3222/// After a merge that succeeded: record which checks were red and tell the
3223/// operator. The decision to merge is already made; this only makes it audible.
3224/// Best-effort - a broken notifier never fails the run.
3225async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3226    let repo_name = repo_label(&state.repo, &pr.url);
3227    let Some(summary) = red_merge_summary(&repo_name, pr) else {
3228        return;
3229    };
3230    if let Some(rec) = state.pr.as_mut() {
3231        rec.red_at_merge = pr.failing.clone();
3232    }
3233    state.event("land", summary.clone());
3234    // The notice pages through `[notify]` itself, once, unless a question
3235    // already carries the cause.
3236    crate::notices::raise_with(
3237        crate::notices::merged_red(&state.id, &summary),
3238        &state.config.notify,
3239    );
3240}
3241
3242/// Run the loop against a real pull request until it merges or the budget runs
3243/// out.
3244///
3245/// The caller decides whether landing happens at all: this is only reached when
3246/// `graph.land` is on. Returns the last observation, so the caller can report
3247/// what magi was looking at when it stopped.
3248pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3249    land_with(state, pr_url, &GhForge).await
3250}
3251
3252/// The forge calls whose timing the loop's decisions depend on, behind a seam
3253/// so a test can script what the pull request looks like from one observation
3254/// to the next. Comments, logs and rebases stay on `gh` and `git` directly.
3255trait Forge {
3256    async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3257        let (ok, out) = gh(
3258            repo,
3259            &[
3260                "pr".into(),
3261                "close".into(),
3262                pr_url.into(),
3263                "--comment".into(),
3264                comment.into(),
3265            ],
3266        )
3267        .await?;
3268        if !ok {
3269            bail!("PR closure failed: {out}");
3270        }
3271        Ok(())
3272    }
3273    async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3274        None
3275    }
3276    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3277    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3278    async fn poll(&self);
3279    /// Rerun the failed jobs of one workflow run.
3280    async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3281    /// Unix seconds, behind the seam so a test owns the clock.
3282    fn now(&self) -> i64;
3283    /// The check contexts the base branch requires, for a stop reason only.
3284    /// `None` when they could not be read, which is not the same as none.
3285    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3286    #[allow(clippy::too_many_arguments)]
3287    async fn fix(
3288        &self,
3289        state: &mut RunState,
3290        pr: &PrState,
3291        round: usize,
3292        budget: usize,
3293        reason: &str,
3294        logs: &str,
3295    ) -> Result<Fixed>;
3296}
3297
3298struct GhForge;
3299
3300impl Forge for GhForge {
3301    async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3302        collect_ci_evidence(state, seen).await
3303    }
3304    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3305        observe(repo, pr_url).await
3306    }
3307    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3308        gh(repo, argv).await
3309    }
3310    async fn poll(&self) {
3311        tokio::time::sleep(POLL).await;
3312    }
3313    async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3314        let args = [
3315            "run".to_owned(),
3316            "rerun".to_owned(),
3317            run.to_owned(),
3318            "--failed".to_owned(),
3319        ];
3320        let (ok, out) = gh(repo, &args).await?;
3321        if !ok {
3322            bail!("gh run rerun {run}: {out}");
3323        }
3324        Ok(())
3325    }
3326    fn now(&self) -> i64 {
3327        jiff::Timestamp::now().as_second()
3328    }
3329    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3330        required_contexts_of(repo, base).await
3331    }
3332    async fn fix(
3333        &self,
3334        state: &mut RunState,
3335        pr: &PrState,
3336        round: usize,
3337        budget: usize,
3338        reason: &str,
3339        logs: &str,
3340    ) -> Result<Fixed> {
3341        fix_round(state, pr, round, budget, reason, logs).await
3342    }
3343}
3344
3345/// Percent-encode a branch name for a URL path segment (`/` included).
3346fn encode_path_segment(s: &str) -> String {
3347    let mut out = String::new();
3348    for b in s.bytes() {
3349        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3350            out.push(b as char);
3351        } else {
3352            let _ = write!(out, "%{b:02X}");
3353        }
3354    }
3355    out
3356}
3357
3358/// Read the required contexts of `base` from classic branch protection and
3359/// from rulesets, once, for a stop reason. Organisation-level rulesets that
3360/// these two endpoints do not list are missed. Any unreadable source makes the
3361/// whole answer `None`: a partial set would read as a complete one.
3362async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3363    let enc = encode_path_segment(base);
3364    let mut all = BTreeSet::new();
3365    // Classic protection answers 404 for an unprotected branch, which is
3366    // "nothing required here", not a failure to read.
3367    let classic = gh(
3368        repo,
3369        &[
3370            "api".to_owned(),
3371            format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3372        ],
3373    )
3374    .await
3375    .ok()?;
3376    if classic.0 {
3377        all.extend(parse_classic_required(&classic.1)?);
3378    } else if !classic.1.contains("404") {
3379        return None;
3380    }
3381    let rules = gh(
3382        repo,
3383        &[
3384            "api".to_owned(),
3385            format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3386        ],
3387    )
3388    .await
3389    .ok()?;
3390    if !rules.0 {
3391        return None;
3392    }
3393    all.extend(parse_ruleset_required(&rules.1)?);
3394    Some(all)
3395}
3396
3397/// `required_status_checks` of classic protection: `contexts` plus the
3398/// `checks[].context` form.
3399fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3400    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3401    let mut out = BTreeSet::new();
3402    for c in v.get("contexts")?.as_array()? {
3403        out.insert(c.as_str()?.to_owned());
3404    }
3405    for c in v
3406        .get("checks")
3407        .and_then(|c| c.as_array())
3408        .into_iter()
3409        .flatten()
3410    {
3411        if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3412            out.insert(name.to_owned());
3413        }
3414    }
3415    Some(out)
3416}
3417
3418/// `rules/branches/<base>`: every `required_status_checks` rule's contexts.
3419fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3420    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3421    let mut out = BTreeSet::new();
3422    for rule in v.as_array()? {
3423        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3424            continue;
3425        }
3426        let checks = rule
3427            .pointer("/parameters/required_status_checks")?
3428            .as_array()?;
3429        for c in checks {
3430            out.insert(c.get("context")?.as_str()?.to_owned());
3431        }
3432    }
3433    Some(out)
3434}
3435
3436/// Is the observation older than the commit a fix round pushed?
3437///
3438/// The forge takes a few seconds to move the pull request to a new head and
3439/// attach that head's check runs, and until it has, the rollup is the previous
3440/// head's - all green, which is exactly what a merge decision must not read.
3441/// An absent or different head counts as not yet: guessing "close enough"
3442/// would reopen the hole.
3443fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3444    awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3445}
3446
3447/// The commit an observation may be decided on, or `None` while it cannot be
3448/// trusted to describe one.
3449///
3450/// `None` when a pushed commit is awaited and the pull request is not on it,
3451/// when the head is unreadable, or when the rollup (`statusCheckRollup` is the
3452/// last commit's) is not the head's: that is the previous commit's checks. The
3453/// caller re-polls on `None`. A rollup that cannot be read (including one
3454/// longer than a page) leaves `rollup_head` empty, so the wait runs to
3455/// [`WAIT_CEILING`] and stops - a safe failure, never a merge.
3456fn bound_head<'a>(
3457    seen_head: &'a str,
3458    rollup_head: &str,
3459    awaiting: Option<&str>,
3460) -> Option<&'a str> {
3461    if seen_head.is_empty()
3462        || awaiting_new_head(awaiting, seen_head)
3463        || !rollup_head.eq_ignore_ascii_case(seen_head)
3464    {
3465        return None;
3466    }
3467    Some(seen_head)
3468}
3469
3470/// What a refused `gh pr merge` means.
3471#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3472enum Refused {
3473    /// An open PR on the observed head has a proven stale base.
3474    Behind,
3475    /// The branch policy is not satisfied *yet*: go back to waiting.
3476    Pending,
3477    /// Checks have settled and the merge state still says no, seen for the
3478    /// first time. The forge updates `mergeStateStatus` a moment after the last
3479    /// check finishes, so one more look is allowed before believing it.
3480    Recheck,
3481    /// Nothing is in flight and the policy still refuses: a person has to
3482    /// supply what it asks for (a review, say).
3483    Final,
3484}
3485
3486/// Judged from the pull request's state after the refusal, never from the
3487/// refusal's wording, which belongs to the forge and changes.
3488fn classify_refusal(
3489    after: Option<&Seen>,
3490    rechecked: bool,
3491    observed_head: &str,
3492    ci: CiExpectation,
3493) -> Refused {
3494    let Some(after) = after else {
3495        // Unreadable is not evidence of anything; the next loop reads again.
3496        return Refused::Pending;
3497    };
3498    if after.pr.state != PrLifecycle::Open {
3499        return Refused::Final;
3500    }
3501    // The branch moved after it was observed (the forge refuses a merge pinned
3502    // to the old commit): not a verdict on anything, look again.
3503    if !after.head.eq_ignore_ascii_case(observed_head) {
3504        return Refused::Pending;
3505    }
3506    if Blocking::of(&after.merge_state) == Blocking::Behind {
3507        return Refused::Behind;
3508    }
3509    // The same binding the loop applies: checks of another commit say nothing.
3510    if bound_head(&after.head, &after.rollup_head, None).is_none() {
3511        return Refused::Pending;
3512    }
3513    let state = after.merge_state.to_ascii_uppercase();
3514    if (ci == CiExpectation::Expected
3515        && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3516        || state.is_empty()
3517        || state == "UNKNOWN"
3518    {
3519        return Refused::Pending;
3520    }
3521    if rechecked {
3522        Refused::Final
3523    } else {
3524        Refused::Recheck
3525    }
3526}
3527
3528/// Take auto-merge back from the forge and forget that it was armed.
3529///
3530/// `Err` carries the forge's message: the caller must not push or move on, as
3531/// an armed merge left behind could still fire for a commit nobody approved.
3532async fn disarm<F: Forge>(
3533    forge: &F,
3534    state: &mut RunState,
3535    repo: &Path,
3536    number: u64,
3537) -> std::result::Result<(), String> {
3538    let argv = disable_automerge_argv(number);
3539    let out = {
3540        let merge_lock = repo_merge_lock(repo);
3541        let _merge_slot = merge_lock.lock().await;
3542        forge.merge(repo, &argv).await
3543    };
3544    match out {
3545        Ok((true, _)) => {
3546            state.land_armed_head = None;
3547            state.event("land", "auto-merge disabled");
3548            state.save().map_err(|e| format!("{e:#}"))?;
3549            Ok(())
3550        }
3551        Ok((false, msg)) => Err(msg),
3552        Err(e) => Err(format!("{e:#}")),
3553    }
3554}
3555
3556/// [`stop`], first taking back an armed auto-merge so a pull request magi
3557/// gave up on does not merge on its own later. A failure to disarm is added
3558/// to the reason rather than hiding it.
3559async fn stop_disarmed<F: Forge>(
3560    forge: &F,
3561    state: &mut RunState,
3562    repo: &Path,
3563    pr: &PrState,
3564    why: &str,
3565) -> Result<()> {
3566    if state.land_armed_head.is_none() {
3567        return stop(state, repo, pr, why).await;
3568    }
3569    match disarm(forge, state, repo, pr.number).await {
3570        Ok(()) => stop(state, repo, pr, why).await,
3571        Err(e) => {
3572            let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3573            stop(state, repo, pr, &why).await
3574        }
3575    }
3576}
3577
3578/// Check the persisted card again around awaits that can outlive an owner tap.
3579fn owner_requested_stop(state: &RunState) -> Result<bool> {
3580    let Some(binding) = &state.land_approval else {
3581        return Ok(false);
3582    };
3583    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3584    Ok(q.run == state.id
3585        && q.node == APPROVAL_NODE
3586        && q.resolution()
3587            .as_deref()
3588            .is_some_and(crate::merge_decision::stops))
3589}
3590
3591/// Read stop choices before checks, repair or rebase. These are about stopping
3592/// ownership, so a changed head never cancels them as it cancels merge consent.
3593async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3594    use crate::merge_decision as md;
3595    let Some(binding) = &state.land_approval else {
3596        return Ok(false);
3597    };
3598    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3599    let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3600        return Ok(false);
3601    };
3602    if q.run != state.id || q.node != APPROVAL_NODE {
3603        bail!("stop decision names another run");
3604    }
3605    let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3606        pr: pr.url.clone(),
3607        head: binding.head.clone(),
3608        language: state.config.graph.language.clone(),
3609    });
3610    if target.pr != pr.url {
3611        bail!("stop decision names another PR");
3612    }
3613    if state.merge_decision.is_none() {
3614        state.merge_decision = Some(md::Decision {
3615            question: q.id.clone(),
3616            target,
3617            choice: choice.clone(),
3618            closed: false,
3619            replacement_run: None,
3620            replacement_pr: None,
3621        });
3622        state.save()?;
3623    }
3624    let repo = state.repo.clone();
3625    // Always disable, including arms left by an older driver.
3626    if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3627        stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3628        return Ok(true);
3629    }
3630    if choice.eq_ignore_ascii_case(HOLD) {
3631        stop(
3632            state,
3633            &repo,
3634            pr,
3635            "owner held the decision: PR left open; no further repair or merge work",
3636        )
3637        .await?;
3638        return Ok(true);
3639    }
3640    if md::selected_agent(&choice).is_some()
3641        || state
3642            .origin
3643            .as_ref()
3644            .and_then(|o| o.task.as_ref())
3645            .is_some()
3646    {
3647        let owners: Vec<_> = crate::queue::Queue::open()
3648            .list()
3649            .into_iter()
3650            .filter(|task| task.execution_runs().last() == Some(&state.id))
3651            .collect();
3652        let owner = (owners.len() == 1).then(|| &owners[0]);
3653        if !owner.is_some_and(|task| {
3654            task.execution_runs().last() == Some(&state.id)
3655                && (!task
3656                    .operator_decided_at
3657                    .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3658                    || task.resumption.as_ref().is_some_and(|release| {
3659                        release.question_id.as_deref() == Some(q.id.as_str())
3660                            && task.operator_decided_at == Some(release.at)
3661                    }))
3662        }) {
3663            stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3664            return Ok(true);
3665        }
3666    }
3667    if pr.state == PrLifecycle::Merged {
3668        stop(
3669            state,
3670            &repo,
3671            pr,
3672            "PR already merged; withdrawal/replacement cannot be applied",
3673        )
3674        .await?;
3675        return Ok(true);
3676    }
3677    let comment = format!(
3678        "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3679        q.id, choice, state.id
3680    );
3681    if pr.state == PrLifecycle::Open {
3682        if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3683            stop(
3684                state,
3685                &repo,
3686                pr,
3687                &format!(
3688                    "owner requested closure but it failed: {e}; task held, no replacement started"
3689                ),
3690            )
3691            .await?;
3692            return Ok(true);
3693        }
3694    }
3695    let confirmed = forge.view(&repo, &pr.url).await?;
3696    if confirmed.pr.state != PrLifecycle::Closed {
3697        stop(
3698            state,
3699            &repo,
3700            pr,
3701            "PR closure was not confirmed; task held, no replacement started",
3702        )
3703        .await?;
3704        return Ok(true);
3705    }
3706    *pr = confirmed.pr;
3707    state.merge_decision.as_mut().unwrap().closed = true;
3708    if let Some(record) = &mut state.pr {
3709        record.state = "closed".into();
3710    }
3711    state.status = RunStatus::Superseded;
3712    state.merge = Some(MergeOutcome {
3713        mode: MergeMode::Pr,
3714        ok: false,
3715        detail: format!("owner decision: {choice}; PR closure confirmed"),
3716        empty: false,
3717    });
3718    state.event(
3719        "land",
3720        format!(
3721            "{} applied: PR closure confirmed; old execution retired",
3722            choice
3723        ),
3724    );
3725    state.save()?;
3726    Ok(true)
3727}
3728
3729/// Keep an unstarted verification resumable without charging a task attempt.
3730fn check_landing_resources(
3731    state: &mut RunState,
3732    node: &str,
3733    outcomes: &[crate::run::CommandOutcome],
3734) -> Result<()> {
3735    if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
3736        let detail = format!("{}: {}", blocked.command, blocked.output_tail);
3737        state
3738            .resource_block
3739            .get_or_insert_with(|| crate::run::ResourceBlock {
3740                cause: crate::run::ResourceBlockCause::Other,
3741                node: node.into(),
3742                kind: "shared build cache".into(),
3743                detail: detail.clone(),
3744                at: jiff::Timestamp::now(),
3745            });
3746        state.event("resource", &detail);
3747        state.save()?;
3748        bail!("landing verification could not start: {detail}");
3749    }
3750    Ok(())
3751}
3752
3753/// Gate the local winner and publish that exact SHA, retaining the saved lease.
3754/// A push completed before a crash is recoverable only when its SHA was gated.
3755async fn publish_landing_head<F: Forge>(
3756    state: &mut RunState,
3757    observed: &str,
3758    pr_url: &str,
3759    forge: &F,
3760) -> Result<String> {
3761    crate::pr_head::ensure_owner(state)?;
3762    let winner = state.winner().cloned().context("landing has no winner")?;
3763    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3764    let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
3765    anyhow::ensure!(
3766        observed == expected
3767            || (observed == head
3768                && state.gate_head.as_deref() == Some(&head)
3769                && state.gate_allows_progress()),
3770        "public head moved outside this run; refusing to overwrite it"
3771    );
3772    anyhow::ensure!(
3773        git::is_clean(&winner.worktree).await?,
3774        "landing worktree is dirty"
3775    );
3776    if state.gate_head.as_deref() != Some(&head)
3777        || !state.gate_ran
3778        || !state.gate_commands_allow_progress()
3779    {
3780        state.reconcile_verification_head(&head);
3781        state.gate.clear();
3782        state.gate_head = None;
3783        state.gate_ran = false;
3784        state.pre_gate.clear();
3785        state.pre_gate_commit = None;
3786        state.save()?;
3787        let inherited = crate::repo_lock::WaitPolicy::current();
3788        let wait = crate::repo_lock::WaitPolicy::new(
3789            Duration::from_secs(state.config.graph.timeout_resource_wait),
3790            move || inherited.cancelled(),
3791        );
3792        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3793        loop {
3794            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
3795                state.gate = outcomes.clone();
3796                check_landing_resources(state, "gate", &outcomes)?;
3797            }
3798            if outcomes.iter().all(|o| o.ok()) {
3799                break;
3800            }
3801            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
3802                crate::graph::GateFix::Retry => {
3803                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3804                }
3805                crate::graph::GateFix::Stop => break,
3806                crate::graph::GateFix::Defer => {
3807                    // The repair checks e2e immediately, before the next gate.
3808                    // Preserve a cache wait here as well as below; otherwise
3809                    // the daemon charges an attempt for unstarted verification.
3810                    if let Some(e2e) = &state.gate_repair_e2e {
3811                        let outcomes = e2e.outcomes.clone();
3812                        check_landing_resources(state, "e2e", &outcomes)?;
3813                    }
3814                    bail!("landing gate repair deferred");
3815                }
3816            }
3817        }
3818        state.gate = outcomes;
3819        state.gate_ran = true;
3820        state.save()?;
3821    }
3822    let inherited = crate::repo_lock::WaitPolicy::current();
3823    let wait = crate::repo_lock::WaitPolicy::new(
3824        Duration::from_secs(state.config.graph.timeout_resource_wait),
3825        move || inherited.cancelled(),
3826    );
3827    let checked = state
3828        .gate_head
3829        .clone()
3830        .context("landing gate has no checked SHA")?;
3831    anyhow::ensure!(
3832        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3833            && git::is_clean(&winner.worktree).await?,
3834        "landing tree changed after gate"
3835    );
3836    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
3837    if matches!(e2e, crate::graph::GateFix::Defer) {
3838        let outcomes = state
3839            .gate_repair_e2e
3840            .as_ref()
3841            .context("deferred landing e2e has no outcomes")?
3842            .outcomes
3843            .clone();
3844        check_landing_resources(state, "e2e", &outcomes)?;
3845    }
3846    anyhow::ensure!(
3847        matches!(e2e, crate::graph::GateFix::Retry),
3848        "post-repair e2e has not passed on the landing head; nothing published"
3849    );
3850    anyhow::ensure!(
3851        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3852            && git::is_clean(&winner.worktree).await?,
3853        "landing tree changed during post-repair e2e"
3854    );
3855    anyhow::ensure!(
3856        crate::graph::verify_current_head(state, &winner, &wait).await?,
3857        "current head e2e has not passed; nothing published"
3858    );
3859    anyhow::ensure!(
3860        state.gate_allows_progress(),
3861        "landing gate failed; nothing published"
3862    );
3863    crate::pr_head::ensure_owner(state)?;
3864    if owner_requested_stop(state)? {
3865        bail!("owner requested stop before publication");
3866    }
3867    let current = forge.view(&state.repo, pr_url).await?;
3868    anyhow::ensure!(
3869        current.pr.state == PrLifecycle::Open,
3870        "PR closed or merged while gating; nothing published"
3871    );
3872    anyhow::ensure!(
3873        current.head == observed || current.head == checked,
3874        "PR head changed while gating; nothing published"
3875    );
3876    anyhow::ensure!(
3877        crate::foreign_checkout::write_back(state, &checked).await?,
3878        "foreign checkout delivery is blocked; see the run events"
3879    );
3880    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
3881    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
3882    let refspec = format!("{checked}:refs/heads/{public}");
3883    let lock = repo_merge_lock(&state.repo);
3884    let _slot = lock.lock().await;
3885    let pushed = git::git_raw(
3886        &winner.worktree,
3887        &["push", &lease, &state.config.merge.remote, &refspec],
3888    )
3889    .await?;
3890    anyhow::ensure!(
3891        pushed.ok(),
3892        "publishing gated landing head failed: {}",
3893        pushed.stderr
3894    );
3895    state.pr_pushed_head = Some(checked.clone());
3896    state.land_sync_pending = false;
3897    state.save()?;
3898    Ok(checked)
3899}
3900
3901/// A scratch rebase moves the winner ref before its index and files. Recover
3902/// only a tree proven unchanged since the saved start; never discard edits.
3903async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
3904    let winner = state.winner().cloned().context("landing has no winner")?;
3905    let inherited = crate::repo_lock::WaitPolicy::current();
3906    let wait = crate::repo_lock::WaitPolicy::new(
3907        Duration::from_secs(state.config.graph.timeout_resource_wait),
3908        move || inherited.cancelled(),
3909    );
3910    let _coordination = crate::repo_lock::SeatLease::operation_with(
3911        &winner.worktree,
3912        state.config.coordination.as_ref(),
3913        &wait,
3914    )
3915    .await?;
3916    if !git::is_clean(&winner.worktree).await? {
3917        let from = state
3918            .land_rebase_from
3919            .as_deref()
3920            .context("landing worktree is dirty")?;
3921        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3922        anyhow::ensure!(head != from, "landing worktree is dirty");
3923        for args in [
3924            vec!["diff", "--cached", "--quiet", from],
3925            vec!["diff", "--quiet"],
3926        ] {
3927            anyhow::ensure!(
3928                git::git_raw(&winner.worktree, &args).await?.ok(),
3929                "landing worktree has edits beyond the interrupted rebase"
3930            );
3931        }
3932        // Preserve build artifacts and local files, including ignored ones.
3933        // read-tree can overwrite ignored paths, so reject collisions with
3934        // the new tree (including file/directory conflicts) before updating.
3935        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
3936        let tracked = git::git(
3937            &winner.worktree,
3938            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
3939        )
3940        .await?;
3941        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
3942            anyhow::ensure!(
3943                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
3944                    path == local
3945                        || path
3946                            .strip_prefix(local)
3947                            .is_some_and(|rest| rest.starts_with('/'))
3948                        || local
3949                            .strip_prefix(path)
3950                            .is_some_and(|rest| rest.starts_with('/'))
3951                }),
3952                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
3953            );
3954        }
3955        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
3956    }
3957    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
3958        anyhow::ensure!(
3959            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
3960            "landing synchronization started outside the foreign checkout history"
3961        );
3962        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
3963            // The rebase's tree already includes the base and the fixer's
3964            // resolutions. Retain that exact tree, but join the pre-sync
3965            // history so delivery remains fast-forward. Keep the checkpoint
3966            // until this succeeds: a crash after rebase (or after this merge)
3967            // must recover through this same idempotent path before gating.
3968            git::git(
3969                &winner.worktree,
3970                &[
3971                    "-c",
3972                    "core.hooksPath=/dev/null",
3973                    "merge",
3974                    "--strategy=ours",
3975                    "--no-ff",
3976                    "--no-autostash",
3977                    "--no-edit",
3978                    "-m",
3979                    "Merge pre-sync history into the repaired landing tree",
3980                    from,
3981                ],
3982            )
3983            .await?;
3984        }
3985    }
3986    crate::worktree_setup::prepare_with(
3987        &state.config,
3988        &state.repo,
3989        &winner.worktree,
3990        crate::build_target::Coordination::Held(_coordination.as_ref()),
3991    )
3992    .await?;
3993    state.land_rebase_from = None;
3994    state.save()?;
3995    Ok(())
3996}
3997
3998async fn rebase_landing_worktree(
3999    state: &mut RunState,
4000    onto: &str,
4001) -> Result<crate::rebase::Rebased> {
4002    restore_landing_worktree(state).await?;
4003    let winner = state.winner().cloned().context("landing has no winner")?;
4004    let scratch = state.dir().join("rebase");
4005    let target = match state.land_sync_target.clone() {
4006        Some(target) => {
4007            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4008            target
4009        }
4010        // Older records lack the target checkpoint, but Git retains the
4011        // exact target of an interrupted operation. It is a continuation too.
4012        None if git::rebase_in_progress(&scratch).await => {
4013            crate::rebase::rebase_target(&scratch).await?
4014        }
4015        None => {
4016            anyhow::ensure!(
4017                state.land_sync_attempts < state.config.graph.land_rounds,
4018                "landing base synchronization budget exhausted"
4019            );
4020            let target = git::rev_parse(&state.repo, onto).await?;
4021            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4022            state.land_sync_attempts += 1;
4023            state.land_sync_target = Some(target.clone());
4024            target
4025        }
4026    };
4027    state.land_sync_target = Some(target.clone());
4028    state.land_sync_pending = true;
4029    state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4030    state.save()?;
4031    // A continuation owns the attempt already charged above, including a
4032    // crash before the scratch rebase started. Finish its pinned base first;
4033    // a newer base must use another attempt on the next observation.
4034    let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4035    state.land_sync_target = None;
4036    state.save()?;
4037    if result == crate::rebase::Rebased::Applied {
4038        restore_landing_worktree(state).await?;
4039    }
4040    Ok(result)
4041}
4042
4043/// Reconcile a stopped landing before changing its branch. This also handles
4044/// old records whose graph status or merge detail no longer identifies land.
4045async fn resume_landing_head<F: Forge>(
4046    state: &mut RunState,
4047    observed: &str,
4048    pr_url: &str,
4049    forge: &F,
4050    reason: Option<Blocking>,
4051) -> Result<String> {
4052    crate::pr_head::ensure_owner(state)?;
4053    let winner = state.winner().cloned().context("landing has no winner")?;
4054    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4055    let expected = state
4056        .pr_pushed_head
4057        .as_deref()
4058        .or(state.gate_head.as_deref())
4059        .context("missing public head lease")?;
4060    anyhow::ensure!(
4061        observed == expected
4062            || (observed == local
4063                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4064                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4065        "public head moved outside this run; refusing to sync"
4066    );
4067    // An operator may have extended and published the winner while approval
4068    // was pending. Matching local/public history can be adopted as the lease,
4069    // but publish_landing_head must gate its new SHA before proceeding. A
4070    // remote-only or divergent update still cannot be overwritten.
4071    // Save reconciliation before rebasing again; a prior push may have reached
4072    // the remote immediately before the previous driver's last save.
4073    state.pr_pushed_head = Some(observed.to_owned());
4074    state.save()?;
4075    restore_landing_worktree(state).await?;
4076    // Recover a rebase that finished before its completion checkpoint was
4077    // saved. Restoration above has already reconciled its files and ancestry.
4078    if let Some(target) = &state.land_sync_target
4079        && !git::rebase_in_progress(&state.dir().join("rebase")).await
4080        && git::ancestry(&winner.worktree, target, &local).await?
4081    {
4082        state.land_sync_target = None;
4083        state.save()?;
4084    }
4085    let remote = state.config.merge.remote.clone();
4086    let base = state.base_branch.clone();
4087    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4088    anyhow::ensure!(
4089        fetched.ok(),
4090        "cannot fetch landing base: {}",
4091        fetched.stderr
4092    );
4093    anyhow::ensure!(
4094        !owner_requested_stop(state)?,
4095        "owner requested stop before base synchronization"
4096    );
4097    let onto = format!("{remote}/{base}");
4098    let tip = git::rev_parse(&state.repo, &onto).await?;
4099    let contains_base = git::ancestry(&state.repo, &tip, &local)
4100        .await
4101        .context("could not determine whether the landing head contains the fetched base")?;
4102    anyhow::ensure!(
4103        reason != Some(Blocking::Behind) || !contains_base,
4104        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4105    );
4106    if !contains_base || reason == Some(Blocking::Conflict) {
4107        match rebase_landing_worktree(state, &onto).await? {
4108            crate::rebase::Rebased::Applied => {}
4109            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4110        }
4111    }
4112    if reason == Some(Blocking::Behind) {
4113        anyhow::ensure!(
4114            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4115            "BEHIND synchronization left the head unchanged"
4116        );
4117    }
4118    publish_landing_head(state, observed, pr_url, forge).await
4119}
4120
4121/// Share the synchronization path with structured evidence retained after a refusal.
4122async fn synchronize_landing<F: Forge>(
4123    state: &mut RunState,
4124    pr: &mut PrState,
4125    observed: &str,
4126    pr_url: &str,
4127    forge: &F,
4128) -> Result<Option<String>> {
4129    if owner_stop(state, pr, forge).await? {
4130        return Ok(None);
4131    }
4132    state.event(
4133        "land",
4134        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4135    );
4136    state.save()?;
4137    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4138    if owner_stop(state, pr, forge).await? {
4139        return Ok(None);
4140    }
4141    match synced {
4142        Ok(head) => {
4143            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4144                crate::graph::refresh_reviewed_commits(state, &branch).await;
4145            }
4146            Ok(Some(head))
4147        }
4148        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4149        Err(e) => {
4150            let repo = state.repo.clone();
4151            stop(
4152                state,
4153                &repo,
4154                pr,
4155                &format!("could not synchronize landing base: {e:#}"),
4156            )
4157            .await?;
4158            Ok(None)
4159        }
4160    }
4161}
4162
4163async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4164    crate::pr_head::ensure_owner(state)?;
4165    state.land_unrelated = None;
4166    let reopening_hold = crate::merge_decision::resumable_hold(state);
4167    let repo = state.repo.clone();
4168    let budget = state.config.graph.land_rounds;
4169    let mut round = 0usize;
4170    let ci = state.config.merge.ci.expectation();
4171    if ci == CiExpectation::Absent {
4172        state.event(
4173            "land",
4174            "CI not expected ([merge] ci = \"none\"); check status ignored",
4175        );
4176    }
4177    let mut waited = Duration::ZERO;
4178    // Comment bodies the fixer has already been shown. A comment is
4179    // outstanding until it has been handed over once; after that it is a
4180    // recorded decision, not an open question, and re-feeding it would loop the
4181    // budget away on a comment the fixer already declined with an argument.
4182    let mut shown: BTreeSet<String> = BTreeSet::new();
4183    // Await the last successfully published head, including across resumes.
4184    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4185    // Whether a settled-checks refusal has already been given its one re-look.
4186    let mut rechecked = false;
4187
4188    // Marks the run resumable through exactly this function, not through a
4189    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4190    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4191    // status specifically to know a resumed run belongs back in `land`
4192    // rather than at a second `gh pr create`. Set on every entry - fresh or
4193    // resumed - because a resume that parked here again must keep reading
4194    // `Landing`, not whatever a first pass through `merge` left behind.
4195    state.status = RunStatus::Landing;
4196    state.event("land", format!("watching {pr_url}"));
4197    state.save()?;
4198
4199    // An armed merge recorded by an earlier pass may or may not have reached
4200    // the forge (the record is written before the call). It is taken back on
4201    // the first observation, where a pull request is known to stop with.
4202    let mut resumed_armed = state.land_armed_head.is_some();
4203
4204    'landing: loop {
4205        let seen = forge.view(&repo, pr_url).await?;
4206        let mut pr = seen.pr.clone();
4207        pr.review_comments.retain(|c| !shown.contains(&c.body));
4208        state.pr = Some(crate::run::PrRecord {
4209            url: pr.url.clone(),
4210            number: pr.number,
4211            state: pr.state.as_str().to_owned(),
4212            checks: pr.checks.as_str().to_owned(),
4213            round,
4214            rounds: budget,
4215            red_at_merge: Vec::new(),
4216        });
4217        state.save()?;
4218
4219        if pr.state == PrLifecycle::Open {
4220            state.observe_branch_owner_holds(&seen.head).await;
4221            state.save()?;
4222        }
4223        crate::pr_head::ensure_owner(state)?;
4224        if reopening_hold {
4225            anyhow::ensure!(
4226                pr.state == PrLifecycle::Open,
4227                "held PR is no longer open; cannot request a fresh decision"
4228            );
4229            // An explicit resume authorizes a fresh question only. Preserve the
4230            // answered card, and never enter repair/rebase/merge on this pass.
4231            disarm(forge, state, &repo, pr.number)
4232                .await
4233                .map_err(anyhow::Error::msg)?;
4234            let previous = state.merge_decision.take();
4235            let binding = state.land_approval.take();
4236            state.config.graph.land_approval = true;
4237            let subject = merge_subject(
4238                crate::graph::landing_title(state, &seen.title),
4239                &crate::graph::landing_subject_source(state),
4240            );
4241            let contested = contested_to_ask(state);
4242            if let Err(error) =
4243                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4244            {
4245                state.merge_decision = previous;
4246                state.land_approval = binding;
4247                return Err(error);
4248            }
4249            state.end_pass_parked(crate::run::ParkCause::Question);
4250            state.parked = true;
4251            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()));
4252            state.save()?;
4253            return Ok(pr);
4254        }
4255        if owner_stop(state, &mut pr, forge).await? {
4256            return Ok(pr);
4257        }
4258
4259        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4260            // An approval already given for the same head is reused, so
4261            // nothing is asked twice. A failed disable
4262            // stops the run with the record kept: pushing on could change the
4263            // head under an arm that is still live.
4264            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4265                let why = format!(
4266                    "a previous pass may have armed auto-merge and it could not be disabled \
4267                     on resume: {e}"
4268                );
4269                stop(state, &repo, &pr, &why).await?;
4270                return Ok(pr);
4271            }
4272        }
4273
4274        // The head moved away from the one auto-merge was armed on, by
4275        // someone other than this loop. The arm is pinned and would refuse to
4276        // merge the new commit, but the approval was for the old one: take it
4277        // back and go through the normal path again.
4278        if pr.state == PrLifecycle::Open
4279            && !seen.head.is_empty()
4280            && state
4281                .land_armed_head
4282                .as_deref()
4283                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4284        {
4285            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4286                let why = format!(
4287                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4288                );
4289                stop(state, &repo, &pr, &why).await?;
4290                return Ok(pr);
4291            }
4292        }
4293
4294        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4295            // Disarming can outlive an owner answer. Consume it before our
4296            // own rebase invalidates the head shown on the decision card.
4297            if owner_stop(state, &mut pr, forge).await? {
4298                return Ok(pr);
4299            }
4300            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4301                binding.head.eq_ignore_ascii_case(&seen.head)
4302                    && ask::Questions::open()
4303                        .get_for_effects(&binding.question)
4304                        .is_ok_and(|q| {
4305                            q.run == state.id
4306                                && q.node == APPROVAL_NODE
4307                                && q.status == ask::QuestionStatus::Answered
4308                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4309                        })
4310            });
4311            if repair_answer {
4312                let subject = merge_subject(
4313                    crate::graph::landing_title(state, &seen.title),
4314                    &crate::graph::landing_subject_source(state),
4315                );
4316                let contested = contested_to_ask(state);
4317                if matches!(
4318                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4319                    ApprovalGate::Repair
4320                ) {
4321                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4322                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4323                        state.save()?;
4324                    }
4325                    return Ok(pr);
4326                }
4327            }
4328            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4329            // A stop detected before publication must apply its durable
4330            // decision, even when verification returned an error meanwhile.
4331            if owner_stop(state, &mut pr, forge).await? {
4332                return Ok(pr);
4333            }
4334            let head = synced?;
4335            awaiting_head = Some(head);
4336            waited = Duration::ZERO;
4337            rechecked = false;
4338            // Read CI and approvals afresh, never from the pre-push observation.
4339            continue;
4340        }
4341
4342        // A stale base is independent of the CI rollup. Keep the public-head
4343        // lease, but synchronize before waiting for checks on the old tree.
4344        if pr.state == PrLifecycle::Open
4345            && pr.blocking == Blocking::Behind
4346            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4347        {
4348            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4349            let Some(head) = synced else {
4350                return Ok(pr);
4351            };
4352            awaiting_head = Some(head);
4353            rechecked = false;
4354            waited = Duration::ZERO;
4355            continue;
4356        }
4357
4358        if pr.state == PrLifecycle::Open {
4359            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4360                if waited >= WAIT_CEILING {
4361                    let want = awaiting_head.as_deref().unwrap_or_default();
4362                    let why = format!(
4363                        "the pull request's checks were still not about one readable head after \
4364                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4365                         someone may have pushed over it",
4366                        WAIT_CEILING.as_secs() / 60,
4367                        if want.is_empty() { "any" } else { want },
4368                        if seen.head.is_empty() {
4369                            "nothing readable"
4370                        } else {
4371                            &seen.head
4372                        },
4373                        if seen.rollup_head.is_empty() {
4374                            "nothing readable"
4375                        } else {
4376                            &seen.rollup_head
4377                        },
4378                    );
4379                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4380                    return Ok(pr);
4381                }
4382                waited += POLL;
4383                forge.poll().await;
4384                continue;
4385            }
4386            // Reset once, when the awaited head first shows up; resetting on
4387            // every re-observation would let a standing refusal wait forever.
4388            if awaiting_head.take().is_some() {
4389                // The checks now being read belong to the new head; give them
4390                // the same grace a fresh pull request gets.
4391                waited = Duration::ZERO;
4392            }
4393        }
4394
4395        // The merge-state grace is head-bound and durable. Reruns reset the
4396        // checks clock, but must not extend this deadline across resumes.
4397        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4398            let first = state
4399                .land_unsaid
4400                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4401            if !first.0.eq_ignore_ascii_case(&seen.head) {
4402                *first = (seen.head.clone(), forge.now());
4403            }
4404            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4405            state.save()?;
4406            elapsed
4407        } else {
4408            waited
4409        };
4410        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4411        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4412            if waited >= WAIT_CEILING {
4413                stop_disarmed(
4414                    forge,
4415                    state,
4416                    &repo,
4417                    &pr,
4418                    "merge state remained unreadable; refusing to merge on a guess",
4419                )
4420                .await?;
4421                return Ok(pr);
4422            }
4423            waited += POLL;
4424            forge.poll().await;
4425            continue;
4426        }
4427
4428        // A failed workflow run is rerun once, judged by its own run rather
4429        // than by the rollup's aggregate: another run still pending, or a fix
4430        // budget already spent, must not keep a flaky failure from its one
4431        // rerun. It spends no round and no attempt.
4432        if ci == CiExpectation::Expected
4433            && pr.state == PrLifecycle::Open
4434            && state.config.graph.rerun_flaky_checks
4435        {
4436            let include_optional = pr.checks == Checks::Red
4437                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4438            let failing = rerunnable_with(&seen.contexts, include_optional);
4439            let now = forge.now();
4440            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4441                RerunStep::Rerun(runs) => {
4442                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4443                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4444                        *rec = LandReruns {
4445                            head: seen.head.clone(),
4446                            runs: BTreeMap::new(),
4447                        };
4448                    }
4449                    for run in &runs {
4450                        rec.runs.insert(run.clone(), now);
4451                    }
4452                    // Durable before the call: a restart must not
4453                    // rerun the same run twice. A save that fails
4454                    // means no rerun.
4455                    state.save()?;
4456                    let mut any = false;
4457                    for run in &runs {
4458                        let names = failing
4459                            .iter()
4460                            .filter(|(_, r)| r.as_deref() == Some(run))
4461                            .map(|(l, _)| l.as_str())
4462                            .collect::<Vec<_>>()
4463                            .join(", ");
4464                        match forge.rerun(&repo, run).await {
4465                            Ok(()) => {
4466                                any = true;
4467                                state.event(
4468                                    "land",
4469                                    format!("reran failed check(s) {names} (run {run})"),
4470                                );
4471                            }
4472                            // Stays recorded: never a retry loop.
4473                            Err(e) => state.event(
4474                                "land",
4475                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4476                            ),
4477                        }
4478                    }
4479                    state.save()?;
4480                    if any {
4481                        waited = Duration::ZERO;
4482                        forge.poll().await;
4483                        continue;
4484                    }
4485                }
4486                RerunStep::Grace => {
4487                    if waited >= WAIT_CEILING {
4488                        let why = format!(
4489                            "checks were still failing after a rerun and {} minutes",
4490                            WAIT_CEILING.as_secs() / 60
4491                        );
4492                        stop(state, &repo, &pr, &why).await?;
4493                        return Ok(pr);
4494                    }
4495                    waited += POLL;
4496                    forge.poll().await;
4497                    continue;
4498                }
4499                RerunStep::Fix => {}
4500            }
4501        }
4502
4503        let step = proposed;
4504        // Armed on exactly this head: the forge is doing the waiting. A
4505        // decision to merge (or keep waiting) is only watched, never re-armed
4506        // and never re-approved; anything else - a red check, a comment, a
4507        // conflict - falls through to its own arm, which disarms first.
4508        let armed_here = state
4509            .land_armed_head
4510            .as_deref()
4511            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4512        if armed_here && matches!(step, Step::Merge | Step::Wait) {
4513            if waited >= WAIT_CEILING {
4514                let required = if seen.base.is_empty() {
4515                    None
4516                } else {
4517                    forge.required_contexts(&repo, &seen.base).await
4518                };
4519                let why = format!(
4520                    "auto-merge was armed on {} but the pull request did not merge within {} \
4521                     minutes ({})",
4522                    seen.head,
4523                    WAIT_CEILING.as_secs() / 60,
4524                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4525                );
4526                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4527                return Ok(pr);
4528            }
4529            waited += POLL;
4530            forge.poll().await;
4531            continue;
4532        }
4533        if armed_here && !matches!(step, Step::Done { .. }) {
4534            // Not merging or waiting any more: whatever is next may change the
4535            // head or give up, and neither may leave the arm standing.
4536            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4537                let why = format!("auto-merge could not be disabled: {e}");
4538                stop(state, &repo, &pr, &why).await?;
4539                return Ok(pr);
4540            }
4541        }
4542        if pr.checks == Checks::Red
4543            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4544            && pr.review_comments.is_empty()
4545            && let Some(evidence) = forge.attribution(state, &seen).await
4546            && evidence.unrelated(&seen.head, &pr.failing)
4547        {
4548            if owner_stop(state, &mut pr, forge).await? {
4549                return Ok(pr);
4550            }
4551            // Attribution does not authorize action against an unseen push.
4552            let fresh = forge.view(&repo, pr_url).await?;
4553            if fresh.head != seen.head
4554                || fresh.rollup_head != seen.rollup_head
4555                || fresh.pr.state != PrLifecycle::Open
4556                || fresh.pr.checks != Checks::Red
4557                || fresh.pr.failing != pr.failing
4558                || fresh
4559                    .pr
4560                    .review_comments
4561                    .iter()
4562                    .any(|c| !shown.contains(&c.body))
4563            {
4564                continue;
4565            }
4566            hold_unrelated(state, &pr, evidence).await?;
4567            return Ok(pr);
4568        }
4569        match step {
4570            Step::Wait => {
4571                if waited >= WAIT_CEILING {
4572                    let why = format!(
4573                        "checks were still running after {} minutes",
4574                        WAIT_CEILING.as_secs() / 60
4575                    );
4576                    stop(state, &repo, &pr, &why).await?;
4577                    return Ok(pr);
4578                }
4579                waited += POLL;
4580                forge.poll().await;
4581            }
4582            Step::Done { merged } => {
4583                if merged {
4584                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
4585                }
4586                // Auto-merge is pinned to the approved head, but the forge's
4587                // own handling of a later push is not something magi can
4588                // see: if the pull request merged on another commit, say so
4589                // loudly rather than record a clean landing.
4590                if let Some(armed) = state.land_armed_head.take() {
4591                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
4592                        let msg = format!(
4593                            "{} merged on {} but the owner approved {armed}; review what landed",
4594                            pr.url, seen.head
4595                        );
4596                        tracing::warn!("{msg}");
4597                        state.event("land", msg);
4598                        // Only an arm left by an older build can get here.
4599                        // The wording is fixed so a repeat does not relight
4600                        // the notice.
4601                        crate::notices::raise_with(
4602                            crate::notices::Notice::warn(
4603                                &format!("merged-unapproved-head:{}", state.id),
4604                                "A pull request merged on a commit the owner did not approve; \
4605                                 review what landed",
4606                            )
4607                            .link(crate::notices::Link::Run {
4608                                id: state.id.clone(),
4609                            }),
4610                            &state.config.notify,
4611                        );
4612                    }
4613                }
4614                state.status = if merged {
4615                    RunStatus::Merged
4616                } else {
4617                    RunStatus::Ready
4618                };
4619                let detail = if merged {
4620                    format!("{} was merged", pr.url)
4621                } else {
4622                    format!("{} was closed without merging", pr.url)
4623                };
4624                state.merge = Some(MergeOutcome {
4625                    mode: MergeMode::Pr,
4626                    ok: merged,
4627                    detail: detail.clone(),
4628                    empty: false,
4629                });
4630                state.event("land", detail);
4631                state.save()?;
4632                write_pr_state_through(state, pr.state);
4633                return Ok(pr);
4634            }
4635            Step::Merge => {
4636                state.check_delivery_evidence(&seen.head)?;
4637                let subject = merge_subject(
4638                    crate::graph::landing_title(state, &seen.title),
4639                    &crate::graph::landing_subject_source(state),
4640                );
4641                // The owner sees the panel before the one irreversible step,
4642                // and an unanswered question is a hold: silence never merges.
4643                //
4644                // The dedicated policy includes existing consent and post-repair
4645                // decisions; repair choice availability never grants merge authority.
4646                let contested = contested_to_ask(state);
4647                if !approval_reasons(state).is_empty() {
4648                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
4649                        .await?
4650                    {
4651                        ApprovalGate::Approved => {}
4652                        ApprovalGate::Repair => {
4653                            // The driver consumes the saved request under the existing
4654                            // run/task claim. No merge, no second run or task.
4655                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4656                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4657                                state.save()?;
4658                            }
4659                            return Ok(pr);
4660                        }
4661                        ApprovalGate::Held => {
4662                            // Another entry point may have saved a stop after
4663                            // the first read above. Apply its durable action.
4664                            if owner_stop(state, &mut pr, forge).await? {
4665                                return Ok(pr);
4666                            }
4667                            stop(
4668                                state,
4669                                &repo,
4670                                &pr,
4671                                "the owner did not approve the merge (held or unanswered)",
4672                            )
4673                            .await?;
4674                            return Ok(pr);
4675                        }
4676                        // Filed (or still standing from an earlier visit) and
4677                        // not yet answered. Park here rather than wait: the
4678                        // question survives on disk, the daemon hands this
4679                        // run's slot to something else, and a later resume
4680                        // re-enters `land`, finds the same question, and
4681                        // either merges or stops depending on what it says
4682                        // by then.
4683                        ApprovalGate::Pending => {
4684                            state.end_pass_parked(crate::run::ParkCause::Question);
4685                            state.parked = true;
4686                            state.event(
4687                                "land",
4688                                "parked awaiting merge approval - resumes once answered",
4689                            );
4690                            state.save()?;
4691                            return Ok(pr);
4692                        }
4693                    }
4694                }
4695                // Open and past the gate above, so `seen.head` is the commit
4696                // the checks were bound to and the owner approved.
4697                //
4698                // Merge directly, bound to that commit. Auto-merge is not
4699                // armed any more: the forge checks `--match-head-commit` only
4700                // when the request is made, so an arm outlives the head it
4701                // was made for, and a push of another commit whose
4702                // requirements are met first would merge without approval.
4703                // A direct merge is checked by the forge at the moment it
4704                // happens, so only the approved head can land.
4705                let observed_head = seen.head.clone();
4706                // Read the pull request again just before: the state seen
4707                // above can be a moment old.
4708                {
4709                    let fresh = forge.view(&repo, pr_url).await.ok();
4710                    if fresh.as_ref().is_some_and(|current| {
4711                        current.pr.state == PrLifecycle::Open
4712                            && current.head.eq_ignore_ascii_case(&observed_head)
4713                            && Blocking::of(&current.merge_state) == Blocking::Behind
4714                    }) {
4715                        pr.blocking = Blocking::Behind;
4716                        let synced =
4717                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4718                                .await?;
4719                        let Some(head) = synced else {
4720                            return Ok(pr);
4721                        };
4722                        awaiting_head = Some(head);
4723                        rechecked = false;
4724                        waited = Duration::ZERO;
4725                        continue 'landing;
4726                    }
4727                    if !direct_merge_is_safe(
4728                        fresh.as_ref(),
4729                        &observed_head,
4730                        &shown,
4731                        round,
4732                        budget,
4733                        waited,
4734                        ci,
4735                    ) {
4736                        if waited >= WAIT_CEILING {
4737                            let why = "the pull request did not settle on the approved head \
4738                                       before it could be merged";
4739                            stop(state, &repo, &pr, why).await?;
4740                            return Ok(pr);
4741                        }
4742                        state.event(
4743                            "land",
4744                            "the pull request changed before merging; looking again",
4745                        );
4746                        waited += POLL;
4747                        forge.poll().await;
4748                        continue;
4749                    }
4750                }
4751                let argv = merge_argv_at(pr.number, &subject, &observed_head);
4752                let out = {
4753                    let merge_lock = repo_merge_lock(&repo);
4754                    let _merge_slot = merge_lock.lock().await;
4755                    crate::pr_head::ensure_owner(state)?;
4756                    if let Some(task_id) = state
4757                        .origin
4758                        .as_ref()
4759                        .and_then(|origin| origin.task.as_ref())
4760                    {
4761                        let task = crate::queue::Queue::open()
4762                            .get(task_id)
4763                            .context("cannot verify the task owner immediately before merge")?;
4764                        if task.execution_runs().last() != Some(&state.id)
4765                            || task.operator_held()
4766                            || task.status == crate::queue::TaskStatus::Done
4767                        {
4768                            bail!(
4769                                "task ownership or an operator hold superseded this merge approval"
4770                            );
4771                        }
4772                    }
4773                    if let Some(binding) = &state.land_approval {
4774                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
4775                        if merge_consent_superseded(state, &current)?
4776                            || current.run != state.id
4777                            || !binding.head.eq_ignore_ascii_case(&observed_head)
4778                            || approval(current.resolution().as_deref()) != Approval::Merge
4779                            || current.merge_target.as_ref().is_some_and(|t| {
4780                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
4781                            })
4782                        {
4783                            bail!(
4784                                "merge decision is stale or no longer authorizes the reviewed head"
4785                            );
4786                        }
4787                    }
4788                    forge.merge(&repo, &argv).await?
4789                };
4790                if out.0 {
4791                    // Exit 0 is not proof of a merge: with a merge queue `gh`
4792                    // enqueues (or reports the pull request already queued)
4793                    // and succeeds while it is still open. Ask the forge; an
4794                    // unreadable answer is not a confirmation either, so it
4795                    // is looked at again rather than recorded as merged.
4796                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
4797                        if c.pr.state == PrLifecycle::Merged {
4798                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
4799                            true
4800                        } else {
4801                            false
4802                        }
4803                    });
4804                    if !confirmed {
4805                        if waited >= WAIT_CEILING {
4806                            let why = "the merge request succeeded but the pull request \
4807                                       could not be confirmed merged after waiting";
4808                            stop(state, &repo, &pr, why).await?;
4809                            return Ok(pr);
4810                        }
4811                        state.event(
4812                            "land",
4813                            "merge accepted but the pull request is not confirmed merged yet; waiting",
4814                        );
4815                        state.save()?;
4816                        waited += POLL;
4817                        forge.poll().await;
4818                        continue;
4819                    }
4820                    pr.state = PrLifecycle::Merged;
4821                    state.status = RunStatus::Merged;
4822                    state.merge = Some(MergeOutcome {
4823                        mode: MergeMode::Pr,
4824                        ok: true,
4825                        detail: format!("gh {}", argv.join(" ")),
4826                        empty: false,
4827                    });
4828                    // The last `state.pr` snapshot is whatever the poll before
4829                    // this merge observed - still `open` - and nothing below
4830                    // refreshes it from GitHub again, so the UI's round rail
4831                    // would otherwise keep animating a merged run forever.
4832                    if let Some(pr_record) = state.pr.as_mut() {
4833                        pr_record.state = pr.state.as_str().to_owned();
4834                    }
4835                    state.event("land", format!("merged {} as `{subject}`", pr.url));
4836                    announce_red_merge(state, &pr).await;
4837                    state.save()?;
4838                    write_pr_state_through(state, pr.state);
4839                    return Ok(pr);
4840                }
4841                let after_seen = forge.view(&repo, pr_url).await.ok();
4842                let after = after_seen.as_ref().map(|s| s.pr.state);
4843                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
4844                    state.pr_merged_head = after_seen
4845                        .as_ref()
4846                        .map(|s| s.head.clone())
4847                        .filter(|h| !h.is_empty());
4848                    pr.state = PrLifecycle::Merged;
4849                    state.status = RunStatus::Merged;
4850                    state.merge = Some(outcome);
4851                    if let Some(pr_record) = state.pr.as_mut() {
4852                        pr_record.state = pr.state.as_str().to_owned();
4853                    }
4854                    state.event("land", format!("merged {} as `{subject}`", pr.url));
4855                    announce_red_merge(state, &pr).await;
4856                    state.save()?;
4857                    write_pr_state_through(state, pr.state);
4858                    return Ok(pr);
4859                }
4860                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
4861                match verdict {
4862                    Refused::Behind => {
4863                        pr.blocking = Blocking::Behind;
4864                        let synced =
4865                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4866                                .await?;
4867                        let Some(head) = synced else {
4868                            return Ok(pr);
4869                        };
4870                        awaiting_head = Some(head);
4871                        rechecked = false;
4872                        waited = Duration::ZERO;
4873                        continue 'landing;
4874                    }
4875                    Refused::Final => {
4876                        let merge_state = after_seen
4877                            .as_ref()
4878                            .map(|s| s.merge_state.as_str())
4879                            .filter(|m| !m.is_empty())
4880                            .unwrap_or("unknown");
4881                        // Which refusal this was decides what a person has to
4882                        // do about it, so the two are worded apart; both carry
4883                        // the forge's own message.
4884                        let why = format!(
4885                            "the merge was refused: {} (merge state: {merge_state})",
4886                            out.1
4887                        );
4888                        stop(state, &repo, &pr, &why).await?;
4889                        return Ok(pr);
4890                    }
4891                    verdict => {
4892                        // Back to the top, which re-decides and passes the
4893                        // approval gate again, a poll later. `waited` is not
4894                        // reset here: only a pushed fix restarts it, or a
4895                        // standing refusal would wait forever.
4896                        if waited >= WAIT_CEILING {
4897                            let why = format!(
4898                                "the merge was still refused after {} minutes: {}",
4899                                WAIT_CEILING.as_secs() / 60,
4900                                out.1
4901                            );
4902                            stop(state, &repo, &pr, &why).await?;
4903                            return Ok(pr);
4904                        }
4905                        if verdict == Refused::Recheck {
4906                            rechecked = true;
4907                        }
4908                        state.event(
4909                            "land",
4910                            "merge refused while the branch policy is not satisfied yet; waiting",
4911                        );
4912                        state.save()?;
4913                        waited += POLL;
4914                        forge.poll().await;
4915                    }
4916                }
4917            }
4918            Step::Rebase => {
4919                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4920                let Some(head) = synced else {
4921                    return Ok(pr);
4922                };
4923                awaiting_head = Some(head);
4924                rechecked = false;
4925                waited = Duration::ZERO;
4926                continue 'landing;
4927            }
4928            Step::GiveUp { reason } => {
4929                stop(state, &repo, &pr, &reason).await?;
4930                return Ok(pr);
4931            }
4932            Step::Fix { reason } => {
4933                round += 1;
4934                waited = Duration::ZERO;
4935                for c in &pr.review_comments {
4936                    shown.insert(c.body.clone());
4937                }
4938                state.event("land", format!("round {round}: {reason}"));
4939                state.save()?;
4940
4941                let logs = failing_logs(&repo, &seen.failing_urls).await;
4942                let was_red = pr.checks == Checks::Red;
4943                if owner_stop(state, &mut pr, forge).await? {
4944                    return Ok(pr);
4945                }
4946                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
4947                if owner_stop(state, &mut pr, forge).await? {
4948                    return Ok(pr);
4949                }
4950                match fixed {
4951                    Fixed::Committed { head } => {
4952                        // Whatever the next look shows may still be the
4953                        // previous head; see `awaiting_new_head`.
4954                        state.pr_pushed_head = Some(head.clone());
4955                        awaiting_head = Some(head);
4956                        rechecked = false;
4957                        waited = Duration::ZERO;
4958                        forge.poll().await;
4959                    }
4960                    Fixed::Declined if was_red => {
4961                        // Review comments may have required this round even
4962                        // when CI was unrelated. Once the fixer has read them,
4963                        // use the same structural attribution before charging
4964                        // a no-commit stop to the task.
4965                        if let Some(evidence) = forge.attribution(state, &seen).await
4966                            && evidence.unrelated(&seen.head, &pr.failing)
4967                        {
4968                            let fresh = forge.view(&repo, pr_url).await?;
4969                            if fresh.head != seen.head
4970                                || fresh.rollup_head != seen.rollup_head
4971                                || fresh.pr.state != PrLifecycle::Open
4972                                || fresh.pr.checks != Checks::Red
4973                                || fresh.pr.failing != pr.failing
4974                                || fresh
4975                                    .pr
4976                                    .review_comments
4977                                    .iter()
4978                                    .any(|c| !shown.contains(&c.body))
4979                            {
4980                                continue;
4981                            }
4982                            if owner_stop(state, &mut pr, forge).await? {
4983                                return Ok(pr);
4984                            }
4985                            hold_unrelated(state, &pr, evidence).await?;
4986                            return Ok(pr);
4987                        }
4988                        let why = format!(
4989                            "the fixer produced no commit while {} check(s) were failing \
4990                             ({}); stopping instead of looping on an unchanged tree",
4991                            pr.failing.len(),
4992                            pr.failing.join(", ")
4993                        );
4994                        stop(state, &repo, &pr, &why).await?;
4995                        return Ok(pr);
4996                    }
4997                    // Comment-driven round with no commit: the fixer read the
4998                    // comments and changed nothing, which is a decision it is
4999                    // allowed to make. The comments are recorded as shown, so
5000                    // the next observation sees a clean pull request.
5001                    Fixed::Declined => state.event(
5002                        "land",
5003                        format!("round {round}: fixer declined the comments, nothing committed"),
5004                    ),
5005                    Fixed::Deferred => {
5006                        // No fixer was available to judge these comments or
5007                        // checks. Keep the previous completed-round count and
5008                        // return without handing the PR off as a task failure.
5009                        state.status = RunStatus::Blocked;
5010                        state.save()?;
5011                        return Ok(pr);
5012                    }
5013                    Fixed::Failed(why) => {
5014                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5015                        return Ok(pr);
5016                    }
5017                }
5018                state.save()?;
5019            }
5020        }
5021    }
5022}
5023
5024/// Owner decision for a CI failure independently reproduced on the base.
5025pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5026
5027/// Durable machine-hold evidence, bound to one observed PR head.
5028#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5029pub struct CiHold {
5030    /// Head that exhibited the independently reproduced failures.
5031    pub head: String,
5032    /// Typed owner question controlling resumption.
5033    pub question: String,
5034    /// Complete structured facts used to attribute the failures.
5035    pub evidence: CiEvidence,
5036}
5037
5038/// Only structured forge annotations are compared, never log prose.
5039#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5040struct CiFailure {
5041    path: String,
5042    start_line: u64,
5043    end_line: u64,
5044    title: String,
5045    message: String,
5046}
5047
5048#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5049struct CiCheckEvidence {
5050    label: String,
5051    head_check: u64,
5052    base_check: u64,
5053    app: u64,
5054    run: String,
5055    base_run: String,
5056    head_failures: Vec<CiFailure>,
5057    base_failures: Vec<CiFailure>,
5058    rerun_exhausted: bool,
5059}
5060
5061/// Pinned Git diff and forge failure annotations used for CI attribution.
5062#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5063pub struct CiEvidence {
5064    head: String,
5065    base: String,
5066    changed: Vec<String>,
5067    checks: Vec<CiCheckEvidence>,
5068}
5069
5070impl CiEvidence {
5071    /// Every red check must have the same located failure on the base, outside
5072    /// the diff. Changes to CI/build configuration invalidate this inference.
5073    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5074        if self.head != head
5075            || self.base.is_empty()
5076            || failing.is_empty()
5077            || self.changed.iter().any(|p| {
5078                p.starts_with(".github/")
5079                    || p.starts_with(".config/")
5080                    || p.starts_with(".cargo/")
5081                    || matches!(
5082                        p.rsplit('/').next().unwrap_or(p),
5083                        "Cargo.toml"
5084                            | "Cargo.lock"
5085                            | "Makefile.toml"
5086                            | "build.rs"
5087                            | "rust-toolchain.toml"
5088                    )
5089            })
5090        {
5091            return false;
5092        }
5093        failing.iter().all(|label| {
5094            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5095            matches.len() == 1
5096                && matches[0].rerun_exhausted
5097                && !matches[0].head_failures.is_empty()
5098                && matches[0].head_failures.iter().all(|f| {
5099                    // Workflow-level exit-code annotations do not identify a
5100                    // failing test or source file, and prove nothing here.
5101                    !f.path.is_empty()
5102                        && !f.path.starts_with('.')
5103                        && !f.path.contains("..")
5104                        && !f.path.starts_with('/')
5105                        && !self.changed.contains(&f.path)
5106                        && matches[0].base_failures.contains(f)
5107                })
5108        })
5109    }
5110}
5111
5112async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5113    let (ok, body) = gh(repo, &["api".into(), endpoint]).await.ok()?;
5114    if !ok {
5115        return None;
5116    }
5117    serde_json::from_str(&body).ok()
5118}
5119
5120async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5121    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5122    if count == 0 || count >= 100 {
5123        return None;
5124    }
5125    let id = check.get("id")?.as_u64()?;
5126    let value = ci_json(
5127        repo,
5128        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5129    )
5130    .await?;
5131    let annotations = value.as_array()?;
5132    if annotations.len() != count as usize {
5133        return None;
5134    }
5135    annotations
5136        .iter()
5137        .filter(|a| a["annotation_level"] == "failure")
5138        .map(|a| {
5139            Some(CiFailure {
5140                path: a["path"].as_str()?.into(),
5141                start_line: a["start_line"].as_u64()?,
5142                end_line: a["end_line"].as_u64()?,
5143                title: a["title"].as_str()?.into(),
5144                message: a["message"].as_str()?.into(),
5145            })
5146        })
5147        .collect()
5148}
5149
5150async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5151    let value = ci_json(
5152        repo,
5153        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5154    )
5155    .await?;
5156    let runs = value["check_runs"].as_array()?;
5157    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5158        return None;
5159    }
5160    Some(runs.clone())
5161}
5162
5163async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5164    let repo = &state.repo;
5165    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5166    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5167        .await
5168        .ok()?;
5169    if !base.ok() {
5170        return None;
5171    }
5172    let range = format!("{}...{}", base.stdout, seen.head);
5173    // No rename detection: both old and new paths must count as changed.
5174    let diff = git::git_raw(
5175        repo,
5176        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5177    )
5178    .await
5179    .ok()?;
5180    if !diff.ok() {
5181        return None;
5182    }
5183    let head_runs = ci_runs(repo, &seen.head).await?;
5184    let base_runs = ci_runs(repo, &base.stdout).await?;
5185    let mut checks = Vec::new();
5186    for label in &seen.pr.failing {
5187        let matching = |runs: &[serde_json::Value]| {
5188            runs.iter()
5189                .filter(|r| r["name"].as_str() == Some(label))
5190                .cloned()
5191                .collect::<Vec<_>>()
5192        };
5193        let heads = matching(&head_runs);
5194        let bases = matching(&base_runs);
5195        if heads.len() != 1 || bases.len() != 1 {
5196            return None;
5197        }
5198        let h = &heads[0];
5199        let b = &bases[0];
5200        if h["conclusion"] != "failure"
5201            || b["conclusion"] != "failure"
5202            || h["status"] != "completed"
5203            || b["status"] != "completed"
5204            || h["head_sha"].as_str()? != seen.head
5205            || b["head_sha"].as_str()? != base.stdout
5206            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5207        {
5208            return None;
5209        }
5210        let run = run_of(h["details_url"].as_str()?)?;
5211        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5212        if contexts.len() != 1
5213            || contexts[0].run.as_ref() != Some(&run)
5214            || contexts[0].verdict != Verdict::Fail
5215        {
5216            return None;
5217        }
5218        // A persisted request alone is not a completed rerun: require the
5219        // workflow's structured attempt number as well.
5220        let workflow =
5221            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5222        let base_run = run_of(b["details_url"].as_str()?)?;
5223        let base_workflow = ci_json(
5224            repo,
5225            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5226        )
5227        .await?;
5228        if base_workflow["head_sha"].as_str()? != base.stdout
5229            || base_workflow["head_branch"].as_str()? != seen.base
5230            || base_workflow["status"] != "completed"
5231            || base_workflow["conclusion"] != "failure"
5232            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5233        {
5234            return None;
5235        }
5236        let exhausted = state
5237            .land_reruns
5238            .as_ref()
5239            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5240            && workflow["head_sha"].as_str()? == seen.head
5241            && workflow["run_attempt"].as_u64()? > 1
5242            && workflow["status"] == "completed";
5243        checks.push(CiCheckEvidence {
5244            label: label.clone(),
5245            head_check: h["id"].as_u64()?,
5246            base_check: b["id"].as_u64()?,
5247            app: h.pointer("/app/id")?.as_u64()?,
5248            run,
5249            base_run,
5250            head_failures: ci_annotations(repo, h).await?,
5251            base_failures: ci_annotations(repo, b).await?,
5252            rerun_exhausted: exhausted,
5253        });
5254    }
5255    Some(CiEvidence {
5256        head: seen.head.clone(),
5257        base: base.stdout,
5258        changed: diff
5259            .stdout
5260            .split('\0')
5261            .filter(|p| !p.is_empty())
5262            .map(str::to_owned)
5263            .collect(),
5264        checks,
5265    })
5266}
5267
5268async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5269    let detail = serde_json::to_string(&evidence)?;
5270    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5271    let hold = "operator: 保留して後で判断する".to_owned();
5272    let mut q = ask::Question::new(
5273        state.id.clone(),
5274        CI_HOLD_NODE.into(),
5275        "land".into(),
5276        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5277        format!(
5278            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5279        ),
5280        vec![resume.clone(), hold.clone()],
5281    );
5282    q.actions.insert(
5283        resume,
5284        ask::ChoiceAction::Resume {
5285            run: state.id.clone(),
5286        },
5287    );
5288    q.actions.insert(hold, ask::ChoiceAction::Hold);
5289    ask::Questions::open().put_executable(&mut q)?;
5290    state.land_unrelated = Some(CiHold {
5291        head: evidence.head.clone(),
5292        question: q.id.clone(),
5293        evidence,
5294    });
5295    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5296    state.end_pass_parked(crate::run::ParkCause::Question);
5297    state.parked = true;
5298    state.save()?;
5299    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5300        tracing::warn!("could not notify about CI hold: {e:#}");
5301    }
5302    // A durable question and evidence are sufficient even if commenting fails.
5303    let body = stop_comment(
5304        &state.id,
5305        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5306    );
5307    let (_, body) = crate::github_text::prepare(state, "", &body);
5308    gh(
5309        &state.repo,
5310        &[
5311            "pr".into(),
5312            "comment".into(),
5313            pr.number.to_string(),
5314            "--body".into(),
5315            body,
5316        ],
5317    )
5318    .await
5319    .ok();
5320    Ok(())
5321}
5322
5323/// One observation, plus the two things [`PrState`] deliberately does not carry:
5324/// the title (needed for the squash subject) and where the failing checks'
5325/// logs live.
5326#[derive(Clone)]
5327struct Seen {
5328    pr: PrState,
5329    title: String,
5330    failing_urls: Vec<(String, String)>,
5331    /// `headRefOid`: the commit this observation, checks included, is about.
5332    head: String,
5333    /// The commit the checks belong to, read from the same GraphQL node as
5334    /// the checks themselves. Empty when unreadable.
5335    rollup_head: String,
5336    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5337    /// and DRAFT together, and a stop reason has to say which.
5338    merge_state: String,
5339    /// Every check of the rollup, for naming what an armed merge waits on.
5340    contexts: Vec<CheckInfo>,
5341    /// `baseRefName`, to look up which contexts the base requires.
5342    base: String,
5343}
5344
5345/// One check of the rollup as far as a stop reason needs it.
5346#[derive(Clone)]
5347struct CheckInfo {
5348    label: String,
5349    verdict: Verdict,
5350    required: Option<bool>,
5351    /// The workflow run the check belongs to; `None` for an external status.
5352    run: Option<String>,
5353}
5354
5355/// What to do with a red head before a fix round is spent on it.
5356#[derive(Debug, Clone, PartialEq, Eq)]
5357enum RerunStep {
5358    /// Rerun these workflow runs (each not yet rerun for this head).
5359    Rerun(Vec<String>),
5360    /// Reran already and the forge may still report the old failure: wait.
5361    Grace,
5362    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5363    Fix,
5364}
5365
5366/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5367/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5368/// pending checks in another run do not delay this run's rerun.
5369#[cfg(test)]
5370fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5371    rerunnable_with(contexts, false)
5372}
5373
5374fn rerunnable_with(
5375    contexts: &[CheckInfo],
5376    include_optional: bool,
5377) -> Vec<(String, Option<String>)> {
5378    contexts
5379        .iter()
5380        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5381        // `gh run rerun --failed` refuses a run with a job still going.
5382        .filter(|c| {
5383            c.run.as_ref().is_none_or(|r| {
5384                !contexts.iter().any(|o| {
5385                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5386                        && o.run.as_ref() == Some(r)
5387                })
5388            })
5389        })
5390        .map(|c| (c.label.clone(), c.run.clone()))
5391        .collect()
5392}
5393
5394/// Pure: rerun once per run id, wait out the grace, then hand over.
5395fn rerun_step(
5396    failing: &[(String, Option<String>)],
5397    record: Option<&LandReruns>,
5398    head: &str,
5399    now: i64,
5400) -> RerunStep {
5401    // A failure with no workflow run (an external status) cannot be rerun, and
5402    // the fixer's push re-runs everything anyway.
5403    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5404        return RerunStep::Fix;
5405    }
5406    // Reruns belong to the head they were made on.
5407    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5408    let mut fresh: Vec<String> = Vec::new();
5409    let mut recent = false;
5410    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5411        match record.and_then(|r| r.runs.get(run)) {
5412            None => {
5413                if !fresh.iter().any(|f| f == run) {
5414                    fresh.push(run.to_owned());
5415                }
5416            }
5417            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5418            Some(_) => {}
5419        }
5420    }
5421    if !fresh.is_empty() {
5422        RerunStep::Rerun(fresh)
5423    } else if recent {
5424        RerunStep::Grace
5425    } else {
5426        RerunStep::Fix
5427    }
5428}
5429
5430/// Read the pull request: `gh pr view` for the top-level thread and merge
5431/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5432/// inline review comments `gh pr view` does not report.
5433async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5434    let view = gh(
5435        repo,
5436        &[
5437            "pr".to_owned(),
5438            "view".to_owned(),
5439            pr_url.to_owned(),
5440            "--json".to_owned(),
5441            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5442                .to_owned(),
5443        ],
5444    )
5445    .await?;
5446    if !view.0 {
5447        bail!("gh pr view {pr_url}: {}", view.1);
5448    }
5449    let number = parse_pr(&view.1)?.number;
5450    let node = last_commit_node(repo, number).await;
5451    let mut seen = seen_from(&view.1, node.as_deref())?;
5452
5453    let inline = gh(
5454        repo,
5455        &[
5456            "api".to_owned(),
5457            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5458        ],
5459    )
5460    .await?;
5461    if inline.0 {
5462        match parse_inline_comments(&inline.1) {
5463            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5464            // An unreadable inline thread must not end a landing: the rollup
5465            // and the top-level thread are still real signal.
5466            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5467        }
5468    } else {
5469        tracing::warn!("gh api pulls/{}/comments: {}", seen.pr.number, inline.1);
5470    }
5471    Ok(seen)
5472}
5473
5474/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
5475/// response. No I/O.
5476///
5477/// The commit oid and the checks are read from the *same* node, so the rollup
5478/// is bound to the commit it belongs to by construction; two reads that agree
5479/// before and after another response prove nothing about what that response
5480/// held. The view's own rollup is never used. A node that is missing,
5481/// unreadable, carries GraphQL errors, or whose checks run past the page
5482/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
5483/// as "look again" and never as a reason to merge.
5484fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5485    let mut pr = parse_pr(view_json)?;
5486    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5487
5488    let mut rollup_head = String::new();
5489    let mut failing_urls = Vec::new();
5490    let mut contexts = Vec::new();
5491    let mut checks = Checks::Unknown;
5492    let mut failing = Vec::new();
5493    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5494        (checks, failing) = rollup_verdict(&rollup);
5495        failing_urls = rollup
5496            .iter()
5497            .filter(|c| c.verdict() == Verdict::Fail)
5498            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5499            .collect();
5500        contexts = rollup
5501            .iter()
5502            .map(|c| CheckInfo {
5503                label: c.label(),
5504                verdict: c.verdict(),
5505                required: c.is_required,
5506                run: c.url().and_then(run_of),
5507            })
5508            .collect();
5509        rollup_head = oid;
5510    }
5511    pr.checks = checks;
5512    pr.failing = failing;
5513
5514    Ok(Seen {
5515        pr,
5516        title: raw.title,
5517        failing_urls,
5518        head: raw.head_ref_oid,
5519        rollup_head,
5520        merge_state: raw.merge_state_status,
5521        contexts,
5522        base: raw.base_ref_name,
5523    })
5524}
5525
5526/// The last commit's oid and its checks from one GraphQL response, `None`
5527/// when anything about it cannot be trusted.
5528fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
5529    let v: serde_json::Value = serde_json::from_str(json).ok()?;
5530    if v.get("errors").is_some_and(|e| !e.is_null()) {
5531        return None;
5532    }
5533    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
5534    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
5535    let contexts = commit.pointer("/statusCheckRollup/contexts");
5536    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
5537        // No rollup at all: the commit has no checks.
5538        return Some((oid.to_owned(), Vec::new()));
5539    };
5540    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
5541        return None;
5542    }
5543    let nodes = contexts.get("nodes")?.as_array()?;
5544    let rollup = nodes
5545        .iter()
5546        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
5547        .collect::<Result<Vec<_>, _>>()
5548        .ok()?;
5549    Some((oid.to_owned(), rollup))
5550}
5551
5552/// The pull request's last commit and its checks, in one response. `None`
5553/// when the forge could not be asked.
5554async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
5555    let out = gh(
5556        repo,
5557        &[
5558            "api".to_owned(),
5559            "graphql".to_owned(),
5560            "-F".to_owned(),
5561            "owner={owner}".to_owned(),
5562            "-F".to_owned(),
5563            "repo={repo}".to_owned(),
5564            "-F".to_owned(),
5565            format!("number={number}"),
5566            "-f".to_owned(),
5567            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
5568             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
5569             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
5570             ... on CheckRun{name status conclusion detailsUrl \
5571             isRequired(pullRequestNumber:$number)} \
5572             ... on StatusContext{context state targetUrl \
5573             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
5574                .to_owned(),
5575        ],
5576    )
5577    .await
5578    .ok()?;
5579    out.0.then_some(out.1)
5580}
5581
5582/// What a fix round did.
5583#[doc(hidden)]
5584#[derive(Debug, PartialEq)]
5585pub enum Fixed {
5586    /// The fixer committed something, and this is the head that was pushed.
5587    Committed {
5588        /// The commit now at the tip of the pushed branch.
5589        head: String,
5590    },
5591    /// The fixer ran and chose to change nothing.
5592    Declined,
5593    /// Machine availability prevented a result; retry this round on resume.
5594    Deferred,
5595    /// The fixer could not run, or said nothing usable.
5596    Failed(String),
5597}
5598
5599/// Hand the failures and the comments to the fixer, then commit and push.
5600///
5601/// The fixer works in the winner's own worktree so its commits land on the
5602/// branch the pull request is built from, and it runs with `allow_write` for
5603/// the same reason.
5604#[doc(hidden)]
5605pub async fn fix_round(
5606    state: &mut RunState,
5607    pr: &PrState,
5608    round: usize,
5609    budget: usize,
5610    reason: &str,
5611    logs: &str,
5612) -> Result<Fixed> {
5613    let winner = state
5614        .winner()
5615        .cloned()
5616        .context("landing needs a winning candidate; none is recorded on this run")?;
5617    let roles = state
5618        .config
5619        .resolve_roles()
5620        .context("resolve the roster for the fix round")?;
5621    // Same chain as the review loop (see `crate::fixer`): the configured
5622    // fixers in order, otherwise the winner's own author continuing its own
5623    // conversation - the competition is over, so its context is pure benefit.
5624    let attempts = crate::fixer::attempts(state, &roles, &winner);
5625    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
5626
5627    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
5628    let mut artifacts = agent::artifacts_dir(&state.dir());
5629    if let Some(request) = state
5630        .merge_repairs
5631        .last()
5632        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
5633    {
5634        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
5635    }
5636    let prompt =
5637        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
5638            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
5639        } else {
5640            prompt
5641        };
5642    // Read before the fixer runs: it normally commits for itself, so HEAD has
5643    // already moved by the time it returns and a later read would see no
5644    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
5645    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5646    // Each id at most once, forward only: the next one is asked only when the
5647    // call advances, and only the last attempt's result is judged below, so an
5648    // exhausted chain ends as a single failed fixer does.
5649    let mut last = None;
5650    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
5651        if owner_requested_stop(state)? {
5652            return Ok(Fixed::Declined);
5653        }
5654        let mut seat = seat_of(state, &seat_key, &spec.id);
5655        let stem = if i == 0 {
5656            format!("land-{round}")
5657        } else {
5658            format!("land-{round}-{}", spec.id)
5659        };
5660        let out = agent::invoke(
5661            &spec,
5662            &mut seat,
5663            &Invocation {
5664                coordination: state.config.coordination.as_ref(),
5665                fetched_base: state.fetched_base.as_ref(),
5666                cwd: &winner.worktree,
5667                prompt: &prompt,
5668                timeout: Duration::from_secs(state.config.graph.timeout_fix),
5669                allow_write: true,
5670                sessions: state.config.graph.sessions,
5671                artifacts: &artifacts,
5672                stem: &stem,
5673                run: &state.id,
5674                node: "land",
5675                cache_dir: state.config.cache_dir().as_deref(),
5676                attachments: &[],
5677                writable: &[],
5678            },
5679        )
5680        .await;
5681        state.seats.insert(seat.key.clone(), seat);
5682        if let Some(next) = ids.get(i + 1)
5683            && agent::chain_advances(&out)
5684        {
5685            let (class, why) = crate::fixer::failure_of(&out);
5686            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
5687            continue;
5688        }
5689        last = Some((seat_key, out));
5690        break;
5691    }
5692    let (seat_key, out) = last.expect("the fixer chain always has an entry");
5693
5694    match out {
5695        Ok(o) if o.quota_exhausted() => {
5696            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
5697            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
5698            state.quota.push(loss);
5699            state.status = RunStatus::Blocked;
5700            state.save()?;
5701            // Keep partial edits reachable on the winner branch and leave a
5702            // clean tree for resume_landing_head. The resumed landing gates
5703            // this new commit before it can publish it; no push happens here.
5704            let inherited = crate::repo_lock::WaitPolicy::current();
5705            let wait = crate::repo_lock::WaitPolicy::new(
5706                Duration::from_secs(state.config.graph.timeout_resource_wait),
5707                move || inherited.cancelled(),
5708            );
5709            let _coordination = crate::repo_lock::SeatLease::operation_with(
5710                &winner.worktree,
5711                state.config.coordination.as_ref(),
5712                &wait,
5713            )
5714            .await?;
5715            let rescue = git::rescue_commit(
5716                &winner.worktree,
5717                &format!("magi: deferred land round {round} (uncommitted work)"),
5718            )
5719            .await?;
5720            state.note_withheld("land", &rescue.withheld);
5721            state.save()?;
5722            return Ok(Fixed::Deferred);
5723        }
5724        Ok(o) if !o.usable() => {
5725            return Ok(Fixed::Failed(format!(
5726                "the fixer produced nothing usable ({})",
5727                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
5728            )));
5729        }
5730        Ok(_) => {}
5731        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
5732        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
5733    }
5734
5735    if owner_requested_stop(state)? {
5736        return Ok(Fixed::Declined);
5737    }
5738
5739    // An agent that edited files but never committed would otherwise push
5740    // nothing and look like a refusal.
5741    let wait = crate::repo_lock::WaitPolicy::new(
5742        Duration::from_secs(state.config.graph.timeout_resource_wait),
5743        || false,
5744    );
5745    let coordination = crate::repo_lock::SeatLease::operation_with(
5746        &winner.worktree,
5747        state.config.coordination.as_ref(),
5748        &wait,
5749    )
5750    .await?;
5751    match git::rescue_commit(
5752        &winner.worktree,
5753        &format!("magi: land round {round} fixes (uncommitted work)"),
5754    )
5755    .await
5756    {
5757        Ok(r) => state.note_withheld("land", &r.withheld),
5758        Err(e)
5759            if state
5760                .merge_repairs
5761                .last()
5762                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
5763        {
5764            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
5765        }
5766        Err(_) => {}
5767    }
5768    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5769    drop(coordination);
5770    if after == before {
5771        return Ok(Fixed::Declined);
5772    }
5773
5774    if owner_requested_stop(state)? {
5775        return Ok(Fixed::Declined);
5776    }
5777    crate::pr_head::ensure_owner(state)?;
5778    let remote = state.config.merge.remote.clone();
5779    anyhow::ensure!(
5780        crate::foreign_checkout::write_back(state, &after).await?,
5781        "foreign checkout delivery is blocked; see the run events"
5782    );
5783    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
5784    let push = if state.pr_head.is_some() {
5785        let expected = state
5786            .pr_pushed_head
5787            .as_deref()
5788            .context("missing public head lease")?;
5789        git::push_as(
5790            &winner.worktree,
5791            &remote,
5792            &winner.branch,
5793            &public_head,
5794            expected,
5795        )
5796        .await?
5797    } else {
5798        git::push(&winner.worktree, &remote, &winner.branch).await?
5799    };
5800    if !push.ok() {
5801        return Ok(Fixed::Failed(format!(
5802            "pushing {} to {remote} failed: {}",
5803            public_head, push.stderr
5804        )));
5805    }
5806    state.event(
5807        "land",
5808        format!("round {round}: pushed a fix to {public_head}"),
5809    );
5810    state.pr_pushed_head = Some(after.clone());
5811    state.save()?;
5812    Ok(Fixed::Committed { head: after })
5813}
5814
5815/// Fetch or create a seat, keeping its conversation across nodes.
5816pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
5817    crate::fixer::seat_for(state, key, agent)
5818}
5819
5820/// Recheck the live PR and local worktree before spending the requested fix.
5821/// A moved/closed PR is held, never repaired using obsolete evidence.
5822pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
5823    let seen = observe(&state.repo, url).await?;
5824    let winner = state.winner().context("no winning branch to repair")?;
5825    if seen.pr.state != PrLifecycle::Open || seen.head != head {
5826        anyhow::bail!(
5827            "PR is closed or its head changed; review the current head before requesting repair again"
5828        );
5829    }
5830    if git::rev_parse(&winner.worktree, "HEAD").await? != head
5831        || !git::is_clean(&winner.worktree).await?
5832    {
5833        anyhow::bail!(
5834            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
5835        );
5836    }
5837    // Always disable any forge-side reservation, including one not recorded
5838    // by this run. A repair request is never merge authorization.
5839    let view = gh(
5840        &state.repo,
5841        &[
5842            "pr".into(),
5843            "view".into(),
5844            url.into(),
5845            "--json".into(),
5846            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
5847        ],
5848    )
5849    .await?;
5850    if !view.0 {
5851        bail!("cannot check auto-merge: {}", view.1);
5852    }
5853    let live: serde_json::Value = serde_json::from_str(&view.1)?;
5854    let public = state.pr_branch().unwrap_or(&winner.branch);
5855    if live["state"] != "OPEN"
5856        || live["headRefOid"] != head
5857        || live["headRefName"] != public
5858        || live["baseRefName"] != state.base_branch
5859        || live["isCrossRepository"] != false
5860    {
5861        bail!("PR changed during repair preflight; review its current head explicitly");
5862    }
5863    let auto_merge = live
5864        .get("autoMergeRequest")
5865        .context("cannot read the PR auto-merge reservation; repair held")?;
5866    if !auto_merge.is_null() {
5867        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
5868        if !out.0 {
5869            bail!("cannot disable auto-merge; repair held: {}", out.1);
5870        }
5871    }
5872    Ok(seen.pr)
5873}
5874
5875/// What the fixer is told.
5876fn fix_prompt(
5877    state: &RunState,
5878    pr: &PrState,
5879    round: usize,
5880    budget: usize,
5881    reason: &str,
5882    logs: &str,
5883) -> String {
5884    let mut s = format!(
5885        "Your patch is open as a pull request and it is not landing. Land round \
5886         {round} of {budget}.\n\n\
5887         Pull request: {}\n\n\
5888         What is holding it: {reason}\n\n\
5889         # The task\n\n{}\n",
5890        pr.url, state.instruction
5891    );
5892
5893    if pr.failing.is_empty() {
5894        s.push_str("\n# Failing checks\n\n(none)\n");
5895    } else {
5896        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
5897        if logs.trim().is_empty() {
5898            s.push_str(
5899                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
5900            );
5901        } else {
5902            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
5903        }
5904    }
5905
5906    if pr.review_comments.is_empty() {
5907        s.push_str("\n# Review comments\n\n(none)\n");
5908    } else {
5909        s.push_str("\n# Review comments\n");
5910        for c in &pr.review_comments {
5911            let where_ = match (&c.path, c.line) {
5912                (Some(p), Some(l)) => format!(" ({p}:{l})"),
5913                (Some(p), None) => format!(" ({p})"),
5914                _ => String::new(),
5915            };
5916            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
5917        }
5918    }
5919
5920    s.push_str(
5921        "\n# Rules\n\n\
5922         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
5923            failing test; do not silence a lint with an allow attribute; do not \
5924            stretch a timeout to hide a race. If the check is right, the code is \
5925            wrong.\n\
5926         2. Change nothing the checks and the comments did not raise. A \
5927            drive-by refactor turns a one-line fix into a pull request that \
5928            needs reviewing again.\n\
5929         3. If a comment is wrong, say so with a checkable argument and change \
5930            nothing for it. A declined comment with a reason is a correct \
5931            outcome; a change made to appease a reviewer is not.\n\
5932         4. Commit in this worktree. magi pushes to the pull request's branch \
5933            for you; do not push, merge, or close anything yourself.\n\
5934         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
5935         # Output\n\n\
5936         Say what you changed and why, and what you declined and why.",
5937    );
5938
5939    let language = &state.config.graph.language;
5940    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
5941        let _ = write!(s, "\n\nWrite all prose in {language}.");
5942    }
5943    // After the language line, so the exception is the last word on it.
5944    s.push_str(&crate::prompt::github_rule(
5945        language,
5946        &state.config.graph.github_language,
5947    ));
5948    if let Some(overlay) = state.config.prompts.overlay("fix") {
5949        let _ = write!(s, "\n\n{overlay}");
5950    }
5951    s.push('\n');
5952    s.push_str(crate::prompt::child_run_ownership());
5953    s
5954}
5955
5956/// Failing log tails, the way the operator collects them by hand:
5957/// `gh run view --log-failed`.
5958async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
5959    let mut out = String::new();
5960    for (name, url) in failing.iter().take(MAX_LOGS) {
5961        let args = match (job_of(url), run_of(url)) {
5962            (Some(job), _) => vec![
5963                "run".to_owned(),
5964                "view".to_owned(),
5965                "--log-failed".to_owned(),
5966                "--job".to_owned(),
5967                job,
5968            ],
5969            (None, Some(run)) => vec![
5970                "run".to_owned(),
5971                "view".to_owned(),
5972                run,
5973                "--log-failed".to_owned(),
5974            ],
5975            // Not a GitHub Actions check - an external status has no log here.
5976            (None, None) => continue,
5977        };
5978        let (ok, body) = match gh(repo, &args).await {
5979            Ok(v) => v,
5980            Err(e) => (false, format!("{e:#}")),
5981        };
5982        if !ok && body.trim().is_empty() {
5983            continue;
5984        }
5985        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
5986    }
5987    out
5988}
5989
5990/// Job id out of a check's `detailsUrl`
5991/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
5992fn job_of(details_url: &str) -> Option<String> {
5993    let after = details_url.split("/job/").nth(1)?;
5994    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
5995    (!id.is_empty()).then_some(id)
5996}
5997
5998/// Workflow run id out of a check's `detailsUrl`.
5999pub(crate) fn run_of(details_url: &str) -> Option<String> {
6000    let after = details_url.split("/actions/runs/").nth(1)?;
6001    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6002    (!id.is_empty()).then_some(id)
6003}
6004
6005/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6006/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6007/// it to that.
6008fn stop_comment(run_id: &str, why: &str) -> String {
6009    format!(
6010        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6011         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6012    )
6013}
6014
6015/// Leave the pull request open, say why on it, and mark the run blocked.
6016///
6017/// The comment is what makes an unattended stop actionable: the operator wakes
6018/// up to a pull request that explains itself rather than to a silent queue.
6019async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6020    let body = stop_comment(&state.id, why);
6021    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6022    if !body.contains(MARKER) {
6023        body = format!("{MARKER}\n{body}");
6024    }
6025    let posted = gh(
6026        repo,
6027        &[
6028            "pr".to_owned(),
6029            "comment".to_owned(),
6030            pr.number.to_string(),
6031            "--body".to_owned(),
6032            body,
6033        ],
6034    )
6035    .await;
6036    match posted {
6037        Ok((true, _)) => {}
6038        Ok((false, out)) => tracing::warn!("could not comment on {}: {out}", pr.url),
6039        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6040    }
6041    state.status = RunStatus::Blocked;
6042    state.merge = Some(MergeOutcome {
6043        mode: MergeMode::Pr,
6044        ok: false,
6045        detail: why.to_owned(),
6046        empty: false,
6047    });
6048    state.event("land", format!("stopped: {why}"));
6049    state.save()?;
6050    Ok(())
6051}
6052
6053/// Run `gh` in `repo`, returning success and the combined output.
6054///
6055/// Combined because `gh` reports a refused merge on stderr and the pull request
6056/// json on stdout, and both are evidence.
6057///
6058/// `GH_REPO` is stripped from the child's environment: every call site here
6059/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6060/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6061/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6062/// `GH_REPO` the operator happens to have exported for an unrelated script
6063/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6064/// below) to a different repository than the one actually on disk - which
6065/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6066/// could be made to agree with whatever repository a forged `--merged` URL
6067/// claims, defeating it entirely.
6068pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<(bool, String)> {
6069    let out = tokio::process::Command::new("gh")
6070        .args(args)
6071        .current_dir(cwd)
6072        .env_remove("GH_REPO")
6073        .quiet()
6074        .stdin(std::process::Stdio::null())
6075        .output()
6076        .await
6077        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6078    let mut body = String::from_utf8_lossy(&out.stdout).into_owned();
6079    let err = String::from_utf8_lossy(&out.stderr);
6080    if body.trim().is_empty() {
6081        body = err.into_owned();
6082    } else if !err.trim().is_empty() {
6083        body.push_str(&err);
6084    }
6085    Ok((out.status.success(), body.trim().to_owned()))
6086}
6087
6088/// Verdict of one entry in the status rollup.
6089#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6090pub(crate) enum Verdict {
6091    Pass,
6092    Fail,
6093    Pending,
6094    Unknown,
6095}
6096
6097impl Verdict {
6098    /// Short operator-facing check result.
6099    pub(crate) fn label(self) -> &'static str {
6100        match self {
6101            Self::Pass => "passed",
6102            Self::Fail => "failed",
6103            Self::Pending => "pending",
6104            Self::Unknown => "unknown",
6105        }
6106    }
6107}
6108
6109#[derive(Debug, Deserialize)]
6110#[serde(rename_all = "camelCase")]
6111struct GhPr {
6112    #[serde(default)]
6113    url: String,
6114    #[serde(default)]
6115    number: u64,
6116    #[serde(default)]
6117    state: String,
6118    #[serde(default)]
6119    title: String,
6120    #[serde(default)]
6121    status_check_rollup: Vec<GhCheck>,
6122    /// GitHub's own verdict on whether the pull request can be merged.
6123    ///
6124    /// Worth asking for because it is the only place the *required* check set
6125    /// is applied: the rollup lists every check equally, so a repository that
6126    /// deliberately does not require `coverage` still looks red here. See
6127    /// [`Blocking`].
6128    #[serde(default)]
6129    merge_state_status: String,
6130    /// The commit the pull request currently points at. Compared with the
6131    /// commit a fix round pushed, it is how the loop knows the forge has moved
6132    /// on and the rollup belongs to the new head.
6133    #[serde(default)]
6134    head_ref_oid: String,
6135    #[serde(default)]
6136    base_ref_name: String,
6137    #[serde(default)]
6138    reviews: Vec<GhReview>,
6139    #[serde(default)]
6140    comments: Vec<GhComment>,
6141}
6142
6143/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6144/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6145/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6146/// conclusion at all.
6147#[derive(Debug, Deserialize)]
6148#[serde(rename_all = "camelCase")]
6149struct GhCheck {
6150    #[serde(default)]
6151    name: Option<String>,
6152    #[serde(default)]
6153    context: Option<String>,
6154    #[serde(default)]
6155    status: Option<String>,
6156    #[serde(default)]
6157    conclusion: Option<String>,
6158    #[serde(default)]
6159    state: Option<String>,
6160    #[serde(default)]
6161    details_url: Option<String>,
6162    #[serde(default)]
6163    target_url: Option<String>,
6164    /// Whether the base branch requires this check. Only the GraphQL node
6165    /// carries it; `None` is "not read", never "not required".
6166    #[serde(default)]
6167    is_required: Option<bool>,
6168}
6169
6170impl GhCheck {
6171    /// Name to show a human and hand to the fixer.
6172    fn label(&self) -> String {
6173        self.name
6174            .clone()
6175            .or_else(|| self.context.clone())
6176            .unwrap_or_else(|| "(unnamed check)".to_owned())
6177    }
6178
6179    /// Where this check's logs live, when it has any.
6180    fn url(&self) -> Option<&str> {
6181        self.details_url
6182            .as_deref()
6183            .or(self.target_url.as_deref())
6184            .filter(|u| !u.is_empty())
6185    }
6186
6187    /// Did it pass?
6188    ///
6189    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6190    /// skips release and bot pull requests by design, and a skip that blocked
6191    /// landing would block exactly the pull requests that need no review.
6192    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6193    /// merging over one is merging over a check that never ran.
6194    fn verdict(&self) -> Verdict {
6195        if let Some(status) = self.status.as_deref() {
6196            if !status.eq_ignore_ascii_case("COMPLETED") {
6197                return Verdict::Pending;
6198            }
6199        }
6200        let outcome = self
6201            .conclusion
6202            .as_deref()
6203            .or(self.state.as_deref())
6204            .unwrap_or("");
6205        match outcome.to_ascii_uppercase().as_str() {
6206            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6207            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6208            | "ACTION_REQUIRED" => Verdict::Fail,
6209            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6210                Verdict::Pending
6211            }
6212            _ => Verdict::Unknown,
6213        }
6214    }
6215}
6216
6217#[derive(Debug, Deserialize)]
6218struct GhAuthor {
6219    #[serde(default)]
6220    login: String,
6221}
6222
6223#[derive(Debug, Deserialize)]
6224struct GhReview {
6225    #[serde(default)]
6226    author: GhAuthor,
6227    #[serde(default)]
6228    body: String,
6229}
6230
6231#[derive(Debug, Deserialize)]
6232struct GhComment {
6233    #[serde(default)]
6234    author: GhAuthor,
6235    #[serde(default)]
6236    body: String,
6237}
6238
6239#[derive(Debug, Deserialize)]
6240struct GhUser {
6241    #[serde(default)]
6242    login: String,
6243}
6244
6245#[derive(Debug, Deserialize)]
6246struct GhInline {
6247    #[serde(default)]
6248    user: GhUser,
6249    #[serde(default)]
6250    path: Option<String>,
6251    #[serde(default)]
6252    line: Option<u64>,
6253    #[serde(default)]
6254    body: String,
6255}
6256
6257impl Default for GhAuthor {
6258    fn default() -> Self {
6259        Self {
6260            login: "(unknown)".to_owned(),
6261        }
6262    }
6263}
6264
6265impl Default for GhUser {
6266    fn default() -> Self {
6267        Self {
6268            login: "(unknown)".to_owned(),
6269        }
6270    }
6271}
6272
6273#[cfg(test)]
6274pub(crate) mod tests {
6275    use super::*;
6276    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6277
6278    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6279        format!(
6280            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6281        )
6282    }
6283
6284    #[test]
6285    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6286        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6287        assert_eq!(
6288            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6289            Ok(())
6290        );
6291        for (json, why) in [
6292            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6293            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6294            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6295            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6296            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6297            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6298        ] {
6299            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6300                .unwrap_err()
6301                .why;
6302            assert!(err.contains(why), "{json}: {err}");
6303        }
6304        // A head that moved on past what was verified is left alone.
6305        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6306        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6307        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6308        assert!(
6309            !closable(
6310                &head_json("x", "main", "OPEN", false),
6311                "magi/27b2/A",
6312                "main",
6313                &[]
6314            )
6315            .unwrap_err()
6316            .retry
6317        );
6318        assert!(is_forge_url("https://github.com/o/r.git"));
6319        assert!(is_forge_url("git@github.com:o/r.git"));
6320        assert!(!is_forge_url("/tmp/origin.git"));
6321        assert!(!is_forge_url("C:\\work\\origin.git"));
6322        assert!(!is_forge_url("file:///tmp/origin.git"));
6323        assert!(forge_unavailable(
6324            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6325        ));
6326        assert!(!forge_unavailable(
6327            "gh pr list failed: error connecting to api.github.com"
6328        ));
6329        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6330        // A record that does not say whether it is a fork is not trusted.
6331        assert!(
6332            closable(
6333                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6334                "b",
6335                "main",
6336                &["aaa".to_owned()]
6337            )
6338            .is_err()
6339        );
6340    }
6341
6342    #[test]
6343    fn the_close_comment_names_the_commit_on_the_base() {
6344        let e = crate::already::Evidence {
6345            proof: crate::already::Proof::PatchId,
6346            tip: "1234567890".to_owned(),
6347            commits: vec!["0e368de0000".to_owned()],
6348        };
6349        let c = superseded_comment("main", &e);
6350        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6351    }
6352
6353    /// Real `gh pr view` output for the open pull request #10 (Renovate's apm bump), trimmed to four checks and its one comment. Every check passed or was skipped by the review workflow, and the only comment is CodeRabbit's trigger notice.
6354    const GREEN_OPEN: &str = r####"{
6355  "url": "https://github.com/yukimemi/magi/pull/10",
6356  "number": 10,
6357  "state": "OPEN",
6358  "mergeStateStatus": "CLEAN",
6359  "statusCheckRollup": [
6360    {
6361      "__typename": "CheckRun",
6362      "conclusion": "SKIPPED",
6363      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6364      "name": "review",
6365      "status": "COMPLETED",
6366      "workflowName": "claude-review"
6367    },
6368    {
6369      "__typename": "CheckRun",
6370      "conclusion": "SUCCESS",
6371      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6372      "name": "check (ubuntu-latest)",
6373      "status": "COMPLETED",
6374      "workflowName": "CI"
6375    },
6376    {
6377      "__typename": "CheckRun",
6378      "conclusion": "SUCCESS",
6379      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6380      "name": "rustfmt",
6381      "status": "COMPLETED",
6382      "workflowName": "CI"
6383    },
6384    {
6385      "__typename": "StatusContext",
6386      "context": "CodeRabbit",
6387      "state": "SUCCESS",
6388      "targetUrl": ""
6389    }
6390  ],
6391  "reviews": [],
6392  "comments": [
6393    {
6394      "author": {
6395        "login": "coderabbitai"
6396      },
6397      "authorAssociation": "NONE",
6398      "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"
6399    }
6400  ]
6401}"####;
6402
6403    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
6404    const RED_OPEN: &str = r####"{
6405  "url": "https://github.com/yukimemi/magi/pull/9",
6406  "number": 9,
6407  "state": "OPEN",
6408  "mergeStateStatus": "UNSTABLE",
6409  "statusCheckRollup": [
6410    {
6411      "__typename": "CheckRun",
6412      "conclusion": "SUCCESS",
6413      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6414      "name": "check (ubuntu-latest)",
6415      "status": "COMPLETED",
6416      "workflowName": "CI"
6417    },
6418    {
6419      "__typename": "CheckRun",
6420      "conclusion": "SUCCESS",
6421      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6422      "name": "rustfmt",
6423      "status": "COMPLETED",
6424      "workflowName": "CI"
6425    },
6426    {
6427      "__typename": "CheckRun",
6428      "conclusion": "FAILURE",
6429      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6430      "name": "editorconfig",
6431      "status": "COMPLETED",
6432      "workflowName": "CI"
6433    },
6434    {
6435      "__typename": "StatusContext",
6436      "context": "CodeRabbit",
6437      "state": "SUCCESS",
6438      "targetUrl": ""
6439    }
6440  ],
6441  "reviews": [],
6442  "comments": [
6443    {
6444      "author": {
6445        "login": "coderabbitai"
6446      },
6447      "authorAssociation": "NONE",
6448      "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"
6449    }
6450  ]
6451}"####;
6452
6453    /// Pull request #9's real payload with its `editorconfig` check rewound to the `IN_PROGRESS` / `conclusion: null` pair `gh` reports while a job is still in flight.
6454    const PENDING_OPEN: &str = r####"{
6455  "url": "https://github.com/yukimemi/magi/pull/9",
6456  "number": 9,
6457  "state": "OPEN",
6458  "statusCheckRollup": [
6459    {
6460      "__typename": "CheckRun",
6461      "conclusion": "SUCCESS",
6462      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6463      "name": "check (ubuntu-latest)",
6464      "status": "COMPLETED",
6465      "workflowName": "CI"
6466    },
6467    {
6468      "__typename": "CheckRun",
6469      "conclusion": "SUCCESS",
6470      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6471      "name": "rustfmt",
6472      "status": "COMPLETED",
6473      "workflowName": "CI"
6474    },
6475    {
6476      "__typename": "CheckRun",
6477      "conclusion": null,
6478      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6479      "name": "editorconfig",
6480      "status": "IN_PROGRESS",
6481      "workflowName": "CI"
6482    },
6483    {
6484      "__typename": "StatusContext",
6485      "context": "CodeRabbit",
6486      "state": "SUCCESS",
6487      "targetUrl": ""
6488    }
6489  ],
6490  "reviews": [],
6491  "comments": []
6492}"####;
6493
6494    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
6495    const MERGED: &str = r####"{
6496  "url": "https://github.com/yukimemi/magi/pull/16",
6497  "number": 16,
6498  "state": "MERGED",
6499  "statusCheckRollup": [
6500    {
6501      "__typename": "CheckRun",
6502      "conclusion": "SUCCESS",
6503      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
6504      "name": "check (ubuntu-latest)",
6505      "status": "COMPLETED",
6506      "workflowName": "CI"
6507    },
6508    {
6509      "__typename": "CheckRun",
6510      "conclusion": "SUCCESS",
6511      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
6512      "name": "review",
6513      "status": "COMPLETED",
6514      "workflowName": "claude-review"
6515    }
6516  ],
6517  "reviews": [],
6518  "comments": []
6519}"####;
6520
6521    /// Pull request #12's real payload - a green pull request carrying CodeRabbit's walkthrough and a Claude review that found a real bug - rewound to the `OPEN` state it was in when that review was posted.
6522    const REVIEWED_OPEN: &str = r####"{
6523  "url": "https://github.com/yukimemi/magi/pull/12",
6524  "number": 12,
6525  "state": "OPEN",
6526  "statusCheckRollup": [
6527    {
6528      "__typename": "CheckRun",
6529      "conclusion": "SUCCESS",
6530      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
6531      "name": "check (ubuntu-latest)",
6532      "status": "COMPLETED",
6533      "workflowName": "CI"
6534    },
6535    {
6536      "__typename": "CheckRun",
6537      "conclusion": "SUCCESS",
6538      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
6539      "name": "review",
6540      "status": "COMPLETED",
6541      "workflowName": "claude-review"
6542    }
6543  ],
6544  "reviews": [
6545    {
6546      "author": {
6547        "login": "claude"
6548      },
6549      "state": "COMMENTED",
6550      "body": ""
6551    }
6552  ],
6553  "comments": [
6554    {
6555      "author": {
6556        "login": "coderabbitai"
6557      },
6558      "authorAssociation": "NONE",
6559      "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"
6560    },
6561    {
6562      "author": {
6563        "login": "claude"
6564      },
6565      "authorAssociation": "NONE",
6566      "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"
6567    }
6568  ]
6569}"####;
6570
6571    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
6572    const INLINE: &str = r####"[
6573  {
6574    "user": {
6575      "login": "claude[bot]"
6576    },
6577    "path": "src/graph.rs",
6578    "line": 231,
6579    "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"
6580  }
6581]"####;
6582
6583    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
6584    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
6585<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
6586
6587> [!IMPORTANT]
6588> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
6589> 
6590> This repository does not receive automatic reviews because it has fewer than 10 stars.
6591> 
6592> <details>
6593> <summary>⚙️ Run configuration</summary>
6594> 
6595> **Configuration used**: defaults
6596> 
6597> **Review profile**: CHILL
6598> 
6599> **Plan**: Team
6600> 
6601> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
6602> 
6603> </details>
6604
6605<!-- end of auto-generated comment: skip review by coderabbit.ai -->
6606
6607<!-- tips_start -->
6608
6609---
6610
6611Thanks 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.
6612
6613<details>
6614<summary>❤️ Share</summary>
6615
6616- [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"####;
6617
6618    /// The Claude review job's real comment while it is still working: a heading and a task list, and nothing that asks for a change.
6619    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
6620
6621---
6622### Reviewing PR #16
6623
6624- [x] Read AGENTS.md conventions
6625- [x] Review `src/daemon.rs` changes
6626- [x] Review `src/main.rs` changes (new `doctor` reporting)
6627- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
6628- [x] Check test coverage for new behavior
6629- [x] Run verification commands (blocked — see note)
6630- [x] Post findings"####;
6631
6632    /// The same job's real comment on pull request #12 once it had something to say.
6633    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
6634
6635---
6636### Review: `magi review <branch>` — cheap-half-only graph
6637
6638Read 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.
6639
6640**Correctness**
6641
6642- 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"####;
6643
6644    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
6645        PrState {
6646            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
6647            number: 16,
6648            state: PrLifecycle::Open,
6649            checks,
6650            // These tests are about red-means-fix, so a red here is one the
6651            // forge gates on. Without saying so they would assert the new
6652            // "merge past a check nobody requires" path by accident.
6653            blocking: if matches!(checks, Checks::Red) {
6654                Blocking::Yes
6655            } else {
6656                Blocking::No
6657            },
6658            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
6659            review_comments: (0..comments)
6660                .map(|i| ReviewComment {
6661                    author: "coderabbitai".to_owned(),
6662                    path: Some("src/graph.rs".to_owned()),
6663                    line: Some(231),
6664                    body: format!("finding {i}"),
6665                })
6666                .collect(),
6667        }
6668    }
6669
6670    #[test]
6671    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
6672        use CiExpectation::{Absent, Expected};
6673        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
6674            let p = pr(checks, &["x"], 0);
6675            for waited in [Duration::ZERO, CHECKS_GRACE] {
6676                assert_eq!(
6677                    decide_with(&p, 0, 4, waited, Expected),
6678                    decide(&p, 0, 4, waited)
6679                );
6680            }
6681        }
6682        // Nothing will ever report: no wait, no give-up, no fix round.
6683        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
6684            let p = pr(checks, &["x"], 0);
6685            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
6686            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
6687        }
6688        // Third-party statuses never change the review decision, even at budget.
6689        for comments in [0, 1] {
6690            for round in [0, 4] {
6691                let absent = decide_with(
6692                    &pr(Checks::Unknown, &[], comments),
6693                    round,
6694                    4,
6695                    CHECKS_GRACE,
6696                    Absent,
6697                );
6698                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
6699                    assert_eq!(
6700                        decide_with(
6701                            &pr(checks, &["third-party"], comments),
6702                            round,
6703                            4,
6704                            Duration::ZERO,
6705                            Absent
6706                        ),
6707                        absent
6708                    );
6709                }
6710                if comments != 0 {
6711                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
6712                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
6713                }
6714            }
6715        }
6716        let empty = pr(Checks::Unknown, &[], 0);
6717        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
6718            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
6719        }
6720        assert_eq!(
6721            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
6722            Step::Wait
6723        );
6724        assert_eq!(
6725            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
6726            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
6727        );
6728        // A conflict is not a check: it still wants the rebase.
6729        let mut p = pr(Checks::Unknown, &[], 0);
6730        p.blocking = Blocking::Conflict;
6731        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
6732        // And a pull request that left our hands is still done.
6733        p.state = PrLifecycle::Merged;
6734        assert_eq!(
6735            decide_with(&p, 0, 4, Duration::ZERO, Absent),
6736            Step::Done { merged: true }
6737        );
6738    }
6739
6740    #[test]
6741    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
6742        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
6743        assert_eq!(state.number, 10);
6744        assert_eq!(state.state, PrLifecycle::Open);
6745        assert_eq!(state.checks, Checks::Green);
6746        assert!(state.failing.is_empty());
6747        assert!(
6748            state.review_comments.is_empty(),
6749            "the only comment is CodeRabbit's trigger notice: {:?}",
6750            state.review_comments
6751        );
6752        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
6753    }
6754
6755    #[test]
6756    fn a_failing_check_parses_as_red_and_is_named() {
6757        let state = parse_pr(RED_OPEN).expect("red fixture parses");
6758        assert_eq!(state.checks, Checks::Red);
6759        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
6760        // The captured payload says `UNSTABLE` - mergeable, with a check
6761        // nobody requires red - which is exactly the shape that had to be
6762        // merged by hand. Asserted separately, in
6763        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
6764        // test is about is that a red check is *named*, so the reason a fixer
6765        // is handed says which one; so it asks the blocking question here.
6766        let mut blocking = state.clone();
6767        blocking.blocking = Blocking::Yes;
6768        match decide(&blocking, 0, 4, Duration::ZERO) {
6769            Step::Fix { reason } => {
6770                assert!(reason.contains("editorconfig"), "reason: {reason}");
6771                assert!(reason.contains("failing"), "reason: {reason}");
6772            }
6773            other => panic!("expected a fix round, got {other:?}"),
6774        }
6775    }
6776
6777    #[test]
6778    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
6779        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
6780        assert_eq!(state.checks, Checks::Pending);
6781        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
6782    }
6783
6784    #[test]
6785    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
6786        let state = parse_pr(MERGED).expect("merged fixture parses");
6787        assert_eq!(state.state, PrLifecycle::Merged);
6788        assert_eq!(
6789            decide(&state, 0, 4, Duration::ZERO),
6790            Step::Done { merged: true }
6791        );
6792    }
6793
6794    #[test]
6795    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
6796        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
6797        assert_eq!(state.checks, Checks::Green);
6798        let authors: Vec<&str> = state
6799            .review_comments
6800            .iter()
6801            .map(|c| c.author.as_str())
6802            .collect();
6803        assert_eq!(
6804            authors,
6805            vec!["claude"],
6806            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
6807        );
6808        match decide(&state, 0, 4, Duration::ZERO) {
6809            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
6810            other => panic!("expected a fix round, got {other:?}"),
6811        }
6812    }
6813
6814    #[test]
6815    fn inline_review_comments_keep_their_file_and_line() {
6816        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
6817        assert_eq!(comments.len(), 1);
6818        assert_eq!(comments[0].author, "claude[bot]");
6819        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
6820        assert_eq!(comments[0].line, Some(231));
6821        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
6822    }
6823
6824    #[test]
6825    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
6826        assert!(
6827            is_noise(CODERABBIT_TRIGGER),
6828            "CodeRabbit's trigger notice declares itself not a review"
6829        );
6830        assert!(
6831            is_noise(CLAUDE_CHECKLIST),
6832            "a progress checklist asks for nothing"
6833        );
6834        assert!(
6835            !is_noise(CLAUDE_FINDING),
6836            "a review that names a bug is input, not noise"
6837        );
6838
6839        let mut clean = pr(Checks::Green, &[], 0);
6840        clean.review_comments.push(ReviewComment {
6841            author: "coderabbitai".to_owned(),
6842            path: None,
6843            line: None,
6844            body: CODERABBIT_TRIGGER.to_owned(),
6845        });
6846        clean.review_comments.retain(|c| !is_noise(&c.body));
6847        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
6848
6849        let mut found = pr(Checks::Green, &[], 0);
6850        found.review_comments.push(ReviewComment {
6851            author: "claude".to_owned(),
6852            path: None,
6853            line: None,
6854            body: CLAUDE_FINDING.to_owned(),
6855        });
6856        found.review_comments.retain(|c| !is_noise(&c.body));
6857        assert!(matches!(
6858            decide(&found, 0, 4, Duration::ZERO),
6859            Step::Fix { .. }
6860        ));
6861    }
6862
6863    #[test]
6864    fn the_policy_table_holds_for_every_combination_that_matters() {
6865        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
6866            (
6867                "pending checks are waited for, even on the last round",
6868                pr(Checks::Pending, &[], 0),
6869                4,
6870                4,
6871                Duration::ZERO,
6872                Step::Wait,
6873            ),
6874            (
6875                "red checks are fixed",
6876                pr(Checks::Red, &["editorconfig"], 0),
6877                0,
6878                4,
6879                Duration::ZERO,
6880                Step::Fix {
6881                    reason: "1 check(s) failing: editorconfig".to_owned(),
6882                },
6883            ),
6884            (
6885                "green with comments is fixed, not merged",
6886                pr(Checks::Green, &[], 2),
6887                1,
6888                4,
6889                Duration::ZERO,
6890                Step::Fix {
6891                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
6892                        .to_owned(),
6893                },
6894            ),
6895            (
6896                "green and clean merges",
6897                pr(Checks::Green, &[], 0),
6898                3,
6899                4,
6900                Duration::ZERO,
6901                Step::Merge,
6902            ),
6903            (
6904                "an unreadable rollup is waited on while the grace lasts",
6905                pr(Checks::Unknown, &[], 0),
6906                0,
6907                4,
6908                Duration::ZERO,
6909                Step::Wait,
6910            ),
6911            (
6912                "an unreadable rollup is never merged once the grace is spent",
6913                pr(Checks::Unknown, &[], 0),
6914                0,
6915                4,
6916                CHECKS_GRACE,
6917                Step::GiveUp {
6918                    reason: "no check status is readable on the pull request after 3 minute(s); \
6919                             refusing to merge on a guess"
6920                        .to_owned(),
6921                },
6922            ),
6923        ];
6924        for (what, state, round, budget, waited, want) in cases {
6925            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
6926        }
6927    }
6928
6929    #[test]
6930    fn the_forge_verdict_survives_the_round_trip_from_gh() {
6931        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
6932        // requested but never parsed is the kind of thing that looks wired up
6933        // and answers `Unsaid` forever.
6934        let green = parse_pr(GREEN_OPEN).expect("parse");
6935        assert_eq!(green.blocking, Blocking::No);
6936        let red = parse_pr(RED_OPEN).expect("parse");
6937        assert_eq!(
6938            red.blocking,
6939            Blocking::No,
6940            "`UNSTABLE` is mergeable: the red check is one nobody requires"
6941        );
6942        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
6943        // A payload from an older `gh` has no such field at all.
6944        let quiet =
6945            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
6946        assert_eq!(quiet.blocking, Blocking::Unsaid);
6947    }
6948
6949    #[test]
6950    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
6951        // Pull request 37's only red check was `editorconfig`, failing
6952        // because the action could not fetch its own binary after
6953        // editorconfig-checker v4 renamed its release assets. The repository
6954        // does not require it. magi answered by asking a fixer to repair a
6955        // change that was fine, and the pull request had to be merged by hand.
6956        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
6957        nonblocking.blocking = Blocking::No;
6958        assert_eq!(
6959            decide(&nonblocking, 0, 4, Duration::ZERO),
6960            Step::Merge,
6961            "the forge says nothing is in the way, so nothing is"
6962        );
6963
6964        // The same red, gated on: that is a fix round, as before.
6965        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
6966        blocking.blocking = Blocking::Yes;
6967        assert!(matches!(
6968            decide(&blocking, 0, 4, Duration::ZERO),
6969            Step::Fix { .. }
6970        ));
6971
6972        // A review comment still outranks green-enough: a non-required red
6973        // must not become a way to merge past an unanswered reviewer.
6974        let mut commented = pr(Checks::Red, &["coverage"], 1);
6975        commented.blocking = Blocking::No;
6976        assert!(matches!(
6977            decide(&commented, 0, 4, Duration::ZERO),
6978            Step::Fix { .. }
6979        ));
6980
6981        // And silence from the forge is not consent.
6982        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
6983        unsaid.blocking = Blocking::Unsaid;
6984        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
6985        assert!(matches!(
6986            decide(&unsaid, 0, 4, CHECKS_GRACE),
6987            Step::Fix { .. }
6988        ));
6989    }
6990
6991    #[test]
6992    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
6993        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
6994        red.blocking = Blocking::No;
6995        assert_eq!(
6996            decide(&red, 0, 4, Duration::ZERO),
6997            Step::Merge,
6998            "announcing must not change the decision"
6999        );
7000        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7001        assert!(said.contains("yukimemi/magi"), "{said}");
7002        assert!(said.contains("#16"), "{said}");
7003        assert!(
7004            said.contains("https://github.com/yukimemi/magi/pull/16"),
7005            "{said}"
7006        );
7007        assert!(
7008            said.contains("test (windows-latest)") && said.contains("coverage"),
7009            "{said}"
7010        );
7011
7012        // `failing` can be left over on a green observation; only `checks` counts.
7013        let green = pr(Checks::Green, &["stale"], 0);
7014        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7015    }
7016
7017    #[test]
7018    fn red_merge_notices_omit_empty_check_details() {
7019        for checks in [vec![], vec!["", "  "]] {
7020            let red = pr(Checks::Red, &checks, 0);
7021            let summary = red_merge_summary("owner/repo", &red).unwrap();
7022            let notice = crate::notices::merged_red("run-1", &summary);
7023            assert_eq!(
7024                notice.message,
7025                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7026            );
7027            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7028        }
7029        let red = pr(Checks::Red, &["", " test ", " "], 0);
7030        let summary = red_merge_summary("owner/repo", &red).unwrap();
7031        assert!(summary.contains("with red checks: test ("), "{summary}");
7032    }
7033
7034    #[test]
7035    fn the_repo_label_comes_from_the_pull_request_url() {
7036        let p = Path::new("/tmp/checkout");
7037        assert_eq!(
7038            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7039            "yukimemi/magi"
7040        );
7041        assert_eq!(repo_label(p, "not a url"), "checkout");
7042    }
7043
7044    #[test]
7045    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7046        // Pull requests 35 and 37 were both rebased by hand: a competition
7047        // that runs for two hours against a repository merging pull requests
7048        // all day conflicts on the way in, and that is arithmetic rather
7049        // than a defect in the change.
7050        let mut conflicted = pr(Checks::Green, &[], 0);
7051        conflicted.blocking = Blocking::Conflict;
7052        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7053
7054        // Decided before the checks, and even with the rounds spent: every
7055        // check on a branch that cannot land is an answer about a state that
7056        // cannot land, and a conflict is not the change's fault.
7057        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7058        red.blocking = Blocking::Conflict;
7059        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7060
7061        // The lifecycle still wins over everything, conflict included.
7062        let mut merged = pr(Checks::Red, &[], 0);
7063        merged.blocking = Blocking::Conflict;
7064        merged.state = PrLifecycle::Merged;
7065        assert_eq!(
7066            decide(&merged, 0, 4, Duration::ZERO),
7067            Step::Done { merged: true }
7068        );
7069    }
7070
7071    #[test]
7072    fn the_forge_verdict_is_read_off_merge_state_status() {
7073        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7074        // matters: mergeable, with a non-required check red or still running.
7075        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7076            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7077            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7078        }
7079        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7080        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7081        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7082        // An older `gh`, or a token without the scope, says nothing - and
7083        // refusing to guess is the rule everywhere else in this module.
7084        for quiet in ["", "UNKNOWN"] {
7085            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7086            assert!(Blocking::of(quiet).stops_a_merge());
7087        }
7088    }
7089
7090    #[test]
7091    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7092        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7093        // The exact stderr from run ec12, in a jj-colocated repository.
7094        let jj = "could not determine current branch: failed to run git: not on any branch";
7095
7096        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7097            .expect("the forge says merged, so it merged");
7098        assert!(landed.ok);
7099        assert!(
7100            landed.detail.contains("but the pull request is merged"),
7101            "the record must not read as a clean success: {}",
7102            landed.detail
7103        );
7104        assert!(
7105            landed.detail.contains("not on any branch"),
7106            "and it must keep what the command actually said: {}",
7107            landed.detail
7108        );
7109
7110        // A pull request still open means the merge really failed.
7111        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7112        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7113        // And an unreadable answer is not evidence of success.
7114        assert!(merged_after_all(&argv, jj, None).is_none());
7115    }
7116
7117    #[test]
7118    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7119        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7120        state.state = PrLifecycle::Closed;
7121        assert_eq!(
7122            decide(&state, 0, 4, Duration::ZERO),
7123            Step::Done { merged: false },
7124            "a human closing the pull request ends the loop, whatever CI says"
7125        );
7126    }
7127
7128    #[test]
7129    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7130        let red = decide(
7131            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7132            4,
7133            4,
7134            Duration::ZERO,
7135        );
7136        match red {
7137            Step::GiveUp { reason } => {
7138                assert!(reason.contains("editorconfig"), "reason: {reason}");
7139                assert!(reason.contains("test (macos)"), "reason: {reason}");
7140                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7141            }
7142            other => panic!("expected a give-up, got {other:?}"),
7143        }
7144
7145        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7146        match commented {
7147            Step::GiveUp { reason } => {
7148                assert!(reason.contains("unresolved"), "reason: {reason}");
7149                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7150            }
7151            other => panic!("expected a give-up, got {other:?}"),
7152        }
7153    }
7154
7155    #[test]
7156    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7157        let candidate_commit = "magi: candidate A (uncommitted work)";
7158        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7159        let argv = merge_argv(16, &subject);
7160
7161        assert!(argv.contains(&"--squash".to_owned()));
7162        assert!(argv.contains(&"--delete-branch".to_owned()));
7163        assert!(argv.contains(&"--subject".to_owned()));
7164        assert_eq!(
7165            argv.last().map(String::as_str),
7166            Some("add retries to the uploader"),
7167            "the subject must not be the candidate commit message"
7168        );
7169        assert_ne!(subject, candidate_commit);
7170    }
7171
7172    #[test]
7173    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7174        assert_eq!(
7175            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7176            "feat: a queue, an unattended loop, and a phone UI"
7177        );
7178        assert_eq!(
7179            merge_subject("", "# port the retry logic\n\ndetails"),
7180            "port the retry logic",
7181            "an empty title falls back to the task's first line, heading marks stripped"
7182        );
7183    }
7184
7185    #[test]
7186    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7187        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7188        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7189        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7190        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7191        assert_eq!(run_of(""), None);
7192    }
7193
7194    #[test]
7195    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7196        let mut out = Vec::new();
7197        push_if_outstanding(
7198            &mut out,
7199            ReviewComment {
7200                author: "yukimemi".to_owned(),
7201                path: None,
7202                line: None,
7203                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7204            },
7205        );
7206        assert!(out.is_empty());
7207    }
7208
7209    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7210    /// falls back to the repository - which keeps these tests free of a
7211    /// worktree, a `git` invocation and a network.
7212    fn run_state() -> RunState {
7213        let mut state = RunState::new(
7214            std::path::PathBuf::from("/repo/magi"),
7215            "main".to_owned(),
7216            "abcdef1234".to_owned(),
7217            "add retries to the uploader".to_owned(),
7218            crate::config::Config::default(),
7219        );
7220        // These fixtures test execution flow, independent of host disk capacity.
7221        state.config.disk.min_free_bytes = 0;
7222        // Tests run in parallel against one persistent home and the ids
7223        // `RunState::new` draws from the clock can repeat, so two tests would
7224        // share a run's questions. The home also outlives the process, so the
7225        // counter alone would reuse an earlier run's ids.
7226        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7227        let nanos = std::time::SystemTime::now()
7228            .duration_since(std::time::UNIX_EPOCH)
7229            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7230        state.id = format!(
7231            "20261004-{nanos:06}-{:04x}",
7232            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7233        );
7234        state
7235    }
7236
7237    fn green_pr() -> PrState {
7238        PrState {
7239            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7240            number: 42,
7241            state: PrLifecycle::Open,
7242            checks: Checks::Green,
7243            // The forge sees nothing in the way unless a test says otherwise.
7244            blocking: Blocking::No,
7245            failing: Vec::new(),
7246            review_comments: vec![ReviewComment {
7247                author: "coderabbitai".to_owned(),
7248                path: Some("src/land.rs".to_owned()),
7249                line: Some(212),
7250                body: "this branch never checks the exit code".to_owned(),
7251            }],
7252        }
7253    }
7254
7255    #[test]
7256    fn land_fixer_defers_review_and_verification_without_a_cache() {
7257        let state = run_state();
7258        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7259        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7260        assert!(p.contains("Commit in this worktree"), "{p}");
7261    }
7262
7263    #[test]
7264    fn github_facing_land_text_is_english_whatever_the_language() {
7265        let mut state = run_state();
7266        state.config.graph.language = "ja".to_owned();
7267        let comment = stop_comment(&state.id, "checks are still red");
7268        assert!(crate::github_text::check("", &comment).is_empty());
7269        assert!(comment.is_ascii(), "{comment}");
7270        assert!(comment.starts_with(MARKER));
7271
7272        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7273        let ja_at = p.find("Write all prose in ja").unwrap();
7274        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7275        assert!(ja_at < rule_at, "{p}");
7276        assert!(p.contains("stays in Japanese"), "{p}");
7277
7278        state.config.graph.language = "en".to_owned();
7279        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7280        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7281        assert!(!p.contains("does not apply"), "{p}");
7282    }
7283
7284    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7285
7286    fn panel() -> String {
7287        approval_panel(
7288            &run_state(),
7289            &green_pr(),
7290            NUMSTAT,
7291            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7292            &[
7293                "land: ask before merging".to_owned(),
7294                "land: colour the diff".to_owned(),
7295            ],
7296            "feat: merge approval from the phone",
7297        )
7298    }
7299
7300    #[test]
7301    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7302        let html = panel();
7303        for needle in [
7304            "42",
7305            "main",
7306            "src/land.rs",
7307            "src/web.rs",
7308            "assets/logo.png",
7309            "feat: merge approval from the phone",
7310            "land: ask before merging",
7311            "land: colour the diff",
7312            "coderabbitai",
7313            "this branch never checks the exit code",
7314            "green",
7315        ] {
7316            assert!(html.contains(needle), "the panel must state `{needle}`");
7317        }
7318    }
7319
7320    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7321        crate::run::pin_test_home();
7322        let tmp = tempfile::tempdir().unwrap();
7323        let repo = tmp.path().join("repo");
7324        let remote = tmp.path().join("remote.git");
7325        std::fs::create_dir(&repo).unwrap();
7326        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7327            .await
7328            .unwrap();
7329        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7330        git::git(&repo, &["config", "user.name", "Test"])
7331            .await
7332            .unwrap();
7333        git::git(&repo, &["config", "user.email", "test@example.test"])
7334            .await
7335            .unwrap();
7336        std::fs::write(repo.join("base"), "base").unwrap();
7337        git::git(&repo, &["add", "."]).await.unwrap();
7338        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7339        git::git(
7340            &repo,
7341            &["remote", "add", "origin", remote.to_str().unwrap()],
7342        )
7343        .await
7344        .unwrap();
7345        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7346        git::git(&repo, &["checkout", "-b", "winner"])
7347            .await
7348            .unwrap();
7349        std::fs::write(repo.join("change"), "change").unwrap();
7350        git::git(&repo, &["add", "."]).await.unwrap();
7351        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7352        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7353        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7354            .await
7355            .unwrap();
7356        let mut state = run_state();
7357        state.repo = repo.clone();
7358        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7359        state.config.graph.land = true;
7360        state.config.graph.land_approval = true;
7361        state.pr_head = Some("task-head".into());
7362        state.pr_pushed_head = Some(head.clone());
7363        state.candidates = vec![winning_candidate("change")];
7364        state.candidates[0].worktree = repo;
7365        state.candidates[0].branch = "winner".into();
7366        state.tally = Some(uncontested_tally());
7367        state.gate_ran = true;
7368        state.gate_head = Some(head.clone());
7369        state.land_sync_pending = true;
7370        state.save().unwrap();
7371        (tmp, state, head)
7372    }
7373
7374    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7375        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7376        resume_landing_head(state, head, &green_pr().url, &forge, None).await
7377    }
7378
7379    async fn advance_landing_base(state: &RunState) {
7380        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7381        std::fs::write(state.repo.join("advance"), "advance").unwrap();
7382        git::git(&state.repo, &["add", "."]).await.unwrap();
7383        git::git(&state.repo, &["commit", "-m", "advance base"])
7384            .await
7385            .unwrap();
7386        git::git(&state.repo, &["push", "origin", "main"])
7387            .await
7388            .unwrap();
7389        git::git(&state.repo, &["checkout", "winner"])
7390            .await
7391            .unwrap();
7392    }
7393
7394    #[tokio::test]
7395    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
7396        let (_tmp, mut state, head) = landing_git_fixture().await;
7397        advance_landing_base(&state).await;
7398        let scratch = state.dir().join("rebase");
7399        std::fs::create_dir_all(&scratch).unwrap();
7400        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
7401        let attempts = state.land_sync_attempts;
7402        let error = rebase_landing_worktree(&mut state, "origin/main")
7403            .await
7404            .unwrap_err();
7405        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
7406        assert_eq!(state.land_sync_attempts, attempts);
7407        assert!(state.land_sync_target.is_none());
7408        assert!(state.rebase_fixes.is_empty());
7409        assert!(
7410            state
7411                .base_sync
7412                .as_ref()
7413                .is_none_or(|sync| sync.conflict.is_none())
7414        );
7415        assert!(
7416            state
7417                .resource_block
7418                .as_ref()
7419                .unwrap()
7420                .detail
7421                .contains("worktree add")
7422        );
7423        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
7424        std::fs::remove_dir_all(&scratch).unwrap();
7425        state.resource_block = None;
7426        assert_eq!(
7427            rebase_landing_worktree(&mut state, "origin/main")
7428                .await
7429                .unwrap(),
7430            crate::rebase::Rebased::Applied
7431        );
7432        assert_eq!(state.land_sync_attempts, attempts + 1);
7433        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
7434        assert!(git::is_clean(&state.repo).await.unwrap());
7435        assert!(state.rebase_fixes.is_empty());
7436    }
7437
7438    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7439    {
7440        let (tmp, mut state, old) = landing_git_fixture().await;
7441        let path = tmp.path().join("foreign");
7442        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7443            .await
7444            .unwrap();
7445        state.foreign_checkout = Some(
7446            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7447                .await
7448                .unwrap(),
7449        );
7450        state.config.merge.mode = crate::config::MergeMode::Pr;
7451        state.save().unwrap();
7452        (tmp, state, old, path)
7453    }
7454
7455    #[tokio::test]
7456    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
7457        for phase in 0..4 {
7458            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7459            advance_landing_base(&state).await;
7460            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
7461            if phase == 0 {
7462                // The live Step::Rebase path uses this same synchronization
7463                // and publication pair, without going through resume.
7464                assert_eq!(
7465                    rebase_landing_worktree(&mut state, "origin/main")
7466                        .await
7467                        .unwrap(),
7468                    crate::rebase::Rebased::Applied
7469                );
7470            } else {
7471                interrupt_landing_rebase(&mut state).await;
7472                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
7473                if phase == 2 {
7474                    git::sync_to_head(&state.repo).await.unwrap();
7475                } else if phase == 3 {
7476                    // Crash after joining history, before clearing its saved
7477                    // start. Repeating restoration must not add another merge.
7478                    restore_landing_worktree(&mut state).await.unwrap();
7479                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7480                    state.land_rebase_from = Some(old.clone());
7481                    state.save().unwrap();
7482                    restore_landing_worktree(&mut state).await.unwrap();
7483                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
7484                }
7485                state.save().unwrap();
7486                state = RunState::load(&state.id).unwrap();
7487                restore_landing_worktree(&mut state).await.unwrap();
7488                assert_eq!(
7489                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
7490                    repaired_tree
7491                );
7492            }
7493            let head = if phase == 0 {
7494                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
7495                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
7496                    .await
7497                    .unwrap()
7498            } else {
7499                resume_observed_head(&mut state, &old).await.unwrap()
7500            };
7501            assert!(git::is_ancestor(&state.repo, &old, &head).await);
7502            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7503            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7504            assert_eq!(
7505                git::remote_head(&state.repo, "origin", "task-head")
7506                    .await
7507                    .unwrap(),
7508                Some(head.clone())
7509            );
7510            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7511            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
7512            assert!(state.gate_allows_progress());
7513            assert!(state.land_rebase_from.is_none());
7514            assert!(!state.land_sync_pending);
7515            assert!(git::is_clean(&path).await.unwrap());
7516        }
7517    }
7518
7519    #[tokio::test]
7520    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
7521        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7522        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7523        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7524        git::commit_all(&state.repo, "conflicting base")
7525            .await
7526            .unwrap();
7527        git::git(&state.repo, &["push", "origin", "main"])
7528            .await
7529            .unwrap();
7530        git::git(&state.repo, &["checkout", "winner"])
7531            .await
7532            .unwrap();
7533        landing_gate_fixer(
7534            &mut state,
7535            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7536        );
7537        state.config.graph.gate_fix_rounds = 0;
7538        state.config.verify.gate = vec!["exit 1".into()];
7539        assert!(resume_observed_head(&mut state, &old).await.is_err());
7540        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
7541        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7542        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
7543        assert_eq!(
7544            std::fs::read_to_string(state.repo.join("change")).unwrap(),
7545            "resolved"
7546        );
7547        // A red gate must neither deliver nor publish the repaired tree.
7548        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
7549        assert_eq!(
7550            git::remote_head(&state.repo, "origin", "task-head")
7551                .await
7552                .unwrap(),
7553            Some(old.clone())
7554        );
7555        state = RunState::load(&state.id).unwrap();
7556        state.config.verify.gate = vec!["grep -q resolved change".into()];
7557        let head = resume_observed_head(&mut state, &old).await.unwrap();
7558        assert_eq!(head, repaired);
7559        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7560        assert_eq!(
7561            std::fs::read_to_string(path.join("change")).unwrap(),
7562            "resolved"
7563        );
7564        assert_eq!(
7565            git::remote_head(&state.repo, "origin", "task-head")
7566                .await
7567                .unwrap(),
7568            Some(head.clone())
7569        );
7570        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7571        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7572        assert!(git::is_clean(&path).await.unwrap());
7573    }
7574
7575    #[tokio::test]
7576    async fn landing_resume_completes_the_last_charged_sync_attempt() {
7577        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
7578            let (_tmp, mut state, old) = landing_git_fixture().await;
7579            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7580            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7581            git::commit_all(&state.repo, "conflicting base")
7582                .await
7583                .unwrap();
7584            git::git(&state.repo, &["push", "origin", "main"])
7585                .await
7586                .unwrap();
7587            git::git(&state.repo, &["checkout", "winner"])
7588                .await
7589                .unwrap();
7590            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
7591            state.config.graph.land_rounds = 1;
7592            state.land_sync_attempts = 1;
7593            state.land_sync_target = saved_target.then(|| target.clone());
7594            state.land_rebase_from = Some(old.clone());
7595            landing_gate_fixer(
7596                &mut state,
7597                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7598            );
7599            state.config.verify.gate = vec!["grep -q resolved change".into()];
7600            state.save().unwrap();
7601            // Simulate interruption before the scratch start and at a conflict.
7602            if scratch_started {
7603                assert!(matches!(
7604                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
7605                        .await
7606                        .unwrap(),
7607                    git::RebaseStart::Conflicted(_)
7608                ));
7609            }
7610            state = RunState::load(&state.id).unwrap();
7611            let head = resume_observed_head(&mut state, &old).await.unwrap();
7612            assert_ne!(head, old);
7613            assert_eq!(state.land_sync_attempts, 1);
7614            assert!(state.land_sync_target.is_none());
7615            assert!(state.land_rebase_from.is_none());
7616            assert!(!state.land_sync_pending);
7617            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7618            assert!(state.gate_allows_progress());
7619            assert_eq!(
7620                git::remote_head(&state.repo, "origin", "task-head")
7621                    .await
7622                    .unwrap(),
7623                Some(head)
7624            );
7625            assert!(
7626                rebase_landing_worktree(&mut state, "origin/main")
7627                    .await
7628                    .unwrap_err()
7629                    .to_string()
7630                    .contains("budget exhausted")
7631            );
7632        }
7633    }
7634
7635    #[tokio::test]
7636    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
7637        let (_tmp, mut state, old) = landing_git_fixture().await;
7638        advance_landing_base(&state).await;
7639        state.config.verify.gate = vec!["test -f advance".into()];
7640        let head = resume_observed_head(&mut state, &old).await.unwrap();
7641        assert_ne!(head, old);
7642        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7643        assert!(state.gate_allows_progress());
7644        assert_eq!(
7645            git::remote_head(&state.repo, "origin", "task-head")
7646                .await
7647                .unwrap(),
7648            Some(head.clone())
7649        );
7650        assert_eq!(state.pr_pushed_head, Some(head));
7651        assert!(!state.land_sync_pending);
7652        assert!(state.config.graph.land_approval);
7653    }
7654
7655    fn landing_gate_fixer(state: &mut RunState, script: &str) {
7656        state.config.disk.min_free_bytes = 0;
7657        state.config.graph.gate_fix_rounds = 1;
7658        state.config.agents = vec![crate::config::AgentSpec {
7659            id: "mock".into(),
7660            kind: crate::config::AgentKind::Command,
7661            model: None,
7662            command: vec!["sh".into(), "-c".into(), script.into()],
7663            extra_args: Vec::new(),
7664            env: Default::default(),
7665            prompt_delivery: None,
7666            max_turn_secs: None,
7667        }];
7668        state.candidates[0].agent = "mock".into();
7669    }
7670
7671    #[tokio::test]
7672    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
7673        let (_tmp, mut state, old) = landing_git_fixture().await;
7674        std::fs::write(state.repo.join("change"), "operator update").unwrap();
7675        git::commit_all(&state.repo, "extend winner").await.unwrap();
7676        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7677        git::git(
7678            &state.repo,
7679            &["push", "origin", "HEAD:refs/heads/task-head"],
7680        )
7681        .await
7682        .unwrap();
7683        state.config.verify.gate = vec!["exit 1".into()];
7684        state.config.graph.gate_fix_rounds = 0;
7685        assert!(resume_observed_head(&mut state, &updated).await.is_err());
7686        assert_ne!(old, updated);
7687        assert_eq!(state.gate_head.as_ref(), Some(&updated));
7688        assert!(!state.gate_allows_progress());
7689        assert!(state.land_sync_pending);
7690        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
7691        let head = resume_observed_head(&mut state, &updated).await.unwrap();
7692        assert_eq!(head, updated);
7693        assert!(state.gate_allows_progress());
7694        assert!(!state.land_sync_pending);
7695        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7696        land_with(&mut state, &green_pr().url, &forge)
7697            .await
7698            .unwrap();
7699        assert!(state.parked);
7700        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7701        assert!(forge.argvs().is_empty());
7702    }
7703
7704    #[tokio::test]
7705    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
7706        for divergent in [false, true] {
7707            let (_tmp, mut state, old) = landing_git_fixture().await;
7708            if divergent {
7709                git::git(&state.repo, &["reset", "--hard", "origin/main"])
7710                    .await
7711                    .unwrap();
7712            }
7713            std::fs::write(state.repo.join("external"), "external").unwrap();
7714            git::commit_all(&state.repo, "external update")
7715                .await
7716                .unwrap();
7717            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7718            git::git(
7719                &state.repo,
7720                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
7721            )
7722            .await
7723            .unwrap();
7724            if !divergent {
7725                git::git(&state.repo, &["reset", "--hard", &old])
7726                    .await
7727                    .unwrap();
7728            }
7729            let error = resume_observed_head(&mut state, &external)
7730                .await
7731                .unwrap_err();
7732            assert!(
7733                error
7734                    .to_string()
7735                    .contains("public head moved outside this run")
7736            );
7737            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
7738            assert_eq!(
7739                git::remote_head(&state.repo, "origin", "task-head")
7740                    .await
7741                    .unwrap(),
7742                Some(external)
7743            );
7744        }
7745    }
7746
7747    #[tokio::test]
7748    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
7749        let (_tmp, mut state, old) = landing_git_fixture().await;
7750        advance_landing_base(&state).await;
7751        landing_gate_fixer(
7752            &mut state,
7753            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7754        );
7755        state.config.verify.gate =
7756            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7757        state.config.verify.e2e = vec!["test -f advance".into()];
7758        // First save a red gate without spending a fixer round. Resume must
7759        // still offer the remaining budget for this exact same failed head.
7760        state.config.graph.gate_fix_rounds = 0;
7761        assert!(resume_observed_head(&mut state, &old).await.is_err());
7762        assert_eq!(
7763            git::remote_head(&state.repo, "origin", "task-head")
7764                .await
7765                .unwrap(),
7766            Some(old.clone())
7767        );
7768        state.config.graph.gate_fix_rounds = 1;
7769        let head = resume_observed_head(&mut state, &old).await.unwrap();
7770        assert_eq!(state.gate_fixes.len(), 1);
7771        assert!(state.gate_fixes[0].committed);
7772        assert!(state.gate_allows_progress());
7773        assert_eq!(state.gate_head.as_ref(), Some(&head));
7774        assert_eq!(
7775            git::remote_head(&state.repo, "origin", "task-head")
7776                .await
7777                .unwrap(),
7778            Some(head.clone())
7779        );
7780        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7781        land_with(&mut state, &green_pr().url, &forge)
7782            .await
7783            .unwrap();
7784        assert!(state.parked);
7785        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7786        assert!(forge.argvs().is_empty());
7787    }
7788
7789    #[tokio::test]
7790    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
7791        let (_tmp, mut state, old) = landing_git_fixture().await;
7792        advance_landing_base(&state).await;
7793        landing_gate_fixer(
7794            &mut state,
7795            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7796        );
7797        state.config.verify.gate = vec!["echo still red; exit 1".into()];
7798        for _ in 0..2 {
7799            assert!(resume_observed_head(&mut state, &old).await.is_err());
7800            assert_eq!(state.gate_fixes.len(), 1);
7801            assert_eq!(
7802                git::remote_head(&state.repo, "origin", "task-head")
7803                    .await
7804                    .unwrap(),
7805                Some(old.clone())
7806            );
7807        }
7808    }
7809
7810    #[tokio::test]
7811    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
7812        let (_tmp, mut state, old) = landing_git_fixture().await;
7813        advance_landing_base(&state).await;
7814        landing_gate_fixer(
7815            &mut state,
7816            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7817        );
7818        state.config.verify.gate =
7819            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7820        // The repair makes the gate green while breaking an e2e invariant.
7821        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
7822        for resume in 0..3 {
7823            assert!(resume_observed_head(&mut state, &old).await.is_err());
7824            state = RunState::load(&state.id).unwrap();
7825            let evidence = state.gate_repair_e2e.as_ref().unwrap();
7826            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7827            assert_eq!(evidence.head, head);
7828            assert!(!evidence.passed);
7829            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
7830            assert_eq!(state.gate_fixes.len(), 1);
7831            assert_eq!(
7832                git::remote_head(&state.repo, "origin", "task-head")
7833                    .await
7834                    .unwrap(),
7835                Some(old.clone())
7836            );
7837            if resume > 0 {
7838                assert!(
7839                    state.gate_allows_progress(),
7840                    "a green gate must not bypass red e2e"
7841                );
7842            }
7843        }
7844        // Once e2e genuinely succeeds on the same SHA, the saved requirement
7845        // can be satisfied without another fixer or approval bypass.
7846        state.config.verify.e2e = vec!["grep -q fixed change".into()];
7847        let head = resume_observed_head(&mut state, &old).await.unwrap();
7848        assert!(state.gate_repair_e2e.as_ref().unwrap().passed);
7849        assert_eq!(state.gate_repair_e2e.as_ref().unwrap().head, head);
7850        assert_eq!(state.gate_fixes.len(), 1);
7851        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7852        land_with(&mut state, &green_pr().url, &forge)
7853            .await
7854            .unwrap();
7855        assert!(state.parked);
7856        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7857        assert!(forge.argvs().is_empty());
7858    }
7859
7860    #[tokio::test]
7861    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
7862        for phase in 0..3 {
7863            let (_tmp, mut state, old) = landing_git_fixture().await;
7864            advance_landing_base(&state).await;
7865            let head = resume_observed_head(&mut state, &old).await.unwrap();
7866            // Persist the shapes left by interruption, resource deferral,
7867            // and a successful check for a different (older) SHA.
7868            state.land_sync_pending = true;
7869            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
7870            state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
7871                head: if phase == 2 {
7872                    old.clone()
7873                } else {
7874                    head.clone()
7875                },
7876                passed: phase == 2,
7877                outcomes: if phase == 1 {
7878                    vec![crate::run::CommandOutcome {
7879                        command: state.config.verify.e2e[0].clone(),
7880                        code: None,
7881                        output_tail: "verification resource unavailable".into(),
7882                        duration_ms: 0,
7883                        resource_blocked: true,
7884                    }]
7885                } else {
7886                    Vec::new()
7887                },
7888            });
7889            state.save().unwrap();
7890            for _ in 0..2 {
7891                state = RunState::load(&state.id).unwrap();
7892                assert!(resume_observed_head(&mut state, &head).await.is_err());
7893                let evidence = state.gate_repair_e2e.as_ref().unwrap();
7894                assert_eq!(evidence.head, head);
7895                assert!(!evidence.passed);
7896                assert!(!evidence.outcomes.is_empty());
7897                assert_eq!(
7898                    git::remote_head(&state.repo, "origin", "task-head")
7899                        .await
7900                        .unwrap(),
7901                    Some(head.clone())
7902                );
7903                assert!(state.land_sync_pending);
7904            }
7905        }
7906    }
7907
7908    async fn interrupt_landing_rebase(state: &mut RunState) {
7909        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
7910        state.save().unwrap();
7911        let scratch = state.dir().join("rebase");
7912        assert_eq!(
7913            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
7914                .await
7915                .unwrap(),
7916            crate::rebase::Rebased::Applied
7917        );
7918        assert!(!git::is_clean(&state.repo).await.unwrap());
7919    }
7920
7921    async fn landing_setup(state: &mut RunState) {
7922        git::git(
7923            &state.repo,
7924            &["config", "extensions.worktreeConfig", "true"],
7925        )
7926        .await
7927        .unwrap();
7928        state.config.worktree.setup =
7929            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
7930        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
7931            .await
7932            .unwrap();
7933        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
7934    }
7935
7936    #[tokio::test]
7937    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
7938        let (tmp, mut state, head) = landing_git_fixture().await;
7939        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7940        git::acquire_worktree_config(&state.repo).await.unwrap();
7941        let winner = tmp.path().join("landing");
7942        git::worktree_add_existing(&state.repo, &winner, "winner", false)
7943            .await
7944            .unwrap();
7945        state.candidates[0].worktree = winner.clone();
7946        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
7947        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
7948        state.config.disk.min_free_bytes = 0;
7949        state.config.worktree.setup = vec![crate::config::SetupStep {
7950            run: Some("touch setup-completed".into()),
7951            ..Default::default()
7952        }];
7953        #[cfg(unix)]
7954        {
7955            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
7956            state.config.coordination = Some(crate::config::Coordination {
7957                contract_file: "fixture-contract".into(),
7958                contract_token: "fixture-v1".into(),
7959                lock_file: "fixture-lock".into(),
7960            });
7961        }
7962        state.land_rebase_from = Some(head);
7963        tokio::time::timeout(
7964            Duration::from_secs(15),
7965            restore_landing_worktree(&mut state),
7966        )
7967        .await
7968        .expect("landing setup must not wait for its own repository operation")
7969        .unwrap();
7970        assert!(winner.join("setup-completed").is_file());
7971        assert!(git::is_clean(&winner).await.unwrap());
7972        assert!(state.land_rebase_from.is_none());
7973    }
7974
7975    #[tokio::test]
7976    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
7977        for phase in 0..3 {
7978            let (_tmp, mut state, old) = landing_git_fixture().await;
7979            advance_landing_base(&state).await;
7980            landing_setup(&mut state).await;
7981            if phase > 0 {
7982                interrupt_landing_rebase(&mut state).await;
7983                if phase == 2 {
7984                    // Crash after clean removed setup products, before setup.
7985                    git::sync_to_head(&state.repo).await.unwrap();
7986                    assert!(!state.repo.join(".env").exists());
7987                }
7988                state = RunState::load(&state.id).unwrap();
7989            }
7990            let head = resume_observed_head(&mut state, &old).await.unwrap();
7991            assert_ne!(head, old);
7992            assert!(state.gate_allows_progress());
7993            assert!(state.land_rebase_from.is_none());
7994            assert_eq!(
7995                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
7996                "secret"
7997            );
7998            assert!(git::is_clean(&state.repo).await.unwrap());
7999            assert!(
8000                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8001                    .await
8002                    .unwrap()
8003                    .contains(".env")
8004            );
8005        }
8006    }
8007
8008    #[tokio::test]
8009    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8010        let (_tmp, mut state, _) = landing_git_fixture().await;
8011        advance_landing_base(&state).await;
8012        landing_setup(&mut state).await;
8013        interrupt_landing_rebase(&mut state).await;
8014        // Exercise unusual names without asking Windows to create an invalid
8015        // control-character filename. Unix also covers embedded newlines.
8016        let locals = [
8017            "local notes",
8018            #[cfg(unix)]
8019            "local\nnotes",
8020        ];
8021        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8022            .await
8023            .unwrap();
8024        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8025        for local in locals {
8026            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8027            assert!(
8028                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8029                    .await
8030                    .unwrap()
8031                    .ok()
8032            );
8033        }
8034        restore_landing_worktree(&mut state).await.unwrap();
8035        for local in locals {
8036            assert_eq!(
8037                std::fs::read_to_string(state.repo.join(local)).unwrap(),
8038                "keep these notes"
8039            );
8040        }
8041        assert_eq!(
8042            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8043            "secret"
8044        );
8045        assert!(git::is_clean(&state.repo).await.unwrap());
8046        assert!(state.land_rebase_from.is_none());
8047    }
8048
8049    #[tokio::test]
8050    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8051        for local in ["advance", "advance/notes", "new-directory"] {
8052            let (_tmp, mut state, _) = landing_git_fixture().await;
8053            advance_landing_base(&state).await;
8054            // Also cover a local file blocking a new tracked directory.
8055            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8056            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8057            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8058            git::git(&state.repo, &["add", "."]).await.unwrap();
8059            git::git(&state.repo, &["commit", "-m", "add directory"])
8060                .await
8061                .unwrap();
8062            git::git(&state.repo, &["push", "origin", "main"])
8063                .await
8064                .unwrap();
8065            git::git(&state.repo, &["checkout", "winner"])
8066                .await
8067                .unwrap();
8068            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8069                .await
8070                .unwrap();
8071            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8072            let path = state.repo.join(local);
8073            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8074            std::fs::write(&path, "local notes").unwrap();
8075            interrupt_landing_rebase(&mut state).await;
8076            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8077            let checkpoint = state.land_rebase_from.clone();
8078            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8079            assert!(
8080                error.to_string().contains("conflicting with HEAD"),
8081                "{error:#}"
8082            );
8083            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8084            assert_eq!(
8085                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8086                before
8087            );
8088            assert_eq!(state.land_rebase_from, checkpoint);
8089        }
8090    }
8091
8092    #[tokio::test]
8093    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8094        for interrupted in [false, true] {
8095            let (_tmp, mut state, old) = landing_git_fixture().await;
8096            assert!(state.config.worktree.setup.is_empty());
8097            // A gate product exists before the base moves, without setup metadata.
8098            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8099                .await
8100                .unwrap();
8101            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8102            state.config.verify.gate =
8103                vec!["mkdir -p target && printf artifact > target/probe".into()];
8104            state.gate_ran = false;
8105            resume_observed_head(&mut state, &old).await.unwrap();
8106            assert_eq!(
8107                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8108                "artifact"
8109            );
8110            advance_landing_base(&state).await;
8111            if interrupted {
8112                interrupt_landing_rebase(&mut state).await;
8113                state = RunState::load(&state.id).unwrap();
8114            }
8115            state.config.verify.gate =
8116                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8117            let head = resume_observed_head(&mut state, &old).await.unwrap();
8118            assert_ne!(head, old);
8119            assert!(state.gate_allows_progress());
8120            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8121            assert_eq!(
8122                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8123                "artifact"
8124            );
8125            assert!(state.land_rebase_from.is_none());
8126            assert_eq!(
8127                git::remote_head(&state.repo, "origin", "task-head")
8128                    .await
8129                    .unwrap(),
8130                Some(head.clone())
8131            );
8132            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8133            land_with(&mut state, &green_pr().url, &forge)
8134                .await
8135                .unwrap();
8136            assert!(state.parked);
8137            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8138            assert!(forge.argvs().is_empty());
8139        }
8140    }
8141
8142    #[tokio::test]
8143    #[cfg(unix)]
8144    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8145        use std::os::fd::AsRawFd as _;
8146
8147        for interrupted in [false, true] {
8148            let (_tmp, mut state, _) = landing_git_fixture().await;
8149            advance_landing_base(&state).await;
8150            landing_setup(&mut state).await;
8151            if interrupted {
8152                interrupt_landing_rebase(&mut state).await;
8153            }
8154            state.config.worktree.setup =
8155                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8156            let common = crate::repo_lock::common_dir(&state.repo)
8157                .await
8158                .unwrap()
8159                .unwrap();
8160            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8161            state.config.coordination = crate::config::test_coordination();
8162            state.config.graph.timeout_resource_wait = 0;
8163            let external = std::fs::OpenOptions::new()
8164                .read(true)
8165                .write(true)
8166                .create(true)
8167                .truncate(false)
8168                .open(common.join("updater.lock"))
8169                .unwrap();
8170            // SAFETY: the descriptor belongs to `external` and remains open.
8171            let locked =
8172                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8173            assert_eq!(locked, 0);
8174            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8175            let checkpoint = state.land_rebase_from.clone();
8176            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8177            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8178            assert_eq!(
8179                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8180                before
8181            );
8182            assert_eq!(state.land_rebase_from, checkpoint);
8183            assert_eq!(
8184                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8185                "secret"
8186            );
8187
8188            drop(external);
8189            state.config.graph.timeout_resource_wait = 2;
8190            restore_landing_worktree(&mut state).await.unwrap();
8191            assert!(git::is_clean(&state.repo).await.unwrap());
8192            assert!(state.land_rebase_from.is_none());
8193            assert_eq!(
8194                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8195                "restored"
8196            );
8197        }
8198    }
8199
8200    #[tokio::test]
8201    #[cfg(unix)]
8202    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8203        use std::sync::atomic::{AtomicBool, Ordering};
8204
8205        let (_tmp, mut state, _) = landing_git_fixture().await;
8206        advance_landing_base(&state).await;
8207        landing_setup(&mut state).await;
8208        interrupt_landing_rebase(&mut state).await;
8209        let common = crate::repo_lock::common_dir(&state.repo)
8210            .await
8211            .unwrap()
8212            .unwrap();
8213        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8214        state.config.coordination = crate::config::test_coordination();
8215        let holder = crate::repo_lock::SeatLease::for_checkout(
8216            &state.repo,
8217            true,
8218            state.config.coordination.as_ref(),
8219        )
8220        .await
8221        .unwrap();
8222        assert!(holder.is_some());
8223        let cancelled = Arc::new(AtomicBool::new(false));
8224        let signal = cancelled.clone();
8225        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8226            signal.load(Ordering::SeqCst)
8227        });
8228        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8229        let checkpoint = state.land_rebase_from.clone();
8230        let (result, ()) = tokio::join!(
8231            tokio::time::timeout(
8232                Duration::from_secs(2),
8233                wait.scope(restore_landing_worktree(&mut state)),
8234            ),
8235            async {
8236                tokio::time::sleep(Duration::from_millis(100)).await;
8237                cancelled.store(true, Ordering::SeqCst);
8238            }
8239        );
8240        let error = result
8241            .expect("cancellation must release the waiting driver")
8242            .unwrap_err();
8243        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8244        assert_eq!(
8245            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8246            before
8247        );
8248        assert_eq!(state.land_rebase_from, checkpoint);
8249        assert_eq!(
8250            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8251            "secret"
8252        );
8253        drop(holder);
8254        restore_landing_worktree(&mut state).await.unwrap();
8255        assert!(state.land_rebase_from.is_none());
8256        assert!(git::is_clean(&state.repo).await.unwrap());
8257    }
8258
8259    #[tokio::test]
8260    #[cfg(unix)]
8261    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8262        use std::sync::atomic::{AtomicBool, Ordering};
8263
8264        for e2e in [false, true] {
8265            let (_tmp, mut state, head) = landing_git_fixture().await;
8266            let common = crate::repo_lock::common_dir(&state.repo)
8267                .await
8268                .unwrap()
8269                .unwrap();
8270            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8271            state.config.coordination = crate::config::test_coordination();
8272            if e2e {
8273                state.config.verify.e2e = vec!["true".into()];
8274                state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
8275                    head: head.clone(),
8276                    passed: false,
8277                    outcomes: Vec::new(),
8278                });
8279            } else {
8280                state.config.verify.gate = vec!["true".into()];
8281                state.gate_ran = false;
8282            }
8283            let holder = crate::repo_lock::SeatLease::for_checkout(
8284                &state.repo,
8285                true,
8286                state.config.coordination.as_ref(),
8287            )
8288            .await
8289            .unwrap();
8290            assert!(holder.is_some());
8291            let cancelled = Arc::new(AtomicBool::new(false));
8292            let signal = cancelled.clone();
8293            let waiting = Arc::new(tokio::sync::Notify::new());
8294            let observed = waiting.clone();
8295            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8296                observed.notify_one();
8297                signal.load(Ordering::SeqCst)
8298            });
8299            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8300            let url = green_pr().url;
8301            let result = {
8302                let mut publishing =
8303                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8304                // Git and fixture I/O precede local coordination. Start the
8305                // cancellation deadline only once the inherited wait policy
8306                // is polled, rather than timing those unrelated subprocesses.
8307                tokio::time::timeout(Duration::from_secs(30), async {
8308                    tokio::select! {
8309                        result = &mut publishing => panic!(
8310                            "verification must wait behind the held seat: {result:?}"
8311                        ),
8312                        () = waiting.notified() => {}
8313                    }
8314                })
8315                .await
8316                .expect("verification must reach the inherited coordination wait");
8317                cancelled.store(true, Ordering::SeqCst);
8318                tokio::time::timeout(Duration::from_secs(2), publishing).await
8319            };
8320            let error = result
8321                .expect("cancellation must release the verification waiter")
8322                .unwrap_err();
8323            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8324            assert!(error.to_string().contains("cancelled"), "{error:#}");
8325            assert!(forge.argvs().is_empty());
8326            assert_eq!(
8327                git::remote_head(&state.repo, "origin", "task-head")
8328                    .await
8329                    .unwrap(),
8330                Some(head.clone())
8331            );
8332            drop(holder);
8333            // Cancellation must release its reservation so another attempt can verify.
8334            assert_eq!(
8335                publish_landing_head(&mut state, &head, &url, &forge)
8336                    .await
8337                    .unwrap(),
8338                head
8339            );
8340        }
8341    }
8342
8343    #[tokio::test]
8344    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
8345        for staged in [false, true] {
8346            let (_tmp, mut state, old) = landing_git_fixture().await;
8347            advance_landing_base(&state).await;
8348            interrupt_landing_rebase(&mut state).await;
8349            std::fs::write(state.repo.join("change"), "user edit").unwrap();
8350            if staged {
8351                git::git(&state.repo, &["add", "change"]).await.unwrap();
8352            }
8353            assert!(resume_observed_head(&mut state, &old).await.is_err());
8354            assert_eq!(
8355                std::fs::read_to_string(state.repo.join("change")).unwrap(),
8356                "user edit"
8357            );
8358            assert_eq!(
8359                git::remote_head(&state.repo, "origin", "task-head")
8360                    .await
8361                    .unwrap(),
8362                Some(old)
8363            );
8364        }
8365    }
8366
8367    #[tokio::test]
8368    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
8369        let (_tmp, mut state, head) = landing_git_fixture().await;
8370        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8371        let id = state.id.clone();
8372        let pr = land_with(&mut state, &green_pr().url, &forge)
8373            .await
8374            .unwrap();
8375        assert_eq!(pr.state, PrLifecycle::Open);
8376        assert_eq!(state.id, id);
8377        assert!(state.parked);
8378        assert_eq!(state.status, RunStatus::Landing);
8379        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8380        assert!(forge.argvs().is_empty());
8381
8382        state.land_sync_pending = true;
8383        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
8384        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
8385        closed.pr.state = PrLifecycle::Closed;
8386        let forge = Scripted::new(vec![closed], vec![]);
8387        assert_eq!(
8388            land_with(&mut state, &green_pr().url, &forge)
8389                .await
8390                .unwrap()
8391                .state,
8392            PrLifecycle::Closed
8393        );
8394        assert_eq!(
8395            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
8396            "do not touch"
8397        );
8398        assert!(forge.argvs().is_empty());
8399    }
8400
8401    #[tokio::test]
8402    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
8403        let (_tmp, mut state, old) = landing_git_fixture().await;
8404        advance_landing_base(&state).await;
8405        state.config.verify.gate = vec!["exit 1".into()];
8406        assert!(resume_observed_head(&mut state, &old).await.is_err());
8407        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
8408        assert!(!state.gate_allows_progress());
8409        assert_eq!(
8410            git::remote_head(&state.repo, "origin", "task-head")
8411                .await
8412                .unwrap(),
8413            Some(old)
8414        );
8415        assert!(state.land_sync_pending);
8416    }
8417
8418    #[tokio::test]
8419    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
8420        let (_tmp, mut state, old) = landing_git_fixture().await;
8421        advance_landing_base(&state).await;
8422        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
8423        // Model a crash after the push but before saving its published SHA.
8424        state.pr_pushed_head = Some(old.clone());
8425        state.land_sync_pending = true;
8426        assert_eq!(
8427            resume_observed_head(&mut state, &pushed).await.unwrap(),
8428            pushed
8429        );
8430        // A writer races the observed PR snapshot: the explicit remote lease
8431        // must reject the push even though preflight saw our expected head.
8432        git::git(
8433            &state.repo,
8434            &["push", "--force", "origin", "main:refs/heads/task-head"],
8435        )
8436        .await
8437        .unwrap();
8438        assert!(
8439            publish_landing_head(
8440                &mut state,
8441                &pushed,
8442                &green_pr().url,
8443                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
8444            )
8445            .await
8446            .unwrap_err()
8447            .to_string()
8448            .contains("publishing gated")
8449        );
8450        assert!(
8451            resume_observed_head(&mut state, "foreign-head")
8452                .await
8453                .is_err()
8454        );
8455    }
8456    #[tokio::test]
8457    async fn landing_publication_refuses_a_pr_closed_during_gate() {
8458        let (_tmp, mut state, head) = landing_git_fixture().await;
8459        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
8460        closed.pr.state = PrLifecycle::Closed;
8461        let forge = Scripted::new(vec![closed], vec![]);
8462        assert!(
8463            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
8464                .await
8465                .unwrap_err()
8466                .to_string()
8467                .contains("PR closed or merged")
8468        );
8469    }
8470
8471    /// A candidate selected by the uncontested tally.
8472    fn winning_candidate(summary: &str) -> Candidate {
8473        Candidate {
8474            index: 0,
8475            label: 'A',
8476            agent: "opus".to_owned(),
8477            branch: "magi/x/A".to_owned(),
8478            worktree: PathBuf::from("/wt/A"),
8479            summary: summary.to_owned(),
8480            stat: String::new(),
8481            files: 1,
8482            commits: 1,
8483            empty: false,
8484            failed: None,
8485            verified_noop: None,
8486            duration_ms: 0,
8487            folded: false,
8488        }
8489    }
8490
8491    fn uncontested_tally() -> Tally {
8492        Tally {
8493            first_choice: BTreeMap::from([('A', 1)]),
8494            borda: BTreeMap::new(),
8495            winner: 'A',
8496            rankings: 1,
8497            unanimous_initial: true,
8498            deliberated: false,
8499            changed_votes: 0,
8500            unanimous_final: true,
8501            tie_break: None,
8502            judges: 1,
8503            present: 1,
8504            quorum: 1,
8505            met_quorum: true,
8506            uncontested: None,
8507        }
8508    }
8509
8510    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
8511        ReviewRecord {
8512            attempts: 0,
8513            reviewer,
8514            agent: agent.to_owned(),
8515            summary: summary.to_owned(),
8516            findings: Vec::new(),
8517            vote: None,
8518            failed: None,
8519            duration_ms: 0,
8520        }
8521    }
8522
8523    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
8524        let answered = reviews.len();
8525        ReviewRound {
8526            round,
8527            head: "abc1234".to_owned(),
8528            verified_head: None,
8529            verified_at: None,
8530            reviews,
8531            e2e: Vec::new(),
8532            verify_retried: false,
8533            e2e_deferred: false,
8534            e2e_defer_reason: None,
8535            fix: None,
8536            blocking: 0,
8537            answered,
8538            expected: answered,
8539            clean: true,
8540            progressed: false,
8541            vote_split: false,
8542            reconsideration: Vec::new(),
8543            verdict: None,
8544        }
8545    }
8546
8547    #[test]
8548    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
8549        let en = panel();
8550        assert!(en.contains("Task"), "{en}");
8551        assert!(en.contains("add retries to the uploader"), "{en}");
8552
8553        let mut state = run_state();
8554        state.config.graph.language = "ja".to_owned();
8555        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8556        assert!(ja.contains("タスク"), "{ja}");
8557        assert!(
8558            ja.contains("add retries to the uploader"),
8559            "the task itself is not translated: {ja}"
8560        );
8561    }
8562
8563    #[test]
8564    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
8565        // `run_state()` has no candidates, no tally and no reviews - exactly
8566        // the shape a run has before anything has judged or reviewed it, and
8567        // the panel must not print an empty box for either.
8568        let html = panel();
8569        assert!(!html.contains("What changed"), "{html}");
8570        assert!(!html.contains("Review verdict"), "{html}");
8571    }
8572
8573    #[test]
8574    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
8575        let mut state = run_state();
8576        state.candidates = vec![winning_candidate("")];
8577        state.tally = Some(uncontested_tally());
8578        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8579        assert!(
8580            !html.contains("What changed"),
8581            "an empty summary must not render an empty box: {html}"
8582        );
8583    }
8584
8585    #[test]
8586    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
8587        let mut state = run_state();
8588        state.candidates = vec![winning_candidate(
8589            "Added a retry loop around the uploader PUT call.",
8590        )];
8591        state.tally = Some(uncontested_tally());
8592        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8593        assert!(en.contains("What changed"), "{en}");
8594        assert!(
8595            en.contains("Added a retry loop around the uploader PUT call."),
8596            "{en}"
8597        );
8598
8599        state.config.graph.language = "ja".to_owned();
8600        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8601        assert!(ja.contains("変更内容"), "{ja}");
8602        assert!(
8603            ja.contains("Added a retry loop around the uploader PUT call."),
8604            "{ja}"
8605        );
8606    }
8607
8608    #[test]
8609    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
8610        let mut state = run_state();
8611        state.reviews = vec![
8612            review_round(
8613                1,
8614                vec![review_record(1, "alpha", "found a race, sent back")],
8615            ),
8616            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
8617        ];
8618        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8619        assert!(en.contains("Review verdict"), "{en}");
8620        assert!(en.contains("race is fixed, clean"), "{en}");
8621        assert!(
8622            !en.contains("found a race, sent back"),
8623            "only the round that actually cleared the merge should show: {en}"
8624        );
8625
8626        state.config.graph.language = "ja".to_owned();
8627        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8628        assert!(ja.contains("レビューの結論"), "{ja}");
8629        assert!(ja.contains("レビュアー"), "{ja}");
8630        assert!(ja.contains("race is fixed, clean"), "{ja}");
8631    }
8632
8633    /// The `incomplete_review = "warn"` policy (see
8634    /// `graph::Runner::review_loop`) can push a `clean` round to
8635    /// `state.reviews` while one seat's own record still has `failed: Some`
8636    /// and an empty `summary` - a seat that never answered, not one that
8637    /// answered with nothing to say.
8638    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
8639        ReviewRecord {
8640            attempts: 0,
8641            reviewer,
8642            agent: agent.to_owned(),
8643            summary: String::new(),
8644            findings: Vec::new(),
8645            vote: None,
8646            failed: Some(reason.to_owned()),
8647            duration_ms: 0,
8648        }
8649    }
8650
8651    #[test]
8652    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
8653        let mut state = run_state();
8654        state.reviews = vec![review_round(
8655            1,
8656            vec![
8657                review_record(1, "alpha", "clean, nothing to add"),
8658                unanswered_review_record(2, "beta", "timed out"),
8659            ],
8660        )];
8661        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8662        assert!(en.contains("clean, nothing to add"), "{en}");
8663        assert!(
8664            en.contains("produced no answer: timed out"),
8665            "a seat that never answered must say so, not render a blank box: {en}"
8666        );
8667        assert!(
8668            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
8669            "no reviewer box may be left empty: {en}"
8670        );
8671
8672        state.config.graph.language = "ja".to_owned();
8673        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8674        assert!(ja.contains("回答なし: timed out"), "{ja}");
8675    }
8676
8677    #[test]
8678    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
8679        let html = panel();
8680        assert!(!html.contains("<script"), "no script survives the csp");
8681        assert!(!html.contains("<form"), "form-action is 'none'");
8682        let pr = green_pr();
8683        assert_eq!(
8684            html.matches("http").count(),
8685            html.matches(pr.url.as_str()).count(),
8686            "the only http url in the panel is the pull request's own link"
8687        );
8688        assert!(
8689            html.contains("target=\"_blank\""),
8690            "the PR link must open in a new tab so it escapes the iframe"
8691        );
8692        assert!(
8693            html.contains("rel=\"noopener noreferrer\""),
8694            "external links opening in new tabs must carry noopener noreferrer"
8695        );
8696    }
8697
8698    #[test]
8699    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
8700        let html = panel();
8701        assert!(
8702            html.contains(">+</span>"),
8703            "an added line carries a `+` in the gutter, not only a background"
8704        );
8705        assert!(
8706            html.contains(">-</span>"),
8707            "a removed line carries a `-` in the gutter, not only a background"
8708        );
8709        assert!(
8710            html.contains(">new line</span>"),
8711            "the marker is moved to the gutter, so the body is printed once without it"
8712        );
8713    }
8714
8715    #[test]
8716    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
8717        let total = DIFF_MAX_LINES + 100;
8718        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
8719        let html = approval_panel(
8720            &run_state(),
8721            &green_pr(),
8722            NUMSTAT,
8723            &diff,
8724            &[],
8725            "feat: something long",
8726        );
8727        assert!(
8728            html.contains(&format!("100 of {total} diff lines omitted")),
8729            "the note must say exactly how much was cut"
8730        );
8731        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
8732        assert!(
8733            !html.contains(&format!("line {DIFF_MAX_LINES}")),
8734            "nothing past the threshold is rendered"
8735        );
8736        assert!(
8737            html.contains("/repo/magi"),
8738            "the note says where the rest is"
8739        );
8740    }
8741
8742    #[test]
8743    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
8744        let html = approval_panel(
8745            &run_state(),
8746            &green_pr(),
8747            "1\t2\tsrc/<b>&\"x\"'.rs",
8748            "",
8749            &[],
8750            "subject",
8751        );
8752        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
8753        assert!(
8754            !html.contains("<b>"),
8755            "an agent-influenced path must never become markup"
8756        );
8757    }
8758
8759    #[tokio::test]
8760    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
8761        let a = std::path::PathBuf::from("/repo/a");
8762        let b = std::path::PathBuf::from("/repo/b");
8763
8764        let held = repo_merge_lock(&a).lock_owned().await;
8765
8766        // A second, concurrent land run against the *same* repository must
8767        // wait - `try_lock` fails while `held` is alive.
8768        assert!(
8769            repo_merge_lock(&a).try_lock().is_err(),
8770            "a second merge into the same repository must not proceed concurrently"
8771        );
8772
8773        // A run against a *different* repository must not be blocked by it -
8774        // this is what keeps a slow rebase or `gh pr merge` in one
8775        // repository from also stalling a land-approval resume in another.
8776        assert!(
8777            repo_merge_lock(&b).try_lock().is_ok(),
8778            "a different repository's merge lock must be independent"
8779        );
8780
8781        drop(held);
8782        assert!(
8783            repo_merge_lock(&a).try_lock().is_ok(),
8784            "the lock is released once the holder is done"
8785        );
8786    }
8787
8788    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
8789        let mut state = landing_state();
8790        let mut rec = review_record(1, "alpha", "precise rejection reason");
8791        rec.vote = Some(if reject {
8792            crate::verdict::ReviewVote::Reject
8793        } else {
8794            crate::verdict::ReviewVote::Approve
8795        });
8796        if major {
8797            rec.findings = contested().findings;
8798        }
8799        let mut round = review_round(1, vec![rec]);
8800        round.clean = false;
8801        round.blocking = usize::from(major);
8802        state.reviews.push(round);
8803        state.config.graph.review_rounds = 1;
8804        state
8805    }
8806
8807    #[test]
8808    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
8809        for every in [false, true] {
8810            for contested in [false, true] {
8811                for major in [false, true] {
8812                    for reject in [false, true] {
8813                        let mut state = repair_state(major, reject);
8814                        state.config.graph.land_approval = every;
8815                        state.config.graph.hold_contested_merge = contested;
8816                        let reasons = approval_reasons(&state);
8817                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
8818                        assert_eq!(
8819                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
8820                            contested && major
8821                        );
8822                        assert_eq!(
8823                            reasons.contains(&ApprovalReason::FinalReject),
8824                            contested && reject
8825                        );
8826                        assert_eq!(
8827                            reasons.len(),
8828                            usize::from(every)
8829                                + usize::from(contested && major)
8830                                + usize::from(contested && reject)
8831                        );
8832                    }
8833                }
8834            }
8835        }
8836    }
8837
8838    #[test]
8839    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
8840        use crate::verdict::ReviewVote::{Approve, Reject};
8841        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
8842            let mut state = repair_state(false, initial_reject);
8843            state.reviews[0]
8844                .reconsideration
8845                .push(crate::run::ReviewRevoteRecord {
8846                    reviewer: 1,
8847                    agent: "alpha".into(),
8848                    vote: Some(final_vote),
8849                    reason: "changed after reading the panel <evidence>".into(),
8850                    failed: None,
8851                });
8852            assert_eq!(
8853                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
8854                final_vote == Reject
8855            );
8856            for language in ["en", "ja"] {
8857                state.config.graph.language = language.into();
8858                let evidence = approval_evidence(&state);
8859                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
8860                assert!(evidence.contains("changed after reading the panel <evidence>"));
8861                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
8862                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
8863                assert!(!html.contains("<evidence>"));
8864            }
8865            state.reviews[0].reconsideration[0].vote = None;
8866            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
8867            assert_eq!(
8868                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
8869                initial_reject
8870            );
8871            assert!(approval_evidence(&state).contains("timed out"));
8872        }
8873    }
8874
8875    #[tokio::test]
8876    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
8877        for every in [false, true] {
8878            for contested in [false, true] {
8879                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
8880                {
8881                    let mut state = repair_state(major, reject);
8882                    state.config.graph.land_approval = every;
8883                    state.config.graph.hold_contested_merge = contested;
8884                    let forge = Scripted::new(
8885                        vec![seen("abc", Checks::Green, "CLEAN", false)],
8886                        vec![(true, "")],
8887                    );
8888                    land_with(&mut state, URL, &forge).await.unwrap();
8889                    let expected = every || (contested && (major || reject));
8890                    assert_eq!(state.land_approval.is_some(), expected);
8891                    assert_eq!(forge.calls().contains(&"merge"), !expected);
8892                    if expected {
8893                        assert!(state.parked);
8894                    }
8895                }
8896            }
8897        }
8898    }
8899
8900    #[tokio::test]
8901    async fn reviewed_branch_hold_is_read_before_landing_decision() {
8902        for (base, control) in [
8903            (false, "land_approval"),
8904            (true, "land_approval"),
8905            (false, "hold_contested_merge"),
8906        ] {
8907            let (_tmp, mut state, _) = landing_git_fixture().await;
8908            state.config.graph.land_approval = base;
8909            state.config.graph.hold_contested_merge = false;
8910            state.reviewed_commits = Some(Vec::new());
8911            if control == "hold_contested_merge" {
8912                state.reviews = repair_state(false, true).reviews;
8913            }
8914            std::fs::write(
8915                state.repo.join("magi.toml"),
8916                format!("[graph]\n{control} = {}\n", !base),
8917            )
8918            .unwrap();
8919            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
8920            git::git(&state.repo, &["commit", "-m", "approval policy"])
8921                .await
8922                .unwrap();
8923            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8924            state.land_sync_pending = false;
8925            state.pr_pushed_head = Some(head.clone());
8926            state.gate_head = Some(head.clone());
8927            let forge = Scripted::new(
8928                vec![seen(&head, Checks::Green, "CLEAN", false)],
8929                vec![(true, "")],
8930            );
8931            land_with(&mut state, URL, &forge).await.unwrap();
8932            assert!(
8933                state.land_approval.is_some(),
8934                "base={base}, control={control}"
8935            );
8936            assert!(!forge.calls().contains(&"merge"));
8937            if !base {
8938                let question = ask::Questions::open()
8939                    .get(&state.land_approval.as_ref().unwrap().question)
8940                    .unwrap();
8941                assert!(question.detail.contains(&format!(
8942                    "{control}=true from the reviewed branch's magi.toml"
8943                )));
8944            }
8945        }
8946    }
8947
8948    #[tokio::test]
8949    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
8950        for file in ["magi.toml", ".magi/config.toml"] {
8951            for control in crate::config::OwnerHold::ALL {
8952                let (_tmp, mut state, _) = landing_git_fixture().await;
8953                state.config.graph.land_approval = false;
8954                state.config.graph.hold_contested_merge = false;
8955                state.reviewed_commits = Some(Vec::new());
8956                if control == crate::config::OwnerHold::HoldContestedMerge {
8957                    state.reviews = repair_state(false, true).reviews;
8958                }
8959                let config = state.repo.join(file);
8960                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
8961                std::fs::write(
8962                    &config,
8963                    format!(
8964                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
8965                        control.key()
8966                    ),
8967                )
8968                .unwrap();
8969                git::git(&state.repo, &["add", file]).await.unwrap();
8970                git::git(&state.repo, &["commit", "-m", "require approval"])
8971                    .await
8972                    .unwrap();
8973                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8974                let gate = state.config.verify.gate.clone();
8975                state.observe_branch_owner_holds(&head).await;
8976                assert_eq!(state.config.verify.gate, gate);
8977                assert!(state.owner_hold(control));
8978                let holds = state.branch_owner_holds.clone();
8979                git::git(&state.repo, &["rm", file]).await.unwrap();
8980                git::git(&state.repo, &["commit", "-m", "remove config"])
8981                    .await
8982                    .unwrap();
8983                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8984                state.save().unwrap();
8985                state = RunState::load(&state.id).unwrap();
8986                state.observe_branch_owner_holds(&later).await;
8987                assert_eq!(state.branch_owner_holds, holds);
8988                assert_eq!(state.branch_owner_holds[0].head, head);
8989                state.land_sync_pending = false;
8990                state.pr_pushed_head = Some(later.clone());
8991                state.gate_head = Some(later.clone());
8992                let forge = Scripted::new(
8993                    vec![seen(&later, Checks::Green, "CLEAN", false)],
8994                    vec![(true, "")],
8995                );
8996                land_with(&mut state, URL, &forge).await.unwrap();
8997                assert!(!forge.calls().contains(&"merge"));
8998                assert!(state.parked);
8999                let question = ask::Questions::open()
9000                    .get(&state.land_approval.as_ref().unwrap().question)
9001                    .unwrap();
9002                assert!(question.detail.contains("Approval required because:"));
9003                assert!(question.detail.contains(&format!(
9004                    "{}=true from the reviewed branch's {file}",
9005                    control.key()
9006                )));
9007                assert_eq!(state.branch_owner_holds, holds);
9008                state.save().unwrap();
9009                let resumed = RunState::load(&state.id).unwrap();
9010                assert!(resumed.owner_hold(control));
9011                assert_eq!(resumed.branch_owner_holds, holds);
9012                assert_eq!(
9013                    resumed.land_approval.unwrap().question,
9014                    state.land_approval.unwrap().question
9015                );
9016            }
9017        }
9018    }
9019
9020    #[tokio::test]
9021    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9022        let mut state = repair_state(false, true);
9023        state.reviews[0].clean = true;
9024        let mut finding = contested().findings.remove(0);
9025        finding.severity = crate::verdict::Severity::Minor;
9026        state.reviews[0].reviews[0].findings.push(finding);
9027        assert!(state.open_findings().is_empty());
9028        let mut pr = green_pr();
9029        pr.review_comments.clear();
9030        for language in ["en", "ja"] {
9031            state.config.graph.language = language.into();
9032            let html = approval_panel(&state, &pr, "", "", &[], "subject");
9033            assert!(html.contains("[R3-1-1] minor"));
9034            assert!(html.contains(if language == "ja" {
9035                "内部指摘の解決を意味するものではありません"
9036            } else {
9037                "This does not mean internal findings are resolved"
9038            }));
9039            assert!(
9040                html.find(if language == "ja" {
9041                    "承認が必要な理由:"
9042                } else {
9043                    "Approval required because:"
9044                })
9045                .unwrap()
9046                    < html.find("[R3-1-1]").unwrap()
9047            );
9048        }
9049        state.config.graph.language = "en".into();
9050        let observed = seen("abc", Checks::Green, "CLEAN", false);
9051        assert_eq!(
9052            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9053                .await
9054                .unwrap(),
9055            ApprovalGate::Pending
9056        );
9057        let id = state.land_approval.as_ref().unwrap().question.clone();
9058        let q = ask::Questions::open().get(&id).unwrap();
9059        assert!(q.detail.starts_with("Approval required because:"));
9060        assert!(q.detail.contains("final reviewer reject"));
9061        assert!(q.detail.contains("[R3-1-1] minor"));
9062        assert!(
9063            q.detail
9064                .contains("No adoption or resolution evidence recorded")
9065        );
9066        state.config.graph.land_approval = false;
9067        state.config.graph.hold_contested_merge = false;
9068        state.reviews.clear();
9069        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9070        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9071        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9072        let forge = Scripted::new(vec![observed], vec![]);
9073        land_with(&mut state, URL, &forge).await.unwrap();
9074        assert!(!forge.calls().contains(&"merge"));
9075        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9076        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9077    }
9078
9079    #[tokio::test]
9080    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9081        let mut state = repair_state(false, true);
9082        state.config.graph.land_approval = false;
9083        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9084        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9085        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9086        state.reviews[0].reviews[0].summary = long_reason.clone();
9087        for i in 1..=10 {
9088            let mut finding = contested().findings.remove(0);
9089            finding.id = format!("R1-1-{i}");
9090            finding.severity = if i == 9 {
9091                crate::verdict::Severity::Major
9092            } else {
9093                crate::verdict::Severity::Minor
9094            };
9095            finding.title = long_title.clone();
9096            finding.detail = long_detail.clone();
9097            state.reviews[0].reviews[0].findings.push(finding);
9098        }
9099        state.reviews[0].fix = Some(crate::run::FixRecord {
9100            agent: "fixer".into(),
9101            addressed: vec!["R1-1-9".into()],
9102            rejected: vec![crate::verdict::Rejection {
9103                id: "R1-1-10".into(),
9104                why: long_reason.clone(),
9105            }],
9106            notes: long_detail.clone(),
9107            committed: false,
9108            failed: None,
9109            duration_ms: 0,
9110            continuation: None,
9111        });
9112        assert_eq!(
9113            approval_reasons(&state),
9114            [
9115                ApprovalReason::OpenBlockingFindings,
9116                ApprovalReason::FinalReject
9117            ]
9118        );
9119        let excerpt = approval_excerpt(&long_reason, 300);
9120        assert_eq!(excerpt.chars().count(), 300);
9121        assert!(excerpt.ends_with('…'));
9122        let boundary = "拒".repeat(300);
9123        assert_eq!(approval_excerpt(&boundary, 300), boundary);
9124        for language in ["en", "ja"] {
9125            state.config.graph.language = language.into();
9126            for revote in [
9127                None,
9128                Some(crate::verdict::ReviewVote::Reject),
9129                Some(crate::verdict::ReviewVote::Approve),
9130            ] {
9131                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9132                state.reviews[0].reconsideration.clear();
9133                if let Some(vote) = revote {
9134                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9135                    state.reviews[0]
9136                        .reconsideration
9137                        .push(crate::run::ReviewRevoteRecord {
9138                            reviewer: 1,
9139                            agent: "alpha".into(),
9140                            vote: Some(vote),
9141                            reason: long_reason.clone(),
9142                            failed: None,
9143                        });
9144                }
9145                let evidence = approval_evidence(&state);
9146                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9147                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9148                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9149                assert_eq!(
9150                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9151                    final_vote == crate::verdict::ReviewVote::Reject
9152                );
9153                assert!(evidence.contains(&excerpt));
9154                assert!(evidence.contains("[R1-1-8] minor"));
9155                assert!(evidence.contains("[R1-1-9] major"));
9156                assert!(evidence.contains("[R1-1-10] minor"));
9157                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9158                    assert!(!evidence.contains(tail));
9159                }
9160                assert!(evidence.contains(if language == "ja" {
9161                    "採用申告(解決未確認)"
9162                } else {
9163                    "claimed addressed (resolution unconfirmed)"
9164                }));
9165                assert!(evidence.contains(if language == "ja" {
9166                    "不採用理由"
9167                } else {
9168                    "declined"
9169                }));
9170                let major_evidence = evidence
9171                    .split("[R1-1-9] major")
9172                    .nth(1)
9173                    .unwrap()
9174                    .split("[R1-1-10]")
9175                    .next()
9176                    .unwrap();
9177                assert!(major_evidence.contains(if language == "ja" {
9178                    "採用申告(解決未確認)"
9179                } else {
9180                    "claimed addressed (resolution unconfirmed)"
9181                }));
9182                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9183                assert!(last_evidence.contains(if language == "ja" {
9184                    "不採用理由"
9185                } else {
9186                    "declined"
9187                }));
9188                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9189                assert!(html.contains(&esc(&evidence)));
9190                assert_eq!(
9191                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9192                        .await
9193                        .unwrap(),
9194                    ApprovalGate::Pending
9195                );
9196                let id = &state.land_approval.take().unwrap().question;
9197                let q = ask::Questions::open().get(id).unwrap();
9198                assert!(q.detail.starts_with(&evidence));
9199            }
9200            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9201        }
9202    }
9203
9204    #[test]
9205    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9206        for (major, reject) in [(true, false), (false, true), (true, true)] {
9207            let state = repair_state(major, reject);
9208            assert!(repair_available(&state));
9209            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9210        }
9211        assert!(!repair_available(&repair_state(false, false)));
9212        let mut clean = repair_state(true, false);
9213        clean.reviews[0].clean = true;
9214        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9215        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9216    }
9217
9218    #[tokio::test]
9219    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9220        let mut state = repair_state(true, false);
9221        let pr = green_pr();
9222        approval_gate(&mut state, &pr, "feat: x", None, "abc")
9223            .await
9224            .unwrap();
9225        let store = ask::Questions::open();
9226        let id = state.land_approval.as_ref().unwrap().question.clone();
9227        // Simulate an unanswered two-choice question created by an older build.
9228        store
9229            .update(&id, |q| {
9230                q.choices = vec![APPROVE.into(), HOLD.into()];
9231                Ok(())
9232            })
9233            .unwrap();
9234        let upgraded = store.get(&id).unwrap();
9235        assert_eq!(upgraded.choices, approval_choices(&state));
9236        assert!(!upgraded.actions.contains_key(HOLD));
9237        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9238        assert!(
9239            store
9240                .list()
9241                .iter()
9242                .any(|q| q.id == id && q.choices == upgraded.choices)
9243        );
9244        assert!(
9245            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9246        );
9247        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9248        store
9249            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9250            .unwrap();
9251        // An earlier build may have recorded the repair answer and stopped
9252        // before any driver consumed it. Reconcile that durable decision too.
9253        store
9254            .update(&id, |q| {
9255                q.actions.clear();
9256                Ok(())
9257            })
9258            .unwrap();
9259        assert_eq!(
9260            store.get(&id).unwrap().chosen_action(),
9261            Some(&ask::ChoiceAction::Resume {
9262                run: state.id.clone()
9263            })
9264        );
9265        let binding = state.land_approval.clone();
9266        assert_eq!(
9267            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9268                .await
9269                .unwrap(),
9270            ApprovalGate::Repair
9271        );
9272        assert!(state.land_approval.is_none());
9273        assert_eq!(state.merge_repairs.len(), 1);
9274        let request = &state.merge_repairs[0];
9275        assert_eq!(request.question, id);
9276        assert_eq!(request.head, "abc");
9277        assert_eq!(request.pr, pr.url);
9278        assert_eq!(
9279            request.reviews[0].reviews[0].summary,
9280            "precise rejection reason"
9281        );
9282        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9283        assert_eq!(
9284            request.reviews[0].reviews[0].findings[0].detail,
9285            state.reviews[0].reviews[0].findings[0].detail
9286        );
9287        // A repeated consumption of the same answer never dispatches another repair.
9288        state.land_approval = binding;
9289        assert_eq!(
9290            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9291                .await
9292                .unwrap(),
9293            ApprovalGate::Repair
9294        );
9295        assert_eq!(state.merge_repairs.len(), 1);
9296        state.land_approval = None;
9297        state.config.graph.land_approval = false;
9298        state.config.graph.hold_contested_merge = false;
9299        state.reviews.clear();
9300        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9301        assert_eq!(
9302            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9303                .await
9304                .unwrap(),
9305            ApprovalGate::Pending
9306        );
9307        let fresh_id = &state.land_approval.as_ref().unwrap().question;
9308        assert_ne!(fresh_id, &id);
9309        let fresh = store.get(fresh_id).unwrap();
9310        assert!(
9311            fresh
9312                .detail
9313                .contains("fresh owner approval after merge repair")
9314        );
9315        assert!(fresh.detail.contains("No review recorded"));
9316        assert!(!fresh.detail.contains("precise rejection reason"));
9317    }
9318
9319    #[tokio::test]
9320    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9321        for choice in [REPAIR, HOLD] {
9322            let mut state = repair_state(false, true);
9323            let observed = seen("abc", Checks::Green, "CLEAN", false);
9324            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9325                .await
9326                .unwrap();
9327            let id = state.land_approval.as_ref().unwrap().question.clone();
9328            ask::Questions::open()
9329                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9330                .unwrap();
9331            let forge = Scripted::new(vec![observed], vec![(true, "")]);
9332            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9333                .await
9334                .unwrap();
9335            assert!(
9336                forge
9337                    .argvs()
9338                    .iter()
9339                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
9340            );
9341            assert!(!forge.calls().contains(&"fix"));
9342            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
9343            assert_ne!(state.status, RunStatus::Merged);
9344        }
9345    }
9346
9347    #[test]
9348    fn only_the_merge_choice_merges_and_silence_holds() {
9349        let table = [
9350            (None, Approval::Hold),
9351            (Some("merge"), Approval::Merge),
9352            (Some(" merge\n"), Approval::Merge),
9353            (Some("hold"), Approval::Hold),
9354            (Some(""), Approval::Hold),
9355            (Some("yes"), Approval::Hold),
9356        ];
9357        for (answer, want) in table {
9358            assert_eq!(
9359                approval(answer),
9360                want,
9361                "answer {answer:?} must resolve to {want:?}"
9362            );
9363        }
9364    }
9365
9366    #[tokio::test]
9367    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
9368        let mut state = landing_state();
9369        state.config.graph.land_approval = true;
9370        let pr = green_pr();
9371
9372        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9373            .await
9374            .unwrap();
9375        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
9376        assert!(
9377            !state.parked,
9378            "approval_gate itself never sets `parked`; only its caller does"
9379        );
9380
9381        let store = ask::Questions::open();
9382        let filed: Vec<_> = store
9383            .list()
9384            .into_iter()
9385            .filter(|q| q.run == state.id)
9386            .collect();
9387        assert_eq!(filed.len(), 1, "exactly one question is filed");
9388        assert_eq!(filed[0].node, APPROVAL_NODE);
9389        assert_eq!(filed[0].choices, approval_choices(&state));
9390        assert!(filed[0].status.open());
9391
9392        // A second visit - standing in for a resumed run whose slot the
9393        // daemon handed to something else while nobody had answered - must
9394        // find the same question rather than filing a second one.
9395        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9396            .await
9397            .unwrap();
9398        assert_eq!(again, ApprovalGate::Pending);
9399        let still_one = store
9400            .list()
9401            .into_iter()
9402            .filter(|q| q.run == state.id)
9403            .count();
9404        assert_eq!(
9405            still_one, 1,
9406            "asking twice must not double-file the question"
9407        );
9408    }
9409
9410    #[tokio::test]
9411    async fn approving_the_existing_question_is_read_back_as_approved() {
9412        crate::run::pin_test_home();
9413        let mut state = run_state();
9414        state.config.graph.land_approval = true;
9415        let pr = green_pr();
9416        assert_eq!(
9417            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9418                .await
9419                .unwrap(),
9420            ApprovalGate::Pending
9421        );
9422
9423        let store = ask::Questions::open();
9424        let mut q = store
9425            .list()
9426            .into_iter()
9427            .find(|q| q.run == state.id)
9428            .expect("filed above");
9429        let talks = crate::talk::Talks::open();
9430        let cfg = crate::config::Config {
9431            agents: vec![crate::config::AgentSpec {
9432                id: "mock".into(),
9433                kind: crate::config::AgentKind::Command,
9434                model: None,
9435                command: vec!["true".into()],
9436                extra_args: Vec::new(),
9437                env: Default::default(),
9438                prompt_delivery: None,
9439                max_turn_secs: None,
9440            }],
9441            ..crate::config::Config::default()
9442        };
9443        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
9444        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
9445        crate::talk::drain(&mut talk, &talks).unwrap();
9446        assert_eq!(
9447            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9448                .await
9449                .unwrap(),
9450            ApprovalGate::Pending,
9451            "consultation cannot approve or hold the merge"
9452        );
9453        q = store.get(&q.id).unwrap();
9454        assert!(q.answer.is_none());
9455        // The owner's merge answer (from the chat or the card) is the approval.
9456        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9457        store.put(&mut q).unwrap();
9458
9459        assert_eq!(
9460            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9461                .await
9462                .unwrap(),
9463            ApprovalGate::Approved
9464        );
9465    }
9466
9467    #[tokio::test]
9468    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
9469        crate::run::pin_test_home();
9470        let store = ask::Questions::open();
9471        for via_list in [false, true] {
9472            let mut state = repair_state(false, true);
9473            let pr = green_pr();
9474            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9475                .await
9476                .unwrap();
9477            let id = state.land_approval.as_ref().unwrap().question.clone();
9478            store
9479                .update(&id, |q| {
9480                    q.actions.insert(
9481                        HOLD.to_owned(),
9482                        ask::ChoiceAction::Resume {
9483                            run: state.id.clone(),
9484                        },
9485                    );
9486                    Ok(())
9487                })
9488                .unwrap();
9489            let q = if via_list {
9490                store.list().into_iter().find(|q| q.id == id).unwrap()
9491            } else {
9492                store.get(&id).unwrap()
9493            };
9494            assert!(!q.actions.contains_key(HOLD));
9495            store
9496                .update(&id, |q| {
9497                    // Check the persisted migration, without another read upgrade.
9498                    assert!(!q.actions.contains_key(HOLD));
9499                    assert!(!upgrade_repair_choice(q, &state));
9500                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
9501                })
9502                .unwrap();
9503            assert!(store.get(&id).unwrap().chosen_action().is_none());
9504            assert_eq!(
9505                approval_gate(&mut state, &pr, "feat: x", None, "abc")
9506                    .await
9507                    .unwrap(),
9508                ApprovalGate::Held
9509            );
9510        }
9511    }
9512
9513    #[tokio::test]
9514    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
9515        crate::run::pin_test_home();
9516        let store = ask::Questions::open();
9517
9518        let mut held_state = run_state();
9519        held_state.config.graph.land_approval = true;
9520        let pr = green_pr();
9521        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9522            .await
9523            .unwrap();
9524        let mut q = store
9525            .list()
9526            .into_iter()
9527            .find(|q| q.run == held_state.id)
9528            .expect("filed above");
9529        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
9530        store.put(&mut q).unwrap();
9531        assert_eq!(
9532            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9533                .await
9534                .unwrap(),
9535            ApprovalGate::Held
9536        );
9537
9538        let mut abandoned_state = run_state();
9539        abandoned_state.config.graph.land_approval = true;
9540        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9541            .await
9542            .unwrap();
9543        let mut q = store
9544            .list()
9545            .into_iter()
9546            .find(|q| q.run == abandoned_state.id)
9547            .expect("filed above");
9548        q.abandon("no answer within the timeout");
9549        store.put(&mut q).unwrap();
9550        assert_eq!(
9551            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9552                .await
9553                .unwrap(),
9554            ApprovalGate::Pending,
9555            "an expired approval must ask again without merging"
9556        );
9557        assert_eq!(
9558            store.get(&q.id).unwrap().status,
9559            ask::QuestionStatus::Abandoned
9560        );
9561        assert_ne!(
9562            abandoned_state.land_approval.as_ref().unwrap().question,
9563            q.id
9564        );
9565    }
9566
9567    fn contested() -> ContestedHandoff {
9568        let finding = |id: &str, n: u32| crate::verdict::Finding {
9569            id: id.to_owned(),
9570            severity: crate::verdict::Severity::Major,
9571            file: Some("src/a.rs".to_owned()),
9572            line: Some(n),
9573            title: format!("problem {id}"),
9574            detail: String::new(),
9575        };
9576        ContestedHandoff {
9577            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
9578            rejecters: vec![(1, "alpha".to_owned())],
9579        }
9580    }
9581
9582    #[test]
9583    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
9584        let mut state = run_state();
9585        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
9586        state.contested_handoff = Some(contested());
9587        assert!(contested_to_ask(&state).is_some());
9588        state.config.graph.hold_contested_merge = false;
9589        assert!(
9590            contested_to_ask(&state).is_none(),
9591            "the switch restores today"
9592        );
9593    }
9594
9595    #[test]
9596    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
9597        let q = ask::Question::new(
9598            "run-1".to_owned(),
9599            APPROVAL_NODE.to_owned(),
9600            "land".to_owned(),
9601            "Merge?".to_owned(),
9602            String::new(),
9603            vec![APPROVE.to_owned(), HOLD.to_owned()],
9604        );
9605        let none = deputy_brief(&q, None);
9606        assert!(none.contains("could not be read"), "{none}");
9607        assert!(none.contains("Silence is a hold"), "{none}");
9608
9609        let mut state = run_state();
9610        state.pr = Some(crate::run::PrRecord {
9611            url: "https://example.test/pull/7".to_owned(),
9612            number: 7,
9613            state: "open".to_owned(),
9614            checks: "green".to_owned(),
9615            round: 0,
9616            rounds: 3,
9617            red_at_merge: Vec::new(),
9618        });
9619        state.contested_handoff = Some(contested());
9620        let b = deputy_brief(&q, Some(&state));
9621        assert!(b.contains("https://example.test/pull/7"), "{b}");
9622        assert!(b.contains("not recorded in this legacy question"), "{b}");
9623        assert!(!b.contains("This question was filed although"));
9624        state.contested_handoff = None;
9625        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
9626    }
9627
9628    #[test]
9629    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
9630        for lang in ["en", "ja"] {
9631            let mut cfg = crate::config::Config::default();
9632            cfg.graph.language = lang.to_owned();
9633            let w = words(&cfg.graph.language);
9634            let text = w.approval_detail(
9635                "https://github.com/yukimemi/magi/pull/42",
9636                "main",
9637                "feat: x",
9638                Some(&contested()),
9639            );
9640            assert!(text.contains("pull/42"), "{text}");
9641            assert!(
9642                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
9643                "{text}"
9644            );
9645            assert!(text.contains("R3-1-5"), "{text}");
9646            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
9647            assert!(text.contains("2"), "the rest are counted: {text}");
9648            assert!(text.contains("#1 (alpha)"), "{text}");
9649        }
9650        let plain = words("en").approval_detail("u", "main", "s", None);
9651        assert!(!plain.contains("reject"), "{plain}");
9652    }
9653
9654    #[tokio::test]
9655    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
9656        crate::run::pin_test_home();
9657        let mut state = run_state();
9658        state.config.graph.land_approval = false;
9659        state.contested_handoff = Some(contested());
9660        let pr = green_pr();
9661        let c = contested_to_ask(&state);
9662        assert_eq!(
9663            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9664                .await
9665                .unwrap(),
9666            ApprovalGate::Pending,
9667            "silence is a hold"
9668        );
9669        let store = ask::Questions::open();
9670        let filed: Vec<_> = store
9671            .list()
9672            .into_iter()
9673            .filter(|q| q.run == state.id)
9674            .collect();
9675        assert_eq!(filed.len(), 1);
9676        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
9677
9678        assert_eq!(
9679            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9680                .await
9681                .unwrap(),
9682            ApprovalGate::Pending
9683        );
9684        let mut q = store
9685            .list()
9686            .into_iter()
9687            .find(|q| q.run == state.id)
9688            .unwrap();
9689        assert_eq!(q.id, filed[0].id, "the same question after a resume");
9690        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9691        store.put(&mut q).unwrap();
9692        assert_eq!(
9693            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9694                .await
9695                .unwrap(),
9696            ApprovalGate::Approved
9697        );
9698    }
9699
9700    #[test]
9701    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
9702        let rows = parse_numstat(NUMSTAT);
9703        assert_eq!(
9704            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
9705            ["src/web.rs", "src/land.rs", "assets/logo.png"]
9706        );
9707        assert_eq!(rows[2].added, None, "a binary file has no line counts");
9708    }
9709    #[test]
9710    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
9711        // Reported from a real run: the merge question arrived in English on a
9712        // repository with `language = "ja"`. magi's own strings have to follow
9713        // that setting too - "it is a literal in Rust" is not an answer.
9714        let mut state = run_state();
9715        state.config.graph.language = "ja".to_owned();
9716        let pr = green_pr();
9717        let commits = ["c1".to_owned()];
9718
9719        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9720        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
9721        assert!(ja.contains("squash されるコミット"), "{ja}");
9722        assert!(ja.contains("レビューコメント"), "{ja}");
9723        assert!(ja.contains("差分"), "{ja}");
9724        assert!(
9725            !ja.contains("Commits being squashed"),
9726            "no English left over"
9727        );
9728
9729        let w = words("ja");
9730        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
9731        assert!(
9732            w.approval_detail("http://x/1", "main", "feat: x", None)
9733                .contains("パネル")
9734        );
9735
9736        // The evidence itself is language-neutral and must survive either way.
9737        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
9738        assert!(ja.contains("feat: x"), "nor is the merge subject");
9739
9740        // English stays the default, and a language magi cannot check falls
9741        // back to it rather than shipping a guess.
9742        state.config.graph.language = "en".to_owned();
9743        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9744        assert!(en.contains("Commits being squashed"), "{en}");
9745        assert_eq!(words("Klingon").html_lang, "en");
9746    }
9747
9748    /// A `gh pr list` result naming exactly one pull request whose base and
9749    /// merge time both fit the run is exactly the case
9750    /// [`find_external_merge`] exists to act on.
9751    #[test]
9752    fn pick_open_pr_classifies_by_count_and_base() {
9753        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
9754        assert_eq!(
9755            pick_open_pr(one, "main").unwrap(),
9756            OpenPr::One {
9757                url: "https://x/pull/58".into(),
9758                title: "t".into()
9759            }
9760        );
9761        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
9762        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
9763        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
9764                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
9765        assert_eq!(
9766            pick_open_pr(two, "main").unwrap(),
9767            OpenPr::Many(vec!["u1".into(), "u2".into()])
9768        );
9769        // A fork's same-named branch is not a pull request for this head.
9770        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
9771        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
9772        assert!(pick_open_pr("not json", "main").is_err());
9773        // An incomplete record is an error, never "nothing open".
9774        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
9775        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
9776    }
9777
9778    #[test]
9779    fn pick_merged_pr_picks_the_unique_match() {
9780        let json = r#"[
9781            {"url": "https://github.com/o/r/pull/42", "number": 42,
9782             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
9783        ]"#;
9784        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9785        let found = pick_merged_pr(json, "main", created_at)
9786            .expect("valid json")
9787            .expect("one unambiguous match");
9788        assert_eq!(found.url, "https://github.com/o/r/pull/42");
9789        assert_eq!(found.number, 42);
9790    }
9791
9792    /// Two candidates surviving the filter is exactly as uninformative as
9793    /// zero — a branch name can be reused across runs — so neither is
9794    /// preferred over the other and nothing is recorded automatically.
9795    #[test]
9796    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
9797        let json = r#"[
9798            {"url": "https://github.com/o/r/pull/42", "number": 42,
9799             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
9800            {"url": "https://github.com/o/r/pull/43", "number": 43,
9801             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
9802        ]"#;
9803        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9804        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9805    }
9806
9807    /// A pull request that targets a different base branch cannot be this
9808    /// run's, whatever its head branch is named — a reused branch name from
9809    /// an unrelated task must not be recorded as this run's merge.
9810    #[test]
9811    fn pick_merged_pr_ignores_a_different_base_branch() {
9812        let json = r#"[
9813            {"url": "https://github.com/o/r/pull/42", "number": 42,
9814             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
9815        ]"#;
9816        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9817        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9818    }
9819
9820    /// A pull request merged before this run was even created cannot be this
9821    /// run's winner, no matter how its head branch is spelled.
9822    #[test]
9823    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
9824        let json = r#"[
9825            {"url": "https://github.com/o/r/pull/42", "number": 42,
9826             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
9827        ]"#;
9828        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9829        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9830    }
9831
9832    #[test]
9833    fn slug_of_pr_url_reads_host_owner_and_repo() {
9834        assert_eq!(
9835            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
9836            Some("github.com/yukimemi/shun")
9837        );
9838    }
9839
9840    #[test]
9841    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
9842        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
9843        assert_eq!(slug_of_pr_url("not a url at all"), None);
9844        assert_eq!(slug_of_pr_url("https://github.com"), None);
9845    }
9846
9847    #[test]
9848    fn slug_of_repo_url_reads_host_owner_and_repo() {
9849        assert_eq!(
9850            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
9851            Some("github.com/yukimemi/magi")
9852        );
9853        assert_eq!(slug_of_repo_url("https://github.com"), None);
9854    }
9855
9856    #[test]
9857    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
9858        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
9859            .expect("same repo, different case");
9860    }
9861
9862    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
9863    /// own in-progress run and rewrote its status from a pull request in a
9864    /// completely different repository. This is the guard that must catch
9865    /// that even when an explicit (but wrong) id is given.
9866    #[test]
9867    fn ensure_same_repo_refuses_a_different_repo() {
9868        let err =
9869            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
9870        let msg = format!("{err:#}");
9871        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
9872        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
9873    }
9874
9875    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
9876    /// instance mirroring a `github.com` repository's name, say) must not be
9877    /// treated as the same repository just because the trailing path
9878    /// matches.
9879    #[test]
9880    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
9881        let err = ensure_same_repo(
9882            "github.com/yukimemi/magi",
9883            "github.example.com/yukimemi/magi",
9884        )
9885        .unwrap_err();
9886        let msg = format!("{err:#}");
9887        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
9888        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
9889    }
9890
9891    /// No winner decided yet means there is no branch to ask GitHub about at
9892    /// all — `find_external_merge` must return `None` without ever spawning
9893    /// `gh`, which this proves by never providing a real repository to spawn
9894    /// it in.
9895    #[tokio::test]
9896    async fn find_external_merge_returns_none_without_a_winner() {
9897        let state = RunState::new(
9898            PathBuf::from("/no/such/repo"),
9899            "main".to_owned(),
9900            "0000000000000000000000000000000000000000".to_owned(),
9901            "irrelevant".to_owned(),
9902            crate::config::Config::default(),
9903        );
9904        assert_eq!(find_external_merge(&state).await.unwrap(), None);
9905    }
9906
9907    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
9908        let mut run = RunState::new(
9909            PathBuf::from(repo),
9910            "main".to_owned(),
9911            "abcdef1234".to_owned(),
9912            "x".to_owned(),
9913            crate::config::Config::default(),
9914        );
9915        run.id = id.to_owned();
9916        run.status = status;
9917        run.driver_exited = true;
9918        run.pr = Some(crate::run::PrRecord {
9919            number: url.rsplit('/').next().unwrap().parse().unwrap(),
9920            url: url.to_owned(),
9921            state: state.to_owned(),
9922            checks: "red".to_owned(),
9923            round: 0,
9924            rounds: 2,
9925            red_at_merge: Vec::new(),
9926        });
9927        run.save_under(home).unwrap();
9928    }
9929
9930    fn recorded(home: &Path, id: &str) -> String {
9931        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9932        serde_json::from_str::<RunState>(&body)
9933            .unwrap()
9934            .pr
9935            .unwrap()
9936            .state
9937    }
9938
9939    const PR: &str = "https://github.com/o/r/pull/7";
9940
9941    #[test]
9942    fn write_through_updates_predecessors_and_siblings_only() {
9943        let tmp = tempfile::tempdir().unwrap();
9944        let h = tmp.path();
9945        pr_run(
9946            h,
9947            "20261004-100000-aaaa",
9948            "/repo/r",
9949            RunStatus::Superseded,
9950            PR,
9951            "open",
9952        );
9953        pr_run(
9954            h,
9955            "20261004-100100-bbbb",
9956            "/repo/r",
9957            RunStatus::Blocked,
9958            PR,
9959            "open",
9960        );
9961        // Not terminal: a driver may be writing it.
9962        pr_run(
9963            h,
9964            "20261004-100200-cccc",
9965            "/repo/r",
9966            RunStatus::Landing,
9967            PR,
9968            "open",
9969        );
9970        // Another repository's pull request with the same number.
9971        pr_run(
9972            h,
9973            "20261004-100300-dddd",
9974            "/repo/other",
9975            RunStatus::Blocked,
9976            "https://github.com/o/other/pull/7",
9977            "open",
9978        );
9979        // A different pull request of the same repository.
9980        pr_run(
9981            h,
9982            "20261004-100400-eeee",
9983            "/repo/r",
9984            RunStatus::Blocked,
9985            "https://github.com/o/r/pull/8",
9986            "open",
9987        );
9988        pr_run(
9989            h,
9990            "20261004-100500-ffff",
9991            "/repo/r",
9992            RunStatus::Merged,
9993            PR,
9994            "open",
9995        );
9996        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
9997
9998        assert_eq!(
9999            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10000            2
10001        );
10002        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10003        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10004        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10005        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10006        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10007        // The source's own record is the caller's to write.
10008        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10009        // Idempotent.
10010        assert_eq!(
10011            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10012            0
10013        );
10014        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10015        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10016    }
10017
10018    #[test]
10019    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10020        let home = tempfile::tempdir().unwrap();
10021        let live_id = "20261004-100000-aaaa";
10022        let unknown_id = "20261004-100100-bbbb";
10023        for id in [live_id, unknown_id] {
10024            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10025            let mut s = RunState::load_under(id, home.path()).unwrap();
10026            s.driver_exited = false;
10027            // Model legacy driver evidence, not a newly reserved unstarted run.
10028            s.driver_claimed = None;
10029            if id == live_id {
10030                s.driver_pid = Some(std::process::id());
10031                s.driver_started_at = crate::proc::process_started_at(std::process::id());
10032            }
10033            s.save_under(home.path()).unwrap();
10034            if id == unknown_id {
10035                assert_eq!(
10036                    s.liveness_under(home.path(), false),
10037                    crate::run::Liveness::Unknown
10038                );
10039            }
10040        }
10041        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10042        assert_eq!(apply_pr_states(home.path(), &known), 0);
10043        for id in [live_id, unknown_id] {
10044            assert_eq!(recorded(home.path(), id), "open");
10045        }
10046    }
10047
10048    #[test]
10049    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10050        let tmp = tempfile::tempdir().unwrap();
10051        let h = tmp.path();
10052        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10053        pr_run(
10054            h,
10055            "20261004-100000-aaaa",
10056            "/repo/r",
10057            RunStatus::Superseded,
10058            &url(1),
10059            "open",
10060        );
10061        pr_run(
10062            h,
10063            "20261004-100100-bbbb",
10064            "/repo/r",
10065            RunStatus::Blocked,
10066            &url(2),
10067            "open",
10068        );
10069        pr_run(
10070            h,
10071            "20261004-100200-cccc",
10072            "/repo/r",
10073            RunStatus::Ready,
10074            &url(3),
10075            "open",
10076        );
10077        pr_run(
10078            h,
10079            "20261004-100300-dddd",
10080            "/repo/r",
10081            RunStatus::Ready,
10082            &url(4),
10083            "open",
10084        );
10085        pr_run(
10086            h,
10087            "20261004-100400-eeee",
10088            "/repo/r",
10089            RunStatus::Implementing,
10090            &url(1),
10091            "open",
10092        );
10093        assert_eq!(stale_open_prs(h).len(), 4);
10094
10095        let mut known = BTreeMap::new();
10096        known.insert(url(1), PrLifecycle::Merged);
10097        known.insert(url(2), PrLifecycle::Closed);
10098        known.insert(url(3), PrLifecycle::Open);
10099        // #4: the forge could not be read, so it has no answer.
10100        assert_eq!(apply_pr_states(h, &known), 2);
10101        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10102        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10103        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10104        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10105        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10106        assert_eq!(apply_pr_states(h, &known), 0);
10107    }
10108
10109    // --- the land loop against a scripted forge -------------------------
10110
10111    use std::collections::VecDeque;
10112    use std::sync::Mutex;
10113
10114    /// Answers views from a script (the last one repeats), merges from a
10115    /// queue, and records every call so a test can assert the order.
10116    struct Scripted {
10117        public_repo: Option<PathBuf>,
10118        evidence: Mutex<Option<CiEvidence>>,
10119        views: Mutex<VecDeque<Seen>>,
10120        merges: Mutex<VecDeque<(bool, String)>>,
10121        fix: Mutex<Option<Fixed>>,
10122        log: Mutex<Vec<&'static str>>,
10123        argvs: Mutex<Vec<Vec<String>>>,
10124        required: Mutex<Option<BTreeSet<String>>>,
10125        /// Set once a merge answered ok: the forge then reports `merged`,
10126        /// unless `queued` says the merge only entered a queue.
10127        merged: Mutex<bool>,
10128        queued: Mutex<bool>,
10129        /// Views fail once a merge answered ok.
10130        unreadable_after_merge: Mutex<bool>,
10131        /// Workflow runs asked to rerun, and whether that call fails.
10132        reruns: Mutex<Vec<String>>,
10133        rerun_fails: Mutex<bool>,
10134        /// Unix seconds; every poll moves it on by `POLL`.
10135        clock: Mutex<i64>,
10136    }
10137
10138    impl Scripted {
10139        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10140            Self {
10141                public_repo: None,
10142                evidence: Mutex::new(None),
10143                views: Mutex::new(views.into()),
10144                merges: Mutex::new(
10145                    merges
10146                        .into_iter()
10147                        .map(|(ok, m)| (ok, m.to_owned()))
10148                        .collect(),
10149                ),
10150                fix: Mutex::new(None),
10151                log: Mutex::new(Vec::new()),
10152                argvs: Mutex::new(Vec::new()),
10153                required: Mutex::new(None),
10154                merged: Mutex::new(false),
10155                queued: Mutex::new(false),
10156                unreadable_after_merge: Mutex::new(false),
10157                reruns: Mutex::new(Vec::new()),
10158                rerun_fails: Mutex::new(false),
10159                clock: Mutex::new(1_000),
10160            }
10161        }
10162        fn argvs(&self) -> Vec<Vec<String>> {
10163            self.argvs.lock().unwrap().clone()
10164        }
10165        fn calls(&self) -> Vec<&'static str> {
10166            self.log.lock().unwrap().clone()
10167        }
10168    }
10169
10170    impl Forge for Scripted {
10171        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10172            self.evidence.lock().unwrap().clone()
10173        }
10174        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10175            self.log.lock().unwrap().push("view");
10176            if *self.unreadable_after_merge.lock().unwrap()
10177                && !self.argvs.lock().unwrap().is_empty()
10178            {
10179                anyhow::bail!("forge unreachable");
10180            }
10181            let mut seen = {
10182                let mut v = self.views.lock().unwrap();
10183                if v.len() > 1 {
10184                    v.pop_front().unwrap()
10185                } else {
10186                    v[0].clone()
10187                }
10188            };
10189            if seen.head == "@published" {
10190                let head =
10191                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10192                        .await?
10193                        .context("missing published head")?;
10194                seen.head.clone_from(&head);
10195                seen.rollup_head = head;
10196            }
10197            if *self.merged.lock().unwrap() {
10198                seen.pr.state = PrLifecycle::Merged;
10199            }
10200            Ok(seen)
10201        }
10202        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10203            self.log.lock().unwrap().push("merge");
10204            self.argvs.lock().unwrap().push(argv.to_vec());
10205            let out = self
10206                .merges
10207                .lock()
10208                .unwrap()
10209                .pop_front()
10210                .expect("unscripted merge");
10211            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10212            {
10213                *self.merged.lock().unwrap() = true;
10214            }
10215            Ok(out)
10216        }
10217        async fn poll(&self) {
10218            self.log.lock().unwrap().push("poll");
10219            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10220        }
10221        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10222            self.log.lock().unwrap().push("rerun");
10223            self.reruns.lock().unwrap().push(run.to_owned());
10224            if *self.rerun_fails.lock().unwrap() {
10225                anyhow::bail!("gh run rerun: no");
10226            }
10227            Ok(())
10228        }
10229        fn now(&self) -> i64 {
10230            *self.clock.lock().unwrap()
10231        }
10232        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10233            self.required.lock().unwrap().clone()
10234        }
10235        async fn fix(
10236            &self,
10237            _state: &mut RunState,
10238            _pr: &PrState,
10239            _round: usize,
10240            _budget: usize,
10241            _reason: &str,
10242            _logs: &str,
10243        ) -> Result<Fixed> {
10244            self.log.lock().unwrap().push("fix");
10245            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10246        }
10247    }
10248
10249    const REFUSED: &str =
10250        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10251
10252    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10253        let mut pr = green_pr();
10254        pr.checks = checks;
10255        pr.blocking = Blocking::of(merge_state);
10256        if !comments {
10257            pr.review_comments.clear();
10258        }
10259        Seen {
10260            pr,
10261            title: "feat: x".to_owned(),
10262            failing_urls: Vec::new(),
10263            head: head.to_owned(),
10264            rollup_head: head.to_owned(),
10265            merge_state: merge_state.to_owned(),
10266            contexts: Vec::new(),
10267            base: "main".to_owned(),
10268        }
10269    }
10270
10271    fn landing_state() -> RunState {
10272        crate::run::pin_test_home();
10273        let mut state = run_state();
10274        state.config.graph.land_approval = false;
10275        state
10276    }
10277
10278    #[test]
10279    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10280        assert!(!awaiting_new_head(None, "aaa"));
10281        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10282        assert!(awaiting_new_head(Some("abc123"), "def456"));
10283        assert!(awaiting_new_head(Some("abc123"), ""));
10284    }
10285
10286    #[test]
10287    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10288        let open = |c, m: &str| seen("a", c, m, false);
10289        let table = [
10290            (None, false, Refused::Pending),
10291            (
10292                Some(open(Checks::Pending, "BLOCKED")),
10293                false,
10294                Refused::Pending,
10295            ),
10296            (
10297                Some(open(Checks::Unknown, "BLOCKED")),
10298                false,
10299                Refused::Pending,
10300            ),
10301            (
10302                Some(open(Checks::Green, "UNKNOWN")),
10303                false,
10304                Refused::Pending,
10305            ),
10306            (Some(open(Checks::Green, "")), false, Refused::Pending),
10307            (
10308                Some(open(Checks::Green, "BLOCKED")),
10309                false,
10310                Refused::Recheck,
10311            ),
10312            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10313        ];
10314        for (after, rechecked, want) in table {
10315            assert_eq!(
10316                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10317                want
10318            );
10319        }
10320        let mut closed = open(Checks::Green, "CLEAN");
10321        closed.pr.state = PrLifecycle::Closed;
10322        assert_eq!(
10323            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10324            Refused::Final
10325        );
10326    }
10327
10328    #[test]
10329    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10330        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10331            let pr = seen("a", checks, "BEHIND", false).pr;
10332            assert_eq!(
10333                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10334                Step::Rebase
10335            );
10336        }
10337        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
10338            let current = seen("a", Checks::Green, status, false);
10339            assert_ne!(
10340                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10341                Step::Rebase
10342            );
10343            assert_ne!(
10344                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
10345                Refused::Behind
10346            );
10347        }
10348        let mut current = seen("a", Checks::Pending, "BEHIND", false);
10349        current.rollup_head = "old".into();
10350        assert_eq!(
10351            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10352            Refused::Behind
10353        );
10354        assert_eq!(
10355            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
10356            Refused::Pending
10357        );
10358        current.pr.state = PrLifecycle::Closed;
10359        assert_eq!(
10360            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10361            Refused::Final
10362        );
10363    }
10364
10365    #[tokio::test]
10366    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
10367        for boundary in ["initial", "premerge", "refusal"] {
10368            let (_tmp, mut state, old) = landing_git_fixture().await;
10369            state.land_sync_pending = false;
10370            advance_landing_base(&state).await;
10371            state.config.verify.gate = vec!["test -f advance".into()];
10372            state.config.verify.e2e = vec!["test -f advance".into()];
10373            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
10374                .await
10375                .unwrap();
10376            let old_binding = state.land_approval.clone().unwrap();
10377            let store = ask::Questions::open();
10378            let mut question = store.get(&old_binding.question).unwrap();
10379            question
10380                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10381                .unwrap();
10382            store.put(&mut question).unwrap();
10383            let mut views = Vec::new();
10384            if boundary != "initial" {
10385                views.push(seen(&old, Checks::Green, "CLEAN", false));
10386            }
10387            if boundary == "refusal" {
10388                views.push(seen(&old, Checks::Green, "CLEAN", false));
10389            }
10390            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
10391            behind.rollup_head = "old-ci-head".into();
10392            views.push(behind);
10393            // Publication checks the PR lease while verification has completed.
10394            views.push(seen(&old, Checks::Green, "CLEAN", false));
10395            views.push(seen("@published", Checks::Pending, "CLEAN", false));
10396            views.push(seen("@published", Checks::Green, "CLEAN", false));
10397            let merges = if boundary == "refusal" {
10398                vec![(false, REFUSED)]
10399            } else {
10400                vec![]
10401            };
10402            let mut forge = Scripted::new(views, merges);
10403            forge.public_repo = Some(state.repo.clone());
10404            let run = state.id.clone();
10405            land_with(&mut state, URL, &forge).await.unwrap();
10406            let head = state.pr_pushed_head.clone().unwrap();
10407            assert_ne!(head, old, "{boundary}");
10408            assert_eq!(state.id, run);
10409            assert_eq!(state.pr_branch(), Some("task-head"));
10410            assert_eq!(state.winner().unwrap().branch, "winner");
10411            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
10412            assert!(state.gate_allows_progress());
10413            let e2e = state.head_e2e.as_ref().unwrap();
10414            assert_eq!(e2e.head, head);
10415            assert!(e2e.passed);
10416            assert_eq!(state.land_sync_attempts, 1);
10417            assert!(!state.land_sync_pending);
10418            assert!(state.parked);
10419            let binding = state.land_approval.as_ref().unwrap();
10420            assert_eq!(binding.head, head);
10421            assert_ne!(binding.question, old_binding.question);
10422            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
10423            // The new question authorizes only the synchronized head on resume.
10424            let mut question = store.get(&binding.question).unwrap();
10425            question
10426                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10427                .unwrap();
10428            store.put(&mut question).unwrap();
10429            let forge = Scripted::new(
10430                vec![seen(&head, Checks::Green, "CLEAN", false)],
10431                vec![(true, "")],
10432            );
10433            land_with(&mut state, URL, &forge).await.unwrap();
10434            assert_eq!(state.status, RunStatus::Merged);
10435            assert_eq!(
10436                value_of(&forge.argvs()[0], "--match-head-commit"),
10437                Some(head.as_str())
10438            );
10439        }
10440    }
10441
10442    #[tokio::test]
10443    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
10444        let (_tmp, mut state, old) = landing_git_fixture().await;
10445        state.land_sync_pending = false;
10446        state.config.graph.land_approval = false;
10447        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
10448        advance_landing_base(&state).await;
10449        let mut forge = Scripted::new(
10450            vec![
10451                seen(&old, Checks::Green, "CLEAN", false),
10452                seen(&old, Checks::Green, "CLEAN", false),
10453                seen(&old, Checks::Green, "BEHIND", false),
10454                // The next observation is the publication lease check. The
10455                // refusal's evidence still applies to exactly this old head.
10456                seen(&old, Checks::Green, "CLEAN", false),
10457                seen("@published", Checks::Green, "CLEAN", false),
10458            ],
10459            vec![(false, REFUSED), (true, "")],
10460        );
10461        forge.public_repo = Some(state.repo.clone());
10462        land_with(&mut state, URL, &forge).await.unwrap();
10463        let head = state.pr_pushed_head.as_deref().unwrap();
10464        assert_ne!(head, old);
10465        assert_eq!(state.land_sync_attempts, 1);
10466        assert_eq!(state.gate_head.as_deref(), Some(head));
10467        assert_eq!(state.status, RunStatus::Merged);
10468        let requests = forge.argvs();
10469        assert_eq!(requests.len(), 2);
10470        assert_eq!(
10471            value_of(&requests[0], "--match-head-commit"),
10472            Some(old.as_str())
10473        );
10474        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
10475    }
10476
10477    #[tokio::test]
10478    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
10479        let (tmp, mut state, old) = landing_git_fixture().await;
10480        state.land_sync_pending = false;
10481        // A damaged history must not be interpreted as a missing base. Keep
10482        // the head's tree intact so worktree restoration itself can succeed.
10483        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
10484        let commit = tmp.path().join("broken-commit");
10485        std::fs::write(
10486            &commit,
10487            format!(
10488                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
10489                "f".repeat(40)
10490            ),
10491        )
10492        .unwrap();
10493        let replacement = git::git(
10494            &state.repo,
10495            &[
10496                "hash-object",
10497                "-t",
10498                "commit",
10499                "-w",
10500                commit.to_str().unwrap(),
10501            ],
10502        )
10503        .await
10504        .unwrap();
10505        git::git(&state.repo, &["replace", &old, replacement.trim()])
10506            .await
10507            .unwrap();
10508        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10509        land_with(&mut state, URL, &forge).await.unwrap();
10510        assert_eq!(state.land_sync_attempts, 0);
10511        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10512        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10513        assert!(forge.argvs().is_empty());
10514        assert!(
10515            state.events.iter().any(|e| e.message.contains(
10516                "could not determine whether the landing head contains the fetched base"
10517            ))
10518        );
10519    }
10520
10521    #[tokio::test]
10522    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
10523        let (_tmp, mut state, old) = landing_git_fixture().await;
10524        state.land_sync_pending = false;
10525        git::git(
10526            &state.repo,
10527            &["remote", "set-url", "origin", "missing-remote"],
10528        )
10529        .await
10530        .unwrap();
10531        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10532        land_with(&mut state, URL, &forge).await.unwrap();
10533        assert_eq!(state.land_sync_attempts, 0);
10534        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10535        assert!(
10536            state
10537                .events
10538                .iter()
10539                .any(|e| e.message.contains("cannot fetch landing base"))
10540        );
10541        assert!(forge.argvs().is_empty());
10542    }
10543
10544    #[tokio::test]
10545    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
10546        let (_tmp, mut state, old) = landing_git_fixture().await;
10547        state.land_sync_pending = false;
10548        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10549        land_with(&mut state, URL, &forge).await.unwrap();
10550        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10551        assert_eq!(state.land_sync_attempts, 0);
10552        assert!(
10553            state
10554                .events
10555                .iter()
10556                .any(|e| e.message.contains("already included"))
10557        );
10558        advance_landing_base(&state).await;
10559        state.land_sync_attempts = state.config.graph.land_rounds;
10560        state.land_sync_pending = true;
10561        state.save().unwrap();
10562        let mut restored = RunState::load(&state.id).unwrap();
10563        assert!(
10564            resume_observed_head(&mut restored, &old)
10565                .await
10566                .unwrap_err()
10567                .to_string()
10568                .contains("budget exhausted")
10569        );
10570        assert_eq!(
10571            git::remote_head(&state.repo, "origin", "task-head")
10572                .await
10573                .unwrap(),
10574            Some(old)
10575        );
10576    }
10577
10578    #[tokio::test]
10579    async fn a_normal_landing_merges_on_the_first_look() {
10580        let mut state = landing_state();
10581        let forge = Scripted::new(
10582            vec![seen("a", Checks::Green, "CLEAN", false)],
10583            vec![(true, "")],
10584        );
10585        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10586            .await
10587            .unwrap();
10588        // One fresh read, then the head-bound merge.
10589        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10590        assert_eq!(state.status, RunStatus::Merged);
10591    }
10592
10593    #[tokio::test]
10594    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
10595        let mut state = landing_state();
10596        let forge = Scripted::new(
10597            vec![seen("a", Checks::Green, "CLEAN", false)],
10598            std::iter::repeat_n((true, ""), 100).collect(),
10599        );
10600        *forge.queued.lock().unwrap() = true;
10601        let task = async {
10602            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10603                .await
10604                .unwrap();
10605        };
10606        // Still open after the command succeeded: it keeps watching and
10607        // never records a merge (it stops at the wait ceiling instead).
10608        task.await;
10609        assert_ne!(state.status, RunStatus::Merged);
10610    }
10611
10612    #[tokio::test]
10613    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
10614        let mut state = landing_state();
10615        let forge = Scripted::new(
10616            vec![seen("a", Checks::Green, "CLEAN", false)],
10617            std::iter::repeat_n((true, ""), 100).collect(),
10618        );
10619        *forge.unreadable_after_merge.lock().unwrap() = true;
10620        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10621            .await
10622            .ok();
10623        assert_ne!(state.status, RunStatus::Merged);
10624    }
10625
10626    #[tokio::test]
10627    async fn a_task_public_head_is_awaited_on_land_entry() {
10628        let mut state = landing_state();
10629        state.pr_head = Some("magi/task-abcd-1234".into());
10630        state.pr_pushed_head = Some("new".into());
10631        let forge = Scripted::new(
10632            vec![
10633                seen("old", Checks::Green, "CLEAN", false),
10634                seen("new", Checks::Green, "CLEAN", false),
10635            ],
10636            vec![(true, "")],
10637        );
10638        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10639            .await
10640            .unwrap();
10641        assert_eq!(
10642            forge.calls(),
10643            ["view", "poll", "view", "view", "merge", "view"]
10644        );
10645        assert_eq!(state.status, RunStatus::Merged);
10646    }
10647
10648    #[tokio::test]
10649    async fn a_superseded_public_head_owner_cannot_reenter_land() {
10650        let mut state = landing_state();
10651        state.pr_taken_over_by = Some("next".into());
10652        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
10653        assert!(
10654            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10655                .await
10656                .is_err()
10657        );
10658        assert!(forge.calls().is_empty());
10659    }
10660
10661    #[tokio::test]
10662    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
10663        let mut state = landing_state();
10664        let forge = Scripted::new(
10665            vec![
10666                seen("old", Checks::Green, "CLEAN", true),
10667                // The forge has not moved to the new head yet: still green.
10668                seen("old", Checks::Green, "CLEAN", true),
10669                seen("new", Checks::Pending, "BLOCKED", true),
10670                seen("new", Checks::Green, "CLEAN", true),
10671            ],
10672            vec![(true, "")],
10673        );
10674        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10675            head: "NEW".to_owned(),
10676        });
10677        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10678            .await
10679            .unwrap();
10680        assert_eq!(
10681            forge.calls(),
10682            [
10683                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
10684                "view"
10685            ]
10686        );
10687        assert_eq!(state.status, RunStatus::Merged);
10688    }
10689
10690    #[tokio::test]
10691    async fn a_head_that_never_arrives_stops_naming_both_commits() {
10692        let mut state = landing_state();
10693        let forge = Scripted::new(
10694            vec![
10695                seen("old", Checks::Green, "CLEAN", true),
10696                seen("someone-elses", Checks::Green, "CLEAN", true),
10697            ],
10698            vec![],
10699        );
10700        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10701            head: "mine".to_owned(),
10702        });
10703        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10704            .await
10705            .unwrap();
10706        assert!(!forge.calls().contains(&"merge"));
10707        let why = state.merge.as_ref().unwrap().detail.clone();
10708        assert!(
10709            why.contains("mine") && why.contains("someone-elses"),
10710            "{why}"
10711        );
10712        assert_eq!(state.status, RunStatus::Blocked);
10713    }
10714
10715    #[tokio::test]
10716    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
10717        let mut state = landing_state();
10718        let forge = Scripted::new(
10719            vec![
10720                seen("a", Checks::Green, "CLEAN", false),
10721                seen("a", Checks::Green, "CLEAN", false),
10722                seen("a", Checks::Pending, "BLOCKED", false),
10723                seen("a", Checks::Pending, "BLOCKED", false),
10724                seen("a", Checks::Green, "CLEAN", false),
10725            ],
10726            vec![(false, REFUSED), (true, "")],
10727        );
10728        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10729            .await
10730            .unwrap();
10731        assert_eq!(
10732            forge.calls(),
10733            [
10734                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
10735                "view"
10736            ]
10737        );
10738        assert_eq!(state.status, RunStatus::Merged);
10739    }
10740
10741    #[tokio::test]
10742    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
10743        let mut state = landing_state();
10744        let forge = Scripted::new(
10745            vec![
10746                seen("a", Checks::Green, "CLEAN", false),
10747                seen("a", Checks::Green, "BLOCKED", false),
10748            ],
10749            vec![(false, REFUSED), (false, REFUSED)],
10750        );
10751        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10752            .await
10753            .unwrap();
10754        // One re-look is allowed for the forge's own lag, then it is final.
10755        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
10756        let why = state.merge.as_ref().unwrap().detail.clone();
10757        assert!(
10758            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
10759            "{why}"
10760        );
10761        assert_eq!(state.status, RunStatus::Blocked);
10762    }
10763
10764    #[test]
10765    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
10766        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
10767        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
10768        // The pull request is still on the commit before the push.
10769        assert_eq!(bound_head("old", "old", Some("new")), None);
10770        // The checks are the previous commit's.
10771        assert_eq!(bound_head("new", "old", Some("new")), None);
10772        assert_eq!(bound_head("new", "old", None), None);
10773        // Nothing readable.
10774        assert_eq!(bound_head("", "", None), None);
10775        assert_eq!(bound_head("", "", Some("new")), None);
10776        assert_eq!(bound_head("abc", "", None), None);
10777    }
10778
10779    fn view_json(head: &str) -> String {
10780        format!(
10781            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
10782            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
10783            "reviews":[],"comments":[]}}"#
10784        )
10785    }
10786
10787    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
10788        format!(
10789            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
10790            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
10791            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
10792            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
10793        )
10794    }
10795
10796    #[test]
10797    fn rollup_is_bound_to_the_commit_in_the_same_node() {
10798        // The view already points at the new head, but the node still answers
10799        // for the old commit with its red check: the head stays unbound.
10800        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
10801        assert_eq!(s.rollup_head, "old");
10802        assert_eq!(s.pr.checks, Checks::Red);
10803        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
10804        assert_eq!(s.failing_urls.len(), 1);
10805    }
10806
10807    #[test]
10808    fn checks_come_from_the_node_not_the_view() {
10809        let view = view_json("new").replace(
10810            r#""reviews""#,
10811            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
10812        );
10813        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
10814        assert_eq!(s.pr.checks, Checks::Green);
10815        assert!(s.pr.failing.is_empty());
10816        assert_eq!(
10817            bound_head(&s.head, &s.rollup_head, Some("new")),
10818            Some("new")
10819        );
10820    }
10821
10822    #[test]
10823    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
10824        for node in [
10825            None,
10826            Some("not json".to_owned()),
10827            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
10828            Some(node_json("new", "SUCCESS", true)),
10829        ] {
10830            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
10831            assert!(s.rollup_head.is_empty());
10832            assert_eq!(s.pr.checks, Checks::Unknown);
10833            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
10834        }
10835    }
10836
10837    #[test]
10838    fn the_merge_command_is_pinned_to_the_observed_head() {
10839        let argv = merge_argv_at(7, "feat: x", "deadbeef");
10840        let at = argv
10841            .iter()
10842            .position(|a| a == "--match-head-commit")
10843            .unwrap();
10844        assert_eq!(argv[at + 1], "deadbeef");
10845    }
10846
10847    #[tokio::test]
10848    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
10849        let mut state = landing_state();
10850        // The pull request is on the pushed head but the rollup is still the
10851        // previous commit's red, non-required result.
10852        let mut stale = seen("new", Checks::Red, "CLEAN", false);
10853        stale.rollup_head = "old".to_owned();
10854        let forge = Scripted::new(
10855            vec![seen("old", Checks::Green, "CLEAN", true), stale],
10856            vec![],
10857        );
10858        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10859            head: "new".to_owned(),
10860        });
10861        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10862            .await
10863            .unwrap();
10864        assert!(!forge.calls().contains(&"merge"));
10865        assert_eq!(state.status, RunStatus::Blocked);
10866        let why = state.merge.as_ref().unwrap().detail.clone();
10867        assert!(why.contains("new") && why.contains("old"), "{why}");
10868    }
10869
10870    #[test]
10871    fn a_refusal_read_against_another_commits_checks_is_pending() {
10872        let mut after = seen("a", Checks::Green, "BLOCKED", false);
10873        after.rollup_head = "old".to_owned();
10874        assert_eq!(
10875            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
10876            Refused::Pending
10877        );
10878    }
10879
10880    #[tokio::test]
10881    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
10882        let mut state = landing_state();
10883        state.config.merge.ci = crate::config::MergeCi::None;
10884        state.config.graph.land_approval = true;
10885        let forge = Scripted::new(
10886            vec![seen("a", Checks::Unknown, "CLEAN", false)],
10887            vec![(true, "")],
10888        );
10889        land_with(&mut state, URL, &forge).await.unwrap();
10890        assert!(state.parked);
10891        assert_eq!(forge.calls(), ["view"]);
10892        let store = ask::Questions::open();
10893        let mut q = store
10894            .get(&state.land_approval.as_ref().unwrap().question)
10895            .unwrap();
10896        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10897        store.put(&mut q).unwrap();
10898
10899        land_with(&mut state, URL, &forge).await.unwrap();
10900        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
10901        assert_eq!(state.status, RunStatus::Merged);
10902        assert_eq!(
10903            value_of(&forge.argvs()[0], "--match-head-commit"),
10904            Some("a")
10905        );
10906    }
10907
10908    #[tokio::test]
10909    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
10910        let mut state = landing_state();
10911        state.config.merge.ci = crate::config::MergeCi::None;
10912        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
10913        land_with(&mut state, URL, &forge).await.unwrap();
10914        assert!(forge.reruns.lock().unwrap().is_empty());
10915        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10916        assert_eq!(state.status, RunStatus::Merged);
10917    }
10918
10919    #[test]
10920    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
10921        let shown = BTreeSet::new();
10922        let guard = |s: Option<&Seen>| {
10923            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
10924        };
10925        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
10926        assert!(guard(Some(&fresh)));
10927        assert!(!guard(None));
10928        fresh.rollup_head = "old".to_owned();
10929        assert!(!guard(Some(&fresh)));
10930        fresh.rollup_head = "a".to_owned();
10931        fresh.head = "b".to_owned();
10932        assert!(!guard(Some(&fresh)));
10933        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
10934        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
10935    }
10936
10937    #[test]
10938    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
10939        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
10940            let after = seen("a", checks, "BLOCKED", false);
10941            assert_eq!(
10942                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
10943                Refused::Recheck
10944            );
10945            assert_eq!(
10946                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
10947                Refused::Final
10948            );
10949        }
10950    }
10951
10952    #[tokio::test]
10953    async fn a_matching_head_with_red_non_required_checks_still_merges() {
10954        let mut state = landing_state();
10955        let forge = Scripted::new(
10956            vec![seen("a", Checks::Red, "CLEAN", false)],
10957            vec![(true, "")],
10958        );
10959        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10960            .await
10961            .unwrap();
10962        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10963        assert_eq!(state.status, RunStatus::Merged);
10964    }
10965
10966    #[tokio::test]
10967    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
10968        let mut state = landing_state();
10969        let forge = Scripted::new(
10970            vec![
10971                seen("a", Checks::Green, "CLEAN", false),
10972                seen("a", Checks::Green, "CLEAN", false),
10973                // Re-viewed after the refusal: someone pushed.
10974                seen("b", Checks::Green, "BLOCKED", false),
10975                seen("b", Checks::Green, "CLEAN", false),
10976            ],
10977            vec![(false, REFUSED), (true, "")],
10978        );
10979        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10980            .await
10981            .unwrap();
10982        assert_eq!(
10983            forge.calls(),
10984            [
10985                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
10986            ]
10987        );
10988        assert_eq!(state.status, RunStatus::Merged);
10989    }
10990
10991    fn merged_view(head: &str) -> Seen {
10992        let mut m = seen(head, Checks::Green, "CLEAN", false);
10993        m.pr.state = PrLifecycle::Merged;
10994        m
10995    }
10996
10997    fn has(argv: &[String], flag: &str) -> bool {
10998        argv.iter().any(|a| a == flag)
10999    }
11000
11001    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11002        let at = argv.iter().position(|a| a == flag)?;
11003        argv.get(at + 1).map(String::as_str)
11004    }
11005
11006    const URL: &str = "https://github.com/o/r/pull/42";
11007
11008    #[tokio::test]
11009    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11010        let mut state = landing_state();
11011        let forge = Scripted::new(
11012            vec![
11013                seen("abc", Checks::Green, "CLEAN", false),
11014                seen("abc", Checks::Green, "CLEAN", false),
11015            ],
11016            vec![(true, "")],
11017        );
11018        land_with(&mut state, URL, &forge).await.unwrap();
11019        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11020        let argv = &forge.argvs()[0];
11021        assert!(has(argv, "--squash") && has(argv, "--subject"));
11022        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11023        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11024        assert_eq!(state.status, RunStatus::Merged);
11025        assert!(state.land_armed_head.is_none());
11026    }
11027
11028    #[tokio::test]
11029    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11030        let mut state = landing_state();
11031        state.land_armed_head = Some("a".to_owned());
11032        let forge = Scripted::new(
11033            vec![seen("a", Checks::Green, "CLEAN", false)],
11034            vec![(true, ""), (true, "")],
11035        );
11036        land_with(&mut state, URL, &forge).await.unwrap();
11037        let argvs = forge.argvs();
11038        assert!(has(&argvs[0], "--disable-auto"));
11039        assert!(!has(&argvs[1], "--auto"));
11040        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11041        assert_eq!(state.status, RunStatus::Merged);
11042        assert!(state.land_armed_head.is_none());
11043    }
11044
11045    #[tokio::test]
11046    async fn an_approval_never_carries_over_to_a_new_head() {
11047        crate::run::pin_test_home();
11048        let mut state = run_state();
11049        state.config.graph.land_approval = true;
11050        let pr = green_pr();
11051        let store = ask::Questions::open();
11052
11053        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11054            .await
11055            .unwrap();
11056        let mut q = store
11057            .list()
11058            .into_iter()
11059            .find(|q| q.run == state.id)
11060            .unwrap();
11061        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11062        store.put(&mut q).unwrap();
11063        assert_eq!(
11064            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
11065                .await
11066                .unwrap(),
11067            ApprovalGate::Approved,
11068            "the same head keeps its approval"
11069        );
11070
11071        // A new head is a new question, not the old word.
11072        assert_eq!(
11073            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11074                .await
11075                .unwrap(),
11076            ApprovalGate::Pending
11077        );
11078        let all: Vec<_> = store
11079            .list()
11080            .into_iter()
11081            .filter(|q| q.run == state.id)
11082            .collect();
11083        assert_eq!(all.len(), 2);
11084
11085        // A question recorded before heads were tracked is not reused either.
11086        state.land_approval = None;
11087        assert_eq!(
11088            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11089                .await
11090                .unwrap(),
11091            ApprovalGate::Pending
11092        );
11093        let open = store
11094            .list()
11095            .into_iter()
11096            .filter(|q| q.run == state.id && q.status.open())
11097            .count();
11098        assert_eq!(open, 1, "the superseded question was retired");
11099    }
11100
11101    #[tokio::test]
11102    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11103        let mut state = landing_state();
11104        let forge = Scripted::new(
11105            vec![
11106                seen("a", Checks::Green, "CLEAN", false),
11107                // The fresh read before the merge: someone pushed.
11108                seen("b", Checks::Green, "CLEAN", false),
11109            ],
11110            vec![(true, "")],
11111        );
11112        land_with(&mut state, URL, &forge).await.unwrap();
11113        let argvs = forge.argvs();
11114        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11115        assert!(!has(&argvs[0], "--auto"));
11116        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11117        assert_eq!(state.status, RunStatus::Merged);
11118    }
11119
11120    fn passing(label: &str) -> CheckInfo {
11121        CheckInfo {
11122            label: label.to_owned(),
11123            verdict: Verdict::Pass,
11124            required: Some(false),
11125            run: None,
11126        }
11127    }
11128
11129    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11130        (label.to_owned(), run.map(str::to_owned))
11131    }
11132
11133    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11134        LandReruns {
11135            head: head.to_owned(),
11136            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11137        }
11138    }
11139
11140    #[test]
11141    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11142        let f = [failing("test (macos)", Some("7"))];
11143        assert_eq!(
11144            rerun_step(&f, None, "h", 100),
11145            RerunStep::Rerun(vec!["7".to_owned()])
11146        );
11147        let rec = reran("h", &[("7", 100)]);
11148        let grace = crate::release_watch::RERUN_GRACE;
11149        assert_eq!(
11150            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11151            RerunStep::Grace
11152        );
11153        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11154    }
11155
11156    #[test]
11157    fn a_failure_without_a_run_id_goes_to_the_fixer() {
11158        let f = [failing("a", Some("7")), failing("ci/external", None)];
11159        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11160        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11161    }
11162
11163    #[test]
11164    fn a_moved_head_forgets_the_reruns() {
11165        let f = [failing("a", Some("7"))];
11166        let rec = reran("old", &[("7", 100)]);
11167        assert_eq!(
11168            rerun_step(&f, Some(&rec), "new", 101),
11169            RerunStep::Rerun(vec!["7".to_owned()])
11170        );
11171    }
11172
11173    #[test]
11174    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11175        let f = [
11176            failing("a", Some("7")),
11177            failing("b", Some("7")),
11178            failing("c", Some("8")),
11179        ];
11180        assert_eq!(
11181            rerun_step(&f, None, "h", 0),
11182            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11183        );
11184        let rec = reran("h", &[("7", 0)]);
11185        assert_eq!(
11186            rerun_step(&f, Some(&rec), "h", 1),
11187            RerunStep::Rerun(vec!["8".to_owned()])
11188        );
11189    }
11190
11191    #[test]
11192    fn only_blocking_failures_are_candidates_for_a_rerun() {
11193        let check = |label: &str, verdict, required, run: &str| CheckInfo {
11194            label: label.to_owned(),
11195            verdict,
11196            required,
11197            run: Some(run.to_owned()),
11198        };
11199        let got = rerunnable(&[
11200            check("passed", Verdict::Pass, Some(true), "1"),
11201            check("optional", Verdict::Fail, Some(false), "2"),
11202            check("required", Verdict::Fail, Some(true), "3"),
11203            check("unknown", Verdict::Fail, None, "4"),
11204        ]);
11205        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11206        assert_eq!(labels, ["required", "unknown"]);
11207    }
11208
11209    fn unrelated_ci_fixture() -> CiEvidence {
11210        let failure = CiFailure {
11211            path: "tests/web_render.rs".into(),
11212            start_line: 42,
11213            end_line: 42,
11214            title: "question_identity_disclosure_copy_and_live_updates".into(),
11215            message: "assertion failed".into(),
11216        };
11217        CiEvidence {
11218            head: "a".into(),
11219            base: "base-sha".into(),
11220            changed: vec![
11221                "AGENTS.md".into(),
11222                "src/talk.rs".into(),
11223                "tests/consult_investigation.rs".into(),
11224            ],
11225            checks: vec![CiCheckEvidence {
11226                label: "coverage".into(),
11227                head_check: 70,
11228                base_check: 60,
11229                app: 1,
11230                run: "7".into(),
11231                base_run: "6".into(),
11232                head_failures: vec![failure.clone()],
11233                base_failures: vec![failure],
11234                rerun_exhausted: true,
11235            }],
11236        }
11237    }
11238
11239    #[test]
11240    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11241        let good = unrelated_ci_fixture();
11242        let red = vec!["coverage".into()];
11243        assert!(good.unrelated("a", &red));
11244        assert!(!good.unrelated("another-head", &red));
11245        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11246        assert!(!good.unrelated("a", &[]));
11247        for mutation in 0..8 {
11248            let mut bad = good.clone();
11249            match mutation {
11250                0 => bad.checks[0].rerun_exhausted = false,
11251                1 => bad.checks[0].base_failures.clear(),
11252                2 => bad.checks[0].head_failures.clear(),
11253                3 => bad.changed.push("tests/web_render.rs".into()),
11254                4 => bad.changed.push(".github/workflows/ci.yml".into()),
11255                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11256                6 => bad.checks.push(bad.checks[0].clone()),
11257                _ => bad.base.clear(),
11258            }
11259            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11260        }
11261    }
11262
11263    #[test]
11264    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11265        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11266        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11267        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11268        assert!(matches!(
11269            decide(&pr, 2, 2, CHECKS_GRACE),
11270            Step::GiveUp { .. }
11271        ));
11272        let optional = CheckInfo {
11273            label: "coverage".into(),
11274            verdict: Verdict::Fail,
11275            required: Some(false),
11276            run: Some("7".into()),
11277        };
11278        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11279        assert_eq!(
11280            rerunnable_with(&[optional], true),
11281            vec![("coverage".into(), Some("7".into()))]
11282        );
11283    }
11284
11285    #[tokio::test]
11286    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11287        let mut state = landing_state();
11288        let mut red = coverage_unknown();
11289        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11290        red.pr.failing = vec!["coverage".into()];
11291        let forge = Scripted::new(vec![red], vec![]);
11292        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11293        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11294        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11295        assert!(forge.calls().contains(&"fix"));
11296        assert!(state.land_unrelated.is_some());
11297        assert!(state.parked);
11298        assert!(
11299            !state
11300                .events
11301                .iter()
11302                .any(|e| e.message.contains("fixer produced no commit"))
11303        );
11304    }
11305
11306    fn coverage_unknown() -> Seen {
11307        let mut s = red("a", Some("7"));
11308        s.pr.blocking = Blocking::Unsaid;
11309        s.merge_state = "UNKNOWN".into();
11310        s.pr.failing = vec!["coverage".into()];
11311        s.contexts[0].label = "coverage".into();
11312        s.contexts[0].required = Some(false);
11313        s
11314    }
11315
11316    #[tokio::test]
11317    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11318        let mut state = landing_state();
11319        let unknown = coverage_unknown();
11320        let mut unstable = unknown.clone();
11321        unstable.pr.blocking = Blocking::of("UNSTABLE");
11322        unstable.merge_state = "UNSTABLE".into();
11323        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11324        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11325        assert!(!forge.calls().contains(&"fix"));
11326        assert!(!forge.calls().contains(&"rerun"));
11327        assert_eq!(state.status, RunStatus::Merged);
11328        assert_eq!(state.pr.unwrap().round, 0);
11329    }
11330
11331    #[tokio::test]
11332    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11333        let mut state = landing_state();
11334        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
11335        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11336        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11337        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11338        assert!(!forge.calls().contains(&"fix"));
11339        assert!(state.parked);
11340        assert_eq!(state.status, RunStatus::Landing);
11341        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11342        let hold = state.land_unrelated.as_ref().unwrap();
11343        let q = ask::Questions::open().get(&hold.question).unwrap();
11344        assert!(
11345            q.actions
11346                .values()
11347                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
11348        );
11349        assert!(
11350            state
11351                .events
11352                .iter()
11353                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
11354        );
11355        let first = state.land_unsaid.clone();
11356        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
11357        state.parked = false;
11358        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11359        assert_eq!(state.land_unsaid, first);
11360        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11361    }
11362
11363    fn red(head: &str, run: Option<&str>) -> Seen {
11364        let mut s = seen(head, Checks::Red, "BLOCKED", false);
11365        s.pr.failing = vec!["test (macos)".to_owned()];
11366        s.contexts = vec![CheckInfo {
11367            label: "test (macos)".to_owned(),
11368            verdict: Verdict::Fail,
11369            required: Some(true),
11370            run: run.map(str::to_owned),
11371        }];
11372        s
11373    }
11374
11375    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
11376
11377    #[tokio::test]
11378    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
11379        let mut state = landing_state();
11380        let forge = Scripted::new(
11381            vec![
11382                red("a", Some("7")),
11383                seen("a", Checks::Pending, "BLOCKED", false),
11384                seen("a", Checks::Green, "CLEAN", false),
11385            ],
11386            vec![(true, "")],
11387        );
11388        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11389        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11390        assert!(!forge.calls().contains(&"fix"));
11391        assert_eq!(state.status, RunStatus::Merged);
11392        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11393        let argvs = forge.argvs();
11394        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
11395        assert!(
11396            state
11397                .events
11398                .iter()
11399                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
11400        );
11401    }
11402
11403    #[tokio::test]
11404    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
11405        let mut state = landing_state();
11406        let forge = Scripted::new(
11407            vec![
11408                red("a", Some("7")),
11409                seen("a", Checks::Green, "CLEAN", false),
11410            ],
11411            vec![(true, "")],
11412        );
11413        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11414        // The red view repeats for the grace, then the fixer is asked once.
11415        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11416        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
11417        let calls = forge.calls();
11418        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
11419        let fix_at = calls.iter().position(|c| *c == "fix");
11420        assert!(fix_at.is_none_or(|f| f > rerun_at));
11421    }
11422
11423    #[tokio::test]
11424    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
11425        let mut state = landing_state();
11426        let mut v = red("a", Some("7"));
11427        v.pr.checks = Checks::Pending;
11428        v.contexts.push(CheckInfo {
11429            label: "slow".to_owned(),
11430            verdict: Verdict::Pending,
11431            required: Some(true),
11432            run: Some("8".to_owned()),
11433        });
11434        let forge = Scripted::new(
11435            vec![v, seen("a", Checks::Green, "CLEAN", false)],
11436            vec![(true, "")],
11437        );
11438        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11439        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11440        assert_eq!(state.status, RunStatus::Merged);
11441    }
11442
11443    #[test]
11444    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
11445        let mut v = red("a", Some("7"));
11446        v.contexts.push(CheckInfo {
11447            label: "same run, still going".to_owned(),
11448            verdict: Verdict::Pending,
11449            required: Some(true),
11450            run: Some("7".to_owned()),
11451        });
11452        assert!(rerunnable(&v.contexts).is_empty());
11453    }
11454
11455    #[tokio::test]
11456    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
11457        let mut state = landing_state();
11458        state.config.graph.land_rounds = 0;
11459        let forge = Scripted::new(
11460            vec![
11461                red("a", Some("7")),
11462                seen("a", Checks::Green, "CLEAN", false),
11463            ],
11464            vec![(true, "")],
11465        );
11466        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11467        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11468        assert_eq!(state.status, RunStatus::Merged);
11469        assert!(!forge.calls().contains(&"fix"));
11470        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11471    }
11472
11473    #[tokio::test]
11474    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
11475        let mut state = landing_state();
11476        state.config.graph.land_rounds = 1;
11477        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
11478        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
11479        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11480        assert_eq!(pr.state, PrLifecycle::Open);
11481        assert_eq!(state.status, RunStatus::Blocked);
11482        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11483        assert!(
11484            state.merge_decision.is_none(),
11485            "no ordinary failure handoff"
11486        );
11487        assert!(forge.argvs().is_empty(), "no merge on outage");
11488
11489        let recovered = Scripted::new(
11490            vec![
11491                seen("a", Checks::Green, "CLEAN", true),
11492                seen("b", Checks::Green, "CLEAN", false),
11493            ],
11494            vec![(true, "")],
11495        );
11496        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
11497        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
11498        assert_eq!(state.status, RunStatus::Merged);
11499        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11500        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
11501    }
11502
11503    #[tokio::test]
11504    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
11505        let mut state = landing_state();
11506        state.config.graph.land_rounds = 1;
11507        let forge = Scripted::new(
11508            vec![
11509                seen("a", Checks::Green, "CLEAN", true),
11510                red("b", Some("7")),
11511                seen("b", Checks::Green, "CLEAN", false),
11512            ],
11513            vec![(true, "")],
11514        );
11515        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11516            head: "b".to_owned(),
11517        });
11518        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11519        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11520        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
11521        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11522        assert_eq!(state.status, RunStatus::Merged);
11523        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
11524        assert_eq!(
11525            value_of(&forge.argvs()[0], "--match-head-commit"),
11526            Some("b")
11527        );
11528    }
11529
11530    #[tokio::test]
11531    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
11532        let mut state = landing_state();
11533        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11534        *forge.rerun_fails.lock().unwrap() = true;
11535        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11536        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11537        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
11538        assert_eq!(
11539            forge.calls().iter().filter(|c| **c == "fix").count(),
11540            1,
11541            "{:?}",
11542            forge.calls()
11543        );
11544    }
11545
11546    #[tokio::test]
11547    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
11548        let mut state = landing_state();
11549        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11550        // The record was written just before the previous pass died.
11551        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
11552        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11553        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11554        assert!(forge.reruns.lock().unwrap().is_empty());
11555    }
11556
11557    #[tokio::test]
11558    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
11559        let mut state = landing_state();
11560        state.config.graph.rerun_flaky_checks = false;
11561        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11562        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11563        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11564        assert!(forge.reruns.lock().unwrap().is_empty());
11565        assert!(forge.calls().contains(&"fix"));
11566
11567        let mut state = landing_state();
11568        let forge = Scripted::new(vec![red("a", None)], vec![]);
11569        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11570        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11571        assert!(forge.reruns.lock().unwrap().is_empty());
11572        assert!(forge.calls().contains(&"fix"));
11573    }
11574
11575    fn names(xs: &[&str]) -> BTreeSet<String> {
11576        xs.iter().map(|x| (*x).to_owned()).collect()
11577    }
11578
11579    #[test]
11580    fn a_required_check_the_rollup_never_listed_is_named() {
11581        let req = names(&["build"]);
11582        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
11583        assert!(why.contains("never reported: build"), "{why}");
11584        assert!(!why.contains("probably waiting for a review"), "{why}");
11585    }
11586
11587    #[test]
11588    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
11589        let why = waiting_on("BLOCKED", &[passing("review")], None);
11590        assert!(why.contains("could not be read"), "{why}");
11591        assert!(!why.contains("probably waiting for a review"), "{why}");
11592    }
11593
11594    #[test]
11595    fn all_required_reported_keeps_the_review_guess() {
11596        let req = names(&["build"]);
11597        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11598        assert!(why.contains("probably waiting for a review"), "{why}");
11599        assert!(!why.contains("never reported"), "{why}");
11600    }
11601
11602    #[test]
11603    fn required_names_match_the_rollup_ignoring_case_only() {
11604        let req = names(&["Build"]);
11605        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11606        assert!(!why.contains("never reported"), "{why}");
11607    }
11608
11609    #[test]
11610    fn required_contexts_are_read_from_protection_and_rulesets() {
11611        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
11612        assert_eq!(
11613            parse_classic_required(classic),
11614            Some(names(&["build", "lint"]))
11615        );
11616        let rules = r#"[{"type":"pull_request","parameters":{}},
11617            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
11618        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
11619        assert_eq!(parse_ruleset_required("nope"), None);
11620        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
11621    }
11622
11623    #[test]
11624    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
11625        let shown = BTreeSet::new();
11626        let ok = seen("a", Checks::Green, "CLEAN", false);
11627        let guard = |s: Option<&Seen>| {
11628            direct_merge_is_safe(
11629                s,
11630                "A",
11631                &shown,
11632                0,
11633                4,
11634                Duration::ZERO,
11635                CiExpectation::Expected,
11636            )
11637        };
11638        assert!(guard(Some(&ok)));
11639        assert!(!guard(None));
11640        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
11641        let mut stale = ok.clone();
11642        stale.rollup_head = "old".to_owned();
11643        assert!(!guard(Some(&stale)));
11644        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
11645        assert!(!guard(Some(&merged_view("a"))));
11646    }
11647
11648    #[test]
11649    fn the_rollup_node_carries_whether_each_check_is_required() {
11650        let node = node_json("new", "SUCCESS", false)
11651            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
11652        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
11653        assert_eq!(s.contexts.len(), 1);
11654        assert_eq!(s.contexts[0].required, Some(true));
11655        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
11656        assert_eq!(s.contexts[0].required, None);
11657    }
11658
11659    #[tokio::test]
11660    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
11661        let mut state = landing_state();
11662        state.land_armed_head = Some("a".to_owned());
11663        let forge = Scripted::new(
11664            vec![seen("a", Checks::Green, "CLEAN", true)],
11665            vec![(false, "disable exploded")],
11666        );
11667        land_with(&mut state, URL, &forge).await.unwrap();
11668        assert!(!forge.calls().contains(&"fix"));
11669        assert_eq!(state.status, RunStatus::Blocked);
11670        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
11671        let why = state.merge.as_ref().unwrap().detail.clone();
11672        assert!(why.contains("disable exploded"), "{why}");
11673    }
11674}