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                    && state
1764                        .land_sync_recovery
1765                        .authorizations
1766                        .iter()
1767                        .rev()
1768                        .find(|auth| auth.consumed && auth.invalidated.is_none())
1769                        .is_none_or(|auth| q.asked_at > auth.consumed_at.unwrap_or(auth.at))
1770                    && (a.head.eq_ignore_ascii_case(head)
1771                        || q.resolution()
1772                            .as_deref()
1773                            .is_some_and(crate::merge_decision::stops))
1774            })
1775    });
1776    let reusable = match reusable {
1777        Some(q) if merge_consent_superseded(state, &q)? => None,
1778        other => other,
1779    };
1780    if reusable.is_none() {
1781        for stale in store.list_for_effects().into_iter().filter(|q| {
1782            q.run == state.id
1783                && q.node == APPROVAL_NODE
1784                && q.status.open()
1785                && !store.held_reply(&q.id)
1786        }) {
1787            let why =
1788                "the pull request head or operator decision changed; asked again for approval";
1789            if let Err(e) = store.update(&stale.id, |q| {
1790                q.abandon(why);
1791                Ok(())
1792            }) {
1793                tracing::warn!("could not retire the superseded approval question: {e:#}");
1794            }
1795        }
1796    }
1797
1798    let q = match reusable {
1799        Some(mut q) => {
1800            if upgrade_repair_choice(&mut q, state) {
1801                q = store
1802                    .update(&q.id, |current| {
1803                        upgrade_repair_choice(current, state);
1804                        Ok(())
1805                    })?
1806                    .0;
1807            }
1808            q
1809        }
1810        None => {
1811            let worktree = match state.winner() {
1812                Some(w) => w.worktree.clone(),
1813                None => state.repo.clone(),
1814            };
1815            // The diff is built from the commit being approved, not from the
1816            // branch name, which may already point somewhere else.
1817            let head = if head.is_empty() {
1818                state
1819                    .winner()
1820                    .map_or_else(|| "HEAD".to_owned(), |w| w.branch.clone())
1821            } else {
1822                head.to_owned()
1823            };
1824            // The diff is against what the remote's base holds, never the
1825            // local branch of that name; unreadable means less evidence.
1826            let remote = &state.config.merge.remote;
1827            let tracking = format!("{remote}/{}", state.base_branch);
1828            let base = if git::rev_exists(&worktree, &tracking).await {
1829                tracking
1830            } else {
1831                String::new()
1832            };
1833            let range = format!("{base}...{head}");
1834            // A failed `git` must not decide the merge: the panel degrades to
1835            // less evidence and the owner still chooses. Merging because the
1836            // diff could not be read would be the worst of both.
1837            let numstat = if base.is_empty() {
1838                String::new()
1839            } else {
1840                git::git_raw(&worktree, &["diff", "--numstat", "-M", &range])
1841                    .await
1842                    .map(|o| o.stdout)
1843                    .unwrap_or_default()
1844            };
1845            let diff = if base.is_empty() {
1846                String::new()
1847            } else {
1848                git::diff(&worktree, &base, &head).await.unwrap_or_default()
1849            };
1850            let commits: Vec<String> = if base.is_empty() {
1851                Vec::new()
1852            } else {
1853                git::git_raw(
1854                    &worktree,
1855                    &[
1856                        "log",
1857                        "--reverse",
1858                        "--format=%s",
1859                        &format!("{base}..{head}"),
1860                    ],
1861                )
1862                .await
1863                .map(|o| o.stdout)
1864                .unwrap_or_default()
1865                .lines()
1866                .filter(|l| !l.trim().is_empty())
1867                .map(str::to_owned)
1868                .collect()
1869            };
1870
1871            let w = words(&state.config.graph.language);
1872            let html = approval_panel(state, pr, &numstat, &diff, &commits, subject);
1873            let mut fresh = ask::Question::new(
1874                state.id.clone(),
1875                APPROVAL_NODE.to_owned(),
1876                "land".to_owned(),
1877                w.approval_summary(pr.number, subject),
1878                format!(
1879                    "{}\n\n{}",
1880                    approval_evidence(state),
1881                    w.approval_detail(&pr.url, &state.base_branch, subject, contested)
1882                ),
1883                approval_choices(state),
1884            );
1885            fresh.merge_target = Some(crate::merge_decision::Target {
1886                pr: pr.url.clone(),
1887                head: head.clone(),
1888                language: state.config.graph.language.clone(),
1889            });
1890            if fresh.choices.iter().any(|c| c == REPAIR) {
1891                fresh.actions.insert(
1892                    REPAIR.to_owned(),
1893                    ask::ChoiceAction::Resume {
1894                        run: state.id.clone(),
1895                    },
1896                );
1897                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.");
1898            }
1899            for choice in fresh.choices.clone() {
1900                if crate::merge_decision::stops(&choice)
1901                    && choice != HOLD
1902                    && choice != crate::merge_decision::DISMISS
1903                {
1904                    fresh.actions.insert(
1905                        choice,
1906                        ask::ChoiceAction::Resume {
1907                            run: state.id.clone(),
1908                        },
1909                    );
1910                }
1911            }
1912            store
1913                .put_panel(&mut fresh, &html, &[])
1914                .context("write the merge approval panel")?;
1915            store
1916                .put_executable(&mut fresh)
1917                .context("file the merge approval question")?;
1918            state.land_approval = Some(LandApproval {
1919                question: fresh.id.clone(),
1920                head: head.clone(),
1921            });
1922            state.event(
1923                "land",
1924                format!("asking for merge approval ({})", fresh.short()),
1925            );
1926            state.save()?;
1927            if let Err(e) = ask::notify(&state.config.notify, &fresh).await {
1928                // A broken webhook is not a reason to lose the merge: the
1929                // question is already on disk and the web UI already shows
1930                // it, so the operator still has a way in.
1931                tracing::warn!(
1932                    "could not notify about merge approval question {}: {e:#} - \
1933                     the web UI is the only surface for it now",
1934                    fresh.short()
1935                );
1936            }
1937            fresh
1938        }
1939    };
1940
1941    Ok(match q.status {
1942        ask::QuestionStatus::Open => ApprovalGate::Pending,
1943        // Nobody answered before `state.config.graph.answer_timeout` passed,
1944        // or the question was closed with no decision recorded underneath
1945        // this run - either way there is nothing left to wait on.
1946        ask::QuestionStatus::Abandoned => ApprovalGate::Held,
1947        // The merge gate does not speak `--thread`: an owner who talked back
1948        // instead of choosing never reaches `Answered`, so this arm only
1949        // ever sees an actual decision.
1950        ask::QuestionStatus::Answered => match approval(q.resolution().as_deref()) {
1951            Approval::Merge => ApprovalGate::Approved,
1952            Approval::Repair if !state.reviews.is_empty() => {
1953                if !state.merge_repairs.iter().any(|r| r.question == q.id) {
1954                    state.merge_repairs.push(crate::run::MergeRepair {
1955                        question: q.id.clone(),
1956                        head: head.to_owned(),
1957                        pr: pr.url.clone(),
1958                        reviews: state.reviews.clone(),
1959                        gate: state.gate.clone(),
1960                        gate_head: state.gate_head.clone(),
1961                        gate_fixes: state.gate_fixes.clone(),
1962                        pre_gate: state.pre_gate.clone(),
1963                        phase: crate::run::MergeRepairPhase::Requested,
1964                        failure: None,
1965                    });
1966                    state.land_approval = None;
1967                    state.event(
1968                        "repair",
1969                        "owner requested fix findings and re-review; merge is not approved",
1970                    );
1971                    state.save()?;
1972                }
1973                ApprovalGate::Repair
1974            }
1975            Approval::Repair | Approval::Hold => ApprovalGate::Held,
1976        },
1977    })
1978}
1979
1980/// Fold a rollup's entries into one verdict plus the failing checks' labels.
1981/// No I/O. An empty rollup is `Unknown`, never green.
1982fn rollup_verdict(rollup: &[GhCheck]) -> (Checks, Vec<String>) {
1983    let mut failing = Vec::new();
1984    let mut pending = false;
1985    let mut unknown = false;
1986    for check in rollup {
1987        match check.verdict() {
1988            Verdict::Pass => {}
1989            Verdict::Pending => pending = true,
1990            Verdict::Fail => failing.push(check.label()),
1991            Verdict::Unknown => unknown = true,
1992        }
1993    }
1994    let checks = if rollup.is_empty() {
1995        Checks::Unknown
1996    } else if pending {
1997        Checks::Pending
1998    } else if !failing.is_empty() {
1999        Checks::Red
2000    } else if unknown {
2001        Checks::Unknown
2002    } else {
2003        Checks::Green
2004    };
2005    (checks, failing)
2006}
2007
2008/// Parse `gh pr view --json url,number,state,statusCheckRollup,reviews,comments`
2009/// output into a [`PrState`]. No I/O.
2010pub fn parse_pr(json: &str) -> Result<PrState> {
2011    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2012    let state = match raw.state.to_ascii_uppercase().as_str() {
2013        "OPEN" => PrLifecycle::Open,
2014        "MERGED" => PrLifecycle::Merged,
2015        "CLOSED" => PrLifecycle::Closed,
2016        other => bail!("unknown pull request state `{other}`"),
2017    };
2018
2019    let (checks, failing) = rollup_verdict(&raw.status_check_rollup);
2020
2021    let mut review_comments = Vec::new();
2022    for r in raw.reviews {
2023        push_if_outstanding(
2024            &mut review_comments,
2025            ReviewComment {
2026                author: r.author.login,
2027                path: None,
2028                line: None,
2029                body: r.body,
2030            },
2031        );
2032    }
2033    for c in raw.comments {
2034        push_if_outstanding(
2035            &mut review_comments,
2036            ReviewComment {
2037                author: c.author.login,
2038                path: None,
2039                line: None,
2040                body: c.body,
2041            },
2042        );
2043    }
2044
2045    Ok(PrState {
2046        url: raw.url,
2047        number: raw.number,
2048        state,
2049        checks,
2050        failing,
2051        review_comments,
2052        blocking: Blocking::of(&raw.merge_state_status),
2053    })
2054}
2055
2056/// One rollup entry as the release watcher reads it.
2057#[derive(Debug, Clone, PartialEq, Eq)]
2058pub(crate) struct CheckView {
2059    pub name: String,
2060    pub verdict: Verdict,
2061    /// Workflow run behind the check, when its url names one.
2062    pub run: Option<String>,
2063    pub url: Option<String>,
2064}
2065
2066/// A pull request's lifecycle, head commit and per-check verdicts, without
2067/// [`rollup_verdict`]'s aggregation (a pending check anywhere hides a failure
2068/// from it, which is exactly what the release watcher must not inherit).
2069#[derive(Debug, Clone, PartialEq, Eq)]
2070pub(crate) struct RollupView {
2071    pub url: String,
2072    pub number: u64,
2073    pub state: PrLifecycle,
2074    pub head: String,
2075    pub checks: Vec<CheckView>,
2076}
2077
2078/// Parse `gh pr view --json url,number,state,headRefOid,statusCheckRollup`
2079/// output. No I/O.
2080pub(crate) fn parse_rollup(json: &str) -> Result<RollupView> {
2081    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2082    let state = match raw.state.to_ascii_uppercase().as_str() {
2083        "OPEN" => PrLifecycle::Open,
2084        "MERGED" => PrLifecycle::Merged,
2085        "CLOSED" => PrLifecycle::Closed,
2086        other => bail!("unknown pull request state `{other}`"),
2087    };
2088    let checks = raw
2089        .status_check_rollup
2090        .iter()
2091        .map(|c| CheckView {
2092            name: c.label(),
2093            verdict: c.verdict(),
2094            run: c.url().and_then(run_of),
2095            url: c.url().map(str::to_owned),
2096        })
2097        .collect();
2098    Ok(RollupView {
2099        url: raw.url,
2100        number: raw.number,
2101        state,
2102        head: raw.head_ref_oid,
2103        checks,
2104    })
2105}
2106
2107/// Read just a pull request's lifecycle state - open, merged, or closed -
2108/// with none of the checks/reviews/comments [`land`] itself needs to decide
2109/// what to do next.
2110///
2111/// For a caller that only ever wants one fact and must not risk anything
2112/// else: `magi fold --merged` uses this to confirm a URL the operator hands
2113/// it is actually a merged pull request *before* touching a run's state, so a
2114/// typo or a still-open PR fails loudly instead of quietly recording a merge
2115/// that never happened.
2116pub async fn lifecycle(repo: &Path, pr_url: &str) -> Result<PrLifecycle> {
2117    let view = gh(
2118        repo,
2119        &[
2120            "pr".to_owned(),
2121            "view".to_owned(),
2122            pr_url.to_owned(),
2123            "--json".to_owned(),
2124            "state".to_owned(),
2125        ],
2126    )
2127    .await?;
2128    if !view.ok {
2129        bail!("gh pr view {pr_url}: {}", view.combined());
2130    }
2131    // `parse_pr` reads every other field of `GhPr` as its serde default
2132    // (empty string, empty vec, zero) when this narrower `--json` selection
2133    // does not carry them - harmless, since only `.state` is read back.
2134    Ok(parse_pr(&view.stdout)?.state)
2135}
2136
2137/// A pull request the operator merged outside of `land::land`'s own loop,
2138/// found by asking GitHub about the run's own winning branch rather than
2139/// requiring the operator to go and find the URL themselves.
2140#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2141pub struct ExternalMerge {
2142    /// The pull request's URL, ready to hand to [`correct_manual_merge`].
2143    pub url: String,
2144    /// The pull request's number.
2145    pub number: u64,
2146}
2147
2148#[derive(Debug, Deserialize)]
2149#[serde(rename_all = "camelCase")]
2150struct GhMergedPr {
2151    url: String,
2152    number: u64,
2153    merged_at: String,
2154    base_ref_name: String,
2155}
2156
2157/// Pure half of [`find_external_merge`]: given the raw `gh pr list --head
2158/// <branch> --state merged --json url,number,mergedAt,baseRefName` output,
2159/// decide whether exactly one of the pull requests it lists could actually
2160/// be *this* run's.
2161///
2162/// A branch name alone does not prove it: [`RunState::branch_for`] derives it
2163/// from the run's own short id, so a collision with some other, unrelated
2164/// task's merged pull request from a same-named branch is rare but not
2165/// impossible once branches are deleted and ids run out. Filtering on
2166/// `base_ref_name` (the branch this run actually targets) and `merged_at`
2167/// (which cannot predate the run itself) rules that case out. More than one
2168/// survivor is exactly as uninformative as zero — something this run cannot
2169/// tell apart from another — so only a unique survivor is returned.
2170fn pick_merged_pr(
2171    json: &str,
2172    base_branch: &str,
2173    created_at: Timestamp,
2174) -> Result<Option<ExternalMerge>> {
2175    pick_merged_pr_with(json, base_branch, created_at, false)
2176}
2177
2178fn pick_merged_pr_with(
2179    json: &str,
2180    base_branch: &str,
2181    created_at: Timestamp,
2182    reject_ambiguous: bool,
2183) -> Result<Option<ExternalMerge>> {
2184    let raw: Vec<GhMergedPr> =
2185        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2186    let mut matches: Vec<ExternalMerge> = Vec::new();
2187    for pr in raw {
2188        if pr.base_ref_name != base_branch {
2189            continue;
2190        }
2191        let Ok(merged_at) = pr.merged_at.parse::<Timestamp>() else {
2192            continue;
2193        };
2194        if merged_at < created_at {
2195            continue;
2196        }
2197        matches.push(ExternalMerge {
2198            url: pr.url,
2199            number: pr.number,
2200        });
2201    }
2202    anyhow::ensure!(
2203        !reject_ambiguous || matches.len() <= 1,
2204        "multiple merged pull requests match this run; merge evidence is ambiguous"
2205    );
2206    if matches.len() == 1 {
2207        Ok(matches.pop())
2208    } else {
2209        Ok(None)
2210    }
2211}
2212
2213/// What `gh pr list --head <branch> --base <base> --state open` found.
2214#[derive(Debug, Clone, PartialEq, Eq)]
2215pub enum OpenPr {
2216    /// Nothing open: the caller creates one.
2217    None,
2218    /// Exactly one: the caller adopts it instead of creating a second.
2219    One {
2220        /// The pull request's URL.
2221        url: String,
2222        /// Its current title.
2223        title: String,
2224    },
2225    /// More than one: magi does not pick between them.
2226    Many(Vec<String>),
2227}
2228
2229#[derive(Debug, Deserialize)]
2230#[serde(rename_all = "camelCase")]
2231struct GhOpenPr {
2232    // `url` and `baseRefName` are required: a record missing either must be a
2233    // parse error, not a pull request that silently fails the base filter and
2234    // reads as "none open" (which would go on to create a duplicate).
2235    url: String,
2236    #[serde(default)]
2237    title: String,
2238    base_ref_name: String,
2239    // A fork's branch of the same name is not the task head; `gh pr list --head`
2240    // matches by branch name alone, so the filter has to be ours.
2241    #[serde(default)]
2242    is_cross_repository: bool,
2243}
2244
2245/// Pure half of [`find_open_pr`]: classify the raw `--json
2246/// number,url,title,baseRefName` output. Entries whose base is not `base` are
2247/// dropped even though the query already filtered on it, so a stub or an old
2248/// `gh` that ignores `--base` cannot get a pull request into the wrong branch
2249/// adopted.
2250pub fn pick_open_pr(json: &str, base: &str) -> Result<OpenPr> {
2251    let raw: Vec<GhOpenPr> =
2252        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2253    let mut hits: Vec<GhOpenPr> = raw
2254        .into_iter()
2255        .filter(|p| p.base_ref_name == base && !p.is_cross_repository)
2256        .collect();
2257    Ok(match hits.len() {
2258        0 => OpenPr::None,
2259        1 => {
2260            let p = hits.remove(0);
2261            OpenPr::One {
2262                url: p.url,
2263                title: p.title,
2264            }
2265        }
2266        _ => OpenPr::Many(hits.into_iter().map(|p| p.url).collect()),
2267    })
2268}
2269
2270/// Open pull requests whose head is `branch` and whose base is `base`. A
2271/// failing `gh` is an error carrying its own output, never "none": guessing
2272/// there is how a duplicate gets created.
2273pub async fn find_open_pr(repo: &Path, branch: &str, base: &str) -> Result<OpenPr> {
2274    find_open_pr_with(Path::new("gh"), repo, branch, base).await
2275}
2276
2277pub(crate) async fn find_open_pr_with(
2278    program: &Path,
2279    repo: &Path,
2280    branch: &str,
2281    base: &str,
2282) -> Result<OpenPr> {
2283    let out = gh_with(
2284        program,
2285        repo,
2286        &[
2287            "pr".to_owned(),
2288            "list".to_owned(),
2289            "--head".to_owned(),
2290            branch.to_owned(),
2291            "--base".to_owned(),
2292            base.to_owned(),
2293            "--state".to_owned(),
2294            "open".to_owned(),
2295            "--json".to_owned(),
2296            "number,url,title,baseRefName,isCrossRepository".to_owned(),
2297        ],
2298    )
2299    .await?;
2300    if !out.ok {
2301        bail!("gh pr list failed: {}", out.combined());
2302    }
2303    pick_open_pr(&out.stdout, base)
2304}
2305
2306#[derive(Debug, Deserialize)]
2307#[serde(rename_all = "camelCase")]
2308struct GhPrHead {
2309    head_ref_name: String,
2310    base_ref_name: String,
2311    state: String,
2312    // Required, like `GhOpenPr`'s fields: a record that cannot say whether the
2313    // head lives in a fork must be a parse error, never "same repository".
2314    is_cross_repository: bool,
2315    // Required too: it is what ties the pull request to the commits that were
2316    // actually proven to be on the base.
2317    head_ref_oid: String,
2318}
2319
2320/// Why [`closable`] said no, and whether asking again later could say yes.
2321#[derive(Debug, Clone, PartialEq, Eq)]
2322pub struct Refusal {
2323    /// A later attempt may succeed (the head moved, the view was unreadable);
2324    /// `false` means this pull request is simply not the run's to close.
2325    pub retry: bool,
2326    /// What was wrong.
2327    pub why: String,
2328}
2329
2330impl Refusal {
2331    fn final_(why: String) -> Self {
2332        Self { retry: false, why }
2333    }
2334}
2335
2336/// Pure half of [`close_superseded_pr`]: read `gh pr view --json
2337/// headRefName,baseRefName,state,isCrossRepository` and say whether closing
2338/// is safe, `Err` carrying the reason when it is not.
2339///
2340/// Closing is outward-facing, so every property is checked on what the forge
2341/// says now, not on what magi recorded: the head must be exactly `branch` in
2342/// this repository (a fork's branch of the same name is somebody else's), the
2343/// base must be `base`, and the pull request must still be open.
2344pub fn closable(
2345    json: &str,
2346    branch: &str,
2347    base: &str,
2348    verified: &[String],
2349) -> std::result::Result<(), Refusal> {
2350    let pr: GhPrHead = serde_json::from_str(json).map_err(|e| Refusal {
2351        retry: true,
2352        why: format!("could not read the pull request ({e})"),
2353    })?;
2354    if pr.head_ref_name != branch {
2355        return Err(Refusal::final_(format!(
2356            "its head is `{}`, not this run's `{branch}`",
2357            pr.head_ref_name
2358        )));
2359    }
2360    if pr.is_cross_repository {
2361        return Err(Refusal::final_("its head lives in a fork".to_owned()));
2362    }
2363    if pr.base_ref_name != base {
2364        return Err(Refusal::final_(format!(
2365            "it targets `{}`, not `{base}`",
2366            pr.base_ref_name
2367        )));
2368    }
2369    if !pr.state.eq_ignore_ascii_case("open") {
2370        return Err(Refusal::final_(format!(
2371            "it is already {}",
2372            pr.state.to_ascii_lowercase()
2373        )));
2374    }
2375    // Last, so a pull request that is not this run's at all is reported as
2376    // such. A head that is this branch but not a commit checked against the
2377    // base (somebody pushed since) may well get checked next time: retry.
2378    if !verified.contains(&pr.head_ref_oid) {
2379        return Err(Refusal {
2380            retry: true,
2381            why: format!(
2382                "its head {} is not a commit this run checked against the base",
2383                crate::already::short_sha(&pr.head_ref_oid)
2384            ),
2385        });
2386    }
2387    Ok(())
2388}
2389
2390/// Does `remote` point at something a forge could host - a URL or an scp-style
2391/// `user@host:path` - rather than a filesystem path or nothing at all? Judged
2392/// from the URL alone, so it answers the same on every machine, whatever `gh`
2393/// happens to be installed or logged in to.
2394async fn remote_is_forge(repo: &Path, remote: &str) -> bool {
2395    let Ok(url) = git::git(repo, &["remote", "get-url", remote]).await else {
2396        return false;
2397    };
2398    is_forge_url(url.trim())
2399}
2400
2401fn is_forge_url(url: &str) -> bool {
2402    url.contains("://") && !url.starts_with("file://")
2403        || url
2404            .split_once(':')
2405            .is_some_and(|(host, _)| host.contains('@') && !host.contains(['/', '\\']))
2406}
2407
2408/// Does this `gh` failure mean there is no GitHub to ask, as opposed to a
2409/// request that failed?
2410fn forge_unavailable(message: &str) -> bool {
2411    message.contains("known GitHub host") || message.contains("spawn gh")
2412}
2413
2414/// The comment left on a pull request closed because its change is already on
2415/// the base.
2416pub fn superseded_comment(base: &str, evidence: &crate::already::Evidence) -> String {
2417    let how = match evidence.proof {
2418        crate::already::Proof::PatchId => format!(
2419            "carried by commit {} on `{base}` with the same patch",
2420            evidence.names()
2421        ),
2422        crate::already::Proof::Ancestry => {
2423            format!("already in the history of `{base}` as {}", evidence.names())
2424        }
2425        crate::already::Proof::Tree => format!(
2426            "already part of `{base}` (merging this branch changes nothing at {})",
2427            crate::already::short_sha(&evidence.tip)
2428        ),
2429    };
2430    format!(
2431        "Closing: everything this branch adds is {how}, so there is nothing left to \
2432         land. This pull request was closed automatically after that was verified; \
2433         reopen it if you disagree."
2434    )
2435}
2436
2437/// Close the open pull request for `branch`, if there is one and it is
2438/// provably this run's, with a comment naming what supersedes it. `Ok(Ok(url))` is
2439/// the URL closed; `Ok(Err(why))` is a final "nothing to close" (no pull request,
2440/// not this run's, no forge); `Err` is anything a later attempt could resolve (a
2441/// failed `gh` call, a head that moved since it was checked), which the caller
2442/// must not treat as settled.
2443///
2444/// The recorded `state.pr` is preferred, else the forge is asked for an open
2445/// pull request on `branch`; either way the candidate is re-read and passed
2446/// through [`closable`] before anything is written; `verified` lists the
2447/// commits proven to be on the base, and the pull request's head must be one.
2448pub async fn close_superseded_pr(
2449    state: &mut RunState,
2450    branch: &str,
2451    evidence: &crate::already::Evidence,
2452    verified: &[String],
2453) -> Result<std::result::Result<String, String>> {
2454    let repo = state.repo.clone();
2455    let base = state.base_branch.clone();
2456    let url = match state.pr.as_ref().filter(|p| p.state == "open") {
2457        Some(p) => p.url.clone(),
2458        // No recorded pull request. A forge that cannot be asked at all (no
2459        // GitHub remote, no `gh`) says nothing about this run, so that is
2460        // "none found"; any other lookup failure is an error, because "could
2461        // not look" is not "nothing there" and the caller must retry.
2462        None if !remote_is_forge(&repo, &state.config.merge.remote).await => {
2463            return Ok(Err(
2464                "the remote is not a forge, so there is no pull request".to_owned(),
2465            ));
2466        }
2467        None => match find_open_pr(&repo, branch, &base).await {
2468            Err(e) if forge_unavailable(&format!("{e:#}")) => {
2469                return Ok(Err(format!("no forge to ask: {e:#}")));
2470            }
2471            Err(e) => return Err(e),
2472            Ok(OpenPr::One { url, .. }) => url,
2473            Ok(OpenPr::None) => return Ok(Err("no open pull request".to_owned())),
2474            Ok(OpenPr::Many(urls)) => {
2475                return Ok(Err(format!(
2476                    "{} open pull requests name it; not choosing between them",
2477                    urls.len()
2478                )));
2479            }
2480        },
2481    };
2482    let view = gh(
2483        &repo,
2484        &[
2485            "pr".to_owned(),
2486            "view".to_owned(),
2487            url.clone(),
2488            "--json".to_owned(),
2489            "headRefName,headRefOid,baseRefName,state,isCrossRepository".to_owned(),
2490        ],
2491    )
2492    .await?;
2493    if !view.ok {
2494        bail!("gh pr view {url} failed: {}", view.combined());
2495    }
2496    if let Err(refusal) = closable(&view.stdout, branch, &base, verified) {
2497        // A pull request whose head cannot be tied to what was proven is not
2498        // one to walk away from: the caller keeps the run resumable.
2499        if refusal.retry {
2500            bail!("left {url} open: {}", refusal.why);
2501        }
2502        return Ok(Err(format!("left {url} open: {}", refusal.why)));
2503    }
2504    let out = gh(
2505        &repo,
2506        &[
2507            "pr".to_owned(),
2508            "close".to_owned(),
2509            url.clone(),
2510            "--comment".to_owned(),
2511            superseded_comment(&base, evidence),
2512        ],
2513    )
2514    .await?;
2515    if !out.ok {
2516        bail!("gh pr close {url} failed: {}", out.combined());
2517    }
2518    if let Some(p) = state.pr.as_mut().filter(|p| p.url == url) {
2519        p.state = "closed".to_owned();
2520    }
2521    Ok(Ok(url))
2522}
2523
2524/// `gh pr edit <url> --title <title>`, for an adopted pull request whose title
2525/// differs from the one this run computed. Only the title: the body may have
2526/// been edited by the owner and cannot be compared.
2527pub async fn set_pr_title(state: &mut RunState, repo: &Path, url: &str, title: &str) -> Result<()> {
2528    let (title, _) = crate::github_text::prepare(state, title, "");
2529    edit_pr_title(repo, url, &title).await
2530}
2531
2532/// [`set_pr_title`] for a title the owner explicitly chose to post unmodified
2533/// (`github_text::POST_ORIGINAL` or `github_text::USE_REWRITE`): the posting
2534/// gate is skipped on purpose.
2535pub async fn set_pr_title_verbatim(repo: &Path, url: &str, title: &str) -> Result<()> {
2536    edit_pr_title(repo, url, title).await
2537}
2538
2539/// Post both fields of the owner's chosen rewrite to an adopted pull request,
2540/// unmodified and without the posting gate.
2541pub async fn set_pr_text_verbatim(repo: &Path, url: &str, title: &str, body: &str) -> Result<()> {
2542    let out = gh(
2543        repo,
2544        &[
2545            "pr".to_owned(),
2546            "edit".to_owned(),
2547            url.to_owned(),
2548            "--title".to_owned(),
2549            title.to_owned(),
2550            "--body".to_owned(),
2551            body.to_owned(),
2552        ],
2553    )
2554    .await
2555    .map_err(|_| anyhow::anyhow!("could not run gh pr edit for the chosen rewrite"))?;
2556    if !out.ok {
2557        // Command output may echo the chosen text; keep it out of run events.
2558        bail!("gh pr edit failed while posting the chosen rewrite");
2559    }
2560    Ok(())
2561}
2562
2563async fn edit_pr_title(repo: &Path, url: &str, title: &str) -> Result<()> {
2564    let out = gh(
2565        repo,
2566        &[
2567            "pr".to_owned(),
2568            "edit".to_owned(),
2569            url.to_owned(),
2570            "--title".to_owned(),
2571            title.to_owned(),
2572        ],
2573    )
2574    .await?;
2575    if !out.ok {
2576        bail!("gh pr edit failed: {}", out.combined());
2577    }
2578    Ok(())
2579}
2580
2581/// Ask GitHub whether this run's winning candidate branch was actually merged
2582/// somewhere `land::land`'s own loop never saw — the gap `magi fold
2583/// --merged` exists to close, minus the operator having to find the URL by
2584/// hand.
2585///
2586/// `Ok(None)` covers every case where nothing can be said with confidence: no
2587/// winner decided yet (nothing to check a branch for), no merged pull request
2588/// found, or [`pick_merged_pr`] found more than one candidate and would not
2589/// guess between them. Never wired to a weaker, URL-less signal like
2590/// [`branch_is_ancestor`] — a caller wanting that has to ask for it
2591/// separately, precisely because it cannot drive an automatic correction on
2592/// its own (see that function's own doc).
2593pub async fn find_external_merge(state: &RunState) -> Result<Option<ExternalMerge>> {
2594    let Some(winner) = state.winner() else {
2595        return Ok(None);
2596    };
2597    find_external_merge_with(
2598        state,
2599        state.pr_head.as_deref().unwrap_or(&winner.branch),
2600        false,
2601    )
2602    .await
2603}
2604
2605/// Reopening needs proof of absence, not merely failure to identify one PR.
2606pub(crate) async fn find_external_merge_for_reopen(
2607    state: &RunState,
2608) -> Result<Option<ExternalMerge>> {
2609    let Some(branch) = state.pr_branch() else {
2610        anyhow::ensure!(
2611            state.pr.is_none() && state.pr_pushed_head.is_none(),
2612            "run has public PR evidence but no known branch to check"
2613        );
2614        return Ok(None);
2615    };
2616    find_external_merge_with(state, branch, true).await
2617}
2618
2619async fn find_external_merge_with(
2620    state: &RunState,
2621    branch: &str,
2622    reject_ambiguous: bool,
2623) -> Result<Option<ExternalMerge>> {
2624    let out = gh(
2625        &state.repo,
2626        &[
2627            "pr".to_owned(),
2628            "list".to_owned(),
2629            "--head".to_owned(),
2630            branch.to_owned(),
2631            "--state".to_owned(),
2632            "merged".to_owned(),
2633            "--json".to_owned(),
2634            "url,number,mergedAt,baseRefName".to_owned(),
2635        ],
2636    )
2637    .await?;
2638    if !out.ok {
2639        bail!("gh pr list --head {branch}: {}", out.combined());
2640    }
2641    if reject_ambiguous {
2642        pick_merged_pr_with(&out.stdout, &state.base_branch, state.created_at, true)
2643    } else {
2644        pick_merged_pr(&out.stdout, &state.base_branch, state.created_at)
2645    }
2646}
2647
2648/// Whether `branch` is, right now, an ancestor of `base_branch` in the local
2649/// git graph — the weaker, URL-less signal that a branch landed somewhere.
2650///
2651/// Deliberately never consulted by [`find_external_merge`]: a base branch
2652/// that has moved since the run started can make an old, abandoned branch
2653/// look like an ancestor of the *current* base for reasons that have nothing
2654/// to do with a merge (a later commit that happens to supersede it, an
2655/// unrelated squash), and there is no pull request URL here to confirm
2656/// against or to land through anyway. Its only honest use is a weaker
2657/// notice — "this looks merged, go check" — never an automatic rewrite of
2658/// `status`/`merge`.
2659pub async fn branch_is_ancestor(repo: &Path, branch: &str, base_branch: &str) -> Result<bool> {
2660    let out = tokio::process::Command::new("git")
2661        .args(["merge-base", "--is-ancestor", branch, base_branch])
2662        .current_dir(repo)
2663        .quiet()
2664        .stdin(std::process::Stdio::null())
2665        .output()
2666        .await
2667        .context("spawn git merge-base --is-ancestor")?;
2668    Ok(out.status.success())
2669}
2670
2671/// Parse `host/owner/repo` out of a forge URL, with no network access.
2672///
2673/// The host is part of the slug, not discarded: `owner/repo` alone would
2674/// treat `github.example.com/o/r` and `github.com/o/r` as the same
2675/// repository, which is exactly the mix-up the same-repo guard exists to
2676/// catch. Returns `None` for anything that doesn't have a `<host>/<path>`
2677/// shape at all.
2678fn forge_slug(url: &str) -> Option<(String, &str)> {
2679    let rest = url.rsplit("://").next()?;
2680    let (host, path) = rest.split_once('/')?;
2681    if host.is_empty() {
2682        return None;
2683    }
2684    Some((host.to_ascii_lowercase(), path))
2685}
2686
2687/// Parse `host/owner/repo` out of a GitHub pull request URL, with no network
2688/// access - the first half of the same-repo guard [`correct_manual_merge`]
2689/// applies before it writes anything.
2690///
2691/// Returns `None` for anything that does not look like
2692/// `https://<host>/<owner>/<repo>/pull/<n>`, which the caller treats as
2693/// fail-closed: a URL this cannot make sense of refuses rather than guesses.
2694pub(crate) fn slug_of_pr_url(url: &str) -> Option<String> {
2695    let (host, path) = forge_slug(url)?;
2696    let mut segments = path.split('/');
2697    let owner = segments.next()?;
2698    let repo = segments.next()?;
2699    let kind = segments.next()?;
2700    if owner.is_empty() || repo.is_empty() || kind != "pull" {
2701        return None;
2702    }
2703    Some(format!("{host}/{owner}/{repo}"))
2704}
2705
2706/// Parse `host/owner/repo` out of a plain repository URL (no `/pull/<n>`
2707/// suffix), the shape `gh repo view --json url` returns - the other half of
2708/// the same-repo guard, matched against [`slug_of_pr_url`]'s output.
2709fn slug_of_repo_url(url: &str) -> Option<String> {
2710    let (host, path) = forge_slug(url)?;
2711    let mut segments = path.split('/');
2712    let owner = segments.next()?;
2713    let repo = segments.next()?;
2714    if owner.is_empty() || repo.is_empty() {
2715        return None;
2716    }
2717    Some(format!("{host}/{owner}/{repo}"))
2718}
2719
2720/// Refuse to correct a run against a pull request from a different
2721/// repository than the one it is recorded against.
2722///
2723/// This is the guard the shun/8c75 incident argued for: an operator ran
2724/// `magi fold --merged <shun PR url>` meaning to correct an old `Blocked` run
2725/// in a different repository, omitted the run id, and the id defaulted to
2726/// this machine's most recently created run - an unrelated, still-in-progress
2727/// run in a completely different repository - which then had its `status`
2728/// rewritten to `merged` from a pull request it had nothing to do with.
2729/// `correct_manual_merge` now requires an explicit id (see `magi fold`'s own
2730/// CLI help), but a mistyped or stale id could still name a run in a
2731/// different repository than the one the URL belongs to, so this checks that
2732/// independently rather than trusting the id alone.
2733///
2734/// Comparison is case-insensitive - GitHub owner/repo names are - and a
2735/// mismatch names both slugs rather than just refusing, so an operator whose
2736/// local checkout's `origin` is a fork of the repository the pull request was
2737/// opened against (a legitimate setup this cannot tell apart from a genuine
2738/// mix-up) can judge for themselves rather than being blocked with no way to
2739/// see why.
2740pub(crate) fn ensure_same_repo(run_repo_slug: &str, pr_repo_slug: &str) -> Result<()> {
2741    if run_repo_slug.eq_ignore_ascii_case(pr_repo_slug) {
2742        return Ok(());
2743    }
2744    bail!(
2745        "refusing to correct this run: it is recorded against {run_repo_slug}, but the pull \
2746         request URL belongs to {pr_repo_slug} - pass the run id whose repository the URL \
2747         actually belongs to (or, if `origin` is a fork opened against a different upstream, \
2748         verify by hand before treating this as a false positive)"
2749    );
2750}
2751
2752/// Ask the forge which `host/owner/repo` a local checkout's `origin` remote
2753/// actually resolves to, for the same-repo guard in [`correct_manual_merge`].
2754///
2755/// Asking `gh` rather than parsing `git remote -v` locally is deliberate: it
2756/// normalizes case, SSH vs. HTTPS remotes, and a renamed or transferred
2757/// repository the same way GitHub itself would recognize it, so the
2758/// comparison in [`ensure_same_repo`] is against the same canonical slug on
2759/// both sides. Reads `url` rather than `nameWithOwner` so the host is part of
2760/// the answer too - `nameWithOwner` alone cannot tell a `github.com` repo from
2761/// a same-named one on a GitHub Enterprise host.
2762async fn repo_slug(repo: &Path) -> Result<String> {
2763    let out = gh(
2764        repo,
2765        &[
2766            "repo".to_owned(),
2767            "view".to_owned(),
2768            "--json".to_owned(),
2769            "url".to_owned(),
2770        ],
2771    )
2772    .await?;
2773    if !out.ok {
2774        bail!("gh repo view --json url: {}", out.combined());
2775    }
2776    #[derive(Debug, Deserialize)]
2777    struct GhRepo {
2778        url: String,
2779    }
2780    let parsed: GhRepo = serde_json::from_str(&out.stdout)
2781        .with_context(|| format!("parse `gh repo view` output: {}", out.stdout.trim()))?;
2782    slug_of_repo_url(&parsed.url)
2783        .with_context(|| format!("could not parse a host/owner/repo out of {}", parsed.url))
2784}
2785
2786/// Confirm `url` is actually a merged pull request, then rewrite `state`'s
2787/// `status` and `merge` exactly as the automatic land loop (`land::land`)
2788/// would have written them had magi opened and merged this pull request
2789/// itself.
2790///
2791/// This is `magi fold --merged`'s whole implementation, and also what the
2792/// web `fold-merged` route calls once it has a URL in hand — an operator
2793/// recovery path for a merge magi could not finish on its own: a PR title too
2794/// long for the GraphQL mutation, `gh pr create` unreachable, a stale token -
2795/// closed by hand with a pull request magi never opened and so never
2796/// recorded. Reusing `land::land` rather than writing `status`/`merge`
2797/// directly keeps this one authoritative: a merged pull request decides
2798/// `Step::Done { merged: true }` on the very first read, before any of
2799/// `land`'s own checks/fix/rebase machinery can run, which is what makes it
2800/// safe to call here even though this pull request was never magi's own.
2801///
2802/// [`ensure_same_repo`] is checked before anything else: a pull request from
2803/// a different repository than the one `state` is recorded against is
2804/// refused outright, regardless of its lifecycle. This is the guard for a
2805/// URL an *operator* hands in - the CLI or the web route - where a stale or
2806/// mistyped run id could otherwise get corrected from an unrelated
2807/// repository's pull request (see the shun/8c75 incident in `magi fold`'s own
2808/// CLI help). The automatic janitor sweep (`clean::reconcile_external_merges`)
2809/// goes through [`correct_confirmed_external_merge`] instead, which skips
2810/// this check: its `url` was never operator-supplied, it comes from
2811/// [`find_external_merge`] querying `gh` from inside `state.repo` itself, so
2812/// it is already guaranteed to name a pull request in that same repository -
2813/// re-deriving and re-checking the repository here would only be a second
2814/// `gh repo view` call that can fail for reasons that have nothing to do with
2815/// correctness (a rate limit, a network blip), turning a self-heal that would
2816/// otherwise have succeeded into a run left `Blocked` for another pass.
2817///
2818/// [`lifecycle`] is checked next and separately so a mistyped or still-open
2819/// URL fails loudly without writing anything, rather than handing an open
2820/// pull request to the full autonomous loop by accident.
2821///
2822/// Correcting `status` this way does not run `bump::after_merge`
2823/// (`src/bump.rs`): that call is made only from `graph::Runner::run_land`,
2824/// which this path never goes through. A release version bump the change
2825/// might have earned is therefore not filed automatically and has to be
2826/// requested by hand - recorded as an event on the run so the gap is visible
2827/// to whoever reads it later, not just wherever this was called from. Follow-up
2828/// tasks for findings the merge left open (`crate::followup`) *are* filed here.
2829///
2830/// Returns the status before and after, so every caller (CLI, janitor, web
2831/// route) can build its own log line or response from the same pair rather
2832/// than each re-deriving it.
2833pub async fn correct_manual_merge(
2834    state: &mut RunState,
2835    url: &str,
2836) -> Result<(RunStatus, RunStatus)> {
2837    let Some(pr_slug) = slug_of_pr_url(url) else {
2838        bail!(
2839            "could not parse an owner/repo out of {url}; refusing to guess which repository \
2840             this pull request belongs to"
2841        );
2842    };
2843    let run_slug = repo_slug(&state.repo).await?;
2844    ensure_same_repo(&run_slug, &pr_slug)?;
2845    correct_merge(state, url).await
2846}
2847
2848/// The janitor's own entry point into the same correction
2849/// [`correct_manual_merge`] performs for an operator-supplied URL, minus the
2850/// same-repo guard - see that function's own doc for why skipping it here is
2851/// safe rather than a hole: [`clean::reconcile_external_merges`] only ever
2852/// calls this with a `url` [`find_external_merge`] already found by querying
2853/// `state.repo`'s own remote, so the guard could never do anything here but
2854/// fail on its own transient errors.
2855///
2856/// [`crate::clean`] is the only caller; `pub(crate)` rather than private only
2857/// because it lives in a different module.
2858pub(crate) async fn correct_confirmed_external_merge(
2859    state: &mut RunState,
2860    url: &str,
2861) -> Result<(RunStatus, RunStatus)> {
2862    correct_merge(state, url).await
2863}
2864
2865/// Same pull request, same repository: the url, or the number within one repo.
2866fn names_same_pr(a: &RunState, url: &str, number: u64, repo: &Path) -> bool {
2867    let Some(pr) = a.pr.as_ref() else {
2868        return false;
2869    };
2870    if !url.is_empty()
2871        && pr
2872            .url
2873            .trim_end_matches('/')
2874            .eq_ignore_ascii_case(url.trim_end_matches('/'))
2875    {
2876        return true;
2877    }
2878    number > 0
2879        && pr.number == number
2880        && match (a.repo.canonicalize(), repo.canonicalize()) {
2881            (Ok(x), Ok(y)) => x == y,
2882            _ => a.repo == repo,
2883        }
2884}
2885
2886/// Rewrite `pr.state` to a final state on every run record under `home` that
2887/// `decide` picks, and report how many were rewritten.
2888///
2889/// Lifecycle writes through to other runs are deliberately narrow (task-head
2890/// ownership is recorded separately): only a **terminal** run (never one a
2891/// driver may still be writing), only a proven-stopped driver with no daemon
2892/// claim (the shared liveness judge), only a record
2893/// whose `pr.state` is still `open`, and only `merged` / `closed` ever goes in.
2894/// The record is read as folding reads it (no schema check: every bump so far
2895/// only added fields, and the whole struct round-trips) and written through
2896/// [`RunState::save_under`], the path every record uses, so nothing but
2897/// `pr.state` and an event line changes (and `updated_at`, as for any save).
2898/// A run that cannot be read or written is skipped with a warning.
2899fn rewrite_open_prs(
2900    home: &Path,
2901    decide: &mut dyn FnMut(&RunState) -> Option<PrLifecycle>,
2902) -> usize {
2903    let now = Timestamp::now();
2904    let mut changed = 0;
2905    for id in crate::run::list_ids_in(&home.join("runs")) {
2906        let path = home.join("runs").join(&id).join("run.json");
2907        let read = || {
2908            let body = std::fs::read_to_string(&path).ok()?;
2909            serde_json::from_str::<RunState>(&body).ok()
2910        };
2911        // Do not contend with recovery of unrelated runs. This first read is
2912        // only a filter; every write still uses the record read under its lock.
2913        let Some(snapshot) = read() else {
2914            continue;
2915        };
2916        if !snapshot.status.done()
2917            || snapshot.pr.as_ref().is_none_or(|p| p.state != "open")
2918            || !matches!(
2919                decide(&snapshot),
2920                Some(PrLifecycle::Merged | PrLifecycle::Closed)
2921            )
2922        {
2923            continue;
2924        }
2925        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2926            continue;
2927        };
2928        let Some(mut state) = read() else {
2929            continue;
2930        };
2931        if !state.status.done()
2932            || state.pr.as_ref().is_none_or(|p| p.state != "open")
2933            || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2934                != crate::run::Liveness::Dead
2935        {
2936            continue;
2937        }
2938        let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2939            continue;
2940        };
2941        if let Some(pr) = state.pr.as_mut() {
2942            pr.state = to.as_str().to_owned();
2943        }
2944        let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2945        state.event(
2946            "land",
2947            format!("recorded {url} as {}: another run settled it", to.as_str()),
2948        );
2949        match state.save_under(home) {
2950            Ok(()) => changed += 1,
2951            Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2952        }
2953    }
2954    changed
2955}
2956
2957/// A run reached a final state for its pull request: tell every other terminal
2958/// run in the same repository that names the same pull request (handed-over
2959/// predecessors, blocked attempts, anything), so their records stop saying
2960/// `open`. Best effort; `run`'s own record is the caller's.
2961pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2962    if to == PrLifecycle::Open {
2963        return;
2964    }
2965    let Some(home) = crate::run::try_home() else {
2966        return;
2967    };
2968    write_pr_state_through_in(&home, run, to);
2969}
2970
2971pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2972    let Some(pr) = run.pr.as_ref() else {
2973        return 0;
2974    };
2975    let (url, number) = (pr.url.clone(), pr.number);
2976    rewrite_open_prs(home, &mut |other| {
2977        (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2978    })
2979}
2980
2981/// Terminal runs whose record still says their pull request is open, as
2982/// `(run id, repo, url)`, for [`repair_stale_pr_states`].
2983pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
2984    let now = Timestamp::now();
2985    let mut out = Vec::new();
2986    for id in crate::run::list_ids_in(&home.join("runs")) {
2987        let path = home.join("runs").join(&id).join("run.json");
2988        let Ok(body) = std::fs::read_to_string(&path) else {
2989            continue;
2990        };
2991        let Ok(state) = serde_json::from_str::<RunState>(&body) else {
2992            continue;
2993        };
2994        if let Some(pr) = state.pr.as_ref()
2995            && state.status.done()
2996            && pr.state == "open"
2997            && !pr.url.is_empty()
2998            && !crate::daemon::is_working_on(home, &id, now)
2999        {
3000            out.push((id, state.repo.clone(), pr.url.clone()));
3001        }
3002    }
3003    out
3004}
3005
3006/// Apply forge answers (`pr url -> state`) to every stale terminal record.
3007/// A url with no answer (the forge was unreadable) changes nothing.
3008pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
3009    rewrite_open_prs(home, &mut |s| {
3010        s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
3011    })
3012}
3013
3014/// Observe terminal records' open pull requests, with a bounded rotating scan.
3015/// Rewrite settled PRs and record conclusive stale-base observations separately
3016/// from the synchronization budget. Unknown answers leave evidence unchanged.
3017pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
3018    let mut known = BTreeMap::new();
3019    let mut failed = 0;
3020    let mut observed = 0;
3021    let mut groups = BTreeMap::<String, (PathBuf, Vec<String>)>::new();
3022    for (id, repo, url) in stale_open_prs(home) {
3023        groups
3024            .entry(url)
3025            .or_insert_with(|| (repo, Vec::new()))
3026            .1
3027            .push(id);
3028    }
3029    let mut groups = groups.into_iter().collect::<Vec<_>>();
3030    static CURSOR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3031    if !groups.is_empty() {
3032        let offset =
3033            CURSOR.fetch_add(max_lookups, std::sync::atomic::Ordering::Relaxed) % groups.len();
3034        groups.rotate_left(offset);
3035    }
3036    for (url, (repo, ids)) in groups.into_iter().take(max_lookups) {
3037        let view = gh(
3038            &repo,
3039            &[
3040                "pr".into(),
3041                "view".into(),
3042                url.clone(),
3043                "--json".into(),
3044                "state,mergeStateStatus,headRefOid,baseRefName".into(),
3045            ],
3046        )
3047        .await
3048        .and_then(|out| {
3049            anyhow::ensure!(out.ok, "gh pr view: {}", out.combined());
3050            let raw: GhPr = serde_json::from_str(&out.stdout)?;
3051            let state = match raw.state.to_ascii_uppercase().as_str() {
3052                "OPEN" => PrLifecycle::Open,
3053                "MERGED" => PrLifecycle::Merged,
3054                "CLOSED" => PrLifecycle::Closed,
3055                other => bail!("unknown pull request state `{other}`"),
3056            };
3057            Ok((state, raw))
3058        });
3059        match view {
3060            Ok((state, raw)) => {
3061                for id in ids {
3062                    if state != PrLifecycle::Open {
3063                        continue;
3064                    }
3065                    let Ok(snapshot) = RunState::load_under(&id, home) else {
3066                        continue;
3067                    };
3068                    if snapshot.status != RunStatus::Ready || snapshot.pr_taken_over_by.is_some() {
3069                        continue;
3070                    }
3071                    let tip = if matches!(
3072                        Blocking::of(&raw.merge_state_status),
3073                        Blocking::Conflict | Blocking::Behind
3074                    ) {
3075                        tokio::time::timeout(
3076                            std::time::Duration::from_secs(15),
3077                            git::remote_head(
3078                                &snapshot.repo,
3079                                &snapshot.config.merge.remote,
3080                                &snapshot.base_branch,
3081                            ),
3082                        )
3083                        .await
3084                        .ok()
3085                        .and_then(Result::ok)
3086                        .flatten()
3087                    } else {
3088                        None
3089                    };
3090                    if let Ok(_lock) = crate::pr_head::owner_lock(home, &id)
3091                        && let Ok(mut run) = RunState::load_under(&id, home)
3092                        && run.repo == snapshot.repo
3093                        && run.config.merge.remote == snapshot.config.merge.remote
3094                        && run.base_branch == snapshot.base_branch
3095                        && run.updated_at == snapshot.updated_at
3096                        && run.status == RunStatus::Ready
3097                        && run.pr_taken_over_by.is_none()
3098                        && run.retired_to.is_none()
3099                        && !run.released()
3100                        && run
3101                            .pr
3102                            .as_ref()
3103                            .is_some_and(|p| p.url == url && p.state == "open")
3104                        && run.liveness_under(
3105                            home,
3106                            crate::daemon::is_working_on(home, &id, Timestamp::now()),
3107                        ) == crate::run::Liveness::Dead
3108                        && raw.base_ref_name == run.base_branch
3109                        && !raw.head_ref_oid.is_empty()
3110                    {
3111                        let recorded = run
3112                            .base_sync
3113                            .as_ref()
3114                            .map_or(run.base_commit.as_str(), |bs| bs.tip.as_str());
3115                        let next = stale_public_pr(
3116                            &raw,
3117                            recorded,
3118                            tip.as_deref(),
3119                            run.stale_public_pr.as_ref(),
3120                        );
3121                        if run.stale_public_pr != next {
3122                            run.stale_public_pr = next;
3123                            match run.save_under(home) {
3124                                Ok(()) => {
3125                                    observed += 1;
3126                                    if let Some(detail) = run.stale_pr_cause() {
3127                                        crate::notices::raise_in(
3128                                            home,
3129                                            crate::notices::Notice::warn(
3130                                                &format!("stale-pr:{id}"),
3131                                                detail,
3132                                            )
3133                                            .link(crate::notices::Link::Run { id: id.clone() })
3134                                            .about([id.clone()]),
3135                                        );
3136                                    }
3137                                }
3138                                Err(e) => tracing::warn!(
3139                                    "record PR synchronization state for {id}: {e:#}"
3140                                ),
3141                            }
3142                        }
3143                    }
3144                }
3145                known.insert(url, state);
3146            }
3147            Err(e) => {
3148                tracing::warn!("repair pr state of {url}: {e:#}");
3149                failed += 1;
3150            }
3151        }
3152    }
3153    (apply_pr_states(home, &known) + observed, failed)
3154}
3155
3156pub(crate) fn stale_pr_recovery_command(task: &str, url: &str, head: &str) -> String {
3157    format!("magi task recover-pr {task} --pr {url} --head {head} --disposition land")
3158}
3159
3160fn pr_went_stale(
3161    recorded_base: &str,
3162    base_tip: &str,
3163    state: PrLifecycle,
3164    blocking: Blocking,
3165) -> bool {
3166    state == PrLifecycle::Open
3167        && !recorded_base.is_empty()
3168        && !base_tip.is_empty()
3169        && recorded_base != base_tip
3170        && matches!(blocking, Blocking::Conflict | Blocking::Behind)
3171}
3172
3173fn stale_public_pr(
3174    raw: &GhPr,
3175    recorded_base: &str,
3176    base_tip: Option<&str>,
3177    previous: Option<&crate::run::StalePublicPr>,
3178) -> Option<crate::run::StalePublicPr> {
3179    use crate::run::{PublicBaseState, StalePublicPr};
3180    let state = match raw.merge_state_status.as_str() {
3181        "DIRTY" => PublicBaseState::Conflicting,
3182        "BEHIND" => PublicBaseState::Behind,
3183        "CLEAN" | "UNSTABLE" => return None,
3184        _ => return previous.cloned(),
3185    };
3186    if raw.head_ref_oid.len() != 40 || !raw.head_ref_oid.bytes().all(|b| b.is_ascii_hexdigit()) {
3187        return previous.cloned();
3188    }
3189    let Some(base_tip) = base_tip.filter(|tip| !tip.is_empty() && !recorded_base.is_empty()) else {
3190        return previous.cloned();
3191    };
3192    if !pr_went_stale(
3193        recorded_base,
3194        base_tip,
3195        PrLifecycle::Open,
3196        Blocking::of(&raw.merge_state_status),
3197    ) {
3198        return None;
3199    }
3200    Some(StalePublicPr {
3201        head: raw.head_ref_oid.clone(),
3202        state,
3203        recorded_base: recorded_base.into(),
3204        base_tip: base_tip.into(),
3205    })
3206}
3207
3208#[test]
3209fn stale_pr_needs_moved_base_and_forge_evidence() {
3210    use PrLifecycle::{Closed, Merged, Open};
3211    assert!(pr_went_stale("a", "b", Open, Blocking::Conflict));
3212    assert!(pr_went_stale("a", "b", Open, Blocking::Behind));
3213    assert!(!pr_went_stale("a", "a", Open, Blocking::Conflict));
3214    assert!(!pr_went_stale("a", "b", Open, Blocking::No));
3215    assert!(!pr_went_stale("a", "b", Open, Blocking::Unsaid));
3216    assert!(!pr_went_stale("a", "b", Merged, Blocking::Conflict));
3217    assert!(!pr_went_stale("a", "b", Closed, Blocking::Conflict));
3218    assert!(!pr_went_stale("a", "", Open, Blocking::Conflict));
3219    assert!(!pr_went_stale("", "b", Open, Blocking::Conflict));
3220}
3221
3222#[test]
3223fn stale_public_pr_retains_conflict_until_conclusive_observation() {
3224    use crate::run::PublicBaseState;
3225    let raw = |status: &str| -> GhPr {
3226        serde_json::from_value(serde_json::json!({
3227            "mergeStateStatus": status,
3228            "headRefOid": "a".repeat(40)
3229        }))
3230        .unwrap()
3231    };
3232    let conflict = stale_public_pr(&raw("DIRTY"), "a", Some("b"), None).unwrap();
3233    assert_eq!(conflict.state, PublicBaseState::Conflicting);
3234    assert_eq!(
3235        stale_public_pr(&raw("UNKNOWN"), "a", Some("b"), Some(&conflict)),
3236        Some(conflict.clone())
3237    );
3238    assert_eq!(
3239        stale_public_pr(&raw("DIRTY"), "a", None, Some(&conflict)),
3240        Some(conflict.clone())
3241    );
3242    assert_eq!(stale_public_pr(&raw("DIRTY"), "a", Some("a"), None), None);
3243    assert_eq!(
3244        stale_public_pr(&raw("CLEAN"), "a", None, Some(&conflict)),
3245        None
3246    );
3247    assert_eq!(
3248        stale_public_pr(&raw("BEHIND"), "a", Some("b"), None)
3249            .unwrap()
3250            .state,
3251        PublicBaseState::Behind
3252    );
3253}
3254
3255async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
3256    match lifecycle(&state.repo, url).await? {
3257        PrLifecycle::Merged => {}
3258        other => bail!(
3259            "{url} is {}, not merged; refusing to record {} as merged on a guess",
3260            other.as_str(),
3261            state.id
3262        ),
3263    }
3264    let before = state.status;
3265    if let Err(e) = land(state, url).await {
3266        // `land` sets `status` to `Landing` and saves before its first read
3267        // of the pull request — see its own doc — so a failure here (a
3268        // transient `gh` hiccup between the two forge reads this function
3269        // makes) can leave the run stuck on that in-between value with
3270        // nothing left driving it. Land it on the same terminal shape an
3271        // automated `land` failure lands on instead of leaving it stuck.
3272        state.status = RunStatus::Blocked;
3273        state.event("fold", format!("manual-merge correction failed: {e:#}"));
3274        state.save()?;
3275        return Err(e).context(format!("confirming the merge of {url}"));
3276    }
3277    state.event(
3278        "fold",
3279        "operator recorded this pull request as a manual merge; this run never \
3280         re-entered `land`, so `bump::after_merge` did not run for it - a release \
3281         bump this change might warrant has to be filed by hand",
3282    );
3283    // Unlike the bump, the findings the merge left open are filed on this
3284    // path too: nothing else would ever carry them forward.
3285    if state.status == RunStatus::Merged {
3286        crate::followup::after_merge(state, url).await;
3287    }
3288    state.save()?;
3289    Ok((before, state.status))
3290}
3291
3292/// Parse `gh api repos/{owner}/{repo}/pulls/<n>/comments` into inline review
3293/// comments. No I/O.
3294///
3295/// `gh pr view` does not surface inline comments, and inline is exactly where
3296/// both review bots put their findings - a landing loop that read only the
3297/// top-level thread would never see the thing it is supposed to fix.
3298pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3299    let raw: Vec<GhInline> =
3300        serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3301    let mut out = Vec::new();
3302    for c in raw {
3303        push_if_outstanding(
3304            &mut out,
3305            ReviewComment {
3306                author: c.user.login,
3307                path: c.path,
3308                line: c.line,
3309                body: c.body,
3310            },
3311        );
3312    }
3313    Ok(out)
3314}
3315
3316/// Keep a comment only when it asks for something.
3317///
3318/// An inline comment always does: it names a file and a line. A top-level
3319/// comment is dropped when it is empty, when it is magi's own, or when it is
3320/// [noise](is_noise).
3321fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3322    if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3323        return;
3324    }
3325    if comment.path.is_none() && is_noise(&comment.body) {
3326        return;
3327    }
3328    out.push(comment);
3329}
3330
3331/// Is this comment body machinery rather than a finding?
3332///
3333/// Two tests, both structural, because guessing from prose is how a "looks
3334/// good to me" turns into a fix round:
3335///
3336/// 1. The bot said so - the body carries one of the [`NOT_A_REVIEW`] markers
3337///    with which CodeRabbit labels its trigger notice, its walkthrough, and its
3338///    footer.
3339/// 2. It asks for nothing - once HTML comments, `<details>` blocks, headings,
3340///    horizontal rules, and the bot's own status banner are removed, every
3341///    remaining line is a task-list item. That is exactly the shape of the
3342///    comment the Claude review job posts while it is still working.
3343///
3344/// Anything else is input, including bot prose. A bot that writes a paragraph
3345/// has said something, and the fix prompt tells the fixer it may decline a
3346/// comment with an argument - a wasted sentence in a prompt is cheaper than a
3347/// missed finding.
3348pub fn is_noise(body: &str) -> bool {
3349    if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3350        return true;
3351    }
3352    let mut content = false;
3353    for line in strip_blocks(body).lines() {
3354        let line = unquote(line);
3355        if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3356            continue;
3357        }
3358        content = true;
3359        break;
3360    }
3361    !content
3362}
3363
3364/// Remove HTML comments and collapsed `<details>` blocks.
3365fn strip_blocks(body: &str) -> String {
3366    let mut out = String::with_capacity(body.len());
3367    let mut rest = body;
3368    loop {
3369        let open = ["<!--", "<details>"]
3370            .iter()
3371            .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3372            .min_by_key(|(i, _)| *i);
3373        let Some((at, tag)) = open else {
3374            out.push_str(rest);
3375            return out;
3376        };
3377        out.push_str(&rest[..at]);
3378        let after = &rest[at + tag.len()..];
3379        let close = if tag == "<!--" { "-->" } else { "</details>" };
3380        match after.find(close) {
3381            Some(end) => rest = &after[end + close.len()..],
3382            // Unterminated: the rest of the body is inside the block.
3383            None => return out,
3384        }
3385    }
3386}
3387
3388/// Strip blockquote markers, which both bots wrap their callouts in.
3389fn unquote(line: &str) -> &str {
3390    let mut s = line.trim();
3391    while let Some(rest) = s.strip_prefix('>') {
3392        s = rest.trim_start();
3393    }
3394    s.trim()
3395}
3396
3397/// `- [ ]` / `- [x]`, in any of the bullet styles GitHub renders.
3398fn is_checklist(line: &str) -> bool {
3399    let rest = line
3400        .strip_prefix("- ")
3401        .or_else(|| line.strip_prefix("* "))
3402        .unwrap_or("");
3403    let rest = rest.trim_start();
3404    matches!(
3405        rest.get(..3),
3406        Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3407    )
3408}
3409
3410/// A heading, a horizontal rule, or a callout tag - shape, never content.
3411fn is_decoration(line: &str) -> bool {
3412    line.starts_with('#')
3413        || line.starts_with("[!")
3414        || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3415}
3416
3417/// A line that is nothing but emphasis and links.
3418///
3419/// Both review jobs open with a status banner
3420/// (`**Claude finished ... in 4m 14s** —— [View job](url)`). It reads as prose
3421/// to a line-based test and asks for nothing, so it is measured the same way a
3422/// heading is: strip the markup, and if no word survives, it was decoration.
3423fn is_banner(line: &str) -> bool {
3424    let plain = drop_spans(line, "**", "**");
3425    let plain = if plain.contains("](") {
3426        drop_spans(&plain, "[", ")")
3427    } else {
3428        plain
3429    };
3430    !plain.chars().any(char::is_alphanumeric)
3431}
3432
3433/// Remove every `open` .. `close` span, including the delimiters. An
3434/// unterminated span swallows the rest of the input, which is what a reader
3435/// sees too.
3436fn drop_spans(s: &str, open: &str, close: &str) -> String {
3437    let mut out = String::with_capacity(s.len());
3438    let mut rest = s;
3439    while let Some(at) = rest.find(open) {
3440        out.push_str(&rest[..at]);
3441        let after = &rest[at + open.len()..];
3442        match after.find(close) {
3443            Some(end) => rest = &after[end + close.len()..],
3444            None => return out,
3445        }
3446    }
3447    out.push_str(rest);
3448    out
3449}
3450
3451/// The lock that keeps at most one run per repository actually moving the
3452/// base branch at a time: a rebase push, or `gh pr merge`.
3453///
3454/// Deliberately narrow. Everything else in [`land`]'s loop - watching CI,
3455/// running a fix round in the winner's own worktree, waiting on the owner's
3456/// approval - touches nothing a *different* run in the same repository could
3457/// collide with, and holding a lock across any of that would serialise one
3458/// run's CI wait (up to [`WAIT_CEILING`]) against another run's land-approval
3459/// resume, which is precisely the "must not wait on another task" property
3460/// the daemon's slot-freeing exists to give a resume. Only the two moments
3461/// that actually write to the shared base branch need mutual exclusion, and
3462/// both are brief.
3463///
3464/// One entry per repository, each its own `tokio::sync::Mutex`, so two
3465/// different repositories' runs never wait on each other. The outer
3466/// `std::sync::Mutex` guards only the map itself, held long enough to find or
3467/// insert an entry and clone its `Arc`, never across an `.await`.
3468fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3469    static LOCKS: std::sync::LazyLock<
3470        std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3471    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3472    LOCKS
3473        .lock()
3474        .unwrap_or_else(std::sync::PoisonError::into_inner)
3475        .entry(repo.to_path_buf())
3476        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3477        .clone()
3478}
3479
3480/// `owner/repo` out of a pull request url, falling back to the checkout's
3481/// directory name when the url is not the usual `host/owner/repo/pull/N`.
3482fn repo_label(repo: &Path, pr_url: &str) -> String {
3483    let parts: Vec<&str> = pr_url.split('/').collect();
3484    if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3485        && at >= 2
3486        && !parts[at - 1].is_empty()
3487        && !parts[at - 2].is_empty()
3488    {
3489        return format!("{}/{}", parts[at - 2], parts[at - 1]);
3490    }
3491    repo.file_name()
3492        .map(|n| n.to_string_lossy().into_owned())
3493        .unwrap_or_default()
3494}
3495
3496/// The operator-facing sentence for a merge that went ahead with red checks,
3497/// or `None` when the checks were not red. Judged on `checks`, not on
3498/// `failing`, which can be non-empty on a green observation.
3499fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3500    (pr.checks == Checks::Red).then(|| {
3501        let details = crate::notices::format_list(&pr.failing)
3502            .map(|names| format!(": {names}"))
3503            .unwrap_or_default();
3504        format!(
3505            "Merged {repo_name} PR #{} with red checks{details} ({})",
3506            pr.number, pr.url
3507        )
3508    })
3509}
3510
3511/// After a merge that succeeded: record which checks were red and tell the
3512/// operator. The decision to merge is already made; this only makes it audible.
3513/// Best-effort - a broken notifier never fails the run.
3514async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3515    let repo_name = repo_label(&state.repo, &pr.url);
3516    let Some(summary) = red_merge_summary(&repo_name, pr) else {
3517        return;
3518    };
3519    if let Some(rec) = state.pr.as_mut() {
3520        rec.red_at_merge = pr.failing.clone();
3521    }
3522    state.event("land", summary.clone());
3523    // The notice pages through `[notify]` itself, once, unless a question
3524    // already carries the cause.
3525    crate::notices::raise_with(
3526        crate::notices::merged_red(&state.id, &summary),
3527        &state.config.notify,
3528    );
3529}
3530
3531/// Run the loop against a real pull request until it merges or the budget runs
3532/// out.
3533///
3534/// The caller decides whether landing happens at all: this is only reached when
3535/// `graph.land` is on. Returns the last observation, so the caller can report
3536/// what magi was looking at when it stopped.
3537pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3538    land_with(state, pr_url, &GhForge).await
3539}
3540
3541/// The forge calls whose timing the loop's decisions depend on, behind a seam
3542/// so a test can script what the pull request looks like from one observation
3543/// to the next. Comments, logs and rebases stay on `gh` and `git` directly.
3544trait Forge {
3545    async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3546        let out = gh(
3547            repo,
3548            &[
3549                "pr".into(),
3550                "close".into(),
3551                pr_url.into(),
3552                "--comment".into(),
3553                comment.into(),
3554            ],
3555        )
3556        .await?;
3557        if !out.ok {
3558            bail!("PR closure failed: {}", out.combined());
3559        }
3560        Ok(())
3561    }
3562    async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3563        None
3564    }
3565    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3566    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3567    async fn poll(&self);
3568    /// Rerun the failed jobs of one workflow run.
3569    async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3570    /// Unix seconds, behind the seam so a test owns the clock.
3571    fn now(&self) -> i64;
3572    /// The check contexts the base branch requires, for a stop reason only.
3573    /// `None` when they could not be read, which is not the same as none.
3574    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3575    #[allow(clippy::too_many_arguments)]
3576    async fn fix(
3577        &self,
3578        state: &mut RunState,
3579        pr: &PrState,
3580        round: usize,
3581        budget: usize,
3582        reason: &str,
3583        logs: &str,
3584    ) -> Result<Fixed>;
3585}
3586
3587struct GhForge;
3588
3589impl Forge for GhForge {
3590    async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3591        collect_ci_evidence(state, seen).await
3592    }
3593    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3594        observe(repo, pr_url).await
3595    }
3596    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3597        let out = gh(repo, argv).await?;
3598        Ok((out.ok, out.combined()))
3599    }
3600    async fn poll(&self) {
3601        tokio::time::sleep(POLL).await;
3602    }
3603    async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3604        let args = [
3605            "run".to_owned(),
3606            "rerun".to_owned(),
3607            run.to_owned(),
3608            "--failed".to_owned(),
3609        ];
3610        let out = gh(repo, &args).await?;
3611        if !out.ok {
3612            bail!("gh run rerun {run}: {}", out.combined());
3613        }
3614        Ok(())
3615    }
3616    fn now(&self) -> i64 {
3617        jiff::Timestamp::now().as_second()
3618    }
3619    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3620        required_contexts_of(repo, base).await
3621    }
3622    async fn fix(
3623        &self,
3624        state: &mut RunState,
3625        pr: &PrState,
3626        round: usize,
3627        budget: usize,
3628        reason: &str,
3629        logs: &str,
3630    ) -> Result<Fixed> {
3631        fix_round(state, pr, round, budget, reason, logs).await
3632    }
3633}
3634
3635/// Percent-encode a branch name for a URL path segment (`/` included).
3636fn encode_path_segment(s: &str) -> String {
3637    let mut out = String::new();
3638    for b in s.bytes() {
3639        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3640            out.push(b as char);
3641        } else {
3642            let _ = write!(out, "%{b:02X}");
3643        }
3644    }
3645    out
3646}
3647
3648/// Read the required contexts of `base` from classic branch protection and
3649/// from rulesets, once, for a stop reason. Organisation-level rulesets that
3650/// these two endpoints do not list are missed. Any unreadable source makes the
3651/// whole answer `None`: a partial set would read as a complete one.
3652async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3653    let enc = encode_path_segment(base);
3654    let mut all = BTreeSet::new();
3655    // Classic protection answers 404 for an unprotected branch, which is
3656    // "nothing required here", not a failure to read.
3657    let classic = gh(
3658        repo,
3659        &[
3660            "api".to_owned(),
3661            format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3662        ],
3663    )
3664    .await
3665    .ok()?;
3666    if classic.ok {
3667        all.extend(parse_classic_required(&classic.stdout)?);
3668    } else if !classic.combined().contains("404") {
3669        return None;
3670    }
3671    let rules = gh(
3672        repo,
3673        &[
3674            "api".to_owned(),
3675            format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3676        ],
3677    )
3678    .await
3679    .ok()?;
3680    if !rules.ok {
3681        return None;
3682    }
3683    all.extend(parse_ruleset_required(&rules.stdout)?);
3684    Some(all)
3685}
3686
3687/// `required_status_checks` of classic protection: `contexts` plus the
3688/// `checks[].context` form.
3689fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3690    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3691    let mut out = BTreeSet::new();
3692    for c in v.get("contexts")?.as_array()? {
3693        out.insert(c.as_str()?.to_owned());
3694    }
3695    for c in v
3696        .get("checks")
3697        .and_then(|c| c.as_array())
3698        .into_iter()
3699        .flatten()
3700    {
3701        if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3702            out.insert(name.to_owned());
3703        }
3704    }
3705    Some(out)
3706}
3707
3708/// `rules/branches/<base>`: every `required_status_checks` rule's contexts.
3709fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3710    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3711    let mut out = BTreeSet::new();
3712    for rule in v.as_array()? {
3713        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3714            continue;
3715        }
3716        let checks = rule
3717            .pointer("/parameters/required_status_checks")?
3718            .as_array()?;
3719        for c in checks {
3720            out.insert(c.get("context")?.as_str()?.to_owned());
3721        }
3722    }
3723    Some(out)
3724}
3725
3726/// Is the observation older than the commit a fix round pushed?
3727///
3728/// The forge takes a few seconds to move the pull request to a new head and
3729/// attach that head's check runs, and until it has, the rollup is the previous
3730/// head's - all green, which is exactly what a merge decision must not read.
3731/// An absent or different head counts as not yet: guessing "close enough"
3732/// would reopen the hole.
3733fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3734    awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3735}
3736
3737/// The commit an observation may be decided on, or `None` while it cannot be
3738/// trusted to describe one.
3739///
3740/// `None` when a pushed commit is awaited and the pull request is not on it,
3741/// when the head is unreadable, or when the rollup (`statusCheckRollup` is the
3742/// last commit's) is not the head's: that is the previous commit's checks. The
3743/// caller re-polls on `None`. A rollup that cannot be read (including one
3744/// longer than a page) leaves `rollup_head` empty, so the wait runs to
3745/// [`WAIT_CEILING`] and stops - a safe failure, never a merge.
3746fn bound_head<'a>(
3747    seen_head: &'a str,
3748    rollup_head: &str,
3749    awaiting: Option<&str>,
3750) -> Option<&'a str> {
3751    if seen_head.is_empty()
3752        || awaiting_new_head(awaiting, seen_head)
3753        || !rollup_head.eq_ignore_ascii_case(seen_head)
3754    {
3755        return None;
3756    }
3757    Some(seen_head)
3758}
3759
3760/// What a refused `gh pr merge` means.
3761#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3762enum Refused {
3763    /// An open PR on the observed head has a proven stale base.
3764    Behind,
3765    /// The branch policy is not satisfied *yet*: go back to waiting.
3766    Pending,
3767    /// Checks have settled and the merge state still says no, seen for the
3768    /// first time. The forge updates `mergeStateStatus` a moment after the last
3769    /// check finishes, so one more look is allowed before believing it.
3770    Recheck,
3771    /// Nothing is in flight and the policy still refuses: a person has to
3772    /// supply what it asks for (a review, say).
3773    Final,
3774}
3775
3776/// Judged from the pull request's state after the refusal, never from the
3777/// refusal's wording, which belongs to the forge and changes.
3778fn classify_refusal(
3779    after: Option<&Seen>,
3780    rechecked: bool,
3781    observed_head: &str,
3782    ci: CiExpectation,
3783) -> Refused {
3784    let Some(after) = after else {
3785        // Unreadable is not evidence of anything; the next loop reads again.
3786        return Refused::Pending;
3787    };
3788    if after.pr.state != PrLifecycle::Open {
3789        return Refused::Final;
3790    }
3791    // The branch moved after it was observed (the forge refuses a merge pinned
3792    // to the old commit): not a verdict on anything, look again.
3793    if !after.head.eq_ignore_ascii_case(observed_head) {
3794        return Refused::Pending;
3795    }
3796    if Blocking::of(&after.merge_state) == Blocking::Behind {
3797        return Refused::Behind;
3798    }
3799    // The same binding the loop applies: checks of another commit say nothing.
3800    if bound_head(&after.head, &after.rollup_head, None).is_none() {
3801        return Refused::Pending;
3802    }
3803    let state = after.merge_state.to_ascii_uppercase();
3804    if (ci == CiExpectation::Expected
3805        && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3806        || state.is_empty()
3807        || state == "UNKNOWN"
3808    {
3809        return Refused::Pending;
3810    }
3811    if rechecked {
3812        Refused::Final
3813    } else {
3814        Refused::Recheck
3815    }
3816}
3817
3818/// Take auto-merge back from the forge and forget that it was armed.
3819///
3820/// `Err` carries the forge's message: the caller must not push or move on, as
3821/// an armed merge left behind could still fire for a commit nobody approved.
3822async fn disarm<F: Forge>(
3823    forge: &F,
3824    state: &mut RunState,
3825    repo: &Path,
3826    number: u64,
3827) -> std::result::Result<(), String> {
3828    let argv = disable_automerge_argv(number);
3829    let out = {
3830        let merge_lock = repo_merge_lock(repo);
3831        let _merge_slot = merge_lock.lock().await;
3832        forge.merge(repo, &argv).await
3833    };
3834    match out {
3835        Ok((true, _)) => {
3836            state.land_armed_head = None;
3837            state.event("land", "auto-merge disabled");
3838            state.save().map_err(|e| format!("{e:#}"))?;
3839            Ok(())
3840        }
3841        Ok((false, msg)) => Err(msg),
3842        Err(e) => Err(format!("{e:#}")),
3843    }
3844}
3845
3846/// [`stop`], first taking back an armed auto-merge so a pull request magi
3847/// gave up on does not merge on its own later. A failure to disarm is added
3848/// to the reason rather than hiding it.
3849async fn stop_disarmed<F: Forge>(
3850    forge: &F,
3851    state: &mut RunState,
3852    repo: &Path,
3853    pr: &PrState,
3854    why: &str,
3855) -> Result<()> {
3856    if state.land_armed_head.is_none() {
3857        return stop(state, repo, pr, why).await;
3858    }
3859    match disarm(forge, state, repo, pr.number).await {
3860        Ok(()) => stop(state, repo, pr, why).await,
3861        Err(e) => {
3862            let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3863            stop(state, repo, pr, &why).await
3864        }
3865    }
3866}
3867
3868/// Check the persisted card again around awaits that can outlive an owner tap.
3869fn owner_requested_stop(state: &RunState) -> Result<bool> {
3870    let Some(binding) = &state.land_approval else {
3871        return Ok(false);
3872    };
3873    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3874    Ok(q.run == state.id
3875        && q.node == APPROVAL_NODE
3876        && q.resolution()
3877            .as_deref()
3878            .is_some_and(crate::merge_decision::stops))
3879}
3880
3881/// Read stop choices before checks, repair or rebase. These are about stopping
3882/// ownership, so a changed head never cancels them as it cancels merge consent.
3883async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3884    use crate::merge_decision as md;
3885    let Some(binding) = &state.land_approval else {
3886        return Ok(false);
3887    };
3888    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3889    let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3890        return Ok(false);
3891    };
3892    if q.run != state.id || q.node != APPROVAL_NODE {
3893        bail!("stop decision names another run");
3894    }
3895    let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3896        pr: pr.url.clone(),
3897        head: binding.head.clone(),
3898        language: state.config.graph.language.clone(),
3899    });
3900    if target.pr != pr.url {
3901        bail!("stop decision names another PR");
3902    }
3903    if state.merge_decision.is_none() {
3904        state.merge_decision = Some(md::Decision {
3905            question: q.id.clone(),
3906            target,
3907            choice: choice.clone(),
3908            closed: false,
3909            replacement_run: None,
3910            replacement_pr: None,
3911        });
3912        state.save()?;
3913    }
3914    let repo = state.repo.clone();
3915    // Always disable, including arms left by an older driver.
3916    if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3917        stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3918        return Ok(true);
3919    }
3920    if choice.eq_ignore_ascii_case(HOLD) {
3921        stop(
3922            state,
3923            &repo,
3924            pr,
3925            "owner held the decision: PR left open; no further repair or merge work",
3926        )
3927        .await?;
3928        return Ok(true);
3929    }
3930    if md::selected_agent(&choice).is_some()
3931        || state
3932            .origin
3933            .as_ref()
3934            .and_then(|o| o.task.as_ref())
3935            .is_some()
3936    {
3937        let owners: Vec<_> = crate::queue::Queue::open()
3938            .list()
3939            .into_iter()
3940            .filter(|task| task.execution_runs().last() == Some(&state.id))
3941            .collect();
3942        let owner = (owners.len() == 1).then(|| &owners[0]);
3943        if !owner.is_some_and(|task| {
3944            task.execution_runs().last() == Some(&state.id)
3945                && (!task
3946                    .operator_decided_at
3947                    .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3948                    || task.resumption.as_ref().is_some_and(|release| {
3949                        release.question_id.as_deref() == Some(q.id.as_str())
3950                            && task.operator_decided_at == Some(release.at)
3951                    }))
3952        }) {
3953            stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3954            return Ok(true);
3955        }
3956    }
3957    if pr.state == PrLifecycle::Merged {
3958        stop(
3959            state,
3960            &repo,
3961            pr,
3962            "PR already merged; withdrawal/replacement cannot be applied",
3963        )
3964        .await?;
3965        return Ok(true);
3966    }
3967    let comment = format!(
3968        "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3969        q.id, choice, state.id
3970    );
3971    if pr.state == PrLifecycle::Open {
3972        if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3973            stop(
3974                state,
3975                &repo,
3976                pr,
3977                &format!(
3978                    "owner requested closure but it failed: {e}; task held, no replacement started"
3979                ),
3980            )
3981            .await?;
3982            return Ok(true);
3983        }
3984    }
3985    let confirmed = forge.view(&repo, &pr.url).await?;
3986    if confirmed.pr.state != PrLifecycle::Closed {
3987        stop(
3988            state,
3989            &repo,
3990            pr,
3991            "PR closure was not confirmed; task held, no replacement started",
3992        )
3993        .await?;
3994        return Ok(true);
3995    }
3996    *pr = confirmed.pr;
3997    state.merge_decision.as_mut().unwrap().closed = true;
3998    if let Some(record) = &mut state.pr {
3999        record.state = "closed".into();
4000    }
4001    state.status = RunStatus::Superseded;
4002    state.merge = Some(MergeOutcome {
4003        mode: MergeMode::Pr,
4004        ok: false,
4005        detail: format!("owner decision: {choice}; PR closure confirmed"),
4006        empty: false,
4007    });
4008    state.event(
4009        "land",
4010        format!(
4011            "{} applied: PR closure confirmed; old execution retired",
4012            choice
4013        ),
4014    );
4015    state.save()?;
4016    Ok(true)
4017}
4018
4019/// Keep an unstarted verification resumable without charging a task attempt.
4020fn check_landing_resources(
4021    state: &mut RunState,
4022    node: &str,
4023    outcomes: &[crate::run::CommandOutcome],
4024) -> Result<()> {
4025    if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
4026        let detail = format!("{}: {}", blocked.command, blocked.output_tail);
4027        state
4028            .resource_block
4029            .get_or_insert_with(|| crate::run::ResourceBlock {
4030                cause: crate::run::ResourceBlockCause::Other,
4031                node: node.into(),
4032                kind: "shared build cache".into(),
4033                detail: detail.clone(),
4034                at: jiff::Timestamp::now(),
4035            });
4036        state.event("resource", &detail);
4037        state.save()?;
4038        bail!("landing verification could not start: {detail}");
4039    }
4040    Ok(())
4041}
4042
4043/// Gate the local winner and publish that exact SHA, retaining the saved lease.
4044/// A push completed before a crash is recoverable only when its SHA was gated.
4045async fn publish_landing_head<F: Forge>(
4046    state: &mut RunState,
4047    observed: &str,
4048    pr_url: &str,
4049    forge: &F,
4050) -> Result<String> {
4051    crate::pr_head::ensure_owner(state)?;
4052    let winner = state.winner().cloned().context("landing has no winner")?;
4053    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
4054    let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
4055    anyhow::ensure!(
4056        observed == expected
4057            || (observed == head
4058                && state.gate_head.as_deref() == Some(&head)
4059                && state.gate_allows_progress()),
4060        "public head moved outside this run; refusing to overwrite it"
4061    );
4062    anyhow::ensure!(
4063        git::is_clean(&winner.worktree).await?,
4064        "landing worktree is dirty"
4065    );
4066    // Even without a rebase, verification can change HEAD through gate repair.
4067    // Persist the start before either verification or repair can run.
4068    if state.land_sync_unstarted_grant() {
4069        state.land_sync_attempts += 1;
4070        state.land_sync_pending = true;
4071        state.event(
4072            "land-sync-recovery",
4073            "started recovery attempt without rebase",
4074        );
4075        state.save()?;
4076    }
4077    if state.gate_head.as_deref() != Some(&head)
4078        || !state.gate_ran
4079        || !state.gate_commands_allow_progress()
4080    {
4081        state.reconcile_verification_head(&head);
4082        state.gate.clear();
4083        state.gate_head = None;
4084        state.gate_ran = false;
4085        state.pre_gate.clear();
4086        state.pre_gate_commit = None;
4087        state.save()?;
4088        let inherited = crate::repo_lock::WaitPolicy::current();
4089        let wait = crate::repo_lock::WaitPolicy::new(
4090            Duration::from_secs(state.config.graph.timeout_resource_wait),
4091            move || inherited.cancelled(),
4092        );
4093        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
4094        loop {
4095            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
4096                state.gate = outcomes.clone();
4097                check_landing_resources(state, "gate", &outcomes)?;
4098            }
4099            if outcomes.iter().all(|o| o.ok()) {
4100                break;
4101            }
4102            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
4103                crate::graph::GateFix::Retry => {
4104                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
4105                }
4106                crate::graph::GateFix::Stop => break,
4107                crate::graph::GateFix::Defer => {
4108                    // The repair checks e2e immediately, before the next gate.
4109                    // Preserve a cache wait here as well as below; otherwise
4110                    // the daemon charges an attempt for unstarted verification.
4111                    if let Some(e2e) = &state.gate_repair_e2e {
4112                        let outcomes = e2e.outcomes.clone();
4113                        check_landing_resources(state, "e2e", &outcomes)?;
4114                    }
4115                    bail!("landing gate repair deferred");
4116                }
4117            }
4118        }
4119        state.gate = outcomes;
4120        state.gate_ran = true;
4121        state.save()?;
4122    }
4123    let inherited = crate::repo_lock::WaitPolicy::current();
4124    let wait = crate::repo_lock::WaitPolicy::new(
4125        Duration::from_secs(state.config.graph.timeout_resource_wait),
4126        move || inherited.cancelled(),
4127    );
4128    let checked = state
4129        .gate_head
4130        .clone()
4131        .context("landing gate has no checked SHA")?;
4132    anyhow::ensure!(
4133        git::rev_parse(&winner.worktree, "HEAD").await? == checked
4134            && git::is_clean(&winner.worktree).await?,
4135        "landing tree changed after gate"
4136    );
4137    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
4138    if matches!(e2e, crate::graph::GateFix::Defer) {
4139        let outcomes = state
4140            .gate_repair_e2e
4141            .as_ref()
4142            .context("deferred landing e2e has no outcomes")?
4143            .outcomes
4144            .clone();
4145        check_landing_resources(state, "e2e", &outcomes)?;
4146    }
4147    anyhow::ensure!(
4148        matches!(e2e, crate::graph::GateFix::Retry),
4149        "post-repair e2e has not passed on the landing head; nothing published"
4150    );
4151    anyhow::ensure!(
4152        git::rev_parse(&winner.worktree, "HEAD").await? == checked
4153            && git::is_clean(&winner.worktree).await?,
4154        "landing tree changed during post-repair e2e"
4155    );
4156    anyhow::ensure!(
4157        crate::graph::verify_current_head(state, &winner, &wait).await?,
4158        "current head e2e has not passed; nothing published"
4159    );
4160    anyhow::ensure!(
4161        state.gate_allows_progress(),
4162        "landing gate failed; nothing published"
4163    );
4164    crate::pr_head::ensure_owner(state)?;
4165    if owner_requested_stop(state)? {
4166        bail!("owner requested stop before publication");
4167    }
4168    let current = forge.view(&state.repo, pr_url).await?;
4169    anyhow::ensure!(
4170        current.pr.state == PrLifecycle::Open,
4171        "PR closed or merged while gating; nothing published"
4172    );
4173    anyhow::ensure!(
4174        current.head == observed || current.head == checked,
4175        "PR head changed while gating; nothing published"
4176    );
4177    anyhow::ensure!(
4178        crate::foreign_checkout::write_back(state, &checked).await?,
4179        "foreign checkout delivery is blocked; see the run events"
4180    );
4181    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
4182    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
4183    let refspec = format!("{checked}:refs/heads/{public}");
4184    let lock = repo_merge_lock(&state.repo);
4185    let _slot = lock.lock().await;
4186    let pushed = git::git_raw(
4187        &winner.worktree,
4188        &["push", &lease, &state.config.merge.remote, &refspec],
4189    )
4190    .await?;
4191    anyhow::ensure!(
4192        pushed.ok(),
4193        "publishing gated landing head failed: {}",
4194        pushed.stderr
4195    );
4196    state.pr_pushed_head = Some(checked.clone());
4197    state.land_sync_pending = false;
4198    state.save()?;
4199    Ok(checked)
4200}
4201
4202/// A scratch rebase moves the winner ref before its index and files. Recover
4203/// only a tree proven unchanged since the saved start; never discard edits.
4204async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
4205    let winner = state.winner().cloned().context("landing has no winner")?;
4206    let inherited = crate::repo_lock::WaitPolicy::current();
4207    let wait = crate::repo_lock::WaitPolicy::new(
4208        Duration::from_secs(state.config.graph.timeout_resource_wait),
4209        move || inherited.cancelled(),
4210    );
4211    let _coordination = crate::repo_lock::SeatLease::operation_with(
4212        &winner.worktree,
4213        state.config.coordination.as_ref(),
4214        &wait,
4215    )
4216    .await?;
4217    if !git::is_clean(&winner.worktree).await? {
4218        let from = state
4219            .land_rebase_from
4220            .as_deref()
4221            .context("landing worktree is dirty")?;
4222        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
4223        anyhow::ensure!(head != from, "landing worktree is dirty");
4224        for args in [
4225            vec!["diff", "--cached", "--quiet", from],
4226            vec!["diff", "--quiet"],
4227        ] {
4228            anyhow::ensure!(
4229                git::git_raw(&winner.worktree, &args).await?.ok(),
4230                "landing worktree has edits beyond the interrupted rebase"
4231            );
4232        }
4233        // Preserve build artifacts and local files, including ignored ones.
4234        // read-tree can overwrite ignored paths, so reject collisions with
4235        // the new tree (including file/directory conflicts) before updating.
4236        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
4237        let tracked = git::git(
4238            &winner.worktree,
4239            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
4240        )
4241        .await?;
4242        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
4243            anyhow::ensure!(
4244                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
4245                    path == local
4246                        || path
4247                            .strip_prefix(local)
4248                            .is_some_and(|rest| rest.starts_with('/'))
4249                        || local
4250                            .strip_prefix(path)
4251                            .is_some_and(|rest| rest.starts_with('/'))
4252                }),
4253                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
4254            );
4255        }
4256        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
4257    }
4258    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
4259        anyhow::ensure!(
4260            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
4261            "landing synchronization started outside the foreign checkout history"
4262        );
4263        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
4264            // The rebase's tree already includes the base and the fixer's
4265            // resolutions. Retain that exact tree, but join the pre-sync
4266            // history so delivery remains fast-forward. Keep the checkpoint
4267            // until this succeeds: a crash after rebase (or after this merge)
4268            // must recover through this same idempotent path before gating.
4269            git::git(
4270                &winner.worktree,
4271                &[
4272                    "-c",
4273                    "core.hooksPath=/dev/null",
4274                    "merge",
4275                    "--strategy=ours",
4276                    "--no-ff",
4277                    "--no-autostash",
4278                    "--no-edit",
4279                    "-m",
4280                    "Merge pre-sync history into the repaired landing tree",
4281                    from,
4282                ],
4283            )
4284            .await?;
4285        }
4286    }
4287    crate::worktree_setup::prepare_with(
4288        &state.config,
4289        &state.repo,
4290        &winner.worktree,
4291        crate::build_target::Coordination::Held(_coordination.as_ref()),
4292    )
4293    .await?;
4294    state.land_rebase_from = None;
4295    state.save()?;
4296    Ok(())
4297}
4298
4299async fn rebase_landing_worktree(
4300    state: &mut RunState,
4301    onto: &str,
4302) -> Result<crate::rebase::Rebased> {
4303    restore_landing_worktree(state).await?;
4304    let winner = state.winner().cloned().context("landing has no winner")?;
4305    let scratch = state.dir().join("rebase");
4306    let target = match state.land_sync_target.clone() {
4307        Some(target) => {
4308            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4309            target
4310        }
4311        // Older records lack the target checkpoint, but Git retains the
4312        // exact target of an interrupted operation. It is a continuation too.
4313        None if crate::rebase::checked_progress(state, &scratch, "").await? => {
4314            crate::rebase::rebase_target(&scratch).await?
4315        }
4316        None => {
4317            if state.land_sync_attempts >= state.land_sync_budget() {
4318                let head = git::rev_parse(&winner.worktree, "HEAD")
4319                    .await
4320                    .unwrap_or_default();
4321                let tip = git::rev_parse(&state.repo, onto).await.unwrap_or_default();
4322                let pr_head = state.pr_pushed_head.clone().unwrap_or_else(|| head.clone());
4323                state.land_sync_pending = true;
4324                state.record_land_sync_exhausted_stop(&head, &pr_head, &tip);
4325                let _ = state.save();
4326                bail!("{}", crate::land_sync_recovery::EXHAUSTED_DETAIL);
4327            }
4328            let target = git::rev_parse(&state.repo, onto).await?;
4329            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4330            state.land_sync_attempts += 1;
4331            state.land_sync_target = Some(target.clone());
4332            target
4333        }
4334    };
4335    state.land_sync_target = Some(target.clone());
4336    state.land_sync_pending = true;
4337    state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4338    state.save()?;
4339    // A continuation owns the attempt already charged above, including a
4340    // crash before the scratch rebase started. Finish its pinned base first;
4341    // a newer base must use another attempt on the next observation.
4342    let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4343    state.land_sync_target = None;
4344    state.save()?;
4345    if result == crate::rebase::Rebased::Applied {
4346        restore_landing_worktree(state).await?;
4347    }
4348    Ok(result)
4349}
4350
4351/// Reconcile a stopped landing before changing its branch. This also handles
4352/// old records whose graph status or merge detail no longer identifies land.
4353async fn resume_landing_head<F: Forge>(
4354    state: &mut RunState,
4355    observed: &str,
4356    pr_url: &str,
4357    forge: &F,
4358    reason: Option<Blocking>,
4359) -> Result<String> {
4360    crate::pr_head::ensure_owner(state)?;
4361    let winner = state.winner().cloned().context("landing has no winner")?;
4362    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4363    let expected = state
4364        .pr_pushed_head
4365        .as_deref()
4366        .or(state.gate_head.as_deref())
4367        .context("missing public head lease")?;
4368    anyhow::ensure!(
4369        observed == expected
4370            || (observed == local
4371                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4372                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4373        "public head moved outside this run; refusing to sync"
4374    );
4375    // An operator may have extended and published the winner while approval
4376    // was pending. Matching local/public history can be adopted as the lease,
4377    // but publish_landing_head must gate its new SHA before proceeding. A
4378    // remote-only or divergent update still cannot be overwritten.
4379    // Save reconciliation before rebasing again; a prior push may have reached
4380    // the remote immediately before the previous driver's last save.
4381    state.pr_pushed_head = Some(observed.to_owned());
4382    state.save()?;
4383    restore_landing_worktree(state).await?;
4384    // Recover a rebase that finished before its completion checkpoint was
4385    // saved. Restoration above has already reconciled its files and ancestry.
4386    let scratch = state.dir().join("rebase");
4387    if let Some(target) = state.land_sync_target.clone()
4388        && !crate::rebase::checked_progress(state, &scratch, "").await?
4389        && git::ancestry(&winner.worktree, &target, &local).await?
4390    {
4391        state.land_sync_target = None;
4392        state.save()?;
4393    }
4394    let remote = state.config.merge.remote.clone();
4395    let base = state.base_branch.clone();
4396    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4397    anyhow::ensure!(
4398        fetched.ok(),
4399        "cannot fetch landing base: {}",
4400        fetched.stderr
4401    );
4402    anyhow::ensure!(
4403        !owner_requested_stop(state)?,
4404        "owner requested stop before base synchronization"
4405    );
4406    let onto = format!("{remote}/{base}");
4407    let tip = git::rev_parse(&state.repo, &onto).await?;
4408    if state.land_sync_unstarted_grant() {
4409        let auth = state
4410            .land_sync_recovery
4411            .authorizations
4412            .last()
4413            .context("missing recovery grant")?;
4414        anyhow::ensure!(
4415            auth.invalidated.is_none()
4416                && git::ancestry(&state.repo, &auth.scope.tip, &tip).await?
4417                && git::ancestry(&state.repo, &auth.stop.tip, &tip).await?,
4418            "fetched landing base is outside the authorized recovery lineage"
4419        );
4420    }
4421    let contains_base = git::ancestry(&state.repo, &tip, &local)
4422        .await
4423        .context("could not determine whether the landing head contains the fetched base")?;
4424    anyhow::ensure!(
4425        reason != Some(Blocking::Behind) || !contains_base,
4426        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4427    );
4428    if !contains_base || reason == Some(Blocking::Conflict) {
4429        match rebase_landing_worktree(state, &tip).await? {
4430            crate::rebase::Rebased::Applied => {}
4431            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4432        }
4433    }
4434    if reason == Some(Blocking::Behind) {
4435        anyhow::ensure!(
4436            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4437            "BEHIND synchronization left the head unchanged"
4438        );
4439    }
4440    publish_landing_head(state, observed, pr_url, forge).await
4441}
4442
4443/// Share the synchronization path with structured evidence retained after a refusal.
4444async fn synchronize_landing<F: Forge>(
4445    state: &mut RunState,
4446    pr: &mut PrState,
4447    observed: &str,
4448    pr_url: &str,
4449    forge: &F,
4450) -> Result<Option<String>> {
4451    if owner_stop(state, pr, forge).await? {
4452        return Ok(None);
4453    }
4454    state.event(
4455        "land",
4456        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4457    );
4458    state.save()?;
4459    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4460    if owner_stop(state, pr, forge).await? {
4461        return Ok(None);
4462    }
4463    match synced {
4464        Ok(head) => {
4465            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4466                crate::graph::refresh_reviewed_commits(state, &branch).await;
4467            }
4468            Ok(Some(head))
4469        }
4470        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4471        Err(e) => {
4472            let repo = state.repo.clone();
4473            stop(
4474                state,
4475                &repo,
4476                pr,
4477                &format!("could not synchronize landing base: {e:#}"),
4478            )
4479            .await?;
4480            Ok(None)
4481        }
4482    }
4483}
4484
4485enum LandSyncPrep {
4486    Continue(Option<Seen>),
4487    Stop(PrState),
4488}
4489
4490/// Revalidate and durably consume a pending landing base-sync recovery
4491/// authorization under the live execution lease before mutating landing status
4492/// or adopting any observed PR head.
4493async fn prepare_land_sync_recovery<F: Forge>(
4494    state: &mut RunState,
4495    pr_url: &str,
4496    forge: &F,
4497) -> Result<LandSyncPrep> {
4498    let has_unconsumed = state.has_unconsumed_land_sync_authorization();
4499    let unstarted = state.land_sync_unstarted_grant();
4500    let exhausted = state.land_sync_exhausted();
4501    if !has_unconsumed && !exhausted && !unstarted {
4502        return Ok(LandSyncPrep::Continue(None));
4503    }
4504    let repo = state.repo.clone();
4505    let seen = forge.view(&repo, pr_url).await?;
4506    if seen.pr.state != PrLifecycle::Open {
4507        anyhow::ensure!(
4508            state
4509                .pr
4510                .as_ref()
4511                .is_some_and(|pr| pr.url == seen.pr.url && pr.number == seen.pr.number),
4512            "terminal pull request does not match the retained run"
4513        );
4514        return Ok(LandSyncPrep::Continue(Some(seen)));
4515    }
4516    if !has_unconsumed && !unstarted {
4517        bail!(
4518            "{}; explicit recover-land-sync authorization required",
4519            crate::land_sync_recovery::EXHAUSTED_DETAIL
4520        );
4521    }
4522    let observed = crate::land_sync_recovery::ObservedPr {
4523        url: seen.pr.url.clone(),
4524        number: seen.pr.number,
4525        open: seen.pr.state == PrLifecycle::Open,
4526        head: seen.head.clone(),
4527        base_branch: (!seen.base.is_empty()).then(|| seen.base.clone()),
4528    };
4529    let home = crate::run::home();
4530    let validation = if owner_requested_stop(state)? {
4531        Err("owner requested stop before landing base-sync recovery".into())
4532    } else {
4533        crate::land_sync_recovery::validate_pending_authorization(
4534            &home,
4535            state,
4536            None,
4537            Some(&observed),
4538            &crate::land_sync_recovery::GhPrObserver,
4539        )
4540        .await
4541    };
4542    match validation {
4543        Ok((local_head, pr_head)) => {
4544            if unstarted {
4545                return Ok(LandSyncPrep::Continue(Some(seen)));
4546            }
4547            if let Err(reason) = state.consume_land_sync_recovery(&local_head, &pr_head) {
4548                state.status = RunStatus::Blocked;
4549                state.event("land-sync-recovery", format!("refused: {reason}"));
4550                state.save()?;
4551                return Ok(LandSyncPrep::Stop(seen.pr));
4552            }
4553            state.event(
4554                "land-sync-recovery",
4555                format!(
4556                    "consumed recovery grant {}/{}: authorized {} landing sync attempt ({}/{}); prior verification archived, fresh E2E and gate required",
4557                    state.land_sync_recovery.extra_attempts,
4558                    crate::land_sync_recovery::MAX_GRANTS,
4559                    crate::land_sync_recovery::GRANT_ATTEMPTS,
4560                    state.land_sync_attempts,
4561                    state.land_sync_budget()
4562                ),
4563            );
4564            state.save()?;
4565            Ok(LandSyncPrep::Continue(Some(seen)))
4566        }
4567        Err(failure) => {
4568            let reason = failure.reason;
4569            if !failure.observation_failed
4570                && let Some(auth) = state
4571                    .land_sync_recovery
4572                    .authorizations
4573                    .iter_mut()
4574                    .rev()
4575                    .find(|a| {
4576                        a.invalidated.is_none()
4577                            && (!a.consumed || unstarted && a.archived_verification.is_some())
4578                    })
4579            {
4580                auth.refuse(&reason);
4581            }
4582            state.status = RunStatus::Blocked;
4583            state.event("land-sync-recovery", format!("refused: {reason}"));
4584            state.save()?;
4585            Ok(LandSyncPrep::Stop(seen.pr))
4586        }
4587    }
4588}
4589
4590async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4591    crate::pr_head::ensure_owner(state)?;
4592    let mut initial_seen = match prepare_land_sync_recovery(state, pr_url, forge).await? {
4593        LandSyncPrep::Continue(seen) => seen,
4594        LandSyncPrep::Stop(pr) => return Ok(pr),
4595    };
4596    state.land_unrelated = None;
4597    let reopening_hold = crate::merge_decision::resumable_hold(state);
4598    let repo = state.repo.clone();
4599    let budget = state.config.graph.land_rounds;
4600    let mut round = 0usize;
4601    let ci = state.config.merge.ci.expectation();
4602    if ci == CiExpectation::Absent {
4603        state.event(
4604            "land",
4605            "CI not expected ([merge] ci = \"none\"); check status ignored",
4606        );
4607    }
4608    let mut waited = Duration::ZERO;
4609    // Comment bodies the fixer has already been shown. A comment is
4610    // outstanding until it has been handed over once; after that it is a
4611    // recorded decision, not an open question, and re-feeding it would loop the
4612    // budget away on a comment the fixer already declined with an argument.
4613    let mut shown: BTreeSet<String> = BTreeSet::new();
4614    // Await the last successfully published head, including across resumes.
4615    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4616    // Whether a settled-checks refusal has already been given its one re-look.
4617    let mut rechecked = false;
4618
4619    // Marks the run resumable through exactly this function, not through a
4620    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4621    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4622    // status specifically to know a resumed run belongs back in `land`
4623    // rather than at a second `gh pr create`. Set on every entry - fresh or
4624    // resumed - because a resume that parked here again must keep reading
4625    // `Landing`, not whatever a first pass through `merge` left behind.
4626    state.status = RunStatus::Landing;
4627    state.event("land", format!("watching {pr_url}"));
4628    state.save()?;
4629
4630    // An armed merge recorded by an earlier pass may or may not have reached
4631    // the forge (the record is written before the call). It is taken back on
4632    // the first observation, where a pull request is known to stop with.
4633    let mut resumed_armed = state.land_armed_head.is_some();
4634
4635    'landing: loop {
4636        let seen = match initial_seen.take() {
4637            Some(seen) => seen,
4638            None => forge.view(&repo, pr_url).await?,
4639        };
4640        let mut pr = seen.pr.clone();
4641        pr.review_comments.retain(|c| !shown.contains(&c.body));
4642        state.pr = Some(crate::run::PrRecord {
4643            url: pr.url.clone(),
4644            number: pr.number,
4645            state: pr.state.as_str().to_owned(),
4646            checks: pr.checks.as_str().to_owned(),
4647            round,
4648            rounds: budget,
4649            red_at_merge: Vec::new(),
4650        });
4651        state.save()?;
4652
4653        if pr.state == PrLifecycle::Open {
4654            state.observe_branch_owner_holds(&seen.head).await;
4655            state.save()?;
4656        }
4657        crate::pr_head::ensure_owner(state)?;
4658        if reopening_hold {
4659            anyhow::ensure!(
4660                pr.state == PrLifecycle::Open,
4661                "held PR is no longer open; cannot request a fresh decision"
4662            );
4663            // An explicit resume authorizes a fresh question only. Preserve the
4664            // answered card, and never enter repair/rebase/merge on this pass.
4665            disarm(forge, state, &repo, pr.number)
4666                .await
4667                .map_err(anyhow::Error::msg)?;
4668            let previous = state.merge_decision.take();
4669            let binding = state.land_approval.take();
4670            state.config.graph.land_approval = true;
4671            let subject = merge_subject(
4672                crate::graph::landing_title(state, &seen.title),
4673                &crate::graph::landing_subject_source(state),
4674            );
4675            let contested = contested_to_ask(state);
4676            if let Err(error) =
4677                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4678            {
4679                state.merge_decision = previous;
4680                state.land_approval = binding;
4681                return Err(error);
4682            }
4683            state.end_pass_parked(crate::run::ParkCause::Question);
4684            state.parked = true;
4685            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()));
4686            state.save()?;
4687            return Ok(pr);
4688        }
4689        if owner_stop(state, &mut pr, forge).await? {
4690            return Ok(pr);
4691        }
4692
4693        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4694            // An approval already given for the same head is reused, so
4695            // nothing is asked twice. A failed disable
4696            // stops the run with the record kept: pushing on could change the
4697            // head under an arm that is still live.
4698            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4699                let why = format!(
4700                    "a previous pass may have armed auto-merge and it could not be disabled \
4701                     on resume: {e}"
4702                );
4703                stop(state, &repo, &pr, &why).await?;
4704                return Ok(pr);
4705            }
4706        }
4707
4708        // The head moved away from the one auto-merge was armed on, by
4709        // someone other than this loop. The arm is pinned and would refuse to
4710        // merge the new commit, but the approval was for the old one: take it
4711        // back and go through the normal path again.
4712        if pr.state == PrLifecycle::Open
4713            && !seen.head.is_empty()
4714            && state
4715                .land_armed_head
4716                .as_deref()
4717                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4718        {
4719            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4720                let why = format!(
4721                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4722                );
4723                stop(state, &repo, &pr, &why).await?;
4724                return Ok(pr);
4725            }
4726        }
4727
4728        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4729            // Disarming can outlive an owner answer. Consume it before our
4730            // own rebase invalidates the head shown on the decision card.
4731            if owner_stop(state, &mut pr, forge).await? {
4732                return Ok(pr);
4733            }
4734            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4735                binding.head.eq_ignore_ascii_case(&seen.head)
4736                    && ask::Questions::open()
4737                        .get_for_effects(&binding.question)
4738                        .is_ok_and(|q| {
4739                            q.run == state.id
4740                                && q.node == APPROVAL_NODE
4741                                && q.status == ask::QuestionStatus::Answered
4742                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4743                        })
4744            });
4745            if repair_answer {
4746                let subject = merge_subject(
4747                    crate::graph::landing_title(state, &seen.title),
4748                    &crate::graph::landing_subject_source(state),
4749                );
4750                let contested = contested_to_ask(state);
4751                if matches!(
4752                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4753                    ApprovalGate::Repair
4754                ) {
4755                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4756                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4757                        state.save()?;
4758                    }
4759                    return Ok(pr);
4760                }
4761            }
4762            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4763            // A stop detected before publication must apply its durable
4764            // decision, even when verification returned an error meanwhile.
4765            if owner_stop(state, &mut pr, forge).await? {
4766                return Ok(pr);
4767            }
4768            let head = synced?;
4769            awaiting_head = Some(head);
4770            waited = Duration::ZERO;
4771            rechecked = false;
4772            // Read CI and approvals afresh, never from the pre-push observation.
4773            continue;
4774        }
4775
4776        // A stale base is independent of the CI rollup. Keep the public-head
4777        // lease, but synchronize before waiting for checks on the old tree.
4778        if pr.state == PrLifecycle::Open
4779            && pr.blocking == Blocking::Behind
4780            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4781        {
4782            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4783            let Some(head) = synced else {
4784                return Ok(pr);
4785            };
4786            awaiting_head = Some(head);
4787            rechecked = false;
4788            waited = Duration::ZERO;
4789            continue;
4790        }
4791
4792        if pr.state == PrLifecycle::Open {
4793            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4794                if waited >= WAIT_CEILING {
4795                    let want = awaiting_head.as_deref().unwrap_or_default();
4796                    let why = format!(
4797                        "the pull request's checks were still not about one readable head after \
4798                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4799                         someone may have pushed over it",
4800                        WAIT_CEILING.as_secs() / 60,
4801                        if want.is_empty() { "any" } else { want },
4802                        if seen.head.is_empty() {
4803                            "nothing readable"
4804                        } else {
4805                            &seen.head
4806                        },
4807                        if seen.rollup_head.is_empty() {
4808                            "nothing readable"
4809                        } else {
4810                            &seen.rollup_head
4811                        },
4812                    );
4813                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4814                    return Ok(pr);
4815                }
4816                waited += POLL;
4817                forge.poll().await;
4818                continue;
4819            }
4820            // Reset once, when the awaited head first shows up; resetting on
4821            // every re-observation would let a standing refusal wait forever.
4822            if awaiting_head.take().is_some() {
4823                // The checks now being read belong to the new head; give them
4824                // the same grace a fresh pull request gets.
4825                waited = Duration::ZERO;
4826            }
4827        }
4828
4829        // The merge-state grace is head-bound and durable. Reruns reset the
4830        // checks clock, but must not extend this deadline across resumes.
4831        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4832            let first = state
4833                .land_unsaid
4834                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4835            if !first.0.eq_ignore_ascii_case(&seen.head) {
4836                *first = (seen.head.clone(), forge.now());
4837            }
4838            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4839            state.save()?;
4840            elapsed
4841        } else {
4842            waited
4843        };
4844        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4845        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4846            if waited >= WAIT_CEILING {
4847                stop_disarmed(
4848                    forge,
4849                    state,
4850                    &repo,
4851                    &pr,
4852                    "merge state remained unreadable; refusing to merge on a guess",
4853                )
4854                .await?;
4855                return Ok(pr);
4856            }
4857            waited += POLL;
4858            forge.poll().await;
4859            continue;
4860        }
4861
4862        // A failed workflow run is rerun once, judged by its own run rather
4863        // than by the rollup's aggregate: another run still pending, or a fix
4864        // budget already spent, must not keep a flaky failure from its one
4865        // rerun. It spends no round and no attempt.
4866        if ci == CiExpectation::Expected
4867            && pr.state == PrLifecycle::Open
4868            && state.config.graph.rerun_flaky_checks
4869        {
4870            let include_optional = pr.checks == Checks::Red
4871                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4872            let failing = rerunnable_with(&seen.contexts, include_optional);
4873            let now = forge.now();
4874            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4875                RerunStep::Rerun(runs) => {
4876                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4877                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4878                        *rec = LandReruns {
4879                            head: seen.head.clone(),
4880                            runs: BTreeMap::new(),
4881                        };
4882                    }
4883                    for run in &runs {
4884                        rec.runs.insert(run.clone(), now);
4885                    }
4886                    // Durable before the call: a restart must not
4887                    // rerun the same run twice. A save that fails
4888                    // means no rerun.
4889                    state.save()?;
4890                    let mut any = false;
4891                    for run in &runs {
4892                        let names = failing
4893                            .iter()
4894                            .filter(|(_, r)| r.as_deref() == Some(run))
4895                            .map(|(l, _)| l.as_str())
4896                            .collect::<Vec<_>>()
4897                            .join(", ");
4898                        match forge.rerun(&repo, run).await {
4899                            Ok(()) => {
4900                                any = true;
4901                                state.event(
4902                                    "land",
4903                                    format!("reran failed check(s) {names} (run {run})"),
4904                                );
4905                            }
4906                            // Stays recorded: never a retry loop.
4907                            Err(e) => state.event(
4908                                "land",
4909                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4910                            ),
4911                        }
4912                    }
4913                    state.save()?;
4914                    if any {
4915                        waited = Duration::ZERO;
4916                        forge.poll().await;
4917                        continue;
4918                    }
4919                }
4920                RerunStep::Grace => {
4921                    if waited >= WAIT_CEILING {
4922                        let why = format!(
4923                            "checks were still failing after a rerun and {} minutes",
4924                            WAIT_CEILING.as_secs() / 60
4925                        );
4926                        stop(state, &repo, &pr, &why).await?;
4927                        return Ok(pr);
4928                    }
4929                    waited += POLL;
4930                    forge.poll().await;
4931                    continue;
4932                }
4933                RerunStep::Fix => {}
4934            }
4935        }
4936
4937        let step = proposed;
4938        // Armed on exactly this head: the forge is doing the waiting. A
4939        // decision to merge (or keep waiting) is only watched, never re-armed
4940        // and never re-approved; anything else - a red check, a comment, a
4941        // conflict - falls through to its own arm, which disarms first.
4942        let armed_here = state
4943            .land_armed_head
4944            .as_deref()
4945            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4946        if armed_here && matches!(step, Step::Merge | Step::Wait) {
4947            if waited >= WAIT_CEILING {
4948                let required = if seen.base.is_empty() {
4949                    None
4950                } else {
4951                    forge.required_contexts(&repo, &seen.base).await
4952                };
4953                let why = format!(
4954                    "auto-merge was armed on {} but the pull request did not merge within {} \
4955                     minutes ({})",
4956                    seen.head,
4957                    WAIT_CEILING.as_secs() / 60,
4958                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4959                );
4960                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4961                return Ok(pr);
4962            }
4963            waited += POLL;
4964            forge.poll().await;
4965            continue;
4966        }
4967        if armed_here && !matches!(step, Step::Done { .. }) {
4968            // Not merging or waiting any more: whatever is next may change the
4969            // head or give up, and neither may leave the arm standing.
4970            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4971                let why = format!("auto-merge could not be disabled: {e}");
4972                stop(state, &repo, &pr, &why).await?;
4973                return Ok(pr);
4974            }
4975        }
4976        if pr.checks == Checks::Red
4977            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4978            && pr.review_comments.is_empty()
4979            && let Some(evidence) = forge.attribution(state, &seen).await
4980            && evidence.unrelated(&seen.head, &pr.failing)
4981        {
4982            if owner_stop(state, &mut pr, forge).await? {
4983                return Ok(pr);
4984            }
4985            // Attribution does not authorize action against an unseen push.
4986            let fresh = forge.view(&repo, pr_url).await?;
4987            if fresh.head != seen.head
4988                || fresh.rollup_head != seen.rollup_head
4989                || fresh.pr.state != PrLifecycle::Open
4990                || fresh.pr.checks != Checks::Red
4991                || fresh.pr.failing != pr.failing
4992                || fresh
4993                    .pr
4994                    .review_comments
4995                    .iter()
4996                    .any(|c| !shown.contains(&c.body))
4997            {
4998                continue;
4999            }
5000            hold_unrelated(state, &pr, evidence).await?;
5001            return Ok(pr);
5002        }
5003        match step {
5004            Step::Wait => {
5005                if waited >= WAIT_CEILING {
5006                    let why = format!(
5007                        "checks were still running after {} minutes",
5008                        WAIT_CEILING.as_secs() / 60
5009                    );
5010                    stop(state, &repo, &pr, &why).await?;
5011                    return Ok(pr);
5012                }
5013                waited += POLL;
5014                forge.poll().await;
5015            }
5016            Step::Done { merged } => {
5017                if merged {
5018                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
5019                }
5020                // Auto-merge is pinned to the approved head, but the forge's
5021                // own handling of a later push is not something magi can
5022                // see: if the pull request merged on another commit, say so
5023                // loudly rather than record a clean landing.
5024                if let Some(armed) = state.land_armed_head.take() {
5025                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
5026                        let msg = format!(
5027                            "{} merged on {} but the owner approved {armed}; review what landed",
5028                            pr.url, seen.head
5029                        );
5030                        tracing::warn!("{msg}");
5031                        state.event("land", msg);
5032                        // Only an arm left by an older build can get here.
5033                        // The wording is fixed so a repeat does not relight
5034                        // the notice.
5035                        crate::notices::raise_with(
5036                            crate::notices::Notice::warn(
5037                                &format!("merged-unapproved-head:{}", state.id),
5038                                "A pull request merged on a commit the owner did not approve; \
5039                                 review what landed",
5040                            )
5041                            .link(crate::notices::Link::Run {
5042                                id: state.id.clone(),
5043                            }),
5044                            &state.config.notify,
5045                        );
5046                    }
5047                }
5048                state.status = if merged {
5049                    RunStatus::Merged
5050                } else {
5051                    RunStatus::Ready
5052                };
5053                let detail = if merged {
5054                    format!("{} was merged", pr.url)
5055                } else {
5056                    format!("{} was closed without merging", pr.url)
5057                };
5058                state.merge = Some(MergeOutcome {
5059                    mode: MergeMode::Pr,
5060                    ok: merged,
5061                    detail: detail.clone(),
5062                    empty: false,
5063                });
5064                state.event("land", detail);
5065                state.save()?;
5066                write_pr_state_through(state, pr.state);
5067                return Ok(pr);
5068            }
5069            Step::Merge => {
5070                state.check_delivery_evidence(&seen.head)?;
5071                let subject = merge_subject(
5072                    crate::graph::landing_title(state, &seen.title),
5073                    &crate::graph::landing_subject_source(state),
5074                );
5075                // The owner sees the panel before the one irreversible step,
5076                // and an unanswered question is a hold: silence never merges.
5077                //
5078                // The dedicated policy includes existing consent and post-repair
5079                // decisions; repair choice availability never grants merge authority.
5080                let contested = contested_to_ask(state);
5081                if !approval_reasons(state).is_empty() {
5082                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
5083                        .await?
5084                    {
5085                        ApprovalGate::Approved => {}
5086                        ApprovalGate::Repair => {
5087                            // The driver consumes the saved request under the existing
5088                            // run/task claim. No merge, no second run or task.
5089                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
5090                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
5091                                state.save()?;
5092                            }
5093                            return Ok(pr);
5094                        }
5095                        ApprovalGate::Held => {
5096                            // Another entry point may have saved a stop after
5097                            // the first read above. Apply its durable action.
5098                            if owner_stop(state, &mut pr, forge).await? {
5099                                return Ok(pr);
5100                            }
5101                            stop(
5102                                state,
5103                                &repo,
5104                                &pr,
5105                                "the owner did not approve the merge (held or unanswered)",
5106                            )
5107                            .await?;
5108                            return Ok(pr);
5109                        }
5110                        // Filed (or still standing from an earlier visit) and
5111                        // not yet answered. Park here rather than wait: the
5112                        // question survives on disk, the daemon hands this
5113                        // run's slot to something else, and a later resume
5114                        // re-enters `land`, finds the same question, and
5115                        // either merges or stops depending on what it says
5116                        // by then.
5117                        ApprovalGate::Pending => {
5118                            state.end_pass_parked(crate::run::ParkCause::Question);
5119                            state.parked = true;
5120                            state.event(
5121                                "land",
5122                                "parked awaiting merge approval - resumes once answered",
5123                            );
5124                            state.save()?;
5125                            return Ok(pr);
5126                        }
5127                    }
5128                }
5129                // Open and past the gate above, so `seen.head` is the commit
5130                // the checks were bound to and the owner approved.
5131                //
5132                // Merge directly, bound to that commit. Auto-merge is not
5133                // armed any more: the forge checks `--match-head-commit` only
5134                // when the request is made, so an arm outlives the head it
5135                // was made for, and a push of another commit whose
5136                // requirements are met first would merge without approval.
5137                // A direct merge is checked by the forge at the moment it
5138                // happens, so only the approved head can land.
5139                let observed_head = seen.head.clone();
5140                // Read the pull request again just before: the state seen
5141                // above can be a moment old.
5142                {
5143                    let fresh = forge.view(&repo, pr_url).await.ok();
5144                    if fresh.as_ref().is_some_and(|current| {
5145                        current.pr.state == PrLifecycle::Open
5146                            && current.head.eq_ignore_ascii_case(&observed_head)
5147                            && Blocking::of(&current.merge_state) == Blocking::Behind
5148                    }) {
5149                        pr.blocking = Blocking::Behind;
5150                        let synced =
5151                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5152                                .await?;
5153                        let Some(head) = synced else {
5154                            return Ok(pr);
5155                        };
5156                        awaiting_head = Some(head);
5157                        rechecked = false;
5158                        waited = Duration::ZERO;
5159                        continue 'landing;
5160                    }
5161                    if !direct_merge_is_safe(
5162                        fresh.as_ref(),
5163                        &observed_head,
5164                        &shown,
5165                        round,
5166                        budget,
5167                        waited,
5168                        ci,
5169                    ) {
5170                        if waited >= WAIT_CEILING {
5171                            let why = "the pull request did not settle on the approved head \
5172                                       before it could be merged";
5173                            stop(state, &repo, &pr, why).await?;
5174                            return Ok(pr);
5175                        }
5176                        state.event(
5177                            "land",
5178                            "the pull request changed before merging; looking again",
5179                        );
5180                        waited += POLL;
5181                        forge.poll().await;
5182                        continue;
5183                    }
5184                }
5185                let argv = merge_argv_at(pr.number, &subject, &observed_head);
5186                let out = {
5187                    let merge_lock = repo_merge_lock(&repo);
5188                    let _merge_slot = merge_lock.lock().await;
5189                    crate::pr_head::ensure_owner(state)?;
5190                    if let Some(task_id) = state
5191                        .origin
5192                        .as_ref()
5193                        .and_then(|origin| origin.task.as_ref())
5194                    {
5195                        let task = crate::queue::Queue::open()
5196                            .get(task_id)
5197                            .context("cannot verify the task owner immediately before merge")?;
5198                        if task.execution_runs().last() != Some(&state.id)
5199                            || task.operator_held()
5200                            || task.status == crate::queue::TaskStatus::Done
5201                        {
5202                            bail!(
5203                                "task ownership or an operator hold superseded this merge approval"
5204                            );
5205                        }
5206                    }
5207                    if let Some(binding) = &state.land_approval {
5208                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
5209                        if merge_consent_superseded(state, &current)?
5210                            || current.run != state.id
5211                            || !binding.head.eq_ignore_ascii_case(&observed_head)
5212                            || approval(current.resolution().as_deref()) != Approval::Merge
5213                            || current.merge_target.as_ref().is_some_and(|t| {
5214                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
5215                            })
5216                        {
5217                            bail!(
5218                                "merge decision is stale or no longer authorizes the reviewed head"
5219                            );
5220                        }
5221                    }
5222                    forge.merge(&repo, &argv).await?
5223                };
5224                if out.0 {
5225                    // Exit 0 is not proof of a merge: with a merge queue `gh`
5226                    // enqueues (or reports the pull request already queued)
5227                    // and succeeds while it is still open. Ask the forge; an
5228                    // unreadable answer is not a confirmation either, so it
5229                    // is looked at again rather than recorded as merged.
5230                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
5231                        if c.pr.state == PrLifecycle::Merged {
5232                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
5233                            true
5234                        } else {
5235                            false
5236                        }
5237                    });
5238                    if !confirmed {
5239                        if waited >= WAIT_CEILING {
5240                            let why = "the merge request succeeded but the pull request \
5241                                       could not be confirmed merged after waiting";
5242                            stop(state, &repo, &pr, why).await?;
5243                            return Ok(pr);
5244                        }
5245                        state.event(
5246                            "land",
5247                            "merge accepted but the pull request is not confirmed merged yet; waiting",
5248                        );
5249                        state.save()?;
5250                        waited += POLL;
5251                        forge.poll().await;
5252                        continue;
5253                    }
5254                    pr.state = PrLifecycle::Merged;
5255                    state.status = RunStatus::Merged;
5256                    state.merge = Some(MergeOutcome {
5257                        mode: MergeMode::Pr,
5258                        ok: true,
5259                        detail: format!("gh {}", argv.join(" ")),
5260                        empty: false,
5261                    });
5262                    // The last `state.pr` snapshot is whatever the poll before
5263                    // this merge observed - still `open` - and nothing below
5264                    // refreshes it from GitHub again, so the UI's round rail
5265                    // would otherwise keep animating a merged run forever.
5266                    if let Some(pr_record) = state.pr.as_mut() {
5267                        pr_record.state = pr.state.as_str().to_owned();
5268                    }
5269                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5270                    announce_red_merge(state, &pr).await;
5271                    state.save()?;
5272                    write_pr_state_through(state, pr.state);
5273                    return Ok(pr);
5274                }
5275                let after_seen = forge.view(&repo, pr_url).await.ok();
5276                let after = after_seen.as_ref().map(|s| s.pr.state);
5277                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
5278                    state.pr_merged_head = after_seen
5279                        .as_ref()
5280                        .map(|s| s.head.clone())
5281                        .filter(|h| !h.is_empty());
5282                    pr.state = PrLifecycle::Merged;
5283                    state.status = RunStatus::Merged;
5284                    state.merge = Some(outcome);
5285                    if let Some(pr_record) = state.pr.as_mut() {
5286                        pr_record.state = pr.state.as_str().to_owned();
5287                    }
5288                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5289                    announce_red_merge(state, &pr).await;
5290                    state.save()?;
5291                    write_pr_state_through(state, pr.state);
5292                    return Ok(pr);
5293                }
5294                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
5295                match verdict {
5296                    Refused::Behind => {
5297                        pr.blocking = Blocking::Behind;
5298                        let synced =
5299                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5300                                .await?;
5301                        let Some(head) = synced else {
5302                            return Ok(pr);
5303                        };
5304                        awaiting_head = Some(head);
5305                        rechecked = false;
5306                        waited = Duration::ZERO;
5307                        continue 'landing;
5308                    }
5309                    Refused::Final => {
5310                        let merge_state = after_seen
5311                            .as_ref()
5312                            .map(|s| s.merge_state.as_str())
5313                            .filter(|m| !m.is_empty())
5314                            .unwrap_or("unknown");
5315                        // Which refusal this was decides what a person has to
5316                        // do about it, so the two are worded apart; both carry
5317                        // the forge's own message.
5318                        let why = format!(
5319                            "the merge was refused: {} (merge state: {merge_state})",
5320                            out.1
5321                        );
5322                        stop(state, &repo, &pr, &why).await?;
5323                        return Ok(pr);
5324                    }
5325                    verdict => {
5326                        // Back to the top, which re-decides and passes the
5327                        // approval gate again, a poll later. `waited` is not
5328                        // reset here: only a pushed fix restarts it, or a
5329                        // standing refusal would wait forever.
5330                        if waited >= WAIT_CEILING {
5331                            let why = format!(
5332                                "the merge was still refused after {} minutes: {}",
5333                                WAIT_CEILING.as_secs() / 60,
5334                                out.1
5335                            );
5336                            stop(state, &repo, &pr, &why).await?;
5337                            return Ok(pr);
5338                        }
5339                        if verdict == Refused::Recheck {
5340                            rechecked = true;
5341                        }
5342                        state.event(
5343                            "land",
5344                            "merge refused while the branch policy is not satisfied yet; waiting",
5345                        );
5346                        state.save()?;
5347                        waited += POLL;
5348                        forge.poll().await;
5349                    }
5350                }
5351            }
5352            Step::Rebase => {
5353                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
5354                let Some(head) = synced else {
5355                    return Ok(pr);
5356                };
5357                awaiting_head = Some(head);
5358                rechecked = false;
5359                waited = Duration::ZERO;
5360                continue 'landing;
5361            }
5362            Step::GiveUp { reason } => {
5363                stop(state, &repo, &pr, &reason).await?;
5364                return Ok(pr);
5365            }
5366            Step::Fix { reason } => {
5367                round += 1;
5368                waited = Duration::ZERO;
5369                for c in &pr.review_comments {
5370                    shown.insert(c.body.clone());
5371                }
5372                state.event("land", format!("round {round}: {reason}"));
5373                state.save()?;
5374
5375                let logs = failing_logs(&repo, &seen.failing_urls).await;
5376                let was_red = pr.checks == Checks::Red;
5377                if owner_stop(state, &mut pr, forge).await? {
5378                    return Ok(pr);
5379                }
5380                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
5381                if owner_stop(state, &mut pr, forge).await? {
5382                    return Ok(pr);
5383                }
5384                match fixed {
5385                    Fixed::Committed { head } => {
5386                        // Whatever the next look shows may still be the
5387                        // previous head; see `awaiting_new_head`.
5388                        state.pr_pushed_head = Some(head.clone());
5389                        awaiting_head = Some(head);
5390                        rechecked = false;
5391                        waited = Duration::ZERO;
5392                        forge.poll().await;
5393                    }
5394                    Fixed::Declined if was_red => {
5395                        // Review comments may have required this round even
5396                        // when CI was unrelated. Once the fixer has read them,
5397                        // use the same structural attribution before charging
5398                        // a no-commit stop to the task.
5399                        if let Some(evidence) = forge.attribution(state, &seen).await
5400                            && evidence.unrelated(&seen.head, &pr.failing)
5401                        {
5402                            let fresh = forge.view(&repo, pr_url).await?;
5403                            if fresh.head != seen.head
5404                                || fresh.rollup_head != seen.rollup_head
5405                                || fresh.pr.state != PrLifecycle::Open
5406                                || fresh.pr.checks != Checks::Red
5407                                || fresh.pr.failing != pr.failing
5408                                || fresh
5409                                    .pr
5410                                    .review_comments
5411                                    .iter()
5412                                    .any(|c| !shown.contains(&c.body))
5413                            {
5414                                continue;
5415                            }
5416                            if owner_stop(state, &mut pr, forge).await? {
5417                                return Ok(pr);
5418                            }
5419                            hold_unrelated(state, &pr, evidence).await?;
5420                            return Ok(pr);
5421                        }
5422                        let why = format!(
5423                            "the fixer produced no commit while {} check(s) were failing \
5424                             ({}); stopping instead of looping on an unchanged tree",
5425                            pr.failing.len(),
5426                            pr.failing.join(", ")
5427                        );
5428                        stop(state, &repo, &pr, &why).await?;
5429                        return Ok(pr);
5430                    }
5431                    // Comment-driven round with no commit: the fixer read the
5432                    // comments and changed nothing, which is a decision it is
5433                    // allowed to make. The comments are recorded as shown, so
5434                    // the next observation sees a clean pull request.
5435                    Fixed::Declined => state.event(
5436                        "land",
5437                        format!("round {round}: fixer declined the comments, nothing committed"),
5438                    ),
5439                    Fixed::Deferred => {
5440                        // No fixer was available to judge these comments or
5441                        // checks. Keep the previous completed-round count and
5442                        // return without handing the PR off as a task failure.
5443                        state.status = RunStatus::Blocked;
5444                        state.save()?;
5445                        return Ok(pr);
5446                    }
5447                    Fixed::Failed(why) => {
5448                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5449                        return Ok(pr);
5450                    }
5451                }
5452                state.save()?;
5453            }
5454        }
5455    }
5456}
5457
5458/// Owner decision for a CI failure independently reproduced on the base.
5459pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5460
5461/// Durable machine-hold evidence, bound to one observed PR head.
5462#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5463pub struct CiHold {
5464    /// Head that exhibited the independently reproduced failures.
5465    pub head: String,
5466    /// Typed owner question controlling resumption.
5467    pub question: String,
5468    /// Complete structured facts used to attribute the failures.
5469    pub evidence: CiEvidence,
5470}
5471
5472/// Only structured forge annotations are compared, never log prose.
5473#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5474struct CiFailure {
5475    path: String,
5476    start_line: u64,
5477    end_line: u64,
5478    title: String,
5479    message: String,
5480}
5481
5482#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5483struct CiCheckEvidence {
5484    label: String,
5485    head_check: u64,
5486    base_check: u64,
5487    app: u64,
5488    run: String,
5489    base_run: String,
5490    head_failures: Vec<CiFailure>,
5491    base_failures: Vec<CiFailure>,
5492    rerun_exhausted: bool,
5493}
5494
5495/// Pinned Git diff and forge failure annotations used for CI attribution.
5496#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5497pub struct CiEvidence {
5498    head: String,
5499    base: String,
5500    changed: Vec<String>,
5501    checks: Vec<CiCheckEvidence>,
5502}
5503
5504impl CiEvidence {
5505    /// Every red check must have the same located failure on the base, outside
5506    /// the diff. Changes to CI/build configuration invalidate this inference.
5507    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5508        if self.head != head
5509            || self.base.is_empty()
5510            || failing.is_empty()
5511            || self.changed.iter().any(|p| {
5512                p.starts_with(".github/")
5513                    || p.starts_with(".config/")
5514                    || p.starts_with(".cargo/")
5515                    || matches!(
5516                        p.rsplit('/').next().unwrap_or(p),
5517                        "Cargo.toml"
5518                            | "Cargo.lock"
5519                            | "Makefile.toml"
5520                            | "build.rs"
5521                            | "rust-toolchain.toml"
5522                    )
5523            })
5524        {
5525            return false;
5526        }
5527        failing.iter().all(|label| {
5528            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5529            matches.len() == 1
5530                && matches[0].rerun_exhausted
5531                && !matches[0].head_failures.is_empty()
5532                && matches[0].head_failures.iter().all(|f| {
5533                    // Workflow-level exit-code annotations do not identify a
5534                    // failing test or source file, and prove nothing here.
5535                    !f.path.is_empty()
5536                        && !f.path.starts_with('.')
5537                        && !f.path.contains("..")
5538                        && !f.path.starts_with('/')
5539                        && !self.changed.contains(&f.path)
5540                        && matches[0].base_failures.contains(f)
5541                })
5542        })
5543    }
5544}
5545
5546async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5547    let out = gh(repo, &["api".into(), endpoint]).await.ok()?;
5548    if !out.ok {
5549        return None;
5550    }
5551    serde_json::from_str(&out.stdout).ok()
5552}
5553
5554async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5555    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5556    if count == 0 || count >= 100 {
5557        return None;
5558    }
5559    let id = check.get("id")?.as_u64()?;
5560    let value = ci_json(
5561        repo,
5562        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5563    )
5564    .await?;
5565    let annotations = value.as_array()?;
5566    if annotations.len() != count as usize {
5567        return None;
5568    }
5569    annotations
5570        .iter()
5571        .filter(|a| a["annotation_level"] == "failure")
5572        .map(|a| {
5573            Some(CiFailure {
5574                path: a["path"].as_str()?.into(),
5575                start_line: a["start_line"].as_u64()?,
5576                end_line: a["end_line"].as_u64()?,
5577                title: a["title"].as_str()?.into(),
5578                message: a["message"].as_str()?.into(),
5579            })
5580        })
5581        .collect()
5582}
5583
5584async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5585    let value = ci_json(
5586        repo,
5587        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5588    )
5589    .await?;
5590    let runs = value["check_runs"].as_array()?;
5591    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5592        return None;
5593    }
5594    Some(runs.clone())
5595}
5596
5597async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5598    let repo = &state.repo;
5599    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5600    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5601        .await
5602        .ok()?;
5603    if !base.ok() {
5604        return None;
5605    }
5606    let range = format!("{}...{}", base.stdout, seen.head);
5607    // No rename detection: both old and new paths must count as changed.
5608    let diff = git::git_raw(
5609        repo,
5610        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5611    )
5612    .await
5613    .ok()?;
5614    if !diff.ok() {
5615        return None;
5616    }
5617    let head_runs = ci_runs(repo, &seen.head).await?;
5618    let base_runs = ci_runs(repo, &base.stdout).await?;
5619    let mut checks = Vec::new();
5620    for label in &seen.pr.failing {
5621        let matching = |runs: &[serde_json::Value]| {
5622            runs.iter()
5623                .filter(|r| r["name"].as_str() == Some(label))
5624                .cloned()
5625                .collect::<Vec<_>>()
5626        };
5627        let heads = matching(&head_runs);
5628        let bases = matching(&base_runs);
5629        if heads.len() != 1 || bases.len() != 1 {
5630            return None;
5631        }
5632        let h = &heads[0];
5633        let b = &bases[0];
5634        if h["conclusion"] != "failure"
5635            || b["conclusion"] != "failure"
5636            || h["status"] != "completed"
5637            || b["status"] != "completed"
5638            || h["head_sha"].as_str()? != seen.head
5639            || b["head_sha"].as_str()? != base.stdout
5640            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5641        {
5642            return None;
5643        }
5644        let run = run_of(h["details_url"].as_str()?)?;
5645        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5646        if contexts.len() != 1
5647            || contexts[0].run.as_ref() != Some(&run)
5648            || contexts[0].verdict != Verdict::Fail
5649        {
5650            return None;
5651        }
5652        // A persisted request alone is not a completed rerun: require the
5653        // workflow's structured attempt number as well.
5654        let workflow =
5655            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5656        let base_run = run_of(b["details_url"].as_str()?)?;
5657        let base_workflow = ci_json(
5658            repo,
5659            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5660        )
5661        .await?;
5662        if base_workflow["head_sha"].as_str()? != base.stdout
5663            || base_workflow["head_branch"].as_str()? != seen.base
5664            || base_workflow["status"] != "completed"
5665            || base_workflow["conclusion"] != "failure"
5666            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5667        {
5668            return None;
5669        }
5670        let exhausted = state
5671            .land_reruns
5672            .as_ref()
5673            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5674            && workflow["head_sha"].as_str()? == seen.head
5675            && workflow["run_attempt"].as_u64()? > 1
5676            && workflow["status"] == "completed";
5677        checks.push(CiCheckEvidence {
5678            label: label.clone(),
5679            head_check: h["id"].as_u64()?,
5680            base_check: b["id"].as_u64()?,
5681            app: h.pointer("/app/id")?.as_u64()?,
5682            run,
5683            base_run,
5684            head_failures: ci_annotations(repo, h).await?,
5685            base_failures: ci_annotations(repo, b).await?,
5686            rerun_exhausted: exhausted,
5687        });
5688    }
5689    Some(CiEvidence {
5690        head: seen.head.clone(),
5691        base: base.stdout,
5692        changed: diff
5693            .stdout
5694            .split('\0')
5695            .filter(|p| !p.is_empty())
5696            .map(str::to_owned)
5697            .collect(),
5698        checks,
5699    })
5700}
5701
5702async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5703    let detail = serde_json::to_string(&evidence)?;
5704    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5705    let hold = "operator: 保留して後で判断する".to_owned();
5706    let mut q = ask::Question::new(
5707        state.id.clone(),
5708        CI_HOLD_NODE.into(),
5709        "land".into(),
5710        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5711        format!(
5712            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5713        ),
5714        vec![resume.clone(), hold.clone()],
5715    );
5716    q.actions.insert(
5717        resume,
5718        ask::ChoiceAction::Resume {
5719            run: state.id.clone(),
5720        },
5721    );
5722    q.actions.insert(hold, ask::ChoiceAction::Hold);
5723    ask::Questions::open().put_executable(&mut q)?;
5724    state.land_unrelated = Some(CiHold {
5725        head: evidence.head.clone(),
5726        question: q.id.clone(),
5727        evidence,
5728    });
5729    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5730    state.end_pass_parked(crate::run::ParkCause::Question);
5731    state.parked = true;
5732    state.save()?;
5733    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5734        tracing::warn!("could not notify about CI hold: {e:#}");
5735    }
5736    // A durable question and evidence are sufficient even if commenting fails.
5737    let body = stop_comment(
5738        &state.id,
5739        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5740    );
5741    let (_, body) = crate::github_text::prepare(state, "", &body);
5742    gh(
5743        &state.repo,
5744        &[
5745            "pr".into(),
5746            "comment".into(),
5747            pr.number.to_string(),
5748            "--body".into(),
5749            body,
5750        ],
5751    )
5752    .await
5753    .ok();
5754    Ok(())
5755}
5756
5757/// One observation, plus the two things [`PrState`] deliberately does not carry:
5758/// the title (needed for the squash subject) and where the failing checks'
5759/// logs live.
5760#[derive(Clone)]
5761struct Seen {
5762    pr: PrState,
5763    title: String,
5764    failing_urls: Vec<(String, String)>,
5765    /// `headRefOid`: the commit this observation, checks included, is about.
5766    head: String,
5767    /// The commit the checks belong to, read from the same GraphQL node as
5768    /// the checks themselves. Empty when unreadable.
5769    rollup_head: String,
5770    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5771    /// and DRAFT together, and a stop reason has to say which.
5772    merge_state: String,
5773    /// Every check of the rollup, for naming what an armed merge waits on.
5774    contexts: Vec<CheckInfo>,
5775    /// `baseRefName`, to look up which contexts the base requires.
5776    base: String,
5777}
5778
5779/// One check of the rollup as far as a stop reason needs it.
5780#[derive(Clone)]
5781struct CheckInfo {
5782    label: String,
5783    verdict: Verdict,
5784    required: Option<bool>,
5785    /// The workflow run the check belongs to; `None` for an external status.
5786    run: Option<String>,
5787}
5788
5789/// What to do with a red head before a fix round is spent on it.
5790#[derive(Debug, Clone, PartialEq, Eq)]
5791enum RerunStep {
5792    /// Rerun these workflow runs (each not yet rerun for this head).
5793    Rerun(Vec<String>),
5794    /// Reran already and the forge may still report the old failure: wait.
5795    Grace,
5796    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5797    Fix,
5798}
5799
5800/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5801/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5802/// pending checks in another run do not delay this run's rerun.
5803#[cfg(test)]
5804fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5805    rerunnable_with(contexts, false)
5806}
5807
5808fn rerunnable_with(
5809    contexts: &[CheckInfo],
5810    include_optional: bool,
5811) -> Vec<(String, Option<String>)> {
5812    contexts
5813        .iter()
5814        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5815        // `gh run rerun --failed` refuses a run with a job still going.
5816        .filter(|c| {
5817            c.run.as_ref().is_none_or(|r| {
5818                !contexts.iter().any(|o| {
5819                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5820                        && o.run.as_ref() == Some(r)
5821                })
5822            })
5823        })
5824        .map(|c| (c.label.clone(), c.run.clone()))
5825        .collect()
5826}
5827
5828/// Pure: rerun once per run id, wait out the grace, then hand over.
5829fn rerun_step(
5830    failing: &[(String, Option<String>)],
5831    record: Option<&LandReruns>,
5832    head: &str,
5833    now: i64,
5834) -> RerunStep {
5835    // A failure with no workflow run (an external status) cannot be rerun, and
5836    // the fixer's push re-runs everything anyway.
5837    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5838        return RerunStep::Fix;
5839    }
5840    // Reruns belong to the head they were made on.
5841    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5842    let mut fresh: Vec<String> = Vec::new();
5843    let mut recent = false;
5844    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5845        match record.and_then(|r| r.runs.get(run)) {
5846            None => {
5847                if !fresh.iter().any(|f| f == run) {
5848                    fresh.push(run.to_owned());
5849                }
5850            }
5851            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5852            Some(_) => {}
5853        }
5854    }
5855    if !fresh.is_empty() {
5856        RerunStep::Rerun(fresh)
5857    } else if recent {
5858        RerunStep::Grace
5859    } else {
5860        RerunStep::Fix
5861    }
5862}
5863
5864/// Read minimal live PR metadata (`url`, `number`, `state`, `headRefOid`,
5865/// `baseRefName`) for landing base-sync recovery admission and dispatch checks.
5866pub(crate) async fn observe_pr_summary(
5867    repo: &Path,
5868    pr_url: &str,
5869) -> Result<crate::land_sync_recovery::ObservedPr> {
5870    #[derive(serde::Deserialize)]
5871    struct Summary {
5872        #[serde(default)]
5873        url: String,
5874        #[serde(default)]
5875        number: u64,
5876        #[serde(default)]
5877        state: String,
5878        #[serde(default, rename = "headRefOid")]
5879        head_ref_oid: String,
5880        #[serde(default, rename = "baseRefName")]
5881        base_ref_name: String,
5882    }
5883    let view = gh(
5884        repo,
5885        &[
5886            "pr".to_owned(),
5887            "view".to_owned(),
5888            pr_url.to_owned(),
5889            "--json".to_owned(),
5890            "url,number,state,headRefOid,baseRefName".to_owned(),
5891        ],
5892    )
5893    .await?;
5894    if !view.ok {
5895        bail!("gh pr view {pr_url}: {}", view.combined());
5896    }
5897    let parsed: Summary = serde_json::from_str(&view.stdout).context("parse pull request json")?;
5898    Ok(crate::land_sync_recovery::ObservedPr {
5899        url: parsed.url,
5900        number: parsed.number,
5901        open: parsed.state.eq_ignore_ascii_case("OPEN"),
5902        head: parsed.head_ref_oid,
5903        base_branch: (!parsed.base_ref_name.is_empty()).then_some(parsed.base_ref_name),
5904    })
5905}
5906
5907/// Read the pull request: `gh pr view` for the top-level thread and merge
5908/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5909/// inline review comments `gh pr view` does not report.
5910async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5911    let view = gh(
5912        repo,
5913        &[
5914            "pr".to_owned(),
5915            "view".to_owned(),
5916            pr_url.to_owned(),
5917            "--json".to_owned(),
5918            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5919                .to_owned(),
5920        ],
5921    )
5922    .await?;
5923    if !view.ok {
5924        bail!("gh pr view {pr_url}: {}", view.combined());
5925    }
5926    let number = parse_pr(&view.stdout)?.number;
5927    let node = last_commit_node(repo, number).await;
5928    let mut seen = seen_from(&view.stdout, node.as_deref())?;
5929
5930    let inline = gh(
5931        repo,
5932        &[
5933            "api".to_owned(),
5934            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5935        ],
5936    )
5937    .await?;
5938    if inline.ok {
5939        match parse_inline_comments(&inline.stdout) {
5940            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5941            // An unreadable inline thread must not end a landing: the rollup
5942            // and the top-level thread are still real signal.
5943            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5944        }
5945    } else {
5946        tracing::warn!(
5947            "gh api pulls/{}/comments: {}",
5948            seen.pr.number,
5949            inline.combined()
5950        );
5951    }
5952    Ok(seen)
5953}
5954
5955/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
5956/// response. No I/O.
5957///
5958/// The commit oid and the checks are read from the *same* node, so the rollup
5959/// is bound to the commit it belongs to by construction; two reads that agree
5960/// before and after another response prove nothing about what that response
5961/// held. The view's own rollup is never used. A node that is missing,
5962/// unreadable, carries GraphQL errors, or whose checks run past the page
5963/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
5964/// as "look again" and never as a reason to merge.
5965fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5966    let mut pr = parse_pr(view_json)?;
5967    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5968
5969    let mut rollup_head = String::new();
5970    let mut failing_urls = Vec::new();
5971    let mut contexts = Vec::new();
5972    let mut checks = Checks::Unknown;
5973    let mut failing = Vec::new();
5974    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5975        (checks, failing) = rollup_verdict(&rollup);
5976        failing_urls = rollup
5977            .iter()
5978            .filter(|c| c.verdict() == Verdict::Fail)
5979            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5980            .collect();
5981        contexts = rollup
5982            .iter()
5983            .map(|c| CheckInfo {
5984                label: c.label(),
5985                verdict: c.verdict(),
5986                required: c.is_required,
5987                run: c.url().and_then(run_of),
5988            })
5989            .collect();
5990        rollup_head = oid;
5991    }
5992    pr.checks = checks;
5993    pr.failing = failing;
5994
5995    Ok(Seen {
5996        pr,
5997        title: raw.title,
5998        failing_urls,
5999        head: raw.head_ref_oid,
6000        rollup_head,
6001        merge_state: raw.merge_state_status,
6002        contexts,
6003        base: raw.base_ref_name,
6004    })
6005}
6006
6007/// The last commit's oid and its checks from one GraphQL response, `None`
6008/// when anything about it cannot be trusted.
6009fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
6010    let v: serde_json::Value = serde_json::from_str(json).ok()?;
6011    if v.get("errors").is_some_and(|e| !e.is_null()) {
6012        return None;
6013    }
6014    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
6015    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
6016    let contexts = commit.pointer("/statusCheckRollup/contexts");
6017    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
6018        // No rollup at all: the commit has no checks.
6019        return Some((oid.to_owned(), Vec::new()));
6020    };
6021    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
6022        return None;
6023    }
6024    let nodes = contexts.get("nodes")?.as_array()?;
6025    let rollup = nodes
6026        .iter()
6027        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
6028        .collect::<Result<Vec<_>, _>>()
6029        .ok()?;
6030    Some((oid.to_owned(), rollup))
6031}
6032
6033/// The pull request's last commit and its checks, in one response. `None`
6034/// when the forge could not be asked.
6035async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
6036    let out = gh(
6037        repo,
6038        &[
6039            "api".to_owned(),
6040            "graphql".to_owned(),
6041            "-F".to_owned(),
6042            "owner={owner}".to_owned(),
6043            "-F".to_owned(),
6044            "repo={repo}".to_owned(),
6045            "-F".to_owned(),
6046            format!("number={number}"),
6047            "-f".to_owned(),
6048            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
6049             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
6050             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
6051             ... on CheckRun{name status conclusion detailsUrl \
6052             isRequired(pullRequestNumber:$number)} \
6053             ... on StatusContext{context state targetUrl \
6054             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
6055                .to_owned(),
6056        ],
6057    )
6058    .await
6059    .ok()?;
6060    out.ok.then_some(out.stdout)
6061}
6062
6063/// What a fix round did.
6064#[doc(hidden)]
6065#[derive(Debug, PartialEq)]
6066pub enum Fixed {
6067    /// The fixer committed something, and this is the head that was pushed.
6068    Committed {
6069        /// The commit now at the tip of the pushed branch.
6070        head: String,
6071    },
6072    /// The fixer ran and chose to change nothing.
6073    Declined,
6074    /// Machine availability prevented a result; retry this round on resume.
6075    Deferred,
6076    /// The fixer could not run, or said nothing usable.
6077    Failed(String),
6078}
6079
6080/// Hand the failures and the comments to the fixer, then commit and push.
6081///
6082/// The fixer works in the winner's own worktree so its commits land on the
6083/// branch the pull request is built from, and it runs with `allow_write` for
6084/// the same reason.
6085#[doc(hidden)]
6086pub async fn fix_round(
6087    state: &mut RunState,
6088    pr: &PrState,
6089    round: usize,
6090    budget: usize,
6091    reason: &str,
6092    logs: &str,
6093) -> Result<Fixed> {
6094    let winner = state
6095        .winner()
6096        .cloned()
6097        .context("landing needs a winning candidate; none is recorded on this run")?;
6098    let roles = state
6099        .config
6100        .resolve_roles()
6101        .context("resolve the roster for the fix round")?;
6102    // Same chain as the review loop (see `crate::fixer`): the configured
6103    // fixers in order, otherwise the winner's own author continuing its own
6104    // conversation - the competition is over, so its context is pure benefit.
6105    let attempts = crate::fixer::attempts(state, &roles, &winner);
6106    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
6107
6108    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
6109    let mut artifacts = agent::artifacts_dir(&state.dir());
6110    if let Some(request) = state
6111        .merge_repairs
6112        .last()
6113        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
6114    {
6115        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
6116    }
6117    let prompt =
6118        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
6119            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
6120        } else {
6121            prompt
6122        };
6123    // Read before the fixer runs: it normally commits for itself, so HEAD has
6124    // already moved by the time it returns and a later read would see no
6125    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
6126    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
6127    // Each id at most once, forward only: the next one is asked only when the
6128    // call advances, and only the last attempt's result is judged below, so an
6129    // exhausted chain ends as a single failed fixer does.
6130    let mut last = None;
6131    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
6132        if owner_requested_stop(state)? {
6133            return Ok(Fixed::Declined);
6134        }
6135        let mut seat = seat_of(state, &seat_key, &spec.id);
6136        let stem = if i == 0 {
6137            format!("land-{round}")
6138        } else {
6139            format!("land-{round}-{}", spec.id)
6140        };
6141        let out = agent::invoke(
6142            &spec,
6143            &mut seat,
6144            &Invocation {
6145                coordination: state.config.coordination.as_ref(),
6146                fetched_base: state.fetched_base.as_ref(),
6147                cwd: &winner.worktree,
6148                prompt: &prompt,
6149                timeout: Duration::from_secs(state.config.graph.timeout_fix),
6150                allow_write: true,
6151                sessions: state.config.graph.sessions,
6152                artifacts: &artifacts,
6153                stem: &stem,
6154                run: &state.id,
6155                node: "land",
6156                cache_dir: state.config.cache_dir().as_deref(),
6157                attachments: &[],
6158                writable: &[],
6159            },
6160        )
6161        .await;
6162        state.seats.insert(seat.key.clone(), seat);
6163        if let Some(next) = ids.get(i + 1)
6164            && agent::chain_advances(&out)
6165        {
6166            let (class, why) = crate::fixer::failure_of(&out);
6167            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
6168            continue;
6169        }
6170        last = Some((seat_key, out));
6171        break;
6172    }
6173    let (seat_key, out) = last.expect("the fixer chain always has an entry");
6174
6175    match out {
6176        Ok(o) if o.quota_exhausted() => {
6177            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
6178            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
6179            state.quota.push(loss);
6180            state.status = RunStatus::Blocked;
6181            state.save()?;
6182            // Keep partial edits reachable on the winner branch and leave a
6183            // clean tree for resume_landing_head. The resumed landing gates
6184            // this new commit before it can publish it; no push happens here.
6185            let inherited = crate::repo_lock::WaitPolicy::current();
6186            let wait = crate::repo_lock::WaitPolicy::new(
6187                Duration::from_secs(state.config.graph.timeout_resource_wait),
6188                move || inherited.cancelled(),
6189            );
6190            let _coordination = crate::repo_lock::SeatLease::operation_with(
6191                &winner.worktree,
6192                state.config.coordination.as_ref(),
6193                &wait,
6194            )
6195            .await?;
6196            let rescue = git::rescue_commit(
6197                &winner.worktree,
6198                &format!("magi: deferred land round {round} (uncommitted work)"),
6199            )
6200            .await?;
6201            state.note_withheld("land", &rescue.withheld);
6202            state.save()?;
6203            return Ok(Fixed::Deferred);
6204        }
6205        Ok(o) if !o.usable() => {
6206            return Ok(Fixed::Failed(format!(
6207                "the fixer produced nothing usable ({})",
6208                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
6209            )));
6210        }
6211        Ok(_) => {}
6212        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
6213        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
6214    }
6215
6216    if owner_requested_stop(state)? {
6217        return Ok(Fixed::Declined);
6218    }
6219
6220    // An agent that edited files but never committed would otherwise push
6221    // nothing and look like a refusal.
6222    let wait = crate::repo_lock::WaitPolicy::new(
6223        Duration::from_secs(state.config.graph.timeout_resource_wait),
6224        || false,
6225    );
6226    let coordination = crate::repo_lock::SeatLease::operation_with(
6227        &winner.worktree,
6228        state.config.coordination.as_ref(),
6229        &wait,
6230    )
6231    .await?;
6232    match git::rescue_commit(
6233        &winner.worktree,
6234        &format!("magi: land round {round} fixes (uncommitted work)"),
6235    )
6236    .await
6237    {
6238        Ok(r) => state.note_withheld("land", &r.withheld),
6239        Err(e)
6240            if state
6241                .merge_repairs
6242                .last()
6243                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
6244        {
6245            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
6246        }
6247        Err(_) => {}
6248    }
6249    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
6250    drop(coordination);
6251    if after == before {
6252        return Ok(Fixed::Declined);
6253    }
6254
6255    if owner_requested_stop(state)? {
6256        return Ok(Fixed::Declined);
6257    }
6258    crate::pr_head::ensure_owner(state)?;
6259    let remote = state.config.merge.remote.clone();
6260    anyhow::ensure!(
6261        crate::foreign_checkout::write_back(state, &after).await?,
6262        "foreign checkout delivery is blocked; see the run events"
6263    );
6264    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
6265    let push = if state.pr_head.is_some() {
6266        let expected = state
6267            .pr_pushed_head
6268            .as_deref()
6269            .context("missing public head lease")?;
6270        git::push_as(
6271            &winner.worktree,
6272            &remote,
6273            &winner.branch,
6274            &public_head,
6275            expected,
6276        )
6277        .await?
6278    } else {
6279        git::push(&winner.worktree, &remote, &winner.branch).await?
6280    };
6281    if !push.ok() {
6282        return Ok(Fixed::Failed(format!(
6283            "pushing {} to {remote} failed: {}",
6284            public_head, push.stderr
6285        )));
6286    }
6287    state.event(
6288        "land",
6289        format!("round {round}: pushed a fix to {public_head}"),
6290    );
6291    state.pr_pushed_head = Some(after.clone());
6292    state.save()?;
6293    Ok(Fixed::Committed { head: after })
6294}
6295
6296/// Fetch or create a seat, keeping its conversation across nodes.
6297pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
6298    crate::fixer::seat_for(state, key, agent)
6299}
6300
6301/// Recheck the live PR and local worktree before spending the requested fix.
6302/// A moved/closed PR is held, never repaired using obsolete evidence.
6303pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
6304    let seen = observe(&state.repo, url).await?;
6305    let winner = state.winner().context("no winning branch to repair")?;
6306    if seen.pr.state != PrLifecycle::Open || seen.head != head {
6307        anyhow::bail!(
6308            "PR is closed or its head changed; review the current head before requesting repair again"
6309        );
6310    }
6311    if git::rev_parse(&winner.worktree, "HEAD").await? != head
6312        || !git::is_clean(&winner.worktree).await?
6313    {
6314        anyhow::bail!(
6315            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
6316        );
6317    }
6318    // Always disable any forge-side reservation, including one not recorded
6319    // by this run. A repair request is never merge authorization.
6320    let view = gh(
6321        &state.repo,
6322        &[
6323            "pr".into(),
6324            "view".into(),
6325            url.into(),
6326            "--json".into(),
6327            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
6328        ],
6329    )
6330    .await?;
6331    if !view.ok {
6332        bail!("cannot check auto-merge: {}", view.combined());
6333    }
6334    let live: serde_json::Value = serde_json::from_str(&view.stdout)?;
6335    let public = state.pr_branch().unwrap_or(&winner.branch);
6336    if live["state"] != "OPEN"
6337        || live["headRefOid"] != head
6338        || live["headRefName"] != public
6339        || live["baseRefName"] != state.base_branch
6340        || live["isCrossRepository"] != false
6341    {
6342        bail!("PR changed during repair preflight; review its current head explicitly");
6343    }
6344    let auto_merge = live
6345        .get("autoMergeRequest")
6346        .context("cannot read the PR auto-merge reservation; repair held")?;
6347    if !auto_merge.is_null() {
6348        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
6349        if !out.ok {
6350            bail!("cannot disable auto-merge; repair held: {}", out.combined());
6351        }
6352    }
6353    Ok(seen.pr)
6354}
6355
6356/// What the fixer is told.
6357fn fix_prompt(
6358    state: &RunState,
6359    pr: &PrState,
6360    round: usize,
6361    budget: usize,
6362    reason: &str,
6363    logs: &str,
6364) -> String {
6365    let mut s = format!(
6366        "Your patch is open as a pull request and it is not landing. Land round \
6367         {round} of {budget}.\n\n\
6368         Pull request: {}\n\n\
6369         What is holding it: {reason}\n\n\
6370         # The task\n\n{}\n",
6371        pr.url, state.instruction
6372    );
6373
6374    if pr.failing.is_empty() {
6375        s.push_str("\n# Failing checks\n\n(none)\n");
6376    } else {
6377        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
6378        if logs.trim().is_empty() {
6379            s.push_str(
6380                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
6381            );
6382        } else {
6383            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
6384        }
6385    }
6386
6387    if pr.review_comments.is_empty() {
6388        s.push_str("\n# Review comments\n\n(none)\n");
6389    } else {
6390        s.push_str("\n# Review comments\n");
6391        for c in &pr.review_comments {
6392            let where_ = match (&c.path, c.line) {
6393                (Some(p), Some(l)) => format!(" ({p}:{l})"),
6394                (Some(p), None) => format!(" ({p})"),
6395                _ => String::new(),
6396            };
6397            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
6398        }
6399    }
6400
6401    s.push_str(
6402        "\n# Rules\n\n\
6403         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
6404            failing test; do not silence a lint with an allow attribute; do not \
6405            stretch a timeout to hide a race. If the check is right, the code is \
6406            wrong.\n\
6407         2. Change nothing the checks and the comments did not raise. A \
6408            drive-by refactor turns a one-line fix into a pull request that \
6409            needs reviewing again.\n\
6410         3. If a comment is wrong, say so with a checkable argument and change \
6411            nothing for it. A declined comment with a reason is a correct \
6412            outcome; a change made to appease a reviewer is not.\n\
6413         4. Commit in this worktree. magi pushes to the pull request's branch \
6414            for you; do not push, merge, or close anything yourself.\n\
6415         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
6416         # Output\n\n\
6417         Say what you changed and why, and what you declined and why.",
6418    );
6419
6420    let language = &state.config.graph.language;
6421    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
6422        let _ = write!(s, "\n\nWrite all prose in {language}.");
6423    }
6424    // After the language line, so the exception is the last word on it.
6425    s.push_str(&crate::prompt::github_rule(
6426        language,
6427        &state.config.graph.github_language,
6428    ));
6429    if let Some(overlay) = state.config.prompts.overlay("fix") {
6430        let _ = write!(s, "\n\n{overlay}");
6431    }
6432    s.push('\n');
6433    s.push_str(crate::prompt::child_run_ownership());
6434    s
6435}
6436
6437/// Failing log tails, the way the operator collects them by hand:
6438/// `gh run view --log-failed`.
6439async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6440    let mut out = String::new();
6441    for (name, url) in failing.iter().take(MAX_LOGS) {
6442        let args = match (job_of(url), run_of(url)) {
6443            (Some(job), _) => vec![
6444                "run".to_owned(),
6445                "view".to_owned(),
6446                "--log-failed".to_owned(),
6447                "--job".to_owned(),
6448                job,
6449            ],
6450            (None, Some(run)) => vec![
6451                "run".to_owned(),
6452                "view".to_owned(),
6453                run,
6454                "--log-failed".to_owned(),
6455            ],
6456            // Not a GitHub Actions check - an external status has no log here.
6457            (None, None) => continue,
6458        };
6459        let (ok, body) = match gh(repo, &args).await {
6460            Ok(v) => (v.ok, v.combined()),
6461            Err(e) => (false, format!("{e:#}")),
6462        };
6463        if !ok && body.trim().is_empty() {
6464            continue;
6465        }
6466        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6467    }
6468    out
6469}
6470
6471/// Job id out of a check's `detailsUrl`
6472/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
6473fn job_of(details_url: &str) -> Option<String> {
6474    let after = details_url.split("/job/").nth(1)?;
6475    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6476    (!id.is_empty()).then_some(id)
6477}
6478
6479/// Workflow run id out of a check's `detailsUrl`.
6480pub(crate) fn run_of(details_url: &str) -> Option<String> {
6481    let after = details_url.split("/actions/runs/").nth(1)?;
6482    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6483    (!id.is_empty()).then_some(id)
6484}
6485
6486/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6487/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6488/// it to that.
6489fn stop_comment(run_id: &str, why: &str) -> String {
6490    format!(
6491        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6492         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6493    )
6494}
6495
6496/// Leave the pull request open, say why on it, and mark the run blocked.
6497///
6498/// The comment is what makes an unattended stop actionable: the operator wakes
6499/// up to a pull request that explains itself rather than to a silent queue.
6500async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6501    let body = stop_comment(&state.id, why);
6502    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6503    if !body.contains(MARKER) {
6504        body = format!("{MARKER}\n{body}");
6505    }
6506    let posted = gh(
6507        repo,
6508        &[
6509            "pr".to_owned(),
6510            "comment".to_owned(),
6511            pr.number.to_string(),
6512            "--body".to_owned(),
6513            body,
6514        ],
6515    )
6516    .await;
6517    match posted {
6518        Ok(out) if out.ok => {}
6519        Ok(out) => tracing::warn!("could not comment on {}: {}", pr.url, out.combined()),
6520        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6521    }
6522    state.status = RunStatus::Blocked;
6523    state.merge = Some(MergeOutcome {
6524        mode: MergeMode::Pr,
6525        ok: false,
6526        detail: why.to_owned(),
6527        empty: false,
6528    });
6529    state.event("land", format!("stopped: {why}"));
6530    state.save()?;
6531    Ok(())
6532}
6533
6534/// Output of a `gh` subprocess, keeping machine-readable `stdout` separate from
6535/// diagnostic `stderr`.
6536///
6537/// Newer `gh` releases (for example `gh` 2.105.0) can emit advisory hints on
6538/// `stderr` even when a read-only `--json` or API command succeeds with exit
6539/// status 0. Appending `stderr` onto `stdout` before deserialization breaks
6540/// strict JSON parsing (for example `trailing characters at line 2 column 1`).
6541///
6542/// Output contract:
6543/// - **Successful structured reads** (`--json`, REST `gh api`, GraphQL, etc.):
6544///   check [`Self::ok`], then pass [`Self::stdout`] straight to a strict parser.
6545///   Never fall back to [`Self::stderr`] when `stdout` is empty, and never strip
6546///   specific hint text or heuristically extract JSON substrings.
6547/// - **Failed invocations (`!ok`)**: use [`Self::combined`] so both `stdout`
6548///   and `stderr` diagnostics stay actionable (for example `404` detection and
6549///   refused-merge details).
6550/// - **Human-facing or mutating commands** (`pr merge`, `pr close`, `pr edit`,
6551///   `pr comment`, `run rerun`, `run view --log-failed`): use
6552///   [`Self::combined`] for failure diagnostics or human-readable output.
6553#[derive(Debug, Clone, PartialEq, Eq)]
6554pub(crate) struct GhOutput {
6555    /// Whether `gh` exited with status 0.
6556    pub(crate) ok: bool,
6557    /// Process `stdout`, decoded lossily as UTF-8.
6558    pub(crate) stdout: String,
6559    /// Process `stderr`, decoded lossily as UTF-8.
6560    pub(crate) stderr: String,
6561}
6562
6563impl GhOutput {
6564    /// Build from a completed subprocess output and log non-empty `stderr`
6565    /// emitted on exit status 0 at debug level without logging command
6566    /// arguments.
6567    pub(crate) fn from_output(output: std::process::Output) -> Self {
6568        let parsed = Self {
6569            ok: output.status.success(),
6570            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
6571            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
6572        };
6573        if parsed.ok && !parsed.stderr.trim().is_empty() {
6574            tracing::debug!(
6575                stderr = parsed.stderr.trim(),
6576                "gh exited successfully with stderr diagnostics"
6577            );
6578        }
6579        parsed
6580    }
6581
6582    /// Combined trimmed `stdout` and `stderr` for failure diagnostics and
6583    /// human-facing commands.
6584    pub(crate) fn combined(&self) -> String {
6585        let out = self.stdout.trim();
6586        let err = self.stderr.trim();
6587        match (out.is_empty(), err.is_empty()) {
6588            (true, true) => String::new(),
6589            (false, true) => out.to_owned(),
6590            (true, false) => err.to_owned(),
6591            (false, false) => format!("{out}\n{err}"),
6592        }
6593    }
6594}
6595
6596/// Run `gh` in `cwd`, returning exit status with separated `stdout` and
6597/// `stderr` in [`GhOutput`].
6598///
6599/// Structured callers must check [`GhOutput::ok`] and parse [`GhOutput::stdout`]
6600/// strictly without substituting [`GhOutput::stderr`]. Failed invocations and
6601/// human-facing or mutating commands should use [`GhOutput::combined`] so both
6602/// streams remain available as diagnostics.
6603///
6604/// `GH_REPO` is stripped from the child's environment: every call site here
6605/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6606/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6607/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6608/// `GH_REPO` the operator happens to have exported for an unrelated script
6609/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6610/// below) to a different repository than the one actually on disk - which
6611/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6612/// could be made to agree with whatever repository a forged `--merged` URL
6613/// claims, defeating it entirely.
6614pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<GhOutput> {
6615    gh_with(Path::new("gh"), cwd, args).await
6616}
6617
6618pub(crate) async fn gh_with(program: &Path, cwd: &Path, args: &[String]) -> Result<GhOutput> {
6619    let out = tokio::process::Command::new(program)
6620        .args(args)
6621        .current_dir(cwd)
6622        .env_remove("GH_REPO")
6623        .quiet()
6624        .stdin(std::process::Stdio::null())
6625        .output()
6626        .await
6627        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6628    Ok(GhOutput::from_output(out))
6629}
6630
6631/// Verdict of one entry in the status rollup.
6632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6633pub(crate) enum Verdict {
6634    Pass,
6635    Fail,
6636    Pending,
6637    Unknown,
6638}
6639
6640impl Verdict {
6641    /// Short operator-facing check result.
6642    pub(crate) fn label(self) -> &'static str {
6643        match self {
6644            Self::Pass => "passed",
6645            Self::Fail => "failed",
6646            Self::Pending => "pending",
6647            Self::Unknown => "unknown",
6648        }
6649    }
6650}
6651
6652#[derive(Debug, Deserialize)]
6653#[serde(rename_all = "camelCase")]
6654struct GhPr {
6655    #[serde(default)]
6656    url: String,
6657    #[serde(default)]
6658    number: u64,
6659    #[serde(default)]
6660    state: String,
6661    #[serde(default)]
6662    title: String,
6663    #[serde(default)]
6664    status_check_rollup: Vec<GhCheck>,
6665    /// GitHub's own verdict on whether the pull request can be merged.
6666    ///
6667    /// Worth asking for because it is the only place the *required* check set
6668    /// is applied: the rollup lists every check equally, so a repository that
6669    /// deliberately does not require `coverage` still looks red here. See
6670    /// [`Blocking`].
6671    #[serde(default)]
6672    merge_state_status: String,
6673    /// The commit the pull request currently points at. Compared with the
6674    /// commit a fix round pushed, it is how the loop knows the forge has moved
6675    /// on and the rollup belongs to the new head.
6676    #[serde(default)]
6677    head_ref_oid: String,
6678    #[serde(default)]
6679    base_ref_name: String,
6680    #[serde(default)]
6681    reviews: Vec<GhReview>,
6682    #[serde(default)]
6683    comments: Vec<GhComment>,
6684}
6685
6686/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6687/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6688/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6689/// conclusion at all.
6690#[derive(Debug, Deserialize)]
6691#[serde(rename_all = "camelCase")]
6692struct GhCheck {
6693    #[serde(default)]
6694    name: Option<String>,
6695    #[serde(default)]
6696    context: Option<String>,
6697    #[serde(default)]
6698    status: Option<String>,
6699    #[serde(default)]
6700    conclusion: Option<String>,
6701    #[serde(default)]
6702    state: Option<String>,
6703    #[serde(default)]
6704    details_url: Option<String>,
6705    #[serde(default)]
6706    target_url: Option<String>,
6707    /// Whether the base branch requires this check. Only the GraphQL node
6708    /// carries it; `None` is "not read", never "not required".
6709    #[serde(default)]
6710    is_required: Option<bool>,
6711}
6712
6713impl GhCheck {
6714    /// Name to show a human and hand to the fixer.
6715    fn label(&self) -> String {
6716        self.name
6717            .clone()
6718            .or_else(|| self.context.clone())
6719            .unwrap_or_else(|| "(unnamed check)".to_owned())
6720    }
6721
6722    /// Where this check's logs live, when it has any.
6723    fn url(&self) -> Option<&str> {
6724        self.details_url
6725            .as_deref()
6726            .or(self.target_url.as_deref())
6727            .filter(|u| !u.is_empty())
6728    }
6729
6730    /// Did it pass?
6731    ///
6732    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6733    /// skips release and bot pull requests by design, and a skip that blocked
6734    /// landing would block exactly the pull requests that need no review.
6735    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6736    /// merging over one is merging over a check that never ran.
6737    fn verdict(&self) -> Verdict {
6738        if let Some(status) = self.status.as_deref() {
6739            if !status.eq_ignore_ascii_case("COMPLETED") {
6740                return Verdict::Pending;
6741            }
6742        }
6743        let outcome = self
6744            .conclusion
6745            .as_deref()
6746            .or(self.state.as_deref())
6747            .unwrap_or("");
6748        match outcome.to_ascii_uppercase().as_str() {
6749            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6750            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6751            | "ACTION_REQUIRED" => Verdict::Fail,
6752            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6753                Verdict::Pending
6754            }
6755            _ => Verdict::Unknown,
6756        }
6757    }
6758}
6759
6760#[derive(Debug, Deserialize)]
6761struct GhAuthor {
6762    #[serde(default)]
6763    login: String,
6764}
6765
6766#[derive(Debug, Deserialize)]
6767struct GhReview {
6768    #[serde(default)]
6769    author: GhAuthor,
6770    #[serde(default)]
6771    body: String,
6772}
6773
6774#[derive(Debug, Deserialize)]
6775struct GhComment {
6776    #[serde(default)]
6777    author: GhAuthor,
6778    #[serde(default)]
6779    body: String,
6780}
6781
6782#[derive(Debug, Deserialize)]
6783struct GhUser {
6784    #[serde(default)]
6785    login: String,
6786}
6787
6788#[derive(Debug, Deserialize)]
6789struct GhInline {
6790    #[serde(default)]
6791    user: GhUser,
6792    #[serde(default)]
6793    path: Option<String>,
6794    #[serde(default)]
6795    line: Option<u64>,
6796    #[serde(default)]
6797    body: String,
6798}
6799
6800impl Default for GhAuthor {
6801    fn default() -> Self {
6802        Self {
6803            login: "(unknown)".to_owned(),
6804        }
6805    }
6806}
6807
6808impl Default for GhUser {
6809    fn default() -> Self {
6810        Self {
6811            login: "(unknown)".to_owned(),
6812        }
6813    }
6814}
6815
6816#[cfg(test)]
6817pub(crate) mod tests {
6818    use super::*;
6819    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6820
6821    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6822        format!(
6823            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6824        )
6825    }
6826
6827    #[test]
6828    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6829        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6830        assert_eq!(
6831            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6832            Ok(())
6833        );
6834        for (json, why) in [
6835            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6836            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6837            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6838            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6839            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6840            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6841        ] {
6842            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6843                .unwrap_err()
6844                .why;
6845            assert!(err.contains(why), "{json}: {err}");
6846        }
6847        // A head that moved on past what was verified is left alone.
6848        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6849        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6850        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6851        assert!(
6852            !closable(
6853                &head_json("x", "main", "OPEN", false),
6854                "magi/27b2/A",
6855                "main",
6856                &[]
6857            )
6858            .unwrap_err()
6859            .retry
6860        );
6861        assert!(is_forge_url("https://github.com/o/r.git"));
6862        assert!(is_forge_url("git@github.com:o/r.git"));
6863        assert!(!is_forge_url("/tmp/origin.git"));
6864        assert!(!is_forge_url("C:\\work\\origin.git"));
6865        assert!(!is_forge_url("file:///tmp/origin.git"));
6866        assert!(forge_unavailable(
6867            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6868        ));
6869        assert!(!forge_unavailable(
6870            "gh pr list failed: error connecting to api.github.com"
6871        ));
6872        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6873        // A record that does not say whether it is a fork is not trusted.
6874        assert!(
6875            closable(
6876                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6877                "b",
6878                "main",
6879                &["aaa".to_owned()]
6880            )
6881            .is_err()
6882        );
6883    }
6884
6885    #[test]
6886    fn the_close_comment_names_the_commit_on_the_base() {
6887        let e = crate::already::Evidence {
6888            proof: crate::already::Proof::PatchId,
6889            tip: "1234567890".to_owned(),
6890            commits: vec!["0e368de0000".to_owned()],
6891        };
6892        let c = superseded_comment("main", &e);
6893        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6894    }
6895
6896    /// 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.
6897    const GREEN_OPEN: &str = r####"{
6898  "url": "https://github.com/yukimemi/magi/pull/10",
6899  "number": 10,
6900  "state": "OPEN",
6901  "mergeStateStatus": "CLEAN",
6902  "statusCheckRollup": [
6903    {
6904      "__typename": "CheckRun",
6905      "conclusion": "SKIPPED",
6906      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6907      "name": "review",
6908      "status": "COMPLETED",
6909      "workflowName": "claude-review"
6910    },
6911    {
6912      "__typename": "CheckRun",
6913      "conclusion": "SUCCESS",
6914      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6915      "name": "check (ubuntu-latest)",
6916      "status": "COMPLETED",
6917      "workflowName": "CI"
6918    },
6919    {
6920      "__typename": "CheckRun",
6921      "conclusion": "SUCCESS",
6922      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6923      "name": "rustfmt",
6924      "status": "COMPLETED",
6925      "workflowName": "CI"
6926    },
6927    {
6928      "__typename": "StatusContext",
6929      "context": "CodeRabbit",
6930      "state": "SUCCESS",
6931      "targetUrl": ""
6932    }
6933  ],
6934  "reviews": [],
6935  "comments": [
6936    {
6937      "author": {
6938        "login": "coderabbitai"
6939      },
6940      "authorAssociation": "NONE",
6941      "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"
6942    }
6943  ]
6944}"####;
6945
6946    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
6947    const RED_OPEN: &str = r####"{
6948  "url": "https://github.com/yukimemi/magi/pull/9",
6949  "number": 9,
6950  "state": "OPEN",
6951  "mergeStateStatus": "UNSTABLE",
6952  "statusCheckRollup": [
6953    {
6954      "__typename": "CheckRun",
6955      "conclusion": "SUCCESS",
6956      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6957      "name": "check (ubuntu-latest)",
6958      "status": "COMPLETED",
6959      "workflowName": "CI"
6960    },
6961    {
6962      "__typename": "CheckRun",
6963      "conclusion": "SUCCESS",
6964      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6965      "name": "rustfmt",
6966      "status": "COMPLETED",
6967      "workflowName": "CI"
6968    },
6969    {
6970      "__typename": "CheckRun",
6971      "conclusion": "FAILURE",
6972      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6973      "name": "editorconfig",
6974      "status": "COMPLETED",
6975      "workflowName": "CI"
6976    },
6977    {
6978      "__typename": "StatusContext",
6979      "context": "CodeRabbit",
6980      "state": "SUCCESS",
6981      "targetUrl": ""
6982    }
6983  ],
6984  "reviews": [],
6985  "comments": [
6986    {
6987      "author": {
6988        "login": "coderabbitai"
6989      },
6990      "authorAssociation": "NONE",
6991      "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"
6992    }
6993  ]
6994}"####;
6995
6996    /// 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.
6997    const PENDING_OPEN: &str = r####"{
6998  "url": "https://github.com/yukimemi/magi/pull/9",
6999  "number": 9,
7000  "state": "OPEN",
7001  "statusCheckRollup": [
7002    {
7003      "__typename": "CheckRun",
7004      "conclusion": "SUCCESS",
7005      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
7006      "name": "check (ubuntu-latest)",
7007      "status": "COMPLETED",
7008      "workflowName": "CI"
7009    },
7010    {
7011      "__typename": "CheckRun",
7012      "conclusion": "SUCCESS",
7013      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
7014      "name": "rustfmt",
7015      "status": "COMPLETED",
7016      "workflowName": "CI"
7017    },
7018    {
7019      "__typename": "CheckRun",
7020      "conclusion": null,
7021      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
7022      "name": "editorconfig",
7023      "status": "IN_PROGRESS",
7024      "workflowName": "CI"
7025    },
7026    {
7027      "__typename": "StatusContext",
7028      "context": "CodeRabbit",
7029      "state": "SUCCESS",
7030      "targetUrl": ""
7031    }
7032  ],
7033  "reviews": [],
7034  "comments": []
7035}"####;
7036
7037    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
7038    const MERGED: &str = r####"{
7039  "url": "https://github.com/yukimemi/magi/pull/16",
7040  "number": 16,
7041  "state": "MERGED",
7042  "statusCheckRollup": [
7043    {
7044      "__typename": "CheckRun",
7045      "conclusion": "SUCCESS",
7046      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
7047      "name": "check (ubuntu-latest)",
7048      "status": "COMPLETED",
7049      "workflowName": "CI"
7050    },
7051    {
7052      "__typename": "CheckRun",
7053      "conclusion": "SUCCESS",
7054      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
7055      "name": "review",
7056      "status": "COMPLETED",
7057      "workflowName": "claude-review"
7058    }
7059  ],
7060  "reviews": [],
7061  "comments": []
7062}"####;
7063
7064    /// 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.
7065    const REVIEWED_OPEN: &str = r####"{
7066  "url": "https://github.com/yukimemi/magi/pull/12",
7067  "number": 12,
7068  "state": "OPEN",
7069  "statusCheckRollup": [
7070    {
7071      "__typename": "CheckRun",
7072      "conclusion": "SUCCESS",
7073      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
7074      "name": "check (ubuntu-latest)",
7075      "status": "COMPLETED",
7076      "workflowName": "CI"
7077    },
7078    {
7079      "__typename": "CheckRun",
7080      "conclusion": "SUCCESS",
7081      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
7082      "name": "review",
7083      "status": "COMPLETED",
7084      "workflowName": "claude-review"
7085    }
7086  ],
7087  "reviews": [
7088    {
7089      "author": {
7090        "login": "claude"
7091      },
7092      "state": "COMMENTED",
7093      "body": ""
7094    }
7095  ],
7096  "comments": [
7097    {
7098      "author": {
7099        "login": "coderabbitai"
7100      },
7101      "authorAssociation": "NONE",
7102      "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"
7103    },
7104    {
7105      "author": {
7106        "login": "claude"
7107      },
7108      "authorAssociation": "NONE",
7109      "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"
7110    }
7111  ]
7112}"####;
7113
7114    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
7115    const INLINE: &str = r####"[
7116  {
7117    "user": {
7118      "login": "claude[bot]"
7119    },
7120    "path": "src/graph.rs",
7121    "line": 231,
7122    "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"
7123  }
7124]"####;
7125
7126    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
7127    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
7128<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
7129
7130> [!IMPORTANT]
7131> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
7132> 
7133> This repository does not receive automatic reviews because it has fewer than 10 stars.
7134> 
7135> <details>
7136> <summary>⚙️ Run configuration</summary>
7137> 
7138> **Configuration used**: defaults
7139> 
7140> **Review profile**: CHILL
7141> 
7142> **Plan**: Team
7143> 
7144> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
7145> 
7146> </details>
7147
7148<!-- end of auto-generated comment: skip review by coderabbit.ai -->
7149
7150<!-- tips_start -->
7151
7152---
7153
7154Thanks 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.
7155
7156<details>
7157<summary>❤️ Share</summary>
7158
7159- [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"####;
7160
7161    /// 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.
7162    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
7163
7164---
7165### Reviewing PR #16
7166
7167- [x] Read AGENTS.md conventions
7168- [x] Review `src/daemon.rs` changes
7169- [x] Review `src/main.rs` changes (new `doctor` reporting)
7170- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
7171- [x] Check test coverage for new behavior
7172- [x] Run verification commands (blocked — see note)
7173- [x] Post findings"####;
7174
7175    /// The same job's real comment on pull request #12 once it had something to say.
7176    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
7177
7178---
7179### Review: `magi review <branch>` — cheap-half-only graph
7180
7181Read 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.
7182
7183**Correctness**
7184
7185- 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"####;
7186
7187    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
7188        PrState {
7189            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
7190            number: 16,
7191            state: PrLifecycle::Open,
7192            checks,
7193            // These tests are about red-means-fix, so a red here is one the
7194            // forge gates on. Without saying so they would assert the new
7195            // "merge past a check nobody requires" path by accident.
7196            blocking: if matches!(checks, Checks::Red) {
7197                Blocking::Yes
7198            } else {
7199                Blocking::No
7200            },
7201            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
7202            review_comments: (0..comments)
7203                .map(|i| ReviewComment {
7204                    author: "coderabbitai".to_owned(),
7205                    path: Some("src/graph.rs".to_owned()),
7206                    line: Some(231),
7207                    body: format!("finding {i}"),
7208                })
7209                .collect(),
7210        }
7211    }
7212
7213    #[test]
7214    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
7215        use CiExpectation::{Absent, Expected};
7216        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
7217            let p = pr(checks, &["x"], 0);
7218            for waited in [Duration::ZERO, CHECKS_GRACE] {
7219                assert_eq!(
7220                    decide_with(&p, 0, 4, waited, Expected),
7221                    decide(&p, 0, 4, waited)
7222                );
7223            }
7224        }
7225        // Nothing will ever report: no wait, no give-up, no fix round.
7226        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
7227            let p = pr(checks, &["x"], 0);
7228            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
7229            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
7230        }
7231        // Third-party statuses never change the review decision, even at budget.
7232        for comments in [0, 1] {
7233            for round in [0, 4] {
7234                let absent = decide_with(
7235                    &pr(Checks::Unknown, &[], comments),
7236                    round,
7237                    4,
7238                    CHECKS_GRACE,
7239                    Absent,
7240                );
7241                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
7242                    assert_eq!(
7243                        decide_with(
7244                            &pr(checks, &["third-party"], comments),
7245                            round,
7246                            4,
7247                            Duration::ZERO,
7248                            Absent
7249                        ),
7250                        absent
7251                    );
7252                }
7253                if comments != 0 {
7254                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
7255                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
7256                }
7257            }
7258        }
7259        let empty = pr(Checks::Unknown, &[], 0);
7260        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
7261            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
7262        }
7263        assert_eq!(
7264            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
7265            Step::Wait
7266        );
7267        assert_eq!(
7268            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
7269            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
7270        );
7271        // A conflict is not a check: it still wants the rebase.
7272        let mut p = pr(Checks::Unknown, &[], 0);
7273        p.blocking = Blocking::Conflict;
7274        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
7275        // And a pull request that left our hands is still done.
7276        p.state = PrLifecycle::Merged;
7277        assert_eq!(
7278            decide_with(&p, 0, 4, Duration::ZERO, Absent),
7279            Step::Done { merged: true }
7280        );
7281    }
7282
7283    #[test]
7284    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
7285        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
7286        assert_eq!(state.number, 10);
7287        assert_eq!(state.state, PrLifecycle::Open);
7288        assert_eq!(state.checks, Checks::Green);
7289        assert!(state.failing.is_empty());
7290        assert!(
7291            state.review_comments.is_empty(),
7292            "the only comment is CodeRabbit's trigger notice: {:?}",
7293            state.review_comments
7294        );
7295        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
7296    }
7297
7298    #[test]
7299    fn a_failing_check_parses_as_red_and_is_named() {
7300        let state = parse_pr(RED_OPEN).expect("red fixture parses");
7301        assert_eq!(state.checks, Checks::Red);
7302        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
7303        // The captured payload says `UNSTABLE` - mergeable, with a check
7304        // nobody requires red - which is exactly the shape that had to be
7305        // merged by hand. Asserted separately, in
7306        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
7307        // test is about is that a red check is *named*, so the reason a fixer
7308        // is handed says which one; so it asks the blocking question here.
7309        let mut blocking = state.clone();
7310        blocking.blocking = Blocking::Yes;
7311        match decide(&blocking, 0, 4, Duration::ZERO) {
7312            Step::Fix { reason } => {
7313                assert!(reason.contains("editorconfig"), "reason: {reason}");
7314                assert!(reason.contains("failing"), "reason: {reason}");
7315            }
7316            other => panic!("expected a fix round, got {other:?}"),
7317        }
7318    }
7319
7320    #[test]
7321    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
7322        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
7323        assert_eq!(state.checks, Checks::Pending);
7324        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
7325    }
7326
7327    #[test]
7328    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
7329        let state = parse_pr(MERGED).expect("merged fixture parses");
7330        assert_eq!(state.state, PrLifecycle::Merged);
7331        assert_eq!(
7332            decide(&state, 0, 4, Duration::ZERO),
7333            Step::Done { merged: true }
7334        );
7335    }
7336
7337    #[test]
7338    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
7339        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
7340        assert_eq!(state.checks, Checks::Green);
7341        let authors: Vec<&str> = state
7342            .review_comments
7343            .iter()
7344            .map(|c| c.author.as_str())
7345            .collect();
7346        assert_eq!(
7347            authors,
7348            vec!["claude"],
7349            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
7350        );
7351        match decide(&state, 0, 4, Duration::ZERO) {
7352            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
7353            other => panic!("expected a fix round, got {other:?}"),
7354        }
7355    }
7356
7357    #[test]
7358    fn inline_review_comments_keep_their_file_and_line() {
7359        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
7360        assert_eq!(comments.len(), 1);
7361        assert_eq!(comments[0].author, "claude[bot]");
7362        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
7363        assert_eq!(comments[0].line, Some(231));
7364        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
7365    }
7366
7367    #[test]
7368    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
7369        assert!(
7370            is_noise(CODERABBIT_TRIGGER),
7371            "CodeRabbit's trigger notice declares itself not a review"
7372        );
7373        assert!(
7374            is_noise(CLAUDE_CHECKLIST),
7375            "a progress checklist asks for nothing"
7376        );
7377        assert!(
7378            !is_noise(CLAUDE_FINDING),
7379            "a review that names a bug is input, not noise"
7380        );
7381
7382        let mut clean = pr(Checks::Green, &[], 0);
7383        clean.review_comments.push(ReviewComment {
7384            author: "coderabbitai".to_owned(),
7385            path: None,
7386            line: None,
7387            body: CODERABBIT_TRIGGER.to_owned(),
7388        });
7389        clean.review_comments.retain(|c| !is_noise(&c.body));
7390        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
7391
7392        let mut found = pr(Checks::Green, &[], 0);
7393        found.review_comments.push(ReviewComment {
7394            author: "claude".to_owned(),
7395            path: None,
7396            line: None,
7397            body: CLAUDE_FINDING.to_owned(),
7398        });
7399        found.review_comments.retain(|c| !is_noise(&c.body));
7400        assert!(matches!(
7401            decide(&found, 0, 4, Duration::ZERO),
7402            Step::Fix { .. }
7403        ));
7404    }
7405
7406    #[test]
7407    fn the_policy_table_holds_for_every_combination_that_matters() {
7408        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
7409            (
7410                "pending checks are waited for, even on the last round",
7411                pr(Checks::Pending, &[], 0),
7412                4,
7413                4,
7414                Duration::ZERO,
7415                Step::Wait,
7416            ),
7417            (
7418                "red checks are fixed",
7419                pr(Checks::Red, &["editorconfig"], 0),
7420                0,
7421                4,
7422                Duration::ZERO,
7423                Step::Fix {
7424                    reason: "1 check(s) failing: editorconfig".to_owned(),
7425                },
7426            ),
7427            (
7428                "green with comments is fixed, not merged",
7429                pr(Checks::Green, &[], 2),
7430                1,
7431                4,
7432                Duration::ZERO,
7433                Step::Fix {
7434                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
7435                        .to_owned(),
7436                },
7437            ),
7438            (
7439                "green and clean merges",
7440                pr(Checks::Green, &[], 0),
7441                3,
7442                4,
7443                Duration::ZERO,
7444                Step::Merge,
7445            ),
7446            (
7447                "an unreadable rollup is waited on while the grace lasts",
7448                pr(Checks::Unknown, &[], 0),
7449                0,
7450                4,
7451                Duration::ZERO,
7452                Step::Wait,
7453            ),
7454            (
7455                "an unreadable rollup is never merged once the grace is spent",
7456                pr(Checks::Unknown, &[], 0),
7457                0,
7458                4,
7459                CHECKS_GRACE,
7460                Step::GiveUp {
7461                    reason: "no check status is readable on the pull request after 3 minute(s); \
7462                             refusing to merge on a guess"
7463                        .to_owned(),
7464                },
7465            ),
7466        ];
7467        for (what, state, round, budget, waited, want) in cases {
7468            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
7469        }
7470    }
7471
7472    #[test]
7473    fn the_forge_verdict_survives_the_round_trip_from_gh() {
7474        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
7475        // requested but never parsed is the kind of thing that looks wired up
7476        // and answers `Unsaid` forever.
7477        let green = parse_pr(GREEN_OPEN).expect("parse");
7478        assert_eq!(green.blocking, Blocking::No);
7479        let red = parse_pr(RED_OPEN).expect("parse");
7480        assert_eq!(
7481            red.blocking,
7482            Blocking::No,
7483            "`UNSTABLE` is mergeable: the red check is one nobody requires"
7484        );
7485        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
7486        // A payload from an older `gh` has no such field at all.
7487        let quiet =
7488            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
7489        assert_eq!(quiet.blocking, Blocking::Unsaid);
7490    }
7491
7492    #[test]
7493    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
7494        // Pull request 37's only red check was `editorconfig`, failing
7495        // because the action could not fetch its own binary after
7496        // editorconfig-checker v4 renamed its release assets. The repository
7497        // does not require it. magi answered by asking a fixer to repair a
7498        // change that was fine, and the pull request had to be merged by hand.
7499        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7500        nonblocking.blocking = Blocking::No;
7501        assert_eq!(
7502            decide(&nonblocking, 0, 4, Duration::ZERO),
7503            Step::Merge,
7504            "the forge says nothing is in the way, so nothing is"
7505        );
7506
7507        // The same red, gated on: that is a fix round, as before.
7508        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7509        blocking.blocking = Blocking::Yes;
7510        assert!(matches!(
7511            decide(&blocking, 0, 4, Duration::ZERO),
7512            Step::Fix { .. }
7513        ));
7514
7515        // A review comment still outranks green-enough: a non-required red
7516        // must not become a way to merge past an unanswered reviewer.
7517        let mut commented = pr(Checks::Red, &["coverage"], 1);
7518        commented.blocking = Blocking::No;
7519        assert!(matches!(
7520            decide(&commented, 0, 4, Duration::ZERO),
7521            Step::Fix { .. }
7522        ));
7523
7524        // And silence from the forge is not consent.
7525        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7526        unsaid.blocking = Blocking::Unsaid;
7527        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7528        assert!(matches!(
7529            decide(&unsaid, 0, 4, CHECKS_GRACE),
7530            Step::Fix { .. }
7531        ));
7532    }
7533
7534    #[test]
7535    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7536        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7537        red.blocking = Blocking::No;
7538        assert_eq!(
7539            decide(&red, 0, 4, Duration::ZERO),
7540            Step::Merge,
7541            "announcing must not change the decision"
7542        );
7543        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7544        assert!(said.contains("yukimemi/magi"), "{said}");
7545        assert!(said.contains("#16"), "{said}");
7546        assert!(
7547            said.contains("https://github.com/yukimemi/magi/pull/16"),
7548            "{said}"
7549        );
7550        assert!(
7551            said.contains("test (windows-latest)") && said.contains("coverage"),
7552            "{said}"
7553        );
7554
7555        // `failing` can be left over on a green observation; only `checks` counts.
7556        let green = pr(Checks::Green, &["stale"], 0);
7557        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7558    }
7559
7560    #[test]
7561    fn red_merge_notices_omit_empty_check_details() {
7562        for checks in [vec![], vec!["", "  "]] {
7563            let red = pr(Checks::Red, &checks, 0);
7564            let summary = red_merge_summary("owner/repo", &red).unwrap();
7565            let notice = crate::notices::merged_red("run-1", &summary);
7566            assert_eq!(
7567                notice.message,
7568                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7569            );
7570            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7571        }
7572        let red = pr(Checks::Red, &["", " test ", " "], 0);
7573        let summary = red_merge_summary("owner/repo", &red).unwrap();
7574        assert!(summary.contains("with red checks: test ("), "{summary}");
7575    }
7576
7577    #[test]
7578    fn the_repo_label_comes_from_the_pull_request_url() {
7579        let p = Path::new("/tmp/checkout");
7580        assert_eq!(
7581            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7582            "yukimemi/magi"
7583        );
7584        assert_eq!(repo_label(p, "not a url"), "checkout");
7585    }
7586
7587    #[test]
7588    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7589        // Pull requests 35 and 37 were both rebased by hand: a competition
7590        // that runs for two hours against a repository merging pull requests
7591        // all day conflicts on the way in, and that is arithmetic rather
7592        // than a defect in the change.
7593        let mut conflicted = pr(Checks::Green, &[], 0);
7594        conflicted.blocking = Blocking::Conflict;
7595        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7596
7597        // Decided before the checks, and even with the rounds spent: every
7598        // check on a branch that cannot land is an answer about a state that
7599        // cannot land, and a conflict is not the change's fault.
7600        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7601        red.blocking = Blocking::Conflict;
7602        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7603
7604        // The lifecycle still wins over everything, conflict included.
7605        let mut merged = pr(Checks::Red, &[], 0);
7606        merged.blocking = Blocking::Conflict;
7607        merged.state = PrLifecycle::Merged;
7608        assert_eq!(
7609            decide(&merged, 0, 4, Duration::ZERO),
7610            Step::Done { merged: true }
7611        );
7612    }
7613
7614    #[test]
7615    fn the_forge_verdict_is_read_off_merge_state_status() {
7616        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7617        // matters: mergeable, with a non-required check red or still running.
7618        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7619            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7620            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7621        }
7622        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7623        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7624        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7625        // An older `gh`, or a token without the scope, says nothing - and
7626        // refusing to guess is the rule everywhere else in this module.
7627        for quiet in ["", "UNKNOWN"] {
7628            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7629            assert!(Blocking::of(quiet).stops_a_merge());
7630        }
7631    }
7632
7633    #[test]
7634    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7635        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7636        // The exact stderr from run ec12, in a jj-colocated repository.
7637        let jj = "could not determine current branch: failed to run git: not on any branch";
7638
7639        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7640            .expect("the forge says merged, so it merged");
7641        assert!(landed.ok);
7642        assert!(
7643            landed.detail.contains("but the pull request is merged"),
7644            "the record must not read as a clean success: {}",
7645            landed.detail
7646        );
7647        assert!(
7648            landed.detail.contains("not on any branch"),
7649            "and it must keep what the command actually said: {}",
7650            landed.detail
7651        );
7652
7653        // A pull request still open means the merge really failed.
7654        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7655        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7656        // And an unreadable answer is not evidence of success.
7657        assert!(merged_after_all(&argv, jj, None).is_none());
7658    }
7659
7660    #[test]
7661    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7662        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7663        state.state = PrLifecycle::Closed;
7664        assert_eq!(
7665            decide(&state, 0, 4, Duration::ZERO),
7666            Step::Done { merged: false },
7667            "a human closing the pull request ends the loop, whatever CI says"
7668        );
7669    }
7670
7671    #[test]
7672    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7673        let red = decide(
7674            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7675            4,
7676            4,
7677            Duration::ZERO,
7678        );
7679        match red {
7680            Step::GiveUp { reason } => {
7681                assert!(reason.contains("editorconfig"), "reason: {reason}");
7682                assert!(reason.contains("test (macos)"), "reason: {reason}");
7683                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7684            }
7685            other => panic!("expected a give-up, got {other:?}"),
7686        }
7687
7688        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7689        match commented {
7690            Step::GiveUp { reason } => {
7691                assert!(reason.contains("unresolved"), "reason: {reason}");
7692                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7693            }
7694            other => panic!("expected a give-up, got {other:?}"),
7695        }
7696    }
7697
7698    #[test]
7699    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7700        let candidate_commit = "magi: candidate A (uncommitted work)";
7701        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7702        let argv = merge_argv(16, &subject);
7703
7704        assert!(argv.contains(&"--squash".to_owned()));
7705        assert!(argv.contains(&"--delete-branch".to_owned()));
7706        assert!(argv.contains(&"--subject".to_owned()));
7707        assert_eq!(
7708            argv.last().map(String::as_str),
7709            Some("add retries to the uploader"),
7710            "the subject must not be the candidate commit message"
7711        );
7712        assert_ne!(subject, candidate_commit);
7713    }
7714
7715    #[test]
7716    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7717        assert_eq!(
7718            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7719            "feat: a queue, an unattended loop, and a phone UI"
7720        );
7721        assert_eq!(
7722            merge_subject("", "# port the retry logic\n\ndetails"),
7723            "port the retry logic",
7724            "an empty title falls back to the task's first line, heading marks stripped"
7725        );
7726    }
7727
7728    #[test]
7729    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7730        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7731        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7732        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7733        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7734        assert_eq!(run_of(""), None);
7735    }
7736
7737    #[test]
7738    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7739        let mut out = Vec::new();
7740        push_if_outstanding(
7741            &mut out,
7742            ReviewComment {
7743                author: "yukimemi".to_owned(),
7744                path: None,
7745                line: None,
7746                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7747            },
7748        );
7749        assert!(out.is_empty());
7750    }
7751
7752    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7753    /// falls back to the repository - which keeps these tests free of a
7754    /// worktree, a `git` invocation and a network.
7755    fn run_state() -> RunState {
7756        let mut state = RunState::new(
7757            std::path::PathBuf::from("/repo/magi"),
7758            "main".to_owned(),
7759            "abcdef1234".to_owned(),
7760            "add retries to the uploader".to_owned(),
7761            crate::config::Config::default(),
7762        );
7763        // These fixtures test execution flow, independent of host disk capacity.
7764        state.config.disk.min_free_bytes = 0;
7765        // Tests run in parallel against one persistent home and the ids
7766        // `RunState::new` draws from the clock can repeat, so two tests would
7767        // share a run's questions. The home also outlives the process, so the
7768        // counter alone would reuse an earlier run's ids.
7769        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7770        let nanos = std::time::SystemTime::now()
7771            .duration_since(std::time::UNIX_EPOCH)
7772            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7773        state.id = format!(
7774            "20261004-{nanos:06}-{:04x}",
7775            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7776        );
7777        state
7778    }
7779
7780    fn green_pr() -> PrState {
7781        PrState {
7782            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7783            number: 42,
7784            state: PrLifecycle::Open,
7785            checks: Checks::Green,
7786            // The forge sees nothing in the way unless a test says otherwise.
7787            blocking: Blocking::No,
7788            failing: Vec::new(),
7789            review_comments: vec![ReviewComment {
7790                author: "coderabbitai".to_owned(),
7791                path: Some("src/land.rs".to_owned()),
7792                line: Some(212),
7793                body: "this branch never checks the exit code".to_owned(),
7794            }],
7795        }
7796    }
7797
7798    #[test]
7799    fn land_fixer_defers_review_and_verification_without_a_cache() {
7800        let state = run_state();
7801        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7802        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7803        assert!(p.contains("Commit in this worktree"), "{p}");
7804    }
7805
7806    #[test]
7807    fn github_facing_land_text_is_english_whatever_the_language() {
7808        let mut state = run_state();
7809        state.config.graph.language = "ja".to_owned();
7810        let comment = stop_comment(&state.id, "checks are still red");
7811        assert!(crate::github_text::check("", &comment).is_empty());
7812        assert!(comment.is_ascii(), "{comment}");
7813        assert!(comment.starts_with(MARKER));
7814
7815        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7816        let ja_at = p.find("Write all prose in ja").unwrap();
7817        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7818        assert!(ja_at < rule_at, "{p}");
7819        assert!(p.contains("stays in Japanese"), "{p}");
7820
7821        state.config.graph.language = "en".to_owned();
7822        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7823        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7824        assert!(!p.contains("does not apply"), "{p}");
7825    }
7826
7827    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7828
7829    fn panel() -> String {
7830        approval_panel(
7831            &run_state(),
7832            &green_pr(),
7833            NUMSTAT,
7834            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7835            &[
7836                "land: ask before merging".to_owned(),
7837                "land: colour the diff".to_owned(),
7838            ],
7839            "feat: merge approval from the phone",
7840        )
7841    }
7842
7843    #[test]
7844    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7845        let html = panel();
7846        for needle in [
7847            "42",
7848            "main",
7849            "src/land.rs",
7850            "src/web.rs",
7851            "assets/logo.png",
7852            "feat: merge approval from the phone",
7853            "land: ask before merging",
7854            "land: colour the diff",
7855            "coderabbitai",
7856            "this branch never checks the exit code",
7857            "green",
7858        ] {
7859            assert!(html.contains(needle), "the panel must state `{needle}`");
7860        }
7861    }
7862
7863    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7864        crate::run::pin_test_home();
7865        let tmp = tempfile::tempdir().unwrap();
7866        let repo = tmp.path().join("repo");
7867        let remote = tmp.path().join("remote.git");
7868        std::fs::create_dir(&repo).unwrap();
7869        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7870            .await
7871            .unwrap();
7872        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7873        git::git(&repo, &["config", "user.name", "Test"])
7874            .await
7875            .unwrap();
7876        git::git(&repo, &["config", "user.email", "test@example.test"])
7877            .await
7878            .unwrap();
7879        std::fs::write(repo.join("base"), "base").unwrap();
7880        git::git(&repo, &["add", "."]).await.unwrap();
7881        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7882        git::git(
7883            &repo,
7884            &["remote", "add", "origin", remote.to_str().unwrap()],
7885        )
7886        .await
7887        .unwrap();
7888        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7889        git::git(&repo, &["checkout", "-b", "winner"])
7890            .await
7891            .unwrap();
7892        std::fs::write(repo.join("change"), "change").unwrap();
7893        git::git(&repo, &["add", "."]).await.unwrap();
7894        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7895        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7896        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7897            .await
7898            .unwrap();
7899        let mut state = run_state();
7900        state.repo = repo.clone();
7901        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7902        state.config.graph.land = true;
7903        state.config.graph.land_approval = true;
7904        state.pr_head = Some("task-head".into());
7905        state.pr_pushed_head = Some(head.clone());
7906        state.candidates = vec![winning_candidate("change")];
7907        state.candidates[0].worktree = repo;
7908        state.candidates[0].branch = "winner".into();
7909        state.tally = Some(uncontested_tally());
7910        state.gate_ran = true;
7911        state.gate_head = Some(head.clone());
7912        state.land_sync_pending = true;
7913        state.save().unwrap();
7914        (tmp, state, head)
7915    }
7916
7917    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7918        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7919        resume_landing_head(state, head, &green_pr().url, &forge, None).await
7920    }
7921
7922    async fn advance_landing_base(state: &RunState) {
7923        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7924        std::fs::write(state.repo.join("advance"), "advance").unwrap();
7925        git::git(&state.repo, &["add", "."]).await.unwrap();
7926        git::git(&state.repo, &["commit", "-m", "advance base"])
7927            .await
7928            .unwrap();
7929        git::git(&state.repo, &["push", "origin", "main"])
7930            .await
7931            .unwrap();
7932        git::git(&state.repo, &["checkout", "winner"])
7933            .await
7934            .unwrap();
7935    }
7936
7937    #[tokio::test]
7938    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
7939        let (_tmp, mut state, head) = landing_git_fixture().await;
7940        advance_landing_base(&state).await;
7941        let scratch = state.dir().join("rebase");
7942        std::fs::create_dir_all(&scratch).unwrap();
7943        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
7944        let attempts = state.land_sync_attempts;
7945        let error = rebase_landing_worktree(&mut state, "origin/main")
7946            .await
7947            .unwrap_err();
7948        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
7949        assert_eq!(state.land_sync_attempts, attempts);
7950        assert!(state.land_sync_target.is_none());
7951        assert!(state.rebase_fixes.is_empty());
7952        assert!(
7953            state
7954                .base_sync
7955                .as_ref()
7956                .is_none_or(|sync| sync.conflict.is_none())
7957        );
7958        let block = state.resource_block.as_ref().unwrap();
7959        assert_eq!(block.kind, crate::rebase::SEQUENCER_INFRASTRUCTURE);
7960        assert!(
7961            block.detail.contains("inspect scratch Git backlink"),
7962            "{}",
7963            block.detail
7964        );
7965        assert_eq!(
7966            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
7967            "keep"
7968        );
7969        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
7970        std::fs::remove_dir_all(&scratch).unwrap();
7971        state.resource_block = None;
7972        assert_eq!(
7973            rebase_landing_worktree(&mut state, "origin/main")
7974                .await
7975                .unwrap(),
7976            crate::rebase::Rebased::Applied
7977        );
7978        assert_eq!(state.land_sync_attempts, attempts + 1);
7979        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
7980        assert!(git::is_clean(&state.repo).await.unwrap());
7981        assert!(state.rebase_fixes.is_empty());
7982    }
7983
7984    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7985    {
7986        let (tmp, mut state, old) = landing_git_fixture().await;
7987        let path = tmp.path().join("foreign");
7988        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7989            .await
7990            .unwrap();
7991        state.foreign_checkout = Some(
7992            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7993                .await
7994                .unwrap(),
7995        );
7996        state.config.merge.mode = crate::config::MergeMode::Pr;
7997        state.save().unwrap();
7998        (tmp, state, old, path)
7999    }
8000
8001    #[tokio::test]
8002    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
8003        for phase in 0..4 {
8004            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
8005            advance_landing_base(&state).await;
8006            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
8007            if phase == 0 {
8008                // The live Step::Rebase path uses this same synchronization
8009                // and publication pair, without going through resume.
8010                assert_eq!(
8011                    rebase_landing_worktree(&mut state, "origin/main")
8012                        .await
8013                        .unwrap(),
8014                    crate::rebase::Rebased::Applied
8015                );
8016            } else {
8017                interrupt_landing_rebase(&mut state).await;
8018                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
8019                if phase == 2 {
8020                    git::sync_to_head(&state.repo).await.unwrap();
8021                } else if phase == 3 {
8022                    // Crash after joining history, before clearing its saved
8023                    // start. Repeating restoration must not add another merge.
8024                    restore_landing_worktree(&mut state).await.unwrap();
8025                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8026                    state.land_rebase_from = Some(old.clone());
8027                    state.save().unwrap();
8028                    restore_landing_worktree(&mut state).await.unwrap();
8029                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
8030                }
8031                state.save().unwrap();
8032                state = RunState::load(&state.id).unwrap();
8033                restore_landing_worktree(&mut state).await.unwrap();
8034                assert_eq!(
8035                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
8036                    repaired_tree
8037                );
8038            }
8039            let head = if phase == 0 {
8040                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
8041                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
8042                    .await
8043                    .unwrap()
8044            } else {
8045                resume_observed_head(&mut state, &old).await.unwrap()
8046            };
8047            assert!(git::is_ancestor(&state.repo, &old, &head).await);
8048            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
8049            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
8050            assert_eq!(
8051                git::remote_head(&state.repo, "origin", "task-head")
8052                    .await
8053                    .unwrap(),
8054                Some(head.clone())
8055            );
8056            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8057            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
8058            assert!(state.gate_allows_progress());
8059            assert!(state.land_rebase_from.is_none());
8060            assert!(!state.land_sync_pending);
8061            assert!(git::is_clean(&path).await.unwrap());
8062        }
8063    }
8064
8065    #[tokio::test]
8066    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
8067        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
8068        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8069        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8070        git::commit_all(&state.repo, "conflicting base")
8071            .await
8072            .unwrap();
8073        git::git(&state.repo, &["push", "origin", "main"])
8074            .await
8075            .unwrap();
8076        git::git(&state.repo, &["checkout", "winner"])
8077            .await
8078            .unwrap();
8079        landing_gate_fixer(
8080            &mut state,
8081            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
8082        );
8083        state.config.graph.gate_fix_rounds = 0;
8084        state.config.verify.gate = vec!["exit 1".into()];
8085        assert!(resume_observed_head(&mut state, &old).await.is_err());
8086        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
8087        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8088        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
8089        assert_eq!(
8090            std::fs::read_to_string(state.repo.join("change")).unwrap(),
8091            "resolved"
8092        );
8093        // A red gate must neither deliver nor publish the repaired tree.
8094        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
8095        assert_eq!(
8096            git::remote_head(&state.repo, "origin", "task-head")
8097                .await
8098                .unwrap(),
8099            Some(old.clone())
8100        );
8101        state = RunState::load(&state.id).unwrap();
8102        state.config.verify.gate = vec!["grep -q resolved change".into()];
8103        let head = resume_observed_head(&mut state, &old).await.unwrap();
8104        assert_eq!(head, repaired);
8105        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
8106        assert_eq!(
8107            std::fs::read_to_string(path.join("change")).unwrap(),
8108            "resolved"
8109        );
8110        assert_eq!(
8111            git::remote_head(&state.repo, "origin", "task-head")
8112                .await
8113                .unwrap(),
8114            Some(head.clone())
8115        );
8116        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8117        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
8118        assert!(git::is_clean(&path).await.unwrap());
8119    }
8120
8121    #[tokio::test]
8122    async fn landing_resume_completes_the_last_charged_sync_attempt() {
8123        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
8124            let (_tmp, mut state, old) = landing_git_fixture().await;
8125            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8126            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8127            git::commit_all(&state.repo, "conflicting base")
8128                .await
8129                .unwrap();
8130            git::git(&state.repo, &["push", "origin", "main"])
8131                .await
8132                .unwrap();
8133            git::git(&state.repo, &["checkout", "winner"])
8134                .await
8135                .unwrap();
8136            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
8137            state.config.graph.land_rounds = 1;
8138            state.land_sync_attempts = 1;
8139            state.land_sync_target = saved_target.then(|| target.clone());
8140            state.land_rebase_from = Some(old.clone());
8141            landing_gate_fixer(
8142                &mut state,
8143                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
8144            );
8145            state.config.verify.gate = vec!["grep -q resolved change".into()];
8146            state.save().unwrap();
8147            // Simulate interruption before the scratch start and at a conflict.
8148            if scratch_started {
8149                assert!(matches!(
8150                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
8151                        .await
8152                        .unwrap(),
8153                    git::RebaseStart::Conflicted(_)
8154                ));
8155            }
8156            state = RunState::load(&state.id).unwrap();
8157            let head = resume_observed_head(&mut state, &old).await.unwrap();
8158            assert_ne!(head, old);
8159            assert_eq!(state.land_sync_attempts, 1);
8160            assert!(state.land_sync_target.is_none());
8161            assert!(state.land_rebase_from.is_none());
8162            assert!(!state.land_sync_pending);
8163            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8164            assert!(state.gate_allows_progress());
8165            assert_eq!(
8166                git::remote_head(&state.repo, "origin", "task-head")
8167                    .await
8168                    .unwrap(),
8169                Some(head)
8170            );
8171            assert!(
8172                rebase_landing_worktree(&mut state, "origin/main")
8173                    .await
8174                    .unwrap_err()
8175                    .to_string()
8176                    .contains("budget exhausted")
8177            );
8178        }
8179    }
8180
8181    #[tokio::test]
8182    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
8183        let (_tmp, mut state, old) = landing_git_fixture().await;
8184        advance_landing_base(&state).await;
8185        state.config.verify.gate = vec!["test -f advance".into()];
8186        let head = resume_observed_head(&mut state, &old).await.unwrap();
8187        assert_ne!(head, old);
8188        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8189        assert!(state.gate_allows_progress());
8190        assert_eq!(
8191            git::remote_head(&state.repo, "origin", "task-head")
8192                .await
8193                .unwrap(),
8194            Some(head.clone())
8195        );
8196        assert_eq!(state.pr_pushed_head, Some(head));
8197        assert!(!state.land_sync_pending);
8198        assert!(state.config.graph.land_approval);
8199    }
8200
8201    fn landing_gate_fixer(state: &mut RunState, script: &str) {
8202        state.config.disk.min_free_bytes = 0;
8203        state.config.graph.gate_fix_rounds = 1;
8204        state.config.agents = vec![crate::config::AgentSpec {
8205            id: "mock".into(),
8206            kind: crate::config::AgentKind::Command,
8207            model: None,
8208            command: vec!["sh".into(), "-c".into(), script.into()],
8209            extra_args: Vec::new(),
8210            env: Default::default(),
8211            prompt_delivery: None,
8212            max_turn_secs: None,
8213        }];
8214        state.candidates[0].agent = "mock".into();
8215    }
8216
8217    #[tokio::test]
8218    async fn rebase_fixer_invocation_cap_survives_fallback_and_reload() {
8219        let (tmp, mut state, original) = landing_git_fixture().await;
8220        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8221        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8222        git::commit_all(&state.repo, "conflicting base")
8223            .await
8224            .unwrap();
8225        let target = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8226        git::git(&state.repo, &["checkout", "winner"])
8227            .await
8228            .unwrap();
8229        let scratch = state.dir().join("rebase");
8230        let counter = tmp.path().join("calls");
8231        landing_gate_fixer(
8232            &mut state,
8233            "echo \"$REBASE_AGENT\" >> \"$REBASE_COUNTER\"; exit 1",
8234        );
8235        let template = state.config.agents[0].clone();
8236        let ids = ["mock", "fallback1", "fallback2", "fallback3"].map(str::to_owned);
8237        state.config.agents = ids
8238            .iter()
8239            .map(|id| {
8240                let mut spec = template.clone();
8241                spec.id.clone_from(id);
8242                spec.env.insert("REBASE_AGENT".into(), id.clone());
8243                spec.env
8244                    .insert("REBASE_COUNTER".into(), git::path_arg(&counter));
8245                spec
8246            })
8247            .collect();
8248        state.config.roles.fixer = Some(crate::config::AgentChoice::Chain(ids.to_vec()));
8249        state.config.graph.review_rounds = 3;
8250        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8251        state.config.graph.timeout_resource_wait = 0;
8252        let started = git::rebase_start(&state.repo, &scratch, "winner", &target)
8253            .await
8254            .unwrap();
8255        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
8256        let home = crate::run::home();
8257        let cache = crate::build_target::resolve(&home, &scratch).unwrap();
8258        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", &scratch, &original);
8259        let crate::cache::AcquireOutcome::Acquired(lease) =
8260            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
8261        else {
8262            panic!("test target was already leased");
8263        };
8264        let error = crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8265            .await
8266            .unwrap_err();
8267        assert!(error.is::<crate::agent::IsolatedSeatWait>(), "{error:#}");
8268        assert!(!counter.exists());
8269        assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), ["change"]);
8270        drop(lease);
8271        state = RunState::load(&state.id).unwrap();
8272        for _ in 0..2 {
8273            let crate::rebase::Rebased::Stopped(why) =
8274                crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8275                    .await
8276                    .unwrap()
8277            else {
8278                panic!("the unresolved conflict must stop");
8279            };
8280            assert!(why.contains("after 3 of 3 fixer round(s)"), "{why}");
8281            assert_eq!(
8282                std::fs::read_to_string(&counter)
8283                    .unwrap()
8284                    .lines()
8285                    .collect::<Vec<_>>(),
8286                ["mock", "fallback1", "fallback2"]
8287            );
8288            assert_eq!(
8289                git::rev_parse(&state.repo, "winner").await.unwrap(),
8290                original
8291            );
8292            state = RunState::load(&state.id).unwrap();
8293        }
8294    }
8295
8296    #[tokio::test]
8297    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
8298        let (_tmp, mut state, old) = landing_git_fixture().await;
8299        std::fs::write(state.repo.join("change"), "operator update").unwrap();
8300        git::commit_all(&state.repo, "extend winner").await.unwrap();
8301        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8302        git::git(
8303            &state.repo,
8304            &["push", "origin", "HEAD:refs/heads/task-head"],
8305        )
8306        .await
8307        .unwrap();
8308        state.config.verify.gate = vec!["exit 1".into()];
8309        state.config.graph.gate_fix_rounds = 0;
8310        assert!(resume_observed_head(&mut state, &updated).await.is_err());
8311        assert_ne!(old, updated);
8312        assert_eq!(state.gate_head.as_ref(), Some(&updated));
8313        assert!(!state.gate_allows_progress());
8314        assert!(state.land_sync_pending);
8315        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
8316        let head = resume_observed_head(&mut state, &updated).await.unwrap();
8317        assert_eq!(head, updated);
8318        assert!(state.gate_allows_progress());
8319        assert!(!state.land_sync_pending);
8320        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8321        land_with(&mut state, &green_pr().url, &forge)
8322            .await
8323            .unwrap();
8324        assert!(state.parked);
8325        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8326        assert!(forge.argvs().is_empty());
8327    }
8328
8329    #[tokio::test]
8330    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
8331        for divergent in [false, true] {
8332            let (_tmp, mut state, old) = landing_git_fixture().await;
8333            if divergent {
8334                git::git(&state.repo, &["reset", "--hard", "origin/main"])
8335                    .await
8336                    .unwrap();
8337            }
8338            std::fs::write(state.repo.join("external"), "external").unwrap();
8339            git::commit_all(&state.repo, "external update")
8340                .await
8341                .unwrap();
8342            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8343            git::git(
8344                &state.repo,
8345                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
8346            )
8347            .await
8348            .unwrap();
8349            if !divergent {
8350                git::git(&state.repo, &["reset", "--hard", &old])
8351                    .await
8352                    .unwrap();
8353            }
8354            let error = resume_observed_head(&mut state, &external)
8355                .await
8356                .unwrap_err();
8357            assert!(
8358                error
8359                    .to_string()
8360                    .contains("public head moved outside this run")
8361            );
8362            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
8363            assert_eq!(
8364                git::remote_head(&state.repo, "origin", "task-head")
8365                    .await
8366                    .unwrap(),
8367                Some(external)
8368            );
8369        }
8370    }
8371
8372    #[tokio::test]
8373    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
8374        let (_tmp, mut state, old) = landing_git_fixture().await;
8375        advance_landing_base(&state).await;
8376        landing_gate_fixer(
8377            &mut state,
8378            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8379        );
8380        state.config.verify.gate =
8381            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8382        state.config.verify.e2e = vec!["test -f advance".into()];
8383        // First save a red gate without spending a fixer round. Resume must
8384        // still offer the remaining budget for this exact same failed head.
8385        state.config.graph.gate_fix_rounds = 0;
8386        assert!(resume_observed_head(&mut state, &old).await.is_err());
8387        assert_eq!(
8388            git::remote_head(&state.repo, "origin", "task-head")
8389                .await
8390                .unwrap(),
8391            Some(old.clone())
8392        );
8393        state.config.graph.gate_fix_rounds = 1;
8394        let head = resume_observed_head(&mut state, &old).await.unwrap();
8395        assert_eq!(state.gate_fixes.len(), 1);
8396        assert!(state.gate_fixes[0].committed);
8397        assert!(state.gate_allows_progress());
8398        assert_eq!(state.gate_head.as_ref(), Some(&head));
8399        assert_eq!(
8400            git::remote_head(&state.repo, "origin", "task-head")
8401                .await
8402                .unwrap(),
8403            Some(head.clone())
8404        );
8405        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8406        land_with(&mut state, &green_pr().url, &forge)
8407            .await
8408            .unwrap();
8409        assert!(state.parked);
8410        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8411        assert!(forge.argvs().is_empty());
8412    }
8413
8414    #[tokio::test]
8415    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
8416        let (_tmp, mut state, old) = landing_git_fixture().await;
8417        advance_landing_base(&state).await;
8418        landing_gate_fixer(
8419            &mut state,
8420            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8421        );
8422        state.config.verify.gate = vec!["echo still red; exit 1".into()];
8423        for _ in 0..2 {
8424            assert!(resume_observed_head(&mut state, &old).await.is_err());
8425            assert_eq!(state.gate_fixes.len(), 1);
8426            assert_eq!(
8427                git::remote_head(&state.repo, "origin", "task-head")
8428                    .await
8429                    .unwrap(),
8430                Some(old.clone())
8431            );
8432        }
8433    }
8434
8435    #[tokio::test]
8436    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
8437        let (_tmp, mut state, old) = landing_git_fixture().await;
8438        advance_landing_base(&state).await;
8439        landing_gate_fixer(
8440            &mut state,
8441            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8442        );
8443        state.config.verify.gate =
8444            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8445        // The repair makes the gate green while breaking an e2e invariant.
8446        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
8447        let mut saved_comparison = None;
8448        for resume in 0..3 {
8449            assert!(resume_observed_head(&mut state, &old).await.is_err());
8450            state = RunState::load(&state.id).unwrap();
8451            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8452            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8453            assert_eq!(evidence.head, head);
8454            assert!(!evidence.passed);
8455            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
8456            let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
8457            if let Some(saved) = &saved_comparison {
8458                assert_eq!(comparison, saved);
8459            } else {
8460                saved_comparison = Some(comparison.clone());
8461            }
8462            assert_eq!(state.gate_fixes.len(), 1);
8463            assert_eq!(
8464                git::remote_head(&state.repo, "origin", "task-head")
8465                    .await
8466                    .unwrap(),
8467                Some(old.clone())
8468            );
8469            if resume > 0 {
8470                assert!(
8471                    state.gate_allows_progress(),
8472                    "a green gate must not bypass red e2e"
8473                );
8474            }
8475        }
8476        // A changed command is not new evidence about the already checked SHA.
8477        state.config.verify.e2e = vec!["grep -q fixed change".into()];
8478        assert!(resume_observed_head(&mut state, &old).await.is_err());
8479        assert_eq!(
8480            state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
8481            saved_comparison
8482        );
8483    }
8484
8485    #[tokio::test]
8486    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
8487        for phase in 0..3 {
8488            let (_tmp, mut state, old) = landing_git_fixture().await;
8489            advance_landing_base(&state).await;
8490            let head = resume_observed_head(&mut state, &old).await.unwrap();
8491            // Persist the shapes left by interruption, resource deferral,
8492            // and a successful check for a different (older) SHA.
8493            state.land_sync_pending = true;
8494            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
8495            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8496                if phase == 2 {
8497                    old.clone()
8498                } else {
8499                    head.clone()
8500                },
8501                phase == 2,
8502                if phase == 1 {
8503                    vec![crate::run::CommandOutcome {
8504                        command: state.config.verify.e2e[0].clone(),
8505                        code: None,
8506                        output_tail: "verification resource unavailable".into(),
8507                        duration_ms: 0,
8508                        resource_blocked: true,
8509                        ..Default::default()
8510                    }]
8511                } else {
8512                    Vec::new()
8513                },
8514            ));
8515            state.save().unwrap();
8516            for _ in 0..2 {
8517                state = RunState::load(&state.id).unwrap();
8518                assert!(resume_observed_head(&mut state, &head).await.is_err());
8519                let evidence = state.gate_repair_e2e.as_ref().unwrap();
8520                assert_eq!(evidence.head, head);
8521                assert!(!evidence.passed);
8522                assert!(!evidence.outcomes.is_empty());
8523                assert_eq!(
8524                    git::remote_head(&state.repo, "origin", "task-head")
8525                        .await
8526                        .unwrap(),
8527                    Some(head.clone())
8528                );
8529                assert!(state.land_sync_pending);
8530            }
8531        }
8532    }
8533
8534    #[tokio::test]
8535    async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
8536        for code in [None, Some(126), Some(127)] {
8537            let (_tmp, mut state, old) = landing_git_fixture().await;
8538            advance_landing_base(&state).await;
8539            let head = resume_observed_head(&mut state, &old).await.unwrap();
8540            state.land_sync_pending = true;
8541            state.config.verify.e2e = vec!["true".into()];
8542            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8543                head.clone(),
8544                false,
8545                vec![crate::run::CommandOutcome {
8546                    command: state.config.verify.e2e[0].clone(),
8547                    code,
8548                    output_tail: "verification command did not complete".into(),
8549                    ..Default::default()
8550                }],
8551            ));
8552            state.save().unwrap();
8553            state = RunState::load(&state.id).unwrap();
8554            assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
8555            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8556            assert_eq!(evidence.head, head);
8557            assert!(evidence.passed);
8558            assert_eq!(evidence.outcomes[0].code, Some(0));
8559        }
8560    }
8561
8562    async fn interrupt_landing_rebase(state: &mut RunState) {
8563        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
8564        state.save().unwrap();
8565        let scratch = state.dir().join("rebase");
8566        assert_eq!(
8567            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
8568                .await
8569                .unwrap(),
8570            crate::rebase::Rebased::Applied
8571        );
8572        assert!(!git::is_clean(&state.repo).await.unwrap());
8573    }
8574
8575    async fn landing_setup(state: &mut RunState) {
8576        git::git(
8577            &state.repo,
8578            &["config", "extensions.worktreeConfig", "true"],
8579        )
8580        .await
8581        .unwrap();
8582        state.config.worktree.setup =
8583            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8584        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8585            .await
8586            .unwrap();
8587        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8588    }
8589
8590    #[tokio::test]
8591    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8592        let (tmp, mut state, head) = landing_git_fixture().await;
8593        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8594        git::acquire_worktree_config(&state.repo).await.unwrap();
8595        let winner = tmp.path().join("landing");
8596        git::worktree_add_existing(&state.repo, &winner, "winner", false)
8597            .await
8598            .unwrap();
8599        state.candidates[0].worktree = winner.clone();
8600        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8601        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8602        state.config.disk.min_free_bytes = 0;
8603        state.config.worktree.setup = vec![crate::config::SetupStep {
8604            run: Some("touch setup-completed".into()),
8605            ..Default::default()
8606        }];
8607        #[cfg(unix)]
8608        {
8609            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8610            state.config.coordination = Some(crate::config::Coordination {
8611                contract_file: "fixture-contract".into(),
8612                contract_token: "fixture-v1".into(),
8613                lock_file: "fixture-lock".into(),
8614            });
8615        }
8616        state.land_rebase_from = Some(head);
8617        let restore = restore_landing_worktree(&mut state);
8618        // Only the registered Unix fixture can deadlock by reacquiring its
8619        // own operation lease. Don't time the whole Git/setup path elsewhere.
8620        #[cfg(unix)]
8621        let restore = async {
8622            tokio::time::timeout(Duration::from_secs(15), restore)
8623                .await
8624                .expect("landing setup must not wait for its own repository operation")
8625        };
8626        restore.await.unwrap();
8627        assert!(winner.join("setup-completed").is_file());
8628        assert!(git::is_clean(&winner).await.unwrap());
8629        assert!(state.land_rebase_from.is_none());
8630    }
8631
8632    #[tokio::test]
8633    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8634        for phase in 0..3 {
8635            let (_tmp, mut state, old) = landing_git_fixture().await;
8636            advance_landing_base(&state).await;
8637            landing_setup(&mut state).await;
8638            if phase > 0 {
8639                interrupt_landing_rebase(&mut state).await;
8640                if phase == 2 {
8641                    // Crash after clean removed setup products, before setup.
8642                    git::sync_to_head(&state.repo).await.unwrap();
8643                    assert!(!state.repo.join(".env").exists());
8644                }
8645                state = RunState::load(&state.id).unwrap();
8646            }
8647            let head = resume_observed_head(&mut state, &old).await.unwrap();
8648            assert_ne!(head, old);
8649            assert!(state.gate_allows_progress());
8650            assert!(state.land_rebase_from.is_none());
8651            assert_eq!(
8652                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8653                "secret"
8654            );
8655            assert!(git::is_clean(&state.repo).await.unwrap());
8656            assert!(
8657                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8658                    .await
8659                    .unwrap()
8660                    .contains(".env")
8661            );
8662        }
8663    }
8664
8665    #[tokio::test]
8666    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8667        let (_tmp, mut state, _) = landing_git_fixture().await;
8668        advance_landing_base(&state).await;
8669        landing_setup(&mut state).await;
8670        interrupt_landing_rebase(&mut state).await;
8671        // Exercise unusual names without asking Windows to create an invalid
8672        // control-character filename. Unix also covers embedded newlines.
8673        let locals = [
8674            "local notes",
8675            #[cfg(unix)]
8676            "local\nnotes",
8677        ];
8678        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8679            .await
8680            .unwrap();
8681        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8682        for local in locals {
8683            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8684            assert!(
8685                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8686                    .await
8687                    .unwrap()
8688                    .ok()
8689            );
8690        }
8691        restore_landing_worktree(&mut state).await.unwrap();
8692        for local in locals {
8693            assert_eq!(
8694                std::fs::read_to_string(state.repo.join(local)).unwrap(),
8695                "keep these notes"
8696            );
8697        }
8698        assert_eq!(
8699            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8700            "secret"
8701        );
8702        assert!(git::is_clean(&state.repo).await.unwrap());
8703        assert!(state.land_rebase_from.is_none());
8704    }
8705
8706    #[tokio::test]
8707    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8708        for local in ["advance", "advance/notes", "new-directory"] {
8709            let (_tmp, mut state, _) = landing_git_fixture().await;
8710            advance_landing_base(&state).await;
8711            // Also cover a local file blocking a new tracked directory.
8712            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8713            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8714            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8715            git::git(&state.repo, &["add", "."]).await.unwrap();
8716            git::git(&state.repo, &["commit", "-m", "add directory"])
8717                .await
8718                .unwrap();
8719            git::git(&state.repo, &["push", "origin", "main"])
8720                .await
8721                .unwrap();
8722            git::git(&state.repo, &["checkout", "winner"])
8723                .await
8724                .unwrap();
8725            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8726                .await
8727                .unwrap();
8728            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8729            let path = state.repo.join(local);
8730            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8731            std::fs::write(&path, "local notes").unwrap();
8732            interrupt_landing_rebase(&mut state).await;
8733            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8734            let checkpoint = state.land_rebase_from.clone();
8735            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8736            assert!(
8737                error.to_string().contains("conflicting with HEAD"),
8738                "{error:#}"
8739            );
8740            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8741            assert_eq!(
8742                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8743                before
8744            );
8745            assert_eq!(state.land_rebase_from, checkpoint);
8746        }
8747    }
8748
8749    #[tokio::test]
8750    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8751        for interrupted in [false, true] {
8752            let (_tmp, mut state, old) = landing_git_fixture().await;
8753            assert!(state.config.worktree.setup.is_empty());
8754            // A gate product exists before the base moves, without setup metadata.
8755            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8756                .await
8757                .unwrap();
8758            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8759            state.config.verify.gate =
8760                vec!["mkdir -p target && printf artifact > target/probe".into()];
8761            state.gate_ran = false;
8762            resume_observed_head(&mut state, &old).await.unwrap();
8763            assert_eq!(
8764                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8765                "artifact"
8766            );
8767            advance_landing_base(&state).await;
8768            if interrupted {
8769                interrupt_landing_rebase(&mut state).await;
8770                state = RunState::load(&state.id).unwrap();
8771            }
8772            state.config.verify.gate =
8773                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8774            let head = resume_observed_head(&mut state, &old).await.unwrap();
8775            assert_ne!(head, old);
8776            assert!(state.gate_allows_progress());
8777            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8778            assert_eq!(
8779                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8780                "artifact"
8781            );
8782            assert!(state.land_rebase_from.is_none());
8783            assert_eq!(
8784                git::remote_head(&state.repo, "origin", "task-head")
8785                    .await
8786                    .unwrap(),
8787                Some(head.clone())
8788            );
8789            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8790            land_with(&mut state, &green_pr().url, &forge)
8791                .await
8792                .unwrap();
8793            assert!(state.parked);
8794            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8795            assert!(forge.argvs().is_empty());
8796        }
8797    }
8798
8799    #[tokio::test]
8800    #[cfg(unix)]
8801    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8802        use std::os::fd::AsRawFd as _;
8803
8804        for interrupted in [false, true] {
8805            let (_tmp, mut state, _) = landing_git_fixture().await;
8806            advance_landing_base(&state).await;
8807            landing_setup(&mut state).await;
8808            if interrupted {
8809                interrupt_landing_rebase(&mut state).await;
8810            }
8811            state.config.worktree.setup =
8812                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8813            let common = crate::repo_lock::common_dir(&state.repo)
8814                .await
8815                .unwrap()
8816                .unwrap();
8817            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8818            state.config.coordination = crate::config::test_coordination();
8819            state.config.graph.timeout_resource_wait = 0;
8820            let external = std::fs::OpenOptions::new()
8821                .read(true)
8822                .write(true)
8823                .create(true)
8824                .truncate(false)
8825                .open(common.join("updater.lock"))
8826                .unwrap();
8827            // SAFETY: the descriptor belongs to `external` and remains open.
8828            let locked =
8829                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8830            assert_eq!(locked, 0);
8831            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8832            let checkpoint = state.land_rebase_from.clone();
8833            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8834            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8835            assert_eq!(
8836                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8837                before
8838            );
8839            assert_eq!(state.land_rebase_from, checkpoint);
8840            assert_eq!(
8841                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8842                "secret"
8843            );
8844
8845            drop(external);
8846            state.config.graph.timeout_resource_wait = 2;
8847            restore_landing_worktree(&mut state).await.unwrap();
8848            assert!(git::is_clean(&state.repo).await.unwrap());
8849            assert!(state.land_rebase_from.is_none());
8850            assert_eq!(
8851                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8852                "restored"
8853            );
8854        }
8855    }
8856
8857    #[tokio::test]
8858    #[cfg(unix)]
8859    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8860        use std::sync::atomic::{AtomicBool, Ordering};
8861
8862        let (_tmp, mut state, _) = landing_git_fixture().await;
8863        advance_landing_base(&state).await;
8864        landing_setup(&mut state).await;
8865        interrupt_landing_rebase(&mut state).await;
8866        let common = crate::repo_lock::common_dir(&state.repo)
8867            .await
8868            .unwrap()
8869            .unwrap();
8870        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8871        state.config.coordination = crate::config::test_coordination();
8872        let holder = crate::repo_lock::SeatLease::for_checkout(
8873            &state.repo,
8874            true,
8875            state.config.coordination.as_ref(),
8876        )
8877        .await
8878        .unwrap();
8879        assert!(holder.is_some());
8880        let cancelled = Arc::new(AtomicBool::new(false));
8881        let signal = cancelled.clone();
8882        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8883            signal.load(Ordering::SeqCst)
8884        });
8885        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8886        let checkpoint = state.land_rebase_from.clone();
8887        let (result, ()) = tokio::join!(
8888            tokio::time::timeout(
8889                Duration::from_secs(2),
8890                wait.scope(restore_landing_worktree(&mut state)),
8891            ),
8892            async {
8893                tokio::time::sleep(Duration::from_millis(100)).await;
8894                cancelled.store(true, Ordering::SeqCst);
8895            }
8896        );
8897        let error = result
8898            .expect("cancellation must release the waiting driver")
8899            .unwrap_err();
8900        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8901        assert_eq!(
8902            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8903            before
8904        );
8905        assert_eq!(state.land_rebase_from, checkpoint);
8906        assert_eq!(
8907            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8908            "secret"
8909        );
8910        drop(holder);
8911        restore_landing_worktree(&mut state).await.unwrap();
8912        assert!(state.land_rebase_from.is_none());
8913        assert!(git::is_clean(&state.repo).await.unwrap());
8914    }
8915
8916    #[tokio::test]
8917    #[cfg(unix)]
8918    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8919        use std::sync::atomic::{AtomicBool, Ordering};
8920
8921        for e2e in [false, true] {
8922            let (_tmp, mut state, head) = landing_git_fixture().await;
8923            let common = crate::repo_lock::common_dir(&state.repo)
8924                .await
8925                .unwrap()
8926                .unwrap();
8927            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8928            state.config.coordination = crate::config::test_coordination();
8929            if e2e {
8930                state.config.verify.e2e = vec!["true".into()];
8931                state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8932                    head.clone(),
8933                    false,
8934                    Vec::new(),
8935                ));
8936            } else {
8937                state.config.verify.gate = vec!["true".into()];
8938                state.gate_ran = false;
8939            }
8940            let holder = crate::repo_lock::SeatLease::for_checkout(
8941                &state.repo,
8942                true,
8943                state.config.coordination.as_ref(),
8944            )
8945            .await
8946            .unwrap();
8947            assert!(holder.is_some());
8948            let cancelled = Arc::new(AtomicBool::new(false));
8949            let signal = cancelled.clone();
8950            let waiting = Arc::new(tokio::sync::Notify::new());
8951            let observed = waiting.clone();
8952            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8953                observed.notify_one();
8954                signal.load(Ordering::SeqCst)
8955            });
8956            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8957            let url = green_pr().url;
8958            let result = {
8959                let mut publishing =
8960                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8961                // Git and fixture I/O precede local coordination. Start the
8962                // cancellation deadline only once the inherited wait policy
8963                // is polled, rather than timing those unrelated subprocesses.
8964                tokio::time::timeout(Duration::from_secs(30), async {
8965                    tokio::select! {
8966                        result = &mut publishing => panic!(
8967                            "verification must wait behind the held seat: {result:?}"
8968                        ),
8969                        () = waiting.notified() => {}
8970                    }
8971                })
8972                .await
8973                .expect("verification must reach the inherited coordination wait");
8974                cancelled.store(true, Ordering::SeqCst);
8975                tokio::time::timeout(Duration::from_secs(2), publishing).await
8976            };
8977            let error = result
8978                .expect("cancellation must release the verification waiter")
8979                .unwrap_err();
8980            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8981            assert!(error.to_string().contains("cancelled"), "{error:#}");
8982            assert!(forge.argvs().is_empty());
8983            assert_eq!(
8984                git::remote_head(&state.repo, "origin", "task-head")
8985                    .await
8986                    .unwrap(),
8987                Some(head.clone())
8988            );
8989            drop(holder);
8990            // Cancellation must release its reservation so another attempt can verify.
8991            assert_eq!(
8992                publish_landing_head(&mut state, &head, &url, &forge)
8993                    .await
8994                    .unwrap(),
8995                head
8996            );
8997        }
8998    }
8999
9000    #[tokio::test]
9001    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
9002        for staged in [false, true] {
9003            let (_tmp, mut state, old) = landing_git_fixture().await;
9004            advance_landing_base(&state).await;
9005            interrupt_landing_rebase(&mut state).await;
9006            std::fs::write(state.repo.join("change"), "user edit").unwrap();
9007            if staged {
9008                git::git(&state.repo, &["add", "change"]).await.unwrap();
9009            }
9010            assert!(resume_observed_head(&mut state, &old).await.is_err());
9011            assert_eq!(
9012                std::fs::read_to_string(state.repo.join("change")).unwrap(),
9013                "user edit"
9014            );
9015            assert_eq!(
9016                git::remote_head(&state.repo, "origin", "task-head")
9017                    .await
9018                    .unwrap(),
9019                Some(old)
9020            );
9021        }
9022    }
9023
9024    #[tokio::test]
9025    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
9026        let (_tmp, mut state, head) = landing_git_fixture().await;
9027        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
9028        let id = state.id.clone();
9029        let pr = land_with(&mut state, &green_pr().url, &forge)
9030            .await
9031            .unwrap();
9032        assert_eq!(pr.state, PrLifecycle::Open);
9033        assert_eq!(state.id, id);
9034        assert!(state.parked);
9035        assert_eq!(state.status, RunStatus::Landing);
9036        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
9037        assert!(forge.argvs().is_empty());
9038
9039        state.land_sync_pending = true;
9040        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
9041        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
9042        closed.pr.state = PrLifecycle::Closed;
9043        let forge = Scripted::new(vec![closed], vec![]);
9044        assert_eq!(
9045            land_with(&mut state, &green_pr().url, &forge)
9046                .await
9047                .unwrap()
9048                .state,
9049            PrLifecycle::Closed
9050        );
9051        assert_eq!(
9052            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
9053            "do not touch"
9054        );
9055        assert!(forge.argvs().is_empty());
9056    }
9057
9058    #[tokio::test]
9059    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
9060        let (_tmp, mut state, old) = landing_git_fixture().await;
9061        advance_landing_base(&state).await;
9062        state.config.verify.gate = vec!["exit 1".into()];
9063        assert!(resume_observed_head(&mut state, &old).await.is_err());
9064        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
9065        assert!(!state.gate_allows_progress());
9066        assert_eq!(
9067            git::remote_head(&state.repo, "origin", "task-head")
9068                .await
9069                .unwrap(),
9070            Some(old)
9071        );
9072        assert!(state.land_sync_pending);
9073    }
9074
9075    #[tokio::test]
9076    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
9077        let (_tmp, mut state, old) = landing_git_fixture().await;
9078        advance_landing_base(&state).await;
9079        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
9080        // Model a crash after the push but before saving its published SHA.
9081        state.pr_pushed_head = Some(old.clone());
9082        state.land_sync_pending = true;
9083        assert_eq!(
9084            resume_observed_head(&mut state, &pushed).await.unwrap(),
9085            pushed
9086        );
9087        // A writer races the observed PR snapshot: the explicit remote lease
9088        // must reject the push even though preflight saw our expected head.
9089        git::git(
9090            &state.repo,
9091            &["push", "--force", "origin", "main:refs/heads/task-head"],
9092        )
9093        .await
9094        .unwrap();
9095        assert!(
9096            publish_landing_head(
9097                &mut state,
9098                &pushed,
9099                &green_pr().url,
9100                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
9101            )
9102            .await
9103            .unwrap_err()
9104            .to_string()
9105            .contains("publishing gated")
9106        );
9107        assert!(
9108            resume_observed_head(&mut state, "foreign-head")
9109                .await
9110                .is_err()
9111        );
9112    }
9113    #[tokio::test]
9114    async fn landing_publication_refuses_a_pr_closed_during_gate() {
9115        let (_tmp, mut state, head) = landing_git_fixture().await;
9116        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
9117        closed.pr.state = PrLifecycle::Closed;
9118        let forge = Scripted::new(vec![closed], vec![]);
9119        assert!(
9120            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
9121                .await
9122                .unwrap_err()
9123                .to_string()
9124                .contains("PR closed or merged")
9125        );
9126    }
9127
9128    /// A candidate selected by the uncontested tally.
9129    fn winning_candidate(summary: &str) -> Candidate {
9130        Candidate {
9131            index: 0,
9132            label: 'A',
9133            agent: "opus".to_owned(),
9134            branch: "magi/x/A".to_owned(),
9135            worktree: PathBuf::from("/wt/A"),
9136            summary: summary.to_owned(),
9137            stat: String::new(),
9138            files: 1,
9139            commits: 1,
9140            empty: false,
9141            failed: None,
9142            verified_noop: None,
9143            duration_ms: 0,
9144            folded: false,
9145        }
9146    }
9147
9148    fn uncontested_tally() -> Tally {
9149        Tally {
9150            first_choice: BTreeMap::from([('A', 1)]),
9151            borda: BTreeMap::new(),
9152            winner: 'A',
9153            rankings: 1,
9154            unanimous_initial: true,
9155            deliberated: false,
9156            changed_votes: 0,
9157            unanimous_final: true,
9158            tie_break: None,
9159            judges: 1,
9160            present: 1,
9161            quorum: 1,
9162            met_quorum: true,
9163            uncontested: None,
9164        }
9165    }
9166
9167    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
9168        ReviewRecord {
9169            attempts: 0,
9170            reviewer,
9171            agent: agent.to_owned(),
9172            summary: summary.to_owned(),
9173            findings: Vec::new(),
9174            vote: None,
9175            failed: None,
9176            duration_ms: 0,
9177        }
9178    }
9179
9180    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
9181        let answered = reviews.len();
9182        ReviewRound {
9183            round,
9184            head: "abc1234".to_owned(),
9185            verified_head: None,
9186            verified_at: None,
9187            reviews,
9188            e2e: Vec::new(),
9189            verify_retried: false,
9190            e2e_deferred: false,
9191            e2e_defer_reason: None,
9192            fix: None,
9193            blocking: 0,
9194            answered,
9195            expected: answered,
9196            clean: true,
9197            progressed: false,
9198            vote_split: false,
9199            reconsideration: Vec::new(),
9200            verdict: None,
9201        }
9202    }
9203
9204    #[test]
9205    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
9206        let en = panel();
9207        assert!(en.contains("Task"), "{en}");
9208        assert!(en.contains("add retries to the uploader"), "{en}");
9209
9210        let mut state = run_state();
9211        state.config.graph.language = "ja".to_owned();
9212        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9213        assert!(ja.contains("タスク"), "{ja}");
9214        assert!(
9215            ja.contains("add retries to the uploader"),
9216            "the task itself is not translated: {ja}"
9217        );
9218    }
9219
9220    #[test]
9221    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
9222        // `run_state()` has no candidates, no tally and no reviews - exactly
9223        // the shape a run has before anything has judged or reviewed it, and
9224        // the panel must not print an empty box for either.
9225        let html = panel();
9226        assert!(!html.contains("What changed"), "{html}");
9227        assert!(!html.contains("Review verdict"), "{html}");
9228    }
9229
9230    #[test]
9231    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
9232        let mut state = run_state();
9233        state.candidates = vec![winning_candidate("")];
9234        state.tally = Some(uncontested_tally());
9235        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9236        assert!(
9237            !html.contains("What changed"),
9238            "an empty summary must not render an empty box: {html}"
9239        );
9240    }
9241
9242    #[test]
9243    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
9244        let mut state = run_state();
9245        state.candidates = vec![winning_candidate(
9246            "Added a retry loop around the uploader PUT call.",
9247        )];
9248        state.tally = Some(uncontested_tally());
9249        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9250        assert!(en.contains("What changed"), "{en}");
9251        assert!(
9252            en.contains("Added a retry loop around the uploader PUT call."),
9253            "{en}"
9254        );
9255
9256        state.config.graph.language = "ja".to_owned();
9257        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9258        assert!(ja.contains("変更内容"), "{ja}");
9259        assert!(
9260            ja.contains("Added a retry loop around the uploader PUT call."),
9261            "{ja}"
9262        );
9263    }
9264
9265    #[test]
9266    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
9267        let mut state = run_state();
9268        state.reviews = vec![
9269            review_round(
9270                1,
9271                vec![review_record(1, "alpha", "found a race, sent back")],
9272            ),
9273            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
9274        ];
9275        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9276        assert!(en.contains("Review verdict"), "{en}");
9277        assert!(en.contains("race is fixed, clean"), "{en}");
9278        assert!(
9279            !en.contains("found a race, sent back"),
9280            "only the round that actually cleared the merge should show: {en}"
9281        );
9282
9283        state.config.graph.language = "ja".to_owned();
9284        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9285        assert!(ja.contains("レビューの結論"), "{ja}");
9286        assert!(ja.contains("レビュアー"), "{ja}");
9287        assert!(ja.contains("race is fixed, clean"), "{ja}");
9288    }
9289
9290    /// The `incomplete_review = "warn"` policy (see
9291    /// `graph::Runner::review_loop`) can push a `clean` round to
9292    /// `state.reviews` while one seat's own record still has `failed: Some`
9293    /// and an empty `summary` - a seat that never answered, not one that
9294    /// answered with nothing to say.
9295    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
9296        ReviewRecord {
9297            attempts: 0,
9298            reviewer,
9299            agent: agent.to_owned(),
9300            summary: String::new(),
9301            findings: Vec::new(),
9302            vote: None,
9303            failed: Some(reason.to_owned()),
9304            duration_ms: 0,
9305        }
9306    }
9307
9308    #[test]
9309    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
9310        let mut state = run_state();
9311        state.reviews = vec![review_round(
9312            1,
9313            vec![
9314                review_record(1, "alpha", "clean, nothing to add"),
9315                unanswered_review_record(2, "beta", "timed out"),
9316            ],
9317        )];
9318        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9319        assert!(en.contains("clean, nothing to add"), "{en}");
9320        assert!(
9321            en.contains("produced no answer: timed out"),
9322            "a seat that never answered must say so, not render a blank box: {en}"
9323        );
9324        assert!(
9325            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
9326            "no reviewer box may be left empty: {en}"
9327        );
9328
9329        state.config.graph.language = "ja".to_owned();
9330        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9331        assert!(ja.contains("回答なし: timed out"), "{ja}");
9332    }
9333
9334    #[test]
9335    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
9336        let html = panel();
9337        assert!(!html.contains("<script"), "no script survives the csp");
9338        assert!(!html.contains("<form"), "form-action is 'none'");
9339        let pr = green_pr();
9340        assert_eq!(
9341            html.matches("http").count(),
9342            html.matches(pr.url.as_str()).count(),
9343            "the only http url in the panel is the pull request's own link"
9344        );
9345        assert!(
9346            html.contains("target=\"_blank\""),
9347            "the PR link must open in a new tab so it escapes the iframe"
9348        );
9349        assert!(
9350            html.contains("rel=\"noopener noreferrer\""),
9351            "external links opening in new tabs must carry noopener noreferrer"
9352        );
9353    }
9354
9355    #[test]
9356    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
9357        let html = panel();
9358        assert!(
9359            html.contains(">+</span>"),
9360            "an added line carries a `+` in the gutter, not only a background"
9361        );
9362        assert!(
9363            html.contains(">-</span>"),
9364            "a removed line carries a `-` in the gutter, not only a background"
9365        );
9366        assert!(
9367            html.contains(">new line</span>"),
9368            "the marker is moved to the gutter, so the body is printed once without it"
9369        );
9370    }
9371
9372    #[test]
9373    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
9374        let total = DIFF_MAX_LINES + 100;
9375        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
9376        let html = approval_panel(
9377            &run_state(),
9378            &green_pr(),
9379            NUMSTAT,
9380            &diff,
9381            &[],
9382            "feat: something long",
9383        );
9384        assert!(
9385            html.contains(&format!("100 of {total} diff lines omitted")),
9386            "the note must say exactly how much was cut"
9387        );
9388        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
9389        assert!(
9390            !html.contains(&format!("line {DIFF_MAX_LINES}")),
9391            "nothing past the threshold is rendered"
9392        );
9393        assert!(
9394            html.contains("/repo/magi"),
9395            "the note says where the rest is"
9396        );
9397    }
9398
9399    #[test]
9400    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
9401        let html = approval_panel(
9402            &run_state(),
9403            &green_pr(),
9404            "1\t2\tsrc/<b>&\"x\"'.rs",
9405            "",
9406            &[],
9407            "subject",
9408        );
9409        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
9410        assert!(
9411            !html.contains("<b>"),
9412            "an agent-influenced path must never become markup"
9413        );
9414    }
9415
9416    #[tokio::test]
9417    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
9418        let a = std::path::PathBuf::from("/repo/a");
9419        let b = std::path::PathBuf::from("/repo/b");
9420
9421        let held = repo_merge_lock(&a).lock_owned().await;
9422
9423        // A second, concurrent land run against the *same* repository must
9424        // wait - `try_lock` fails while `held` is alive.
9425        assert!(
9426            repo_merge_lock(&a).try_lock().is_err(),
9427            "a second merge into the same repository must not proceed concurrently"
9428        );
9429
9430        // A run against a *different* repository must not be blocked by it -
9431        // this is what keeps a slow rebase or `gh pr merge` in one
9432        // repository from also stalling a land-approval resume in another.
9433        assert!(
9434            repo_merge_lock(&b).try_lock().is_ok(),
9435            "a different repository's merge lock must be independent"
9436        );
9437
9438        drop(held);
9439        assert!(
9440            repo_merge_lock(&a).try_lock().is_ok(),
9441            "the lock is released once the holder is done"
9442        );
9443    }
9444
9445    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
9446        let mut state = landing_state();
9447        let mut rec = review_record(1, "alpha", "precise rejection reason");
9448        rec.vote = Some(if reject {
9449            crate::verdict::ReviewVote::Reject
9450        } else {
9451            crate::verdict::ReviewVote::Approve
9452        });
9453        if major {
9454            rec.findings = contested().findings;
9455        }
9456        let mut round = review_round(1, vec![rec]);
9457        round.clean = false;
9458        round.blocking = usize::from(major);
9459        state.reviews.push(round);
9460        state.config.graph.review_rounds = 1;
9461        state
9462    }
9463
9464    #[test]
9465    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
9466        for every in [false, true] {
9467            for contested in [false, true] {
9468                for major in [false, true] {
9469                    for reject in [false, true] {
9470                        let mut state = repair_state(major, reject);
9471                        state.config.graph.land_approval = every;
9472                        state.config.graph.hold_contested_merge = contested;
9473                        let reasons = approval_reasons(&state);
9474                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
9475                        assert_eq!(
9476                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
9477                            contested && major
9478                        );
9479                        assert_eq!(
9480                            reasons.contains(&ApprovalReason::FinalReject),
9481                            contested && reject
9482                        );
9483                        assert_eq!(
9484                            reasons.len(),
9485                            usize::from(every)
9486                                + usize::from(contested && major)
9487                                + usize::from(contested && reject)
9488                        );
9489                    }
9490                }
9491            }
9492        }
9493    }
9494
9495    #[test]
9496    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
9497        use crate::verdict::ReviewVote::{Approve, Reject};
9498        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
9499            let mut state = repair_state(false, initial_reject);
9500            state.reviews[0]
9501                .reconsideration
9502                .push(crate::run::ReviewRevoteRecord {
9503                    reviewer: 1,
9504                    agent: "alpha".into(),
9505                    vote: Some(final_vote),
9506                    reason: "changed after reading the panel <evidence>".into(),
9507                    failed: None,
9508                });
9509            assert_eq!(
9510                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9511                final_vote == Reject
9512            );
9513            for language in ["en", "ja"] {
9514                state.config.graph.language = language.into();
9515                let evidence = approval_evidence(&state);
9516                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
9517                assert!(evidence.contains("changed after reading the panel <evidence>"));
9518                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9519                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
9520                assert!(!html.contains("<evidence>"));
9521            }
9522            state.reviews[0].reconsideration[0].vote = None;
9523            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
9524            assert_eq!(
9525                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9526                initial_reject
9527            );
9528            assert!(approval_evidence(&state).contains("timed out"));
9529        }
9530    }
9531
9532    #[tokio::test]
9533    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
9534        for every in [false, true] {
9535            for contested in [false, true] {
9536                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
9537                {
9538                    let mut state = repair_state(major, reject);
9539                    state.config.graph.land_approval = every;
9540                    state.config.graph.hold_contested_merge = contested;
9541                    let forge = Scripted::new(
9542                        vec![seen("abc", Checks::Green, "CLEAN", false)],
9543                        vec![(true, "")],
9544                    );
9545                    land_with(&mut state, URL, &forge).await.unwrap();
9546                    let expected = every || (contested && (major || reject));
9547                    assert_eq!(state.land_approval.is_some(), expected);
9548                    assert_eq!(forge.calls().contains(&"merge"), !expected);
9549                    if expected {
9550                        assert!(state.parked);
9551                    }
9552                }
9553            }
9554        }
9555    }
9556
9557    #[tokio::test]
9558    async fn reviewed_branch_hold_is_read_before_landing_decision() {
9559        for (base, control) in [
9560            (false, "land_approval"),
9561            (true, "land_approval"),
9562            (false, "hold_contested_merge"),
9563        ] {
9564            let (_tmp, mut state, _) = landing_git_fixture().await;
9565            state.config.graph.land_approval = base;
9566            state.config.graph.hold_contested_merge = false;
9567            state.reviewed_commits = Some(Vec::new());
9568            if control == "hold_contested_merge" {
9569                state.reviews = repair_state(false, true).reviews;
9570            }
9571            std::fs::write(
9572                state.repo.join("magi.toml"),
9573                format!("[graph]\n{control} = {}\n", !base),
9574            )
9575            .unwrap();
9576            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
9577            git::git(&state.repo, &["commit", "-m", "approval policy"])
9578                .await
9579                .unwrap();
9580            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9581            state.land_sync_pending = false;
9582            state.pr_pushed_head = Some(head.clone());
9583            state.gate_head = Some(head.clone());
9584            let forge = Scripted::new(
9585                vec![seen(&head, Checks::Green, "CLEAN", false)],
9586                vec![(true, "")],
9587            );
9588            land_with(&mut state, URL, &forge).await.unwrap();
9589            assert!(
9590                state.land_approval.is_some(),
9591                "base={base}, control={control}"
9592            );
9593            assert!(!forge.calls().contains(&"merge"));
9594            if !base {
9595                let question = ask::Questions::open()
9596                    .get(&state.land_approval.as_ref().unwrap().question)
9597                    .unwrap();
9598                assert!(question.detail.contains(&format!(
9599                    "{control}=true from the reviewed branch's magi.toml"
9600                )));
9601            }
9602        }
9603    }
9604
9605    #[tokio::test]
9606    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9607        for file in ["magi.toml", ".magi/config.toml"] {
9608            for control in crate::config::OwnerHold::ALL {
9609                let (_tmp, mut state, _) = landing_git_fixture().await;
9610                state.config.graph.land_approval = false;
9611                state.config.graph.hold_contested_merge = false;
9612                state.reviewed_commits = Some(Vec::new());
9613                if control == crate::config::OwnerHold::HoldContestedMerge {
9614                    state.reviews = repair_state(false, true).reviews;
9615                }
9616                let config = state.repo.join(file);
9617                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9618                std::fs::write(
9619                    &config,
9620                    format!(
9621                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9622                        control.key()
9623                    ),
9624                )
9625                .unwrap();
9626                git::git(&state.repo, &["add", file]).await.unwrap();
9627                git::git(&state.repo, &["commit", "-m", "require approval"])
9628                    .await
9629                    .unwrap();
9630                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9631                let gate = state.config.verify.gate.clone();
9632                state.observe_branch_owner_holds(&head).await;
9633                assert_eq!(state.config.verify.gate, gate);
9634                assert!(state.owner_hold(control));
9635                let holds = state.branch_owner_holds.clone();
9636                git::git(&state.repo, &["rm", file]).await.unwrap();
9637                git::git(&state.repo, &["commit", "-m", "remove config"])
9638                    .await
9639                    .unwrap();
9640                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9641                state.save().unwrap();
9642                state = RunState::load(&state.id).unwrap();
9643                state.observe_branch_owner_holds(&later).await;
9644                assert_eq!(state.branch_owner_holds, holds);
9645                assert_eq!(state.branch_owner_holds[0].head, head);
9646                state.land_sync_pending = false;
9647                state.pr_pushed_head = Some(later.clone());
9648                state.gate_head = Some(later.clone());
9649                let forge = Scripted::new(
9650                    vec![seen(&later, Checks::Green, "CLEAN", false)],
9651                    vec![(true, "")],
9652                );
9653                land_with(&mut state, URL, &forge).await.unwrap();
9654                assert!(!forge.calls().contains(&"merge"));
9655                assert!(state.parked);
9656                let question = ask::Questions::open()
9657                    .get(&state.land_approval.as_ref().unwrap().question)
9658                    .unwrap();
9659                assert!(question.detail.contains("Approval required because:"));
9660                assert!(question.detail.contains(&format!(
9661                    "{}=true from the reviewed branch's {file}",
9662                    control.key()
9663                )));
9664                assert_eq!(state.branch_owner_holds, holds);
9665                state.save().unwrap();
9666                let resumed = RunState::load(&state.id).unwrap();
9667                assert!(resumed.owner_hold(control));
9668                assert_eq!(resumed.branch_owner_holds, holds);
9669                assert_eq!(
9670                    resumed.land_approval.unwrap().question,
9671                    state.land_approval.unwrap().question
9672                );
9673            }
9674        }
9675    }
9676
9677    #[tokio::test]
9678    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9679        let mut state = repair_state(false, true);
9680        state.reviews[0].clean = true;
9681        let mut finding = contested().findings.remove(0);
9682        finding.severity = crate::verdict::Severity::Minor;
9683        state.reviews[0].reviews[0].findings.push(finding);
9684        assert!(state.open_findings().is_empty());
9685        let mut pr = green_pr();
9686        pr.review_comments.clear();
9687        for language in ["en", "ja"] {
9688            state.config.graph.language = language.into();
9689            let html = approval_panel(&state, &pr, "", "", &[], "subject");
9690            assert!(html.contains("[R3-1-1] minor"));
9691            assert!(html.contains(if language == "ja" {
9692                "内部指摘の解決を意味するものではありません"
9693            } else {
9694                "This does not mean internal findings are resolved"
9695            }));
9696            assert!(
9697                html.find(if language == "ja" {
9698                    "承認が必要な理由:"
9699                } else {
9700                    "Approval required because:"
9701                })
9702                .unwrap()
9703                    < html.find("[R3-1-1]").unwrap()
9704            );
9705        }
9706        state.config.graph.language = "en".into();
9707        let observed = seen("abc", Checks::Green, "CLEAN", false);
9708        assert_eq!(
9709            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9710                .await
9711                .unwrap(),
9712            ApprovalGate::Pending
9713        );
9714        let id = state.land_approval.as_ref().unwrap().question.clone();
9715        let q = ask::Questions::open().get(&id).unwrap();
9716        assert!(q.detail.starts_with("Approval required because:"));
9717        assert!(q.detail.contains("final reviewer reject"));
9718        assert!(q.detail.contains("[R3-1-1] minor"));
9719        assert!(
9720            q.detail
9721                .contains("No adoption or resolution evidence recorded")
9722        );
9723        state.config.graph.land_approval = false;
9724        state.config.graph.hold_contested_merge = false;
9725        state.reviews.clear();
9726        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9727        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9728        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9729        let forge = Scripted::new(vec![observed], vec![]);
9730        land_with(&mut state, URL, &forge).await.unwrap();
9731        assert!(!forge.calls().contains(&"merge"));
9732        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9733        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9734    }
9735
9736    #[tokio::test]
9737    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9738        let mut state = repair_state(false, true);
9739        state.config.graph.land_approval = false;
9740        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9741        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9742        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9743        state.reviews[0].reviews[0].summary = long_reason.clone();
9744        for i in 1..=10 {
9745            let mut finding = contested().findings.remove(0);
9746            finding.id = format!("R1-1-{i}");
9747            finding.severity = if i == 9 {
9748                crate::verdict::Severity::Major
9749            } else {
9750                crate::verdict::Severity::Minor
9751            };
9752            finding.title = long_title.clone();
9753            finding.detail = long_detail.clone();
9754            state.reviews[0].reviews[0].findings.push(finding);
9755        }
9756        state.reviews[0].fix = Some(crate::run::FixRecord {
9757            agent: "fixer".into(),
9758            addressed: vec!["R1-1-9".into()],
9759            rejected: vec![crate::verdict::Rejection {
9760                id: "R1-1-10".into(),
9761                why: long_reason.clone(),
9762            }],
9763            notes: long_detail.clone(),
9764            committed: false,
9765            failed: None,
9766            duration_ms: 0,
9767            continuation: None,
9768        });
9769        assert_eq!(
9770            approval_reasons(&state),
9771            [
9772                ApprovalReason::OpenBlockingFindings,
9773                ApprovalReason::FinalReject
9774            ]
9775        );
9776        let excerpt = approval_excerpt(&long_reason, 300);
9777        assert_eq!(excerpt.chars().count(), 300);
9778        assert!(excerpt.ends_with('…'));
9779        let boundary = "拒".repeat(300);
9780        assert_eq!(approval_excerpt(&boundary, 300), boundary);
9781        for language in ["en", "ja"] {
9782            state.config.graph.language = language.into();
9783            for revote in [
9784                None,
9785                Some(crate::verdict::ReviewVote::Reject),
9786                Some(crate::verdict::ReviewVote::Approve),
9787            ] {
9788                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9789                state.reviews[0].reconsideration.clear();
9790                if let Some(vote) = revote {
9791                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9792                    state.reviews[0]
9793                        .reconsideration
9794                        .push(crate::run::ReviewRevoteRecord {
9795                            reviewer: 1,
9796                            agent: "alpha".into(),
9797                            vote: Some(vote),
9798                            reason: long_reason.clone(),
9799                            failed: None,
9800                        });
9801                }
9802                let evidence = approval_evidence(&state);
9803                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9804                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9805                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9806                assert_eq!(
9807                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9808                    final_vote == crate::verdict::ReviewVote::Reject
9809                );
9810                assert!(evidence.contains(&excerpt));
9811                assert!(evidence.contains("[R1-1-8] minor"));
9812                assert!(evidence.contains("[R1-1-9] major"));
9813                assert!(evidence.contains("[R1-1-10] minor"));
9814                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9815                    assert!(!evidence.contains(tail));
9816                }
9817                assert!(evidence.contains(if language == "ja" {
9818                    "採用申告(解決未確認)"
9819                } else {
9820                    "claimed addressed (resolution unconfirmed)"
9821                }));
9822                assert!(evidence.contains(if language == "ja" {
9823                    "不採用理由"
9824                } else {
9825                    "declined"
9826                }));
9827                let major_evidence = evidence
9828                    .split("[R1-1-9] major")
9829                    .nth(1)
9830                    .unwrap()
9831                    .split("[R1-1-10]")
9832                    .next()
9833                    .unwrap();
9834                assert!(major_evidence.contains(if language == "ja" {
9835                    "採用申告(解決未確認)"
9836                } else {
9837                    "claimed addressed (resolution unconfirmed)"
9838                }));
9839                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9840                assert!(last_evidence.contains(if language == "ja" {
9841                    "不採用理由"
9842                } else {
9843                    "declined"
9844                }));
9845                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9846                assert!(html.contains(&esc(&evidence)));
9847                assert_eq!(
9848                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9849                        .await
9850                        .unwrap(),
9851                    ApprovalGate::Pending
9852                );
9853                let id = &state.land_approval.take().unwrap().question;
9854                let q = ask::Questions::open().get(id).unwrap();
9855                assert!(q.detail.starts_with(&evidence));
9856            }
9857            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9858        }
9859    }
9860
9861    #[test]
9862    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9863        for (major, reject) in [(true, false), (false, true), (true, true)] {
9864            let state = repair_state(major, reject);
9865            assert!(repair_available(&state));
9866            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9867        }
9868        assert!(!repair_available(&repair_state(false, false)));
9869        let mut clean = repair_state(true, false);
9870        clean.reviews[0].clean = true;
9871        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9872        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9873    }
9874
9875    #[tokio::test]
9876    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9877        let mut state = repair_state(true, false);
9878        let pr = green_pr();
9879        approval_gate(&mut state, &pr, "feat: x", None, "abc")
9880            .await
9881            .unwrap();
9882        let store = ask::Questions::open();
9883        let id = state.land_approval.as_ref().unwrap().question.clone();
9884        // Simulate an unanswered two-choice question created by an older build.
9885        store
9886            .update(&id, |q| {
9887                q.choices = vec![APPROVE.into(), HOLD.into()];
9888                Ok(())
9889            })
9890            .unwrap();
9891        let upgraded = store.get(&id).unwrap();
9892        assert_eq!(upgraded.choices, approval_choices(&state));
9893        assert!(!upgraded.actions.contains_key(HOLD));
9894        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9895        assert!(
9896            store
9897                .list()
9898                .iter()
9899                .any(|q| q.id == id && q.choices == upgraded.choices)
9900        );
9901        assert!(
9902            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9903        );
9904        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9905        store
9906            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9907            .unwrap();
9908        // An earlier build may have recorded the repair answer and stopped
9909        // before any driver consumed it. Reconcile that durable decision too.
9910        store
9911            .update(&id, |q| {
9912                q.actions.clear();
9913                Ok(())
9914            })
9915            .unwrap();
9916        assert_eq!(
9917            store.get(&id).unwrap().chosen_action(),
9918            Some(&ask::ChoiceAction::Resume {
9919                run: state.id.clone()
9920            })
9921        );
9922        let binding = state.land_approval.clone();
9923        assert_eq!(
9924            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9925                .await
9926                .unwrap(),
9927            ApprovalGate::Repair
9928        );
9929        assert!(state.land_approval.is_none());
9930        assert_eq!(state.merge_repairs.len(), 1);
9931        let request = &state.merge_repairs[0];
9932        assert_eq!(request.question, id);
9933        assert_eq!(request.head, "abc");
9934        assert_eq!(request.pr, pr.url);
9935        assert_eq!(
9936            request.reviews[0].reviews[0].summary,
9937            "precise rejection reason"
9938        );
9939        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9940        assert_eq!(
9941            request.reviews[0].reviews[0].findings[0].detail,
9942            state.reviews[0].reviews[0].findings[0].detail
9943        );
9944        // A repeated consumption of the same answer never dispatches another repair.
9945        state.land_approval = binding;
9946        assert_eq!(
9947            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9948                .await
9949                .unwrap(),
9950            ApprovalGate::Repair
9951        );
9952        assert_eq!(state.merge_repairs.len(), 1);
9953        state.land_approval = None;
9954        state.config.graph.land_approval = false;
9955        state.config.graph.hold_contested_merge = false;
9956        state.reviews.clear();
9957        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9958        assert_eq!(
9959            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9960                .await
9961                .unwrap(),
9962            ApprovalGate::Pending
9963        );
9964        let fresh_id = &state.land_approval.as_ref().unwrap().question;
9965        assert_ne!(fresh_id, &id);
9966        let fresh = store.get(fresh_id).unwrap();
9967        assert!(
9968            fresh
9969                .detail
9970                .contains("fresh owner approval after merge repair")
9971        );
9972        assert!(fresh.detail.contains("No review recorded"));
9973        assert!(!fresh.detail.contains("precise rejection reason"));
9974    }
9975
9976    #[tokio::test]
9977    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9978        for choice in [REPAIR, HOLD] {
9979            let mut state = repair_state(false, true);
9980            let observed = seen("abc", Checks::Green, "CLEAN", false);
9981            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9982                .await
9983                .unwrap();
9984            let id = state.land_approval.as_ref().unwrap().question.clone();
9985            ask::Questions::open()
9986                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9987                .unwrap();
9988            let forge = Scripted::new(vec![observed], vec![(true, "")]);
9989            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9990                .await
9991                .unwrap();
9992            assert!(
9993                forge
9994                    .argvs()
9995                    .iter()
9996                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
9997            );
9998            assert!(!forge.calls().contains(&"fix"));
9999            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
10000            assert_ne!(state.status, RunStatus::Merged);
10001        }
10002    }
10003
10004    #[test]
10005    fn only_the_merge_choice_merges_and_silence_holds() {
10006        let table = [
10007            (None, Approval::Hold),
10008            (Some("merge"), Approval::Merge),
10009            (Some(" merge\n"), Approval::Merge),
10010            (Some("hold"), Approval::Hold),
10011            (Some(""), Approval::Hold),
10012            (Some("yes"), Approval::Hold),
10013        ];
10014        for (answer, want) in table {
10015            assert_eq!(
10016                approval(answer),
10017                want,
10018                "answer {answer:?} must resolve to {want:?}"
10019            );
10020        }
10021    }
10022
10023    #[tokio::test]
10024    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
10025        let mut state = landing_state();
10026        state.config.graph.land_approval = true;
10027        let pr = green_pr();
10028
10029        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
10030            .await
10031            .unwrap();
10032        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
10033        assert!(
10034            !state.parked,
10035            "approval_gate itself never sets `parked`; only its caller does"
10036        );
10037
10038        let store = ask::Questions::open();
10039        let filed: Vec<_> = store
10040            .list()
10041            .into_iter()
10042            .filter(|q| q.run == state.id)
10043            .collect();
10044        assert_eq!(filed.len(), 1, "exactly one question is filed");
10045        assert_eq!(filed[0].node, APPROVAL_NODE);
10046        assert_eq!(filed[0].choices, approval_choices(&state));
10047        assert!(filed[0].status.open());
10048
10049        // A second visit - standing in for a resumed run whose slot the
10050        // daemon handed to something else while nobody had answered - must
10051        // find the same question rather than filing a second one.
10052        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
10053            .await
10054            .unwrap();
10055        assert_eq!(again, ApprovalGate::Pending);
10056        let still_one = store
10057            .list()
10058            .into_iter()
10059            .filter(|q| q.run == state.id)
10060            .count();
10061        assert_eq!(
10062            still_one, 1,
10063            "asking twice must not double-file the question"
10064        );
10065    }
10066
10067    #[tokio::test]
10068    async fn approving_the_existing_question_is_read_back_as_approved() {
10069        crate::run::pin_test_home();
10070        let mut state = run_state();
10071        state.config.graph.land_approval = true;
10072        let pr = green_pr();
10073        assert_eq!(
10074            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10075                .await
10076                .unwrap(),
10077            ApprovalGate::Pending
10078        );
10079
10080        let store = ask::Questions::open();
10081        let mut q = store
10082            .list()
10083            .into_iter()
10084            .find(|q| q.run == state.id)
10085            .expect("filed above");
10086        let talks = crate::talk::Talks::open();
10087        let cfg = crate::config::Config {
10088            agents: vec![crate::config::AgentSpec {
10089                id: "mock".into(),
10090                kind: crate::config::AgentKind::Command,
10091                model: None,
10092                command: vec!["true".into()],
10093                extra_args: Vec::new(),
10094                env: Default::default(),
10095                prompt_delivery: None,
10096                max_turn_secs: None,
10097            }],
10098            ..crate::config::Config::default()
10099        };
10100        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
10101        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
10102        crate::talk::drain(&mut talk, &talks).unwrap();
10103        assert_eq!(
10104            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10105                .await
10106                .unwrap(),
10107            ApprovalGate::Pending,
10108            "consultation cannot approve or hold the merge"
10109        );
10110        q = store.get(&q.id).unwrap();
10111        assert!(q.answer.is_none());
10112        // The owner's merge answer (from the chat or the card) is the approval.
10113        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10114        store.put(&mut q).unwrap();
10115
10116        assert_eq!(
10117            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10118                .await
10119                .unwrap(),
10120            ApprovalGate::Approved
10121        );
10122    }
10123
10124    #[tokio::test]
10125    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
10126        crate::run::pin_test_home();
10127        let store = ask::Questions::open();
10128        for via_list in [false, true] {
10129            let mut state = repair_state(false, true);
10130            let pr = green_pr();
10131            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10132                .await
10133                .unwrap();
10134            let id = state.land_approval.as_ref().unwrap().question.clone();
10135            store
10136                .update(&id, |q| {
10137                    q.actions.insert(
10138                        HOLD.to_owned(),
10139                        ask::ChoiceAction::Resume {
10140                            run: state.id.clone(),
10141                        },
10142                    );
10143                    Ok(())
10144                })
10145                .unwrap();
10146            let q = if via_list {
10147                store.list().into_iter().find(|q| q.id == id).unwrap()
10148            } else {
10149                store.get(&id).unwrap()
10150            };
10151            assert!(!q.actions.contains_key(HOLD));
10152            store
10153                .update(&id, |q| {
10154                    // Check the persisted migration, without another read upgrade.
10155                    assert!(!q.actions.contains_key(HOLD));
10156                    assert!(!upgrade_repair_choice(q, &state));
10157                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
10158                })
10159                .unwrap();
10160            assert!(store.get(&id).unwrap().chosen_action().is_none());
10161            assert_eq!(
10162                approval_gate(&mut state, &pr, "feat: x", None, "abc")
10163                    .await
10164                    .unwrap(),
10165                ApprovalGate::Held
10166            );
10167        }
10168    }
10169
10170    #[tokio::test]
10171    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
10172        crate::run::pin_test_home();
10173        let store = ask::Questions::open();
10174
10175        let mut held_state = run_state();
10176        held_state.config.graph.land_approval = true;
10177        let pr = green_pr();
10178        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
10179            .await
10180            .unwrap();
10181        let mut q = store
10182            .list()
10183            .into_iter()
10184            .find(|q| q.run == held_state.id)
10185            .expect("filed above");
10186        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
10187        store.put(&mut q).unwrap();
10188        assert_eq!(
10189            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
10190                .await
10191                .unwrap(),
10192            ApprovalGate::Held
10193        );
10194
10195        let mut abandoned_state = run_state();
10196        abandoned_state.config.graph.land_approval = true;
10197        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
10198            .await
10199            .unwrap();
10200        let mut q = store
10201            .list()
10202            .into_iter()
10203            .find(|q| q.run == abandoned_state.id)
10204            .expect("filed above");
10205        q.abandon("no answer within the timeout");
10206        store.put(&mut q).unwrap();
10207        assert_eq!(
10208            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
10209                .await
10210                .unwrap(),
10211            ApprovalGate::Pending,
10212            "an expired approval must ask again without merging"
10213        );
10214        assert_eq!(
10215            store.get(&q.id).unwrap().status,
10216            ask::QuestionStatus::Abandoned
10217        );
10218        assert_ne!(
10219            abandoned_state.land_approval.as_ref().unwrap().question,
10220            q.id
10221        );
10222    }
10223
10224    fn contested() -> ContestedHandoff {
10225        let finding = |id: &str, n: u32| crate::verdict::Finding {
10226            id: id.to_owned(),
10227            severity: crate::verdict::Severity::Major,
10228            file: Some("src/a.rs".to_owned()),
10229            line: Some(n),
10230            title: format!("problem {id}"),
10231            detail: String::new(),
10232        };
10233        ContestedHandoff {
10234            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
10235            rejecters: vec![(1, "alpha".to_owned())],
10236        }
10237    }
10238
10239    #[test]
10240    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
10241        let mut state = run_state();
10242        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
10243        state.contested_handoff = Some(contested());
10244        assert!(contested_to_ask(&state).is_some());
10245        state.config.graph.hold_contested_merge = false;
10246        assert!(
10247            contested_to_ask(&state).is_none(),
10248            "the switch restores today"
10249        );
10250    }
10251
10252    #[test]
10253    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
10254        let q = ask::Question::new(
10255            "run-1".to_owned(),
10256            APPROVAL_NODE.to_owned(),
10257            "land".to_owned(),
10258            "Merge?".to_owned(),
10259            String::new(),
10260            vec![APPROVE.to_owned(), HOLD.to_owned()],
10261        );
10262        let none = deputy_brief(&q, None);
10263        assert!(none.contains("could not be read"), "{none}");
10264        assert!(none.contains("Silence is a hold"), "{none}");
10265
10266        let mut state = run_state();
10267        state.pr = Some(crate::run::PrRecord {
10268            url: "https://example.test/pull/7".to_owned(),
10269            number: 7,
10270            state: "open".to_owned(),
10271            checks: "green".to_owned(),
10272            round: 0,
10273            rounds: 3,
10274            red_at_merge: Vec::new(),
10275        });
10276        state.contested_handoff = Some(contested());
10277        let b = deputy_brief(&q, Some(&state));
10278        assert!(b.contains("https://example.test/pull/7"), "{b}");
10279        assert!(b.contains("not recorded in this legacy question"), "{b}");
10280        assert!(!b.contains("This question was filed although"));
10281        state.contested_handoff = None;
10282        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
10283    }
10284
10285    #[test]
10286    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
10287        for lang in ["en", "ja"] {
10288            let mut cfg = crate::config::Config::default();
10289            cfg.graph.language = lang.to_owned();
10290            let w = words(&cfg.graph.language);
10291            let text = w.approval_detail(
10292                "https://github.com/yukimemi/magi/pull/42",
10293                "main",
10294                "feat: x",
10295                Some(&contested()),
10296            );
10297            assert!(text.contains("pull/42"), "{text}");
10298            assert!(
10299                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
10300                "{text}"
10301            );
10302            assert!(text.contains("R3-1-5"), "{text}");
10303            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
10304            assert!(text.contains("2"), "the rest are counted: {text}");
10305            assert!(text.contains("#1 (alpha)"), "{text}");
10306        }
10307        let plain = words("en").approval_detail("u", "main", "s", None);
10308        assert!(!plain.contains("reject"), "{plain}");
10309    }
10310
10311    #[tokio::test]
10312    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
10313        crate::run::pin_test_home();
10314        let mut state = run_state();
10315        state.config.graph.land_approval = false;
10316        state.contested_handoff = Some(contested());
10317        let pr = green_pr();
10318        let c = contested_to_ask(&state);
10319        assert_eq!(
10320            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10321                .await
10322                .unwrap(),
10323            ApprovalGate::Pending,
10324            "silence is a hold"
10325        );
10326        let store = ask::Questions::open();
10327        let filed: Vec<_> = store
10328            .list()
10329            .into_iter()
10330            .filter(|q| q.run == state.id)
10331            .collect();
10332        assert_eq!(filed.len(), 1);
10333        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
10334
10335        assert_eq!(
10336            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10337                .await
10338                .unwrap(),
10339            ApprovalGate::Pending
10340        );
10341        let mut q = store
10342            .list()
10343            .into_iter()
10344            .find(|q| q.run == state.id)
10345            .unwrap();
10346        assert_eq!(q.id, filed[0].id, "the same question after a resume");
10347        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10348        store.put(&mut q).unwrap();
10349        assert_eq!(
10350            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10351                .await
10352                .unwrap(),
10353            ApprovalGate::Approved
10354        );
10355    }
10356
10357    #[test]
10358    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
10359        let rows = parse_numstat(NUMSTAT);
10360        assert_eq!(
10361            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
10362            ["src/web.rs", "src/land.rs", "assets/logo.png"]
10363        );
10364        assert_eq!(rows[2].added, None, "a binary file has no line counts");
10365    }
10366    #[test]
10367    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
10368        // Reported from a real run: the merge question arrived in English on a
10369        // repository with `language = "ja"`. magi's own strings have to follow
10370        // that setting too - "it is a literal in Rust" is not an answer.
10371        let mut state = run_state();
10372        state.config.graph.language = "ja".to_owned();
10373        let pr = green_pr();
10374        let commits = ["c1".to_owned()];
10375
10376        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10377        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
10378        assert!(ja.contains("squash されるコミット"), "{ja}");
10379        assert!(ja.contains("レビューコメント"), "{ja}");
10380        assert!(ja.contains("差分"), "{ja}");
10381        assert!(
10382            !ja.contains("Commits being squashed"),
10383            "no English left over"
10384        );
10385
10386        let w = words("ja");
10387        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
10388        assert!(
10389            w.approval_detail("http://x/1", "main", "feat: x", None)
10390                .contains("パネル")
10391        );
10392
10393        // The evidence itself is language-neutral and must survive either way.
10394        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
10395        assert!(ja.contains("feat: x"), "nor is the merge subject");
10396
10397        // English stays the default, and a language magi cannot check falls
10398        // back to it rather than shipping a guess.
10399        state.config.graph.language = "en".to_owned();
10400        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10401        assert!(en.contains("Commits being squashed"), "{en}");
10402        assert_eq!(words("Klingon").html_lang, "en");
10403    }
10404
10405    /// A `gh pr list` result naming exactly one pull request whose base and
10406    /// merge time both fit the run is exactly the case
10407    /// [`find_external_merge`] exists to act on.
10408    #[test]
10409    fn pick_open_pr_classifies_by_count_and_base() {
10410        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
10411        assert_eq!(
10412            pick_open_pr(one, "main").unwrap(),
10413            OpenPr::One {
10414                url: "https://x/pull/58".into(),
10415                title: "t".into()
10416            }
10417        );
10418        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
10419        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
10420        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
10421                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
10422        assert_eq!(
10423            pick_open_pr(two, "main").unwrap(),
10424            OpenPr::Many(vec!["u1".into(), "u2".into()])
10425        );
10426        // A fork's same-named branch is not a pull request for this head.
10427        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
10428        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
10429        assert!(pick_open_pr("not json", "main").is_err());
10430        // An incomplete record is an error, never "nothing open".
10431        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
10432        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
10433    }
10434
10435    #[test]
10436    fn pick_merged_pr_picks_the_unique_match() {
10437        let json = r#"[
10438            {"url": "https://github.com/o/r/pull/42", "number": 42,
10439             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
10440        ]"#;
10441        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10442        let found = pick_merged_pr(json, "main", created_at)
10443            .expect("valid json")
10444            .expect("one unambiguous match");
10445        assert_eq!(found.url, "https://github.com/o/r/pull/42");
10446        assert_eq!(found.number, 42);
10447    }
10448
10449    /// Two candidates surviving the filter is exactly as uninformative as
10450    /// zero — a branch name can be reused across runs — so neither is
10451    /// preferred over the other and nothing is recorded automatically.
10452    #[test]
10453    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
10454        let json = r#"[
10455            {"url": "https://github.com/o/r/pull/42", "number": 42,
10456             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
10457            {"url": "https://github.com/o/r/pull/43", "number": 43,
10458             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
10459        ]"#;
10460        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10461        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10462        let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
10463        assert!(error.to_string().contains("ambiguous"), "{error:#}");
10464    }
10465
10466    /// A pull request that targets a different base branch cannot be this
10467    /// run's, whatever its head branch is named — a reused branch name from
10468    /// an unrelated task must not be recorded as this run's merge.
10469    #[test]
10470    fn pick_merged_pr_ignores_a_different_base_branch() {
10471        let json = r#"[
10472            {"url": "https://github.com/o/r/pull/42", "number": 42,
10473             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
10474        ]"#;
10475        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10476        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10477    }
10478
10479    /// A pull request merged before this run was even created cannot be this
10480    /// run's winner, no matter how its head branch is spelled.
10481    #[test]
10482    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
10483        let json = r#"[
10484            {"url": "https://github.com/o/r/pull/42", "number": 42,
10485             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
10486        ]"#;
10487        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10488        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10489    }
10490
10491    #[test]
10492    fn slug_of_pr_url_reads_host_owner_and_repo() {
10493        assert_eq!(
10494            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
10495            Some("github.com/yukimemi/shun")
10496        );
10497    }
10498
10499    #[test]
10500    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
10501        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
10502        assert_eq!(slug_of_pr_url("not a url at all"), None);
10503        assert_eq!(slug_of_pr_url("https://github.com"), None);
10504    }
10505
10506    #[test]
10507    fn slug_of_repo_url_reads_host_owner_and_repo() {
10508        assert_eq!(
10509            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
10510            Some("github.com/yukimemi/magi")
10511        );
10512        assert_eq!(slug_of_repo_url("https://github.com"), None);
10513    }
10514
10515    #[test]
10516    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
10517        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
10518            .expect("same repo, different case");
10519    }
10520
10521    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
10522    /// own in-progress run and rewrote its status from a pull request in a
10523    /// completely different repository. This is the guard that must catch
10524    /// that even when an explicit (but wrong) id is given.
10525    #[test]
10526    fn ensure_same_repo_refuses_a_different_repo() {
10527        let err =
10528            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
10529        let msg = format!("{err:#}");
10530        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10531        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
10532    }
10533
10534    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
10535    /// instance mirroring a `github.com` repository's name, say) must not be
10536    /// treated as the same repository just because the trailing path
10537    /// matches.
10538    #[test]
10539    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
10540        let err = ensure_same_repo(
10541            "github.com/yukimemi/magi",
10542            "github.example.com/yukimemi/magi",
10543        )
10544        .unwrap_err();
10545        let msg = format!("{err:#}");
10546        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10547        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
10548    }
10549
10550    /// No winner decided yet means there is no branch to ask GitHub about at
10551    /// all — `find_external_merge` must return `None` without ever spawning
10552    /// `gh`, which this proves by never providing a real repository to spawn
10553    /// it in.
10554    #[tokio::test]
10555    async fn find_external_merge_returns_none_without_a_winner() {
10556        let state = RunState::new(
10557            PathBuf::from("/no/such/repo"),
10558            "main".to_owned(),
10559            "0000000000000000000000000000000000000000".to_owned(),
10560            "irrelevant".to_owned(),
10561            crate::config::Config::default(),
10562        );
10563        assert_eq!(find_external_merge(&state).await.unwrap(), None);
10564    }
10565
10566    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
10567        let mut run = RunState::new(
10568            PathBuf::from(repo),
10569            "main".to_owned(),
10570            "abcdef1234".to_owned(),
10571            "x".to_owned(),
10572            crate::config::Config::default(),
10573        );
10574        run.id = id.to_owned();
10575        run.status = status;
10576        run.driver_exited = true;
10577        run.pr = Some(crate::run::PrRecord {
10578            number: url.rsplit('/').next().unwrap().parse().unwrap(),
10579            url: url.to_owned(),
10580            state: state.to_owned(),
10581            checks: "red".to_owned(),
10582            round: 0,
10583            rounds: 2,
10584            red_at_merge: Vec::new(),
10585        });
10586        run.save_under(home).unwrap();
10587    }
10588
10589    fn recorded(home: &Path, id: &str) -> String {
10590        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10591        serde_json::from_str::<RunState>(&body)
10592            .unwrap()
10593            .pr
10594            .unwrap()
10595            .state
10596    }
10597
10598    const PR: &str = "https://github.com/o/r/pull/7";
10599
10600    #[test]
10601    fn write_through_updates_predecessors_and_siblings_only() {
10602        let tmp = tempfile::tempdir().unwrap();
10603        let h = tmp.path();
10604        pr_run(
10605            h,
10606            "20261004-100000-aaaa",
10607            "/repo/r",
10608            RunStatus::Superseded,
10609            PR,
10610            "open",
10611        );
10612        pr_run(
10613            h,
10614            "20261004-100100-bbbb",
10615            "/repo/r",
10616            RunStatus::Blocked,
10617            PR,
10618            "open",
10619        );
10620        // Not terminal: a driver may be writing it.
10621        pr_run(
10622            h,
10623            "20261004-100200-cccc",
10624            "/repo/r",
10625            RunStatus::Landing,
10626            PR,
10627            "open",
10628        );
10629        // Another repository's pull request with the same number.
10630        pr_run(
10631            h,
10632            "20261004-100300-dddd",
10633            "/repo/other",
10634            RunStatus::Blocked,
10635            "https://github.com/o/other/pull/7",
10636            "open",
10637        );
10638        // A different pull request of the same repository.
10639        pr_run(
10640            h,
10641            "20261004-100400-eeee",
10642            "/repo/r",
10643            RunStatus::Blocked,
10644            "https://github.com/o/r/pull/8",
10645            "open",
10646        );
10647        pr_run(
10648            h,
10649            "20261004-100500-ffff",
10650            "/repo/r",
10651            RunStatus::Merged,
10652            PR,
10653            "open",
10654        );
10655        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10656
10657        assert_eq!(
10658            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10659            2
10660        );
10661        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10662        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10663        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10664        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10665        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10666        // The source's own record is the caller's to write.
10667        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10668        // Idempotent.
10669        assert_eq!(
10670            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10671            0
10672        );
10673        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10674        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10675    }
10676
10677    #[test]
10678    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10679        let home = tempfile::tempdir().unwrap();
10680        let live_id = "20261004-100000-aaaa";
10681        let unknown_id = "20261004-100100-bbbb";
10682        for id in [live_id, unknown_id] {
10683            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10684            let mut s = RunState::load_under(id, home.path()).unwrap();
10685            s.driver_exited = false;
10686            // Model legacy driver evidence, not a newly reserved unstarted run.
10687            s.driver_claimed = None;
10688            if id == live_id {
10689                s.driver_pid = Some(std::process::id());
10690                s.driver_started_at = crate::proc::process_started_at(std::process::id());
10691            }
10692            s.save_under(home.path()).unwrap();
10693            if id == unknown_id {
10694                assert_eq!(
10695                    s.liveness_under(home.path(), false),
10696                    crate::run::Liveness::Unknown
10697                );
10698            }
10699        }
10700        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10701        assert_eq!(apply_pr_states(home.path(), &known), 0);
10702        for id in [live_id, unknown_id] {
10703            assert_eq!(recorded(home.path(), id), "open");
10704        }
10705    }
10706
10707    #[test]
10708    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10709        let tmp = tempfile::tempdir().unwrap();
10710        let h = tmp.path();
10711        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10712        pr_run(
10713            h,
10714            "20261004-100000-aaaa",
10715            "/repo/r",
10716            RunStatus::Superseded,
10717            &url(1),
10718            "open",
10719        );
10720        pr_run(
10721            h,
10722            "20261004-100100-bbbb",
10723            "/repo/r",
10724            RunStatus::Blocked,
10725            &url(2),
10726            "open",
10727        );
10728        pr_run(
10729            h,
10730            "20261004-100200-cccc",
10731            "/repo/r",
10732            RunStatus::Ready,
10733            &url(3),
10734            "open",
10735        );
10736        pr_run(
10737            h,
10738            "20261004-100300-dddd",
10739            "/repo/r",
10740            RunStatus::Ready,
10741            &url(4),
10742            "open",
10743        );
10744        pr_run(
10745            h,
10746            "20261004-100400-eeee",
10747            "/repo/r",
10748            RunStatus::Implementing,
10749            &url(1),
10750            "open",
10751        );
10752        assert_eq!(stale_open_prs(h).len(), 4);
10753
10754        let mut known = BTreeMap::new();
10755        known.insert(url(1), PrLifecycle::Merged);
10756        known.insert(url(2), PrLifecycle::Closed);
10757        known.insert(url(3), PrLifecycle::Open);
10758        // #4: the forge could not be read, so it has no answer.
10759        assert_eq!(apply_pr_states(h, &known), 2);
10760        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10761        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10762        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10763        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10764        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10765        assert_eq!(apply_pr_states(h, &known), 0);
10766    }
10767
10768    // --- the land loop against a scripted forge -------------------------
10769
10770    use std::collections::VecDeque;
10771    use std::sync::Mutex;
10772
10773    /// Answers views from a script (the last one repeats), merges from a
10774    /// queue, and records every call so a test can assert the order.
10775    struct Scripted {
10776        public_repo: Option<PathBuf>,
10777        evidence: Mutex<Option<CiEvidence>>,
10778        views: Mutex<VecDeque<Seen>>,
10779        merges: Mutex<VecDeque<(bool, String)>>,
10780        fix: Mutex<Option<Fixed>>,
10781        log: Mutex<Vec<&'static str>>,
10782        argvs: Mutex<Vec<Vec<String>>>,
10783        required: Mutex<Option<BTreeSet<String>>>,
10784        /// Set once a merge answered ok: the forge then reports `merged`,
10785        /// unless `queued` says the merge only entered a queue.
10786        merged: Mutex<bool>,
10787        queued: Mutex<bool>,
10788        /// Views fail once a merge answered ok.
10789        unreadable_after_merge: Mutex<bool>,
10790        /// Workflow runs asked to rerun, and whether that call fails.
10791        reruns: Mutex<Vec<String>>,
10792        rerun_fails: Mutex<bool>,
10793        /// Unix seconds; every poll moves it on by `POLL`.
10794        clock: Mutex<i64>,
10795    }
10796
10797    impl Scripted {
10798        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10799            Self {
10800                public_repo: None,
10801                evidence: Mutex::new(None),
10802                views: Mutex::new(views.into()),
10803                merges: Mutex::new(
10804                    merges
10805                        .into_iter()
10806                        .map(|(ok, m)| (ok, m.to_owned()))
10807                        .collect(),
10808                ),
10809                fix: Mutex::new(None),
10810                log: Mutex::new(Vec::new()),
10811                argvs: Mutex::new(Vec::new()),
10812                required: Mutex::new(None),
10813                merged: Mutex::new(false),
10814                queued: Mutex::new(false),
10815                unreadable_after_merge: Mutex::new(false),
10816                reruns: Mutex::new(Vec::new()),
10817                rerun_fails: Mutex::new(false),
10818                clock: Mutex::new(1_000),
10819            }
10820        }
10821        fn for_pr(url: &str, mut views: Vec<Seen>) -> Self {
10822            for view in &mut views {
10823                view.pr.url = url.to_owned();
10824            }
10825            Self::new(views, vec![])
10826        }
10827        fn argvs(&self) -> Vec<Vec<String>> {
10828            self.argvs.lock().unwrap().clone()
10829        }
10830        fn calls(&self) -> Vec<&'static str> {
10831            self.log.lock().unwrap().clone()
10832        }
10833    }
10834
10835    impl Forge for Scripted {
10836        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10837            self.evidence.lock().unwrap().clone()
10838        }
10839        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10840            self.log.lock().unwrap().push("view");
10841            if *self.unreadable_after_merge.lock().unwrap()
10842                && !self.argvs.lock().unwrap().is_empty()
10843            {
10844                anyhow::bail!("forge unreachable");
10845            }
10846            let mut seen = {
10847                let mut v = self.views.lock().unwrap();
10848                if v.len() > 1 {
10849                    v.pop_front().unwrap()
10850                } else {
10851                    v[0].clone()
10852                }
10853            };
10854            if seen.head == "@published" {
10855                let head =
10856                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10857                        .await?
10858                        .context("missing published head")?;
10859                seen.head.clone_from(&head);
10860                seen.rollup_head = head;
10861            }
10862            if *self.merged.lock().unwrap() {
10863                seen.pr.state = PrLifecycle::Merged;
10864            }
10865            Ok(seen)
10866        }
10867        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10868            self.log.lock().unwrap().push("merge");
10869            self.argvs.lock().unwrap().push(argv.to_vec());
10870            let out = self
10871                .merges
10872                .lock()
10873                .unwrap()
10874                .pop_front()
10875                .expect("unscripted merge");
10876            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10877            {
10878                *self.merged.lock().unwrap() = true;
10879            }
10880            Ok(out)
10881        }
10882        async fn poll(&self) {
10883            self.log.lock().unwrap().push("poll");
10884            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10885        }
10886        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10887            self.log.lock().unwrap().push("rerun");
10888            self.reruns.lock().unwrap().push(run.to_owned());
10889            if *self.rerun_fails.lock().unwrap() {
10890                anyhow::bail!("gh run rerun: no");
10891            }
10892            Ok(())
10893        }
10894        fn now(&self) -> i64 {
10895            *self.clock.lock().unwrap()
10896        }
10897        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10898            self.required.lock().unwrap().clone()
10899        }
10900        async fn fix(
10901            &self,
10902            _state: &mut RunState,
10903            _pr: &PrState,
10904            _round: usize,
10905            _budget: usize,
10906            _reason: &str,
10907            _logs: &str,
10908        ) -> Result<Fixed> {
10909            self.log.lock().unwrap().push("fix");
10910            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10911        }
10912    }
10913
10914    const REFUSED: &str =
10915        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10916
10917    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10918        let mut pr = green_pr();
10919        pr.checks = checks;
10920        pr.blocking = Blocking::of(merge_state);
10921        if !comments {
10922            pr.review_comments.clear();
10923        }
10924        Seen {
10925            pr,
10926            title: "feat: x".to_owned(),
10927            failing_urls: Vec::new(),
10928            head: head.to_owned(),
10929            rollup_head: head.to_owned(),
10930            merge_state: merge_state.to_owned(),
10931            contexts: Vec::new(),
10932            base: "main".to_owned(),
10933        }
10934    }
10935
10936    fn landing_state() -> RunState {
10937        crate::run::pin_test_home();
10938        let mut state = run_state();
10939        state.config.graph.land_approval = false;
10940        state
10941    }
10942
10943    #[test]
10944    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10945        assert!(!awaiting_new_head(None, "aaa"));
10946        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10947        assert!(awaiting_new_head(Some("abc123"), "def456"));
10948        assert!(awaiting_new_head(Some("abc123"), ""));
10949    }
10950
10951    #[test]
10952    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10953        let open = |c, m: &str| seen("a", c, m, false);
10954        let table = [
10955            (None, false, Refused::Pending),
10956            (
10957                Some(open(Checks::Pending, "BLOCKED")),
10958                false,
10959                Refused::Pending,
10960            ),
10961            (
10962                Some(open(Checks::Unknown, "BLOCKED")),
10963                false,
10964                Refused::Pending,
10965            ),
10966            (
10967                Some(open(Checks::Green, "UNKNOWN")),
10968                false,
10969                Refused::Pending,
10970            ),
10971            (Some(open(Checks::Green, "")), false, Refused::Pending),
10972            (
10973                Some(open(Checks::Green, "BLOCKED")),
10974                false,
10975                Refused::Recheck,
10976            ),
10977            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10978        ];
10979        for (after, rechecked, want) in table {
10980            assert_eq!(
10981                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10982                want
10983            );
10984        }
10985        let mut closed = open(Checks::Green, "CLEAN");
10986        closed.pr.state = PrLifecycle::Closed;
10987        assert_eq!(
10988            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10989            Refused::Final
10990        );
10991    }
10992
10993    #[test]
10994    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10995        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10996            let pr = seen("a", checks, "BEHIND", false).pr;
10997            assert_eq!(
10998                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10999                Step::Rebase
11000            );
11001        }
11002        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
11003            let current = seen("a", Checks::Green, status, false);
11004            assert_ne!(
11005                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
11006                Step::Rebase
11007            );
11008            assert_ne!(
11009                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
11010                Refused::Behind
11011            );
11012        }
11013        let mut current = seen("a", Checks::Pending, "BEHIND", false);
11014        current.rollup_head = "old".into();
11015        assert_eq!(
11016            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
11017            Refused::Behind
11018        );
11019        assert_eq!(
11020            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
11021            Refused::Pending
11022        );
11023        current.pr.state = PrLifecycle::Closed;
11024        assert_eq!(
11025            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
11026            Refused::Final
11027        );
11028    }
11029
11030    #[tokio::test]
11031    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
11032        for boundary in ["initial", "premerge", "refusal"] {
11033            let (_tmp, mut state, old) = landing_git_fixture().await;
11034            state.land_sync_pending = false;
11035            advance_landing_base(&state).await;
11036            state.config.verify.gate = vec!["test -f advance".into()];
11037            state.config.verify.e2e = vec!["test -f advance".into()];
11038            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
11039                .await
11040                .unwrap();
11041            let old_binding = state.land_approval.clone().unwrap();
11042            let store = ask::Questions::open();
11043            let mut question = store.get(&old_binding.question).unwrap();
11044            question
11045                .answer(ask::Answer::Choice(APPROVE.to_owned()))
11046                .unwrap();
11047            store.put(&mut question).unwrap();
11048            let mut views = Vec::new();
11049            if boundary != "initial" {
11050                views.push(seen(&old, Checks::Green, "CLEAN", false));
11051            }
11052            if boundary == "refusal" {
11053                views.push(seen(&old, Checks::Green, "CLEAN", false));
11054            }
11055            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
11056            behind.rollup_head = "old-ci-head".into();
11057            views.push(behind);
11058            // Publication checks the PR lease while verification has completed.
11059            views.push(seen(&old, Checks::Green, "CLEAN", false));
11060            views.push(seen("@published", Checks::Pending, "CLEAN", false));
11061            views.push(seen("@published", Checks::Green, "CLEAN", false));
11062            let merges = if boundary == "refusal" {
11063                vec![(false, REFUSED)]
11064            } else {
11065                vec![]
11066            };
11067            let mut forge = Scripted::new(views, merges);
11068            forge.public_repo = Some(state.repo.clone());
11069            let run = state.id.clone();
11070            land_with(&mut state, URL, &forge).await.unwrap();
11071            let head = state.pr_pushed_head.clone().unwrap();
11072            assert_ne!(head, old, "{boundary}");
11073            assert_eq!(state.id, run);
11074            assert_eq!(state.pr_branch(), Some("task-head"));
11075            assert_eq!(state.winner().unwrap().branch, "winner");
11076            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
11077            assert!(state.gate_allows_progress());
11078            let e2e = state.head_e2e.as_ref().unwrap();
11079            assert_eq!(e2e.head, head);
11080            assert!(e2e.passed);
11081            assert_eq!(state.land_sync_attempts, 1);
11082            assert!(!state.land_sync_pending);
11083            assert!(state.parked);
11084            let binding = state.land_approval.as_ref().unwrap();
11085            assert_eq!(binding.head, head);
11086            assert_ne!(binding.question, old_binding.question);
11087            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
11088            // The new question authorizes only the synchronized head on resume.
11089            let mut question = store.get(&binding.question).unwrap();
11090            question
11091                .answer(ask::Answer::Choice(APPROVE.to_owned()))
11092                .unwrap();
11093            store.put(&mut question).unwrap();
11094            let forge = Scripted::new(
11095                vec![seen(&head, Checks::Green, "CLEAN", false)],
11096                vec![(true, "")],
11097            );
11098            land_with(&mut state, URL, &forge).await.unwrap();
11099            assert_eq!(state.status, RunStatus::Merged);
11100            assert_eq!(
11101                value_of(&forge.argvs()[0], "--match-head-commit"),
11102                Some(head.as_str())
11103            );
11104        }
11105    }
11106
11107    #[tokio::test]
11108    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
11109        let (_tmp, mut state, old) = landing_git_fixture().await;
11110        state.land_sync_pending = false;
11111        state.config.graph.land_approval = false;
11112        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
11113        advance_landing_base(&state).await;
11114        let mut forge = Scripted::new(
11115            vec![
11116                seen(&old, Checks::Green, "CLEAN", false),
11117                seen(&old, Checks::Green, "CLEAN", false),
11118                seen(&old, Checks::Green, "BEHIND", false),
11119                // The next observation is the publication lease check. The
11120                // refusal's evidence still applies to exactly this old head.
11121                seen(&old, Checks::Green, "CLEAN", false),
11122                seen("@published", Checks::Green, "CLEAN", false),
11123            ],
11124            vec![(false, REFUSED), (true, "")],
11125        );
11126        forge.public_repo = Some(state.repo.clone());
11127        land_with(&mut state, URL, &forge).await.unwrap();
11128        let head = state.pr_pushed_head.as_deref().unwrap();
11129        assert_ne!(head, old);
11130        assert_eq!(state.land_sync_attempts, 1);
11131        assert_eq!(state.gate_head.as_deref(), Some(head));
11132        assert_eq!(state.status, RunStatus::Merged);
11133        let requests = forge.argvs();
11134        assert_eq!(requests.len(), 2);
11135        assert_eq!(
11136            value_of(&requests[0], "--match-head-commit"),
11137            Some(old.as_str())
11138        );
11139        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
11140    }
11141
11142    #[tokio::test]
11143    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
11144        let (tmp, mut state, old) = landing_git_fixture().await;
11145        state.land_sync_pending = false;
11146        // A damaged history must not be interpreted as a missing base. Keep
11147        // the head's tree intact so worktree restoration itself can succeed.
11148        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
11149        let commit = tmp.path().join("broken-commit");
11150        std::fs::write(
11151            &commit,
11152            format!(
11153                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
11154                "f".repeat(40)
11155            ),
11156        )
11157        .unwrap();
11158        let replacement = git::git(
11159            &state.repo,
11160            &[
11161                "hash-object",
11162                "-t",
11163                "commit",
11164                "-w",
11165                commit.to_str().unwrap(),
11166            ],
11167        )
11168        .await
11169        .unwrap();
11170        git::git(&state.repo, &["replace", &old, replacement.trim()])
11171            .await
11172            .unwrap();
11173        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11174        land_with(&mut state, URL, &forge).await.unwrap();
11175        assert_eq!(state.land_sync_attempts, 0);
11176        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
11177        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
11178        assert!(forge.argvs().is_empty());
11179        assert!(
11180            state.events.iter().any(|e| e.message.contains(
11181                "could not determine whether the landing head contains the fetched base"
11182            ))
11183        );
11184    }
11185
11186    #[tokio::test]
11187    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
11188        let (_tmp, mut state, old) = landing_git_fixture().await;
11189        state.land_sync_pending = false;
11190        git::git(
11191            &state.repo,
11192            &["remote", "set-url", "origin", "missing-remote"],
11193        )
11194        .await
11195        .unwrap();
11196        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11197        land_with(&mut state, URL, &forge).await.unwrap();
11198        assert_eq!(state.land_sync_attempts, 0);
11199        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
11200        assert!(
11201            state
11202                .events
11203                .iter()
11204                .any(|e| e.message.contains("cannot fetch landing base"))
11205        );
11206        assert!(forge.argvs().is_empty());
11207    }
11208
11209    #[tokio::test]
11210    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
11211        let (_tmp, mut state, old) = landing_git_fixture().await;
11212        state.land_sync_pending = false;
11213        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11214        land_with(&mut state, URL, &forge).await.unwrap();
11215        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
11216        assert_eq!(state.land_sync_attempts, 0);
11217        assert!(
11218            state
11219                .events
11220                .iter()
11221                .any(|e| e.message.contains("already included"))
11222        );
11223        advance_landing_base(&state).await;
11224        state.land_sync_attempts = state.config.graph.land_rounds;
11225        state.land_sync_pending = true;
11226        state.save().unwrap();
11227        let mut restored = RunState::load(&state.id).unwrap();
11228        assert!(
11229            resume_observed_head(&mut restored, &old)
11230                .await
11231                .unwrap_err()
11232                .to_string()
11233                .contains("budget exhausted")
11234        );
11235        assert_eq!(
11236            git::remote_head(&state.repo, "origin", "task-head")
11237                .await
11238                .unwrap(),
11239            Some(old)
11240        );
11241    }
11242
11243    #[tokio::test]
11244    async fn a_normal_landing_merges_on_the_first_look() {
11245        let mut state = landing_state();
11246        let forge = Scripted::new(
11247            vec![seen("a", Checks::Green, "CLEAN", false)],
11248            vec![(true, "")],
11249        );
11250        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11251            .await
11252            .unwrap();
11253        // One fresh read, then the head-bound merge.
11254        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11255        assert_eq!(state.status, RunStatus::Merged);
11256    }
11257
11258    #[tokio::test]
11259    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
11260        let mut state = landing_state();
11261        let forge = Scripted::new(
11262            vec![seen("a", Checks::Green, "CLEAN", false)],
11263            std::iter::repeat_n((true, ""), 100).collect(),
11264        );
11265        *forge.queued.lock().unwrap() = true;
11266        let task = async {
11267            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11268                .await
11269                .unwrap();
11270        };
11271        // Still open after the command succeeded: it keeps watching and
11272        // never records a merge (it stops at the wait ceiling instead).
11273        task.await;
11274        assert_ne!(state.status, RunStatus::Merged);
11275    }
11276
11277    #[tokio::test]
11278    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
11279        let mut state = landing_state();
11280        let forge = Scripted::new(
11281            vec![seen("a", Checks::Green, "CLEAN", false)],
11282            std::iter::repeat_n((true, ""), 100).collect(),
11283        );
11284        *forge.unreadable_after_merge.lock().unwrap() = true;
11285        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11286            .await
11287            .ok();
11288        assert_ne!(state.status, RunStatus::Merged);
11289    }
11290
11291    #[tokio::test]
11292    async fn a_task_public_head_is_awaited_on_land_entry() {
11293        let mut state = landing_state();
11294        state.pr_head = Some("magi/task-abcd-1234".into());
11295        state.pr_pushed_head = Some("new".into());
11296        let forge = Scripted::new(
11297            vec![
11298                seen("old", Checks::Green, "CLEAN", false),
11299                seen("new", Checks::Green, "CLEAN", false),
11300            ],
11301            vec![(true, "")],
11302        );
11303        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11304            .await
11305            .unwrap();
11306        assert_eq!(
11307            forge.calls(),
11308            ["view", "poll", "view", "view", "merge", "view"]
11309        );
11310        assert_eq!(state.status, RunStatus::Merged);
11311    }
11312
11313    #[tokio::test]
11314    async fn a_superseded_public_head_owner_cannot_reenter_land() {
11315        let mut state = landing_state();
11316        state.pr_taken_over_by = Some("next".into());
11317        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
11318        assert!(
11319            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11320                .await
11321                .is_err()
11322        );
11323        assert!(forge.calls().is_empty());
11324    }
11325
11326    #[tokio::test]
11327    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
11328        let mut state = landing_state();
11329        let forge = Scripted::new(
11330            vec![
11331                seen("old", Checks::Green, "CLEAN", true),
11332                // The forge has not moved to the new head yet: still green.
11333                seen("old", Checks::Green, "CLEAN", true),
11334                seen("new", Checks::Pending, "BLOCKED", true),
11335                seen("new", Checks::Green, "CLEAN", true),
11336            ],
11337            vec![(true, "")],
11338        );
11339        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11340            head: "NEW".to_owned(),
11341        });
11342        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11343            .await
11344            .unwrap();
11345        assert_eq!(
11346            forge.calls(),
11347            [
11348                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
11349                "view"
11350            ]
11351        );
11352        assert_eq!(state.status, RunStatus::Merged);
11353    }
11354
11355    #[tokio::test]
11356    async fn a_head_that_never_arrives_stops_naming_both_commits() {
11357        let mut state = landing_state();
11358        let forge = Scripted::new(
11359            vec![
11360                seen("old", Checks::Green, "CLEAN", true),
11361                seen("someone-elses", Checks::Green, "CLEAN", true),
11362            ],
11363            vec![],
11364        );
11365        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11366            head: "mine".to_owned(),
11367        });
11368        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11369            .await
11370            .unwrap();
11371        assert!(!forge.calls().contains(&"merge"));
11372        let why = state.merge.as_ref().unwrap().detail.clone();
11373        assert!(
11374            why.contains("mine") && why.contains("someone-elses"),
11375            "{why}"
11376        );
11377        assert_eq!(state.status, RunStatus::Blocked);
11378    }
11379
11380    #[tokio::test]
11381    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
11382        let mut state = landing_state();
11383        let forge = Scripted::new(
11384            vec![
11385                seen("a", Checks::Green, "CLEAN", false),
11386                seen("a", Checks::Green, "CLEAN", false),
11387                seen("a", Checks::Pending, "BLOCKED", false),
11388                seen("a", Checks::Pending, "BLOCKED", false),
11389                seen("a", Checks::Green, "CLEAN", false),
11390            ],
11391            vec![(false, REFUSED), (true, "")],
11392        );
11393        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11394            .await
11395            .unwrap();
11396        assert_eq!(
11397            forge.calls(),
11398            [
11399                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
11400                "view"
11401            ]
11402        );
11403        assert_eq!(state.status, RunStatus::Merged);
11404    }
11405
11406    #[tokio::test]
11407    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
11408        let mut state = landing_state();
11409        let forge = Scripted::new(
11410            vec![
11411                seen("a", Checks::Green, "CLEAN", false),
11412                seen("a", Checks::Green, "BLOCKED", false),
11413            ],
11414            vec![(false, REFUSED), (false, REFUSED)],
11415        );
11416        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11417            .await
11418            .unwrap();
11419        // One re-look is allowed for the forge's own lag, then it is final.
11420        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
11421        let why = state.merge.as_ref().unwrap().detail.clone();
11422        assert!(
11423            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
11424            "{why}"
11425        );
11426        assert_eq!(state.status, RunStatus::Blocked);
11427    }
11428
11429    #[test]
11430    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
11431        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
11432        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
11433        // The pull request is still on the commit before the push.
11434        assert_eq!(bound_head("old", "old", Some("new")), None);
11435        // The checks are the previous commit's.
11436        assert_eq!(bound_head("new", "old", Some("new")), None);
11437        assert_eq!(bound_head("new", "old", None), None);
11438        // Nothing readable.
11439        assert_eq!(bound_head("", "", None), None);
11440        assert_eq!(bound_head("", "", Some("new")), None);
11441        assert_eq!(bound_head("abc", "", None), None);
11442    }
11443
11444    fn view_json(head: &str) -> String {
11445        format!(
11446            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
11447            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
11448            "reviews":[],"comments":[]}}"#
11449        )
11450    }
11451
11452    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
11453        format!(
11454            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
11455            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
11456            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
11457            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
11458        )
11459    }
11460
11461    #[test]
11462    fn rollup_is_bound_to_the_commit_in_the_same_node() {
11463        // The view already points at the new head, but the node still answers
11464        // for the old commit with its red check: the head stays unbound.
11465        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
11466        assert_eq!(s.rollup_head, "old");
11467        assert_eq!(s.pr.checks, Checks::Red);
11468        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
11469        assert_eq!(s.failing_urls.len(), 1);
11470    }
11471
11472    #[test]
11473    fn checks_come_from_the_node_not_the_view() {
11474        let view = view_json("new").replace(
11475            r#""reviews""#,
11476            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
11477        );
11478        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
11479        assert_eq!(s.pr.checks, Checks::Green);
11480        assert!(s.pr.failing.is_empty());
11481        assert_eq!(
11482            bound_head(&s.head, &s.rollup_head, Some("new")),
11483            Some("new")
11484        );
11485    }
11486
11487    #[test]
11488    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
11489        for node in [
11490            None,
11491            Some("not json".to_owned()),
11492            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
11493            Some(node_json("new", "SUCCESS", true)),
11494        ] {
11495            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
11496            assert!(s.rollup_head.is_empty());
11497            assert_eq!(s.pr.checks, Checks::Unknown);
11498            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
11499        }
11500    }
11501
11502    #[test]
11503    fn the_merge_command_is_pinned_to_the_observed_head() {
11504        let argv = merge_argv_at(7, "feat: x", "deadbeef");
11505        let at = argv
11506            .iter()
11507            .position(|a| a == "--match-head-commit")
11508            .unwrap();
11509        assert_eq!(argv[at + 1], "deadbeef");
11510    }
11511
11512    #[tokio::test]
11513    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
11514        let mut state = landing_state();
11515        // The pull request is on the pushed head but the rollup is still the
11516        // previous commit's red, non-required result.
11517        let mut stale = seen("new", Checks::Red, "CLEAN", false);
11518        stale.rollup_head = "old".to_owned();
11519        let forge = Scripted::new(
11520            vec![seen("old", Checks::Green, "CLEAN", true), stale],
11521            vec![],
11522        );
11523        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11524            head: "new".to_owned(),
11525        });
11526        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11527            .await
11528            .unwrap();
11529        assert!(!forge.calls().contains(&"merge"));
11530        assert_eq!(state.status, RunStatus::Blocked);
11531        let why = state.merge.as_ref().unwrap().detail.clone();
11532        assert!(why.contains("new") && why.contains("old"), "{why}");
11533    }
11534
11535    #[test]
11536    fn a_refusal_read_against_another_commits_checks_is_pending() {
11537        let mut after = seen("a", Checks::Green, "BLOCKED", false);
11538        after.rollup_head = "old".to_owned();
11539        assert_eq!(
11540            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
11541            Refused::Pending
11542        );
11543    }
11544
11545    #[tokio::test]
11546    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
11547        let mut state = landing_state();
11548        state.config.merge.ci = crate::config::MergeCi::None;
11549        state.config.graph.land_approval = true;
11550        let forge = Scripted::new(
11551            vec![seen("a", Checks::Unknown, "CLEAN", false)],
11552            vec![(true, "")],
11553        );
11554        land_with(&mut state, URL, &forge).await.unwrap();
11555        assert!(state.parked);
11556        assert_eq!(forge.calls(), ["view"]);
11557        let store = ask::Questions::open();
11558        let mut q = store
11559            .get(&state.land_approval.as_ref().unwrap().question)
11560            .unwrap();
11561        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11562        store.put(&mut q).unwrap();
11563
11564        land_with(&mut state, URL, &forge).await.unwrap();
11565        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
11566        assert_eq!(state.status, RunStatus::Merged);
11567        assert_eq!(
11568            value_of(&forge.argvs()[0], "--match-head-commit"),
11569            Some("a")
11570        );
11571    }
11572
11573    #[tokio::test]
11574    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
11575        let mut state = landing_state();
11576        state.config.merge.ci = crate::config::MergeCi::None;
11577        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
11578        land_with(&mut state, URL, &forge).await.unwrap();
11579        assert!(forge.reruns.lock().unwrap().is_empty());
11580        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11581        assert_eq!(state.status, RunStatus::Merged);
11582    }
11583
11584    #[test]
11585    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
11586        let shown = BTreeSet::new();
11587        let guard = |s: Option<&Seen>| {
11588            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11589        };
11590        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11591        assert!(guard(Some(&fresh)));
11592        assert!(!guard(None));
11593        fresh.rollup_head = "old".to_owned();
11594        assert!(!guard(Some(&fresh)));
11595        fresh.rollup_head = "a".to_owned();
11596        fresh.head = "b".to_owned();
11597        assert!(!guard(Some(&fresh)));
11598        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11599        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11600    }
11601
11602    #[test]
11603    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11604        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11605            let after = seen("a", checks, "BLOCKED", false);
11606            assert_eq!(
11607                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11608                Refused::Recheck
11609            );
11610            assert_eq!(
11611                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11612                Refused::Final
11613            );
11614        }
11615    }
11616
11617    #[tokio::test]
11618    async fn a_matching_head_with_red_non_required_checks_still_merges() {
11619        let mut state = landing_state();
11620        let forge = Scripted::new(
11621            vec![seen("a", Checks::Red, "CLEAN", false)],
11622            vec![(true, "")],
11623        );
11624        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11625            .await
11626            .unwrap();
11627        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11628        assert_eq!(state.status, RunStatus::Merged);
11629    }
11630
11631    #[tokio::test]
11632    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11633        let mut state = landing_state();
11634        let forge = Scripted::new(
11635            vec![
11636                seen("a", Checks::Green, "CLEAN", false),
11637                seen("a", Checks::Green, "CLEAN", false),
11638                // Re-viewed after the refusal: someone pushed.
11639                seen("b", Checks::Green, "BLOCKED", false),
11640                seen("b", Checks::Green, "CLEAN", false),
11641            ],
11642            vec![(false, REFUSED), (true, "")],
11643        );
11644        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11645            .await
11646            .unwrap();
11647        assert_eq!(
11648            forge.calls(),
11649            [
11650                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
11651            ]
11652        );
11653        assert_eq!(state.status, RunStatus::Merged);
11654    }
11655
11656    fn merged_view(head: &str) -> Seen {
11657        let mut m = seen(head, Checks::Green, "CLEAN", false);
11658        m.pr.state = PrLifecycle::Merged;
11659        m
11660    }
11661
11662    fn has(argv: &[String], flag: &str) -> bool {
11663        argv.iter().any(|a| a == flag)
11664    }
11665
11666    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11667        let at = argv.iter().position(|a| a == flag)?;
11668        argv.get(at + 1).map(String::as_str)
11669    }
11670
11671    const URL: &str = "https://github.com/o/r/pull/42";
11672
11673    #[tokio::test]
11674    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11675        let mut state = landing_state();
11676        let forge = Scripted::new(
11677            vec![
11678                seen("abc", Checks::Green, "CLEAN", false),
11679                seen("abc", Checks::Green, "CLEAN", false),
11680            ],
11681            vec![(true, "")],
11682        );
11683        land_with(&mut state, URL, &forge).await.unwrap();
11684        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11685        let argv = &forge.argvs()[0];
11686        assert!(has(argv, "--squash") && has(argv, "--subject"));
11687        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11688        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11689        assert_eq!(state.status, RunStatus::Merged);
11690        assert!(state.land_armed_head.is_none());
11691    }
11692
11693    #[tokio::test]
11694    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11695        let mut state = landing_state();
11696        state.land_armed_head = Some("a".to_owned());
11697        let forge = Scripted::new(
11698            vec![seen("a", Checks::Green, "CLEAN", false)],
11699            vec![(true, ""), (true, "")],
11700        );
11701        land_with(&mut state, URL, &forge).await.unwrap();
11702        let argvs = forge.argvs();
11703        assert!(has(&argvs[0], "--disable-auto"));
11704        assert!(!has(&argvs[1], "--auto"));
11705        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11706        assert_eq!(state.status, RunStatus::Merged);
11707        assert!(state.land_armed_head.is_none());
11708    }
11709
11710    #[tokio::test]
11711    async fn an_approval_never_carries_over_to_a_new_head() {
11712        crate::run::pin_test_home();
11713        let mut state = run_state();
11714        state.config.graph.land_approval = true;
11715        let pr = green_pr();
11716        let store = ask::Questions::open();
11717
11718        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11719            .await
11720            .unwrap();
11721        let mut q = store
11722            .list()
11723            .into_iter()
11724            .find(|q| q.run == state.id)
11725            .unwrap();
11726        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11727        store.put(&mut q).unwrap();
11728        assert_eq!(
11729            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
11730                .await
11731                .unwrap(),
11732            ApprovalGate::Approved,
11733            "the same head keeps its approval"
11734        );
11735
11736        // A new head is a new question, not the old word.
11737        assert_eq!(
11738            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11739                .await
11740                .unwrap(),
11741            ApprovalGate::Pending
11742        );
11743        let all: Vec<_> = store
11744            .list()
11745            .into_iter()
11746            .filter(|q| q.run == state.id)
11747            .collect();
11748        assert_eq!(all.len(), 2);
11749
11750        // A question recorded before heads were tracked is not reused either.
11751        state.land_approval = None;
11752        assert_eq!(
11753            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11754                .await
11755                .unwrap(),
11756            ApprovalGate::Pending
11757        );
11758        let open = store
11759            .list()
11760            .into_iter()
11761            .filter(|q| q.run == state.id && q.status.open())
11762            .count();
11763        assert_eq!(open, 1, "the superseded question was retired");
11764    }
11765
11766    #[tokio::test]
11767    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11768        let mut state = landing_state();
11769        let forge = Scripted::new(
11770            vec![
11771                seen("a", Checks::Green, "CLEAN", false),
11772                // The fresh read before the merge: someone pushed.
11773                seen("b", Checks::Green, "CLEAN", false),
11774            ],
11775            vec![(true, "")],
11776        );
11777        land_with(&mut state, URL, &forge).await.unwrap();
11778        let argvs = forge.argvs();
11779        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11780        assert!(!has(&argvs[0], "--auto"));
11781        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11782        assert_eq!(state.status, RunStatus::Merged);
11783    }
11784
11785    fn passing(label: &str) -> CheckInfo {
11786        CheckInfo {
11787            label: label.to_owned(),
11788            verdict: Verdict::Pass,
11789            required: Some(false),
11790            run: None,
11791        }
11792    }
11793
11794    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11795        (label.to_owned(), run.map(str::to_owned))
11796    }
11797
11798    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11799        LandReruns {
11800            head: head.to_owned(),
11801            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11802        }
11803    }
11804
11805    #[test]
11806    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11807        let f = [failing("test (macos)", Some("7"))];
11808        assert_eq!(
11809            rerun_step(&f, None, "h", 100),
11810            RerunStep::Rerun(vec!["7".to_owned()])
11811        );
11812        let rec = reran("h", &[("7", 100)]);
11813        let grace = crate::release_watch::RERUN_GRACE;
11814        assert_eq!(
11815            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11816            RerunStep::Grace
11817        );
11818        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11819    }
11820
11821    #[test]
11822    fn a_failure_without_a_run_id_goes_to_the_fixer() {
11823        let f = [failing("a", Some("7")), failing("ci/external", None)];
11824        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11825        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11826    }
11827
11828    #[test]
11829    fn a_moved_head_forgets_the_reruns() {
11830        let f = [failing("a", Some("7"))];
11831        let rec = reran("old", &[("7", 100)]);
11832        assert_eq!(
11833            rerun_step(&f, Some(&rec), "new", 101),
11834            RerunStep::Rerun(vec!["7".to_owned()])
11835        );
11836    }
11837
11838    #[test]
11839    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11840        let f = [
11841            failing("a", Some("7")),
11842            failing("b", Some("7")),
11843            failing("c", Some("8")),
11844        ];
11845        assert_eq!(
11846            rerun_step(&f, None, "h", 0),
11847            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11848        );
11849        let rec = reran("h", &[("7", 0)]);
11850        assert_eq!(
11851            rerun_step(&f, Some(&rec), "h", 1),
11852            RerunStep::Rerun(vec!["8".to_owned()])
11853        );
11854    }
11855
11856    #[test]
11857    fn only_blocking_failures_are_candidates_for_a_rerun() {
11858        let check = |label: &str, verdict, required, run: &str| CheckInfo {
11859            label: label.to_owned(),
11860            verdict,
11861            required,
11862            run: Some(run.to_owned()),
11863        };
11864        let got = rerunnable(&[
11865            check("passed", Verdict::Pass, Some(true), "1"),
11866            check("optional", Verdict::Fail, Some(false), "2"),
11867            check("required", Verdict::Fail, Some(true), "3"),
11868            check("unknown", Verdict::Fail, None, "4"),
11869        ]);
11870        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11871        assert_eq!(labels, ["required", "unknown"]);
11872    }
11873
11874    fn unrelated_ci_fixture() -> CiEvidence {
11875        let failure = CiFailure {
11876            path: "tests/web_render.rs".into(),
11877            start_line: 42,
11878            end_line: 42,
11879            title: "question_identity_disclosure_copy_and_live_updates".into(),
11880            message: "assertion failed".into(),
11881        };
11882        CiEvidence {
11883            head: "a".into(),
11884            base: "base-sha".into(),
11885            changed: vec![
11886                "AGENTS.md".into(),
11887                "src/talk.rs".into(),
11888                "tests/consult_investigation.rs".into(),
11889            ],
11890            checks: vec![CiCheckEvidence {
11891                label: "coverage".into(),
11892                head_check: 70,
11893                base_check: 60,
11894                app: 1,
11895                run: "7".into(),
11896                base_run: "6".into(),
11897                head_failures: vec![failure.clone()],
11898                base_failures: vec![failure],
11899                rerun_exhausted: true,
11900            }],
11901        }
11902    }
11903
11904    #[test]
11905    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11906        let good = unrelated_ci_fixture();
11907        let red = vec!["coverage".into()];
11908        assert!(good.unrelated("a", &red));
11909        assert!(!good.unrelated("another-head", &red));
11910        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11911        assert!(!good.unrelated("a", &[]));
11912        for mutation in 0..8 {
11913            let mut bad = good.clone();
11914            match mutation {
11915                0 => bad.checks[0].rerun_exhausted = false,
11916                1 => bad.checks[0].base_failures.clear(),
11917                2 => bad.checks[0].head_failures.clear(),
11918                3 => bad.changed.push("tests/web_render.rs".into()),
11919                4 => bad.changed.push(".github/workflows/ci.yml".into()),
11920                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11921                6 => bad.checks.push(bad.checks[0].clone()),
11922                _ => bad.base.clear(),
11923            }
11924            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11925        }
11926    }
11927
11928    #[test]
11929    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11930        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11931        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11932        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11933        assert!(matches!(
11934            decide(&pr, 2, 2, CHECKS_GRACE),
11935            Step::GiveUp { .. }
11936        ));
11937        let optional = CheckInfo {
11938            label: "coverage".into(),
11939            verdict: Verdict::Fail,
11940            required: Some(false),
11941            run: Some("7".into()),
11942        };
11943        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11944        assert_eq!(
11945            rerunnable_with(&[optional], true),
11946            vec![("coverage".into(), Some("7".into()))]
11947        );
11948    }
11949
11950    #[tokio::test]
11951    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11952        let mut state = landing_state();
11953        let mut red = coverage_unknown();
11954        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11955        red.pr.failing = vec!["coverage".into()];
11956        let forge = Scripted::new(vec![red], vec![]);
11957        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11958        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11959        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11960        assert!(forge.calls().contains(&"fix"));
11961        assert!(state.land_unrelated.is_some());
11962        assert!(state.parked);
11963        assert!(
11964            !state
11965                .events
11966                .iter()
11967                .any(|e| e.message.contains("fixer produced no commit"))
11968        );
11969    }
11970
11971    fn coverage_unknown() -> Seen {
11972        let mut s = red("a", Some("7"));
11973        s.pr.blocking = Blocking::Unsaid;
11974        s.merge_state = "UNKNOWN".into();
11975        s.pr.failing = vec!["coverage".into()];
11976        s.contexts[0].label = "coverage".into();
11977        s.contexts[0].required = Some(false);
11978        s
11979    }
11980
11981    #[tokio::test]
11982    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11983        let mut state = landing_state();
11984        let unknown = coverage_unknown();
11985        let mut unstable = unknown.clone();
11986        unstable.pr.blocking = Blocking::of("UNSTABLE");
11987        unstable.merge_state = "UNSTABLE".into();
11988        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11989        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11990        assert!(!forge.calls().contains(&"fix"));
11991        assert!(!forge.calls().contains(&"rerun"));
11992        assert_eq!(state.status, RunStatus::Merged);
11993        assert_eq!(state.pr.unwrap().round, 0);
11994    }
11995
11996    #[tokio::test]
11997    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11998        let mut state = landing_state();
11999        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
12000        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
12001        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12002        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12003        assert!(!forge.calls().contains(&"fix"));
12004        assert!(state.parked);
12005        assert_eq!(state.status, RunStatus::Landing);
12006        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12007        let hold = state.land_unrelated.as_ref().unwrap();
12008        let q = ask::Questions::open().get(&hold.question).unwrap();
12009        assert!(
12010            q.actions
12011                .values()
12012                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
12013        );
12014        assert!(
12015            state
12016                .events
12017                .iter()
12018                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
12019        );
12020        let first = state.land_unsaid.clone();
12021        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
12022        state.parked = false;
12023        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12024        assert_eq!(state.land_unsaid, first);
12025        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12026    }
12027
12028    fn red(head: &str, run: Option<&str>) -> Seen {
12029        let mut s = seen(head, Checks::Red, "BLOCKED", false);
12030        s.pr.failing = vec!["test (macos)".to_owned()];
12031        s.contexts = vec![CheckInfo {
12032            label: "test (macos)".to_owned(),
12033            verdict: Verdict::Fail,
12034            required: Some(true),
12035            run: run.map(str::to_owned),
12036        }];
12037        s
12038    }
12039
12040    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
12041
12042    #[tokio::test]
12043    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
12044        let mut state = landing_state();
12045        let forge = Scripted::new(
12046            vec![
12047                red("a", Some("7")),
12048                seen("a", Checks::Pending, "BLOCKED", false),
12049                seen("a", Checks::Green, "CLEAN", false),
12050            ],
12051            vec![(true, "")],
12052        );
12053        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12054        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12055        assert!(!forge.calls().contains(&"fix"));
12056        assert_eq!(state.status, RunStatus::Merged);
12057        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12058        let argvs = forge.argvs();
12059        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
12060        assert!(
12061            state
12062                .events
12063                .iter()
12064                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
12065        );
12066    }
12067
12068    #[tokio::test]
12069    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
12070        let mut state = landing_state();
12071        let forge = Scripted::new(
12072            vec![
12073                red("a", Some("7")),
12074                seen("a", Checks::Green, "CLEAN", false),
12075            ],
12076            vec![(true, "")],
12077        );
12078        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12079        // The red view repeats for the grace, then the fixer is asked once.
12080        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12081        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
12082        let calls = forge.calls();
12083        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
12084        let fix_at = calls.iter().position(|c| *c == "fix");
12085        assert!(fix_at.is_none_or(|f| f > rerun_at));
12086    }
12087
12088    #[tokio::test]
12089    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
12090        let mut state = landing_state();
12091        let mut v = red("a", Some("7"));
12092        v.pr.checks = Checks::Pending;
12093        v.contexts.push(CheckInfo {
12094            label: "slow".to_owned(),
12095            verdict: Verdict::Pending,
12096            required: Some(true),
12097            run: Some("8".to_owned()),
12098        });
12099        let forge = Scripted::new(
12100            vec![v, seen("a", Checks::Green, "CLEAN", false)],
12101            vec![(true, "")],
12102        );
12103        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12104        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12105        assert_eq!(state.status, RunStatus::Merged);
12106    }
12107
12108    #[test]
12109    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
12110        let mut v = red("a", Some("7"));
12111        v.contexts.push(CheckInfo {
12112            label: "same run, still going".to_owned(),
12113            verdict: Verdict::Pending,
12114            required: Some(true),
12115            run: Some("7".to_owned()),
12116        });
12117        assert!(rerunnable(&v.contexts).is_empty());
12118    }
12119
12120    #[tokio::test]
12121    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
12122        let mut state = landing_state();
12123        state.config.graph.land_rounds = 0;
12124        let forge = Scripted::new(
12125            vec![
12126                red("a", Some("7")),
12127                seen("a", Checks::Green, "CLEAN", false),
12128            ],
12129            vec![(true, "")],
12130        );
12131        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12132        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12133        assert_eq!(state.status, RunStatus::Merged);
12134        assert!(!forge.calls().contains(&"fix"));
12135        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12136    }
12137
12138    #[tokio::test]
12139    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
12140        let mut state = landing_state();
12141        state.config.graph.land_rounds = 1;
12142        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
12143        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
12144        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12145        assert_eq!(pr.state, PrLifecycle::Open);
12146        assert_eq!(state.status, RunStatus::Blocked);
12147        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12148        assert!(
12149            state.merge_decision.is_none(),
12150            "no ordinary failure handoff"
12151        );
12152        assert!(forge.argvs().is_empty(), "no merge on outage");
12153
12154        let recovered = Scripted::new(
12155            vec![
12156                seen("a", Checks::Green, "CLEAN", true),
12157                seen("b", Checks::Green, "CLEAN", false),
12158            ],
12159            vec![(true, "")],
12160        );
12161        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
12162        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
12163        assert_eq!(state.status, RunStatus::Merged);
12164        assert_eq!(state.pr.as_ref().unwrap().round, 1);
12165        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
12166    }
12167
12168    #[tokio::test]
12169    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
12170        let mut state = landing_state();
12171        state.config.graph.land_rounds = 1;
12172        let forge = Scripted::new(
12173            vec![
12174                seen("a", Checks::Green, "CLEAN", true),
12175                red("b", Some("7")),
12176                seen("b", Checks::Green, "CLEAN", false),
12177            ],
12178            vec![(true, "")],
12179        );
12180        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
12181            head: "b".to_owned(),
12182        });
12183        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12184        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12185        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
12186        assert_eq!(state.pr.as_ref().unwrap().round, 1);
12187        assert_eq!(state.status, RunStatus::Merged);
12188        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
12189        assert_eq!(
12190            value_of(&forge.argvs()[0], "--match-head-commit"),
12191            Some("b")
12192        );
12193    }
12194
12195    #[tokio::test]
12196    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
12197        let mut state = landing_state();
12198        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12199        *forge.rerun_fails.lock().unwrap() = true;
12200        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12201        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12202        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
12203        assert_eq!(
12204            forge.calls().iter().filter(|c| **c == "fix").count(),
12205            1,
12206            "{:?}",
12207            forge.calls()
12208        );
12209    }
12210
12211    #[tokio::test]
12212    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
12213        let mut state = landing_state();
12214        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12215        // The record was written just before the previous pass died.
12216        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
12217        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12218        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12219        assert!(forge.reruns.lock().unwrap().is_empty());
12220    }
12221
12222    #[tokio::test]
12223    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
12224        let mut state = landing_state();
12225        state.config.graph.rerun_flaky_checks = false;
12226        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12227        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12228        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12229        assert!(forge.reruns.lock().unwrap().is_empty());
12230        assert!(forge.calls().contains(&"fix"));
12231
12232        let mut state = landing_state();
12233        let forge = Scripted::new(vec![red("a", None)], vec![]);
12234        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12235        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12236        assert!(forge.reruns.lock().unwrap().is_empty());
12237        assert!(forge.calls().contains(&"fix"));
12238    }
12239
12240    fn names(xs: &[&str]) -> BTreeSet<String> {
12241        xs.iter().map(|x| (*x).to_owned()).collect()
12242    }
12243
12244    #[test]
12245    fn a_required_check_the_rollup_never_listed_is_named() {
12246        let req = names(&["build"]);
12247        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
12248        assert!(why.contains("never reported: build"), "{why}");
12249        assert!(!why.contains("probably waiting for a review"), "{why}");
12250    }
12251
12252    #[test]
12253    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
12254        let why = waiting_on("BLOCKED", &[passing("review")], None);
12255        assert!(why.contains("could not be read"), "{why}");
12256        assert!(!why.contains("probably waiting for a review"), "{why}");
12257    }
12258
12259    #[test]
12260    fn all_required_reported_keeps_the_review_guess() {
12261        let req = names(&["build"]);
12262        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12263        assert!(why.contains("probably waiting for a review"), "{why}");
12264        assert!(!why.contains("never reported"), "{why}");
12265    }
12266
12267    #[test]
12268    fn required_names_match_the_rollup_ignoring_case_only() {
12269        let req = names(&["Build"]);
12270        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12271        assert!(!why.contains("never reported"), "{why}");
12272    }
12273
12274    #[test]
12275    fn required_contexts_are_read_from_protection_and_rulesets() {
12276        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
12277        assert_eq!(
12278            parse_classic_required(classic),
12279            Some(names(&["build", "lint"]))
12280        );
12281        let rules = r#"[{"type":"pull_request","parameters":{}},
12282            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
12283        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
12284        assert_eq!(parse_ruleset_required("nope"), None);
12285        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
12286    }
12287
12288    #[test]
12289    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
12290        let shown = BTreeSet::new();
12291        let ok = seen("a", Checks::Green, "CLEAN", false);
12292        let guard = |s: Option<&Seen>| {
12293            direct_merge_is_safe(
12294                s,
12295                "A",
12296                &shown,
12297                0,
12298                4,
12299                Duration::ZERO,
12300                CiExpectation::Expected,
12301            )
12302        };
12303        assert!(guard(Some(&ok)));
12304        assert!(!guard(None));
12305        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
12306        let mut stale = ok.clone();
12307        stale.rollup_head = "old".to_owned();
12308        assert!(!guard(Some(&stale)));
12309        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
12310        assert!(!guard(Some(&merged_view("a"))));
12311    }
12312
12313    #[test]
12314    fn the_rollup_node_carries_whether_each_check_is_required() {
12315        let node = node_json("new", "SUCCESS", false)
12316            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
12317        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
12318        assert_eq!(s.contexts.len(), 1);
12319        assert_eq!(s.contexts[0].required, Some(true));
12320        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
12321        assert_eq!(s.contexts[0].required, None);
12322    }
12323
12324    #[tokio::test]
12325    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
12326        let mut state = landing_state();
12327        state.land_armed_head = Some("a".to_owned());
12328        let forge = Scripted::new(
12329            vec![seen("a", Checks::Green, "CLEAN", true)],
12330            vec![(false, "disable exploded")],
12331        );
12332        land_with(&mut state, URL, &forge).await.unwrap();
12333        assert!(!forge.calls().contains(&"fix"));
12334        assert_eq!(state.status, RunStatus::Blocked);
12335        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
12336        let why = state.merge.as_ref().unwrap().detail.clone();
12337        assert!(why.contains("disable exploded"), "{why}");
12338    }
12339
12340    /// Create a cross-platform fake `gh` executable in `dir` backed by exact
12341    /// fixture files, avoiding shell quoting differences and global `PATH`
12342    /// mutation.
12343    pub(crate) fn fake_gh_script(
12344        dir: &Path,
12345        name: &str,
12346        stdout: &str,
12347        stderr: &str,
12348        exit_code: i32,
12349    ) -> PathBuf {
12350        let out_path = dir.join(format!("{name}.stdout"));
12351        let err_path = dir.join(format!("{name}.stderr"));
12352        std::fs::write(&out_path, stdout).unwrap();
12353        std::fs::write(&err_path, stderr).unwrap();
12354        #[cfg(windows)]
12355        {
12356            let script = dir.join(format!("{name}.cmd"));
12357            let mut body = String::from("@echo off\r\n");
12358            if !stdout.is_empty() {
12359                body.push_str(&format!("type \"{}\"\r\n", out_path.display()));
12360            }
12361            if !stderr.is_empty() {
12362                body.push_str(&format!("type \"{}\" 1>&2\r\n", err_path.display()));
12363            }
12364            body.push_str(&format!("exit /b {exit_code}\r\n"));
12365            std::fs::write(&script, body).unwrap();
12366            script
12367        }
12368        #[cfg(unix)]
12369        {
12370            use std::os::unix::fs::PermissionsExt as _;
12371            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
12372            let script = dir.join(name);
12373            let mut body = String::from("#!/bin/sh\n");
12374            if !stdout.is_empty() {
12375                body.push_str(&format!("cat {}\n", quote(&out_path)));
12376            }
12377            if !stderr.is_empty() {
12378                body.push_str(&format!("cat {} >&2\n", quote(&err_path)));
12379            }
12380            body.push_str(&format!("exit {exit_code}\n"));
12381            let status = std::process::Command::new("sh")
12382                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
12383                .arg(&script)
12384                .arg(&body)
12385                .status()
12386                .unwrap();
12387            assert!(status.success());
12388            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
12389            script
12390        }
12391    }
12392
12393    #[test]
12394    fn gh_output_combined_preserves_and_separates_both_streams() {
12395        let mk = |ok, stdout: &str, stderr: &str| GhOutput {
12396            ok,
12397            stdout: stdout.into(),
12398            stderr: stderr.into(),
12399        };
12400        assert_eq!(mk(true, "  ", "\n").combined(), "");
12401        assert_eq!(mk(true, "  only out \n", " \t ").combined(), "only out");
12402        assert_eq!(mk(false, "", "  only err\n").combined(), "only err");
12403        assert_eq!(
12404            mk(false, "{\"status\":\"404\"}", "gh: Not Found (HTTP 404)\n").combined(),
12405            "{\"status\":\"404\"}\ngh: Not Found (HTTP 404)"
12406        );
12407    }
12408
12409    #[tokio::test]
12410    async fn gh_separates_json_stdout_from_stderr_diagnostics() {
12411        let tmp = tempfile::tempdir().unwrap();
12412        let hint = "hint: to listen to pull request events, run `gh pr view --web`\n";
12413        let valid_view = r#"{"url":"https://github.com/example/repo/pull/1","number":1,"state":"OPEN","title":"feat: test","reviews":[],"comments":[],"mergeStateStatus":"CLEAN","headRefOid":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","baseRefName":"main"}"#;
12414        let valid_list = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: test","baseRefName":"main","isCrossRepository":false}]"#;
12415
12416        // Valid JSON stdout + nonempty stderr hint on exit 0: structured reads
12417        // parse stdout cleanly while stderr remains available via `combined()`.
12418        let ok_view = fake_gh_script(tmp.path(), "ok-view", &format!("{valid_view}\n"), hint, 0);
12419        let out = gh_with(&ok_view, tmp.path(), &["pr".into(), "view".into()])
12420            .await
12421            .unwrap();
12422        assert!(out.ok);
12423        assert_eq!(parse_pr(&out.stdout).unwrap().state, PrLifecycle::Open);
12424        assert!(out.stderr.contains("listen to pull request events"));
12425        assert!(out.combined().contains("listen to pull request events"));
12426        assert!(out.combined().contains("feat: test"));
12427
12428        let ok_list = fake_gh_script(tmp.path(), "ok-list", &format!("{valid_list}\n"), hint, 0);
12429        assert_eq!(
12430            find_open_pr_with(&ok_list, tmp.path(), "magi/task-t", "main")
12431                .await
12432                .unwrap(),
12433            OpenPr::One {
12434                url: "https://github.com/example/repo/pull/1".into(),
12435                title: "feat: test".into(),
12436            }
12437        );
12438
12439        // Malformed stdout with trailing characters still fails strict JSON parsing.
12440        let malformed = fake_gh_script(
12441            tmp.path(),
12442            "malformed",
12443            &format!("{valid_view}\ntrailing garbage\n"),
12444            "",
12445            0,
12446        );
12447        let out = gh_with(&malformed, tmp.path(), &["pr".into(), "view".into()])
12448            .await
12449            .unwrap();
12450        assert!(out.ok);
12451        let err = parse_pr(&out.stdout).unwrap_err();
12452        assert!(
12453            format!("{err:#}").contains("trailing characters"),
12454            "{err:#}"
12455        );
12456
12457        // Empty stdout + nonempty stderr on exit 0 never substitutes stderr.
12458        let empty = fake_gh_script(tmp.path(), "empty", "", hint, 0);
12459        let out = gh_with(&empty, tmp.path(), &["pr".into(), "view".into()])
12460            .await
12461            .unwrap();
12462        assert!(out.ok);
12463        assert!(out.stdout.trim().is_empty());
12464        assert!(parse_pr(&out.stdout).is_err());
12465
12466        // Non-zero exit with valid JSON on stdout and error on stderr reports
12467        // failure and preserves both streams in `combined()`.
12468        let failed = fake_gh_script(
12469            tmp.path(),
12470            "failed",
12471            &format!("{valid_view}\n"),
12472            "gh: HTTP 404 Not Found\n",
12473            1,
12474        );
12475        let out = gh_with(&failed, tmp.path(), &["pr".into(), "view".into()])
12476            .await
12477            .unwrap();
12478        assert!(!out.ok);
12479        let diag = out.combined();
12480        assert!(diag.contains("HTTP 404 Not Found"), "{diag}");
12481        assert!(diag.contains("feat: test"), "{diag}");
12482        let list_err = find_open_pr_with(&failed, tmp.path(), "magi/task-t", "main")
12483            .await
12484            .unwrap_err()
12485            .to_string();
12486        assert!(list_err.contains("HTTP 404 Not Found"), "{list_err}");
12487    }
12488
12489    struct StaticPrObserver(crate::land_sync_recovery::ObservedPr);
12490
12491    impl crate::land_sync_recovery::PrObserver for StaticPrObserver {
12492        async fn observe_pr(
12493            &self,
12494            _repo: &Path,
12495            _pr_url: &str,
12496        ) -> Result<crate::land_sync_recovery::ObservedPr> {
12497            Ok(self.0.clone())
12498        }
12499    }
12500
12501    const FIXTURE_PR_PREFIX: &str = "https://github.com/example/landing-sync-";
12502
12503    /// Tests share a process-wide home, so each recovery fixture needs a unique
12504    /// PR URL to prevent another test's `write_pr_state_through` from settling it.
12505    fn fixture_pr_url(state: &RunState) -> String {
12506        format!("{FIXTURE_PR_PREFIX}{}/pull/42", state.id)
12507    }
12508
12509    /// Build a real-shaped legacy landing base-sync exhaustion fixture backed by
12510    /// an isolated temp Git repo, bare origin, queue task, and open PR metadata.
12511    async fn legacy_exhausted_landing_fixture() -> (
12512        tempfile::TempDir,
12513        PathBuf,
12514        crate::queue::Queue,
12515        crate::queue::Task,
12516        RunState,
12517        String,
12518    ) {
12519        let (tmp, mut state, old) = landing_git_fixture().await;
12520        crate::run::pin_test_home();
12521        let home = crate::run::home();
12522        // Move run state under this isolated home so load_under/save_under match.
12523        state.config.graph.land_rounds = 4;
12524        state.config.graph.land_approval = true;
12525        state.config.verify.gate = vec!["git rev-parse HEAD".into()];
12526        state.config.verify.e2e = vec!["git rev-parse HEAD".into()];
12527        state.status = RunStatus::Blocked;
12528        state.driver_exited = true;
12529        state.pr = Some(crate::run::PrRecord {
12530            url: fixture_pr_url(&state),
12531            number: 42,
12532            state: "open".to_owned(),
12533            checks: "green".to_owned(),
12534            round: 0,
12535            rounds: 4,
12536            red_at_merge: Vec::new(),
12537        });
12538        state.merge = Some(MergeOutcome {
12539            mode: MergeMode::Pr,
12540            ok: false,
12541            detail:
12542                "could not synchronize landing base: landing base synchronization budget exhausted"
12543                    .to_owned(),
12544            empty: false,
12545        });
12546        state.reviews = vec![serde_json::from_value(serde_json::json!({
12547            "round": 1,
12548            "head": old,
12549            "expected": 2,
12550            "answered": 2,
12551            "reviews": [],
12552            "clean": true,
12553            "e2e": [{"command": "git rev-parse HEAD", "code": 0, "output_tail": old, "duration_ms": 10}],
12554            "verified_head": old,
12555            "verified_at": jiff::Timestamp::now(),
12556            "e2e_deferred": false
12557        }))
12558        .unwrap()];
12559        let pass_cmd: crate::run::CommandOutcome = serde_json::from_value(serde_json::json!({
12560            "command": "git rev-parse HEAD",
12561            "code": 0,
12562            "output_tail": old,
12563            "duration_ms": 10
12564        }))
12565        .unwrap();
12566        state.head_e2e = Some(crate::run::GateRepairE2e::new(
12567            old.clone(),
12568            true,
12569            vec![pass_cmd.clone()],
12570        ));
12571        state.gate = vec![pass_cmd];
12572        state.gate_ran = true;
12573        state.gate_head = Some(old.clone());
12574        state.land_sync_attempts = 4;
12575        state.land_sync_target = None;
12576        state.land_sync_pending = true;
12577        state.event(
12578            "land",
12579            "stopped: could not synchronize landing base: landing base synchronization budget exhausted",
12580        );
12581
12582        let queue = crate::queue::Queue::at(home.join("queue"));
12583        let mut task = crate::queue::Task::new(
12584            "landing sync".into(),
12585            state.instruction.clone(),
12586            state.repo.clone(),
12587            crate::queue::Source::Human,
12588        );
12589        task.link_run(&state.id);
12590        task.hold_machine(Some("landing base synchronization budget exhausted".into()));
12591        queue.put(&mut task).unwrap();
12592        state.origin = Some(crate::run::Origin::queue(&task.id));
12593        state.save_under(&home).unwrap();
12594        (tmp, home, queue, task, state, old)
12595    }
12596
12597    #[tokio::test]
12598    async fn land_sync_recovery_isolated_from_unrelated_pr_settlement() {
12599        let (_tmp, _home, _queue, _task, mut state, _old) =
12600            legacy_exhausted_landing_fixture().await;
12601        let home = tempfile::tempdir().unwrap();
12602        state.save_under(home.path()).unwrap();
12603        let mut source = run_state();
12604        source.pr = state.pr.clone();
12605        source.pr.as_mut().unwrap().url = green_pr().url;
12606        assert_eq!(
12607            write_pr_state_through_in(home.path(), &source, PrLifecycle::Merged),
12608            0
12609        );
12610        // The unrelated record must not be locked even during selection.
12611        assert_eq!(
12612            rewrite_open_prs(home.path(), &mut |candidate| {
12613                assert_eq!(candidate.id, state.id);
12614                let _owner = crate::pr_head::owner_lock(home.path(), &candidate.id)
12615                    .expect("unrelated PR scan must not hold the recovery owner lock");
12616                names_same_pr(
12617                    candidate,
12618                    &source.pr.as_ref().unwrap().url,
12619                    42,
12620                    &source.repo,
12621                )
12622                .then_some(PrLifecycle::Merged)
12623            }),
12624            0
12625        );
12626        let saved = RunState::load_under(&state.id, home.path()).unwrap();
12627        assert_eq!(saved.pr.as_ref().unwrap().state, "open");
12628        assert!(saved.land_sync_exhausted());
12629    }
12630
12631    #[tokio::test]
12632    async fn land_sync_recovery_continues_legacy_real_shaped_stop_on_existing_pr() {
12633        let (_tmp, home, queue, task, mut state, old) = legacy_exhausted_landing_fixture().await;
12634        let home = home.as_path();
12635
12636        // Advance origin/main once so landing rebase has real work to replay.
12637        advance_landing_base(&state).await;
12638
12639        state.pre_gate = vec![
12640            serde_json::from_value(serde_json::json!({
12641                "command": "prepare sources",
12642                "code": 0,
12643                "output_tail": "prepared",
12644                "duration_ms": 15
12645            }))
12646            .unwrap(),
12647        ];
12648        let pre_gate_commit = git::rev_parse(&state.repo, "HEAD^").await.unwrap();
12649        assert_ne!(pre_gate_commit, old);
12650        state.pre_gate_commit = Some(pre_gate_commit.clone());
12651        let pre_gate = serde_json::to_value(&state.pre_gate).unwrap();
12652        state.save_under(home).unwrap();
12653
12654        // Pre-recovery: legacy shape recognized, recover-base refused, ordinary resume/release refused.
12655        assert!(state.land_sync_exhausted());
12656        assert!(!state.base_sync_blocked());
12657        assert!(crate::land_sync_recovery::held_task(&queue, &task));
12658        let base_err = crate::graph::Runner::authorize_base_recovery(home, &state.id, &task.id)
12659            .await
12660            .unwrap_err();
12661        assert!(
12662            base_err.to_string().contains("run has no base-sync stop"),
12663            "{base_err:#}"
12664        );
12665        assert!(crate::handover::resume_refusal_under(&state, Some(home)).is_none());
12666        assert!(crate::base_sync_recovery::ensure_generic_release(&queue, &task).is_err());
12667
12668        // Ordinary land_with without authorization refuses without refilling budget.
12669        let pr_url = state.pr.as_ref().unwrap().url.clone();
12670        let blocked_forge =
12671            Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
12672        let err = land_with(&mut state, &pr_url, &blocked_forge)
12673            .await
12674            .unwrap_err();
12675        assert!(err.to_string().contains("budget exhausted"), "{err:#}");
12676        assert_eq!(state.land_sync_attempts, 4);
12677        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12678
12679        // Attach a prior head-bound approval on `old` to prove fresh approval is required after recovery.
12680        let questions = ask::Questions::at(home.join("questions"));
12681        let mut old_q = ask::Question::new(
12682            state.id.clone(),
12683            APPROVAL_NODE.into(),
12684            "owner".into(),
12685            "old head approval".into(),
12686            String::new(),
12687            vec![APPROVE.into()],
12688        );
12689        old_q
12690            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12691            .unwrap();
12692        questions.put(&mut old_q).unwrap();
12693        state.land_approval = Some(LandApproval {
12694            question: old_q.id.clone(),
12695            head: old.clone(),
12696        });
12697        state.save_under(home).unwrap();
12698
12699        // Admit explicit recover-land-sync via two-phase control.
12700        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12701            url: pr_url.clone(),
12702            number: 42,
12703            open: true,
12704            head: old.clone(),
12705            base_branch: Some("main".to_owned()),
12706        });
12707        let outcome = crate::land_sync_recovery_control::recover_with(
12708            &queue,
12709            home,
12710            crate::land_sync_recovery_control::Request {
12711                run: state.id.clone(),
12712                head: old.clone(),
12713                actor: "cli".into(),
12714                request: "req-legacy-1".into(),
12715            },
12716            &observer,
12717        )
12718        .await
12719        .unwrap();
12720        assert!(!outcome.repeated);
12721        assert_eq!(
12722            outcome
12723                .task
12724                .resume_override
12725                .as_ref()
12726                .and_then(|pin| pin.pinned_run.as_deref()),
12727            Some(state.id.as_str())
12728        );
12729
12730        // Ordinary fast-forward of origin/main between admission and dispatch is allowed.
12731        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
12732        std::fs::write(state.repo.join("advance2"), "advance2").unwrap();
12733        git::git(&state.repo, &["add", "."]).await.unwrap();
12734        git::git(&state.repo, &["commit", "-m", "advance base again"])
12735            .await
12736            .unwrap();
12737        git::git(&state.repo, &["push", "origin", "main"])
12738            .await
12739            .unwrap();
12740        git::git(&state.repo, &["checkout", "winner"])
12741            .await
12742            .unwrap();
12743
12744        let reloaded_task = queue.get(&task.id).unwrap();
12745        assert!(matches!(
12746            crate::land_sync_recovery::dispatch_check_with(&queue, home, &reloaded_task, &observer)
12747                .await,
12748            crate::land_sync_recovery::DispatchDecision::Proceed
12749        ));
12750
12751        // Execute continuation on the existing PR using real rebase + fresh gate + fresh E2E.
12752        let mut run = RunState::load_under(&state.id, home).unwrap();
12753        assert!(run.land_sync_recovery_pending());
12754        let mut forge = Scripted::for_pr(
12755            &pr_url,
12756            vec![
12757                seen(&old, Checks::Green, "BEHIND", false),
12758                seen(&old, Checks::Green, "BEHIND", false),
12759                seen("@published", Checks::Green, "CLEAN", false),
12760            ],
12761        );
12762        forge.public_repo = Some(run.repo.clone());
12763        let pr = land_with(&mut run, &pr_url, &forge).await.unwrap();
12764        assert_eq!(pr.state, PrLifecycle::Open);
12765        assert!(run.parked, "must park awaiting fresh head-bound approval");
12766
12767        // Verify attempts preserved (4 -> 5), 1 grant consumed, fresh head published,
12768        // prior verification archived, fresh gate + E2E ran on new head, fresh approval asked.
12769        let new_head = git::rev_parse(&run.repo, "HEAD").await.unwrap();
12770        assert_ne!(new_head, old);
12771        assert_eq!(run.land_sync_attempts, 5);
12772        assert_eq!(run.land_sync_recovery.extra_attempts, 1);
12773        assert_eq!(run.land_sync_budget(), 5);
12774        assert!(!run.land_sync_pending);
12775        assert_eq!(run.pr_pushed_head.as_deref(), Some(new_head.as_str()));
12776        assert_eq!(
12777            git::remote_head(&run.repo, "origin", "task-head")
12778                .await
12779                .unwrap()
12780                .as_deref(),
12781            Some(new_head.as_str())
12782        );
12783        assert!(run.gate_ran);
12784        assert_eq!(run.gate_head.as_deref(), Some(new_head.as_str()));
12785        assert!(
12786            run.head_e2e
12787                .as_ref()
12788                .is_some_and(|e| e.head == new_head && e.passed)
12789        );
12790        assert_eq!(run.reviews.len(), 1);
12791        assert!(run.reviews[0].clean);
12792        assert_eq!(run.reviews[0].answered, 2);
12793        assert!(run.reviews[0].verified_head.is_none());
12794        assert!(!run.verification_history.is_empty());
12795        assert_eq!(run.land_sync_recovery.stops.len(), 1);
12796        assert_eq!(run.land_sync_recovery.authorizations.len(), 1);
12797        let auth = &run.land_sync_recovery.authorizations[0];
12798        assert!(auth.consumed);
12799        assert!(auth.invalidated.is_none());
12800        assert!(run.pre_gate.is_empty());
12801        assert!(run.pre_gate_commit.is_none());
12802        let saved = RunState::load_under(&run.id, home).unwrap();
12803        assert!(saved.pre_gate.is_empty());
12804        assert!(saved.pre_gate_commit.is_none());
12805        let archived = saved.land_sync_recovery.authorizations[0]
12806            .archived_verification
12807            .as_ref()
12808            .unwrap();
12809        assert_eq!(serde_json::to_value(&archived.pre_gate).unwrap(), pre_gate);
12810        assert_eq!(
12811            archived.pre_gate_commit.as_deref(),
12812            Some(pre_gate_commit.as_str())
12813        );
12814
12815        let mut legacy = serde_json::to_value(archived).unwrap();
12816        let fields = legacy.as_object_mut().unwrap();
12817        fields.remove("pre_gate");
12818        fields.remove("pre_gate_commit");
12819        let legacy: crate::land_sync_recovery::ArchivedVerification =
12820            serde_json::from_value(legacy).unwrap();
12821        assert!(legacy.pre_gate.is_empty());
12822        assert!(legacy.pre_gate_commit.is_none());
12823        let new_approval = run.land_approval.as_ref().unwrap();
12824        assert_ne!(new_approval.question, old_q.id);
12825        assert_eq!(new_approval.head, new_head);
12826    }
12827
12828    #[tokio::test]
12829    async fn land_sync_recovery_observes_external_merge_without_grant() {
12830        let (_tmp, home, queue, mut task, mut state, old) =
12831            legacy_exhausted_landing_fixture().await;
12832        let pr_url = state.pr.as_ref().unwrap().url.clone();
12833        task.resume_override = Some(crate::queue::OperatorResume {
12834            question_id: String::new(),
12835            at: jiff::Timestamp::now(),
12836            conductor_rehold: None,
12837            forced: true,
12838            pinned_run: Some(state.id.clone()),
12839        });
12840        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12841            url: pr_url.clone(),
12842            number: 42,
12843            open: false,
12844            head: old.clone(),
12845            base_branch: Some("main".into()),
12846        });
12847        assert!(matches!(
12848            crate::land_sync_recovery::dispatch_check_with(&queue, &home, &task, &observer).await,
12849            crate::land_sync_recovery::DispatchDecision::Proceed
12850        ));
12851        let forge = Scripted::for_pr(&pr_url, vec![merged_view(&old)]);
12852        land_with(&mut state, &pr_url, &forge).await.unwrap();
12853        assert_eq!(state.status, RunStatus::Merged);
12854        assert_eq!(state.land_sync_attempts, 4);
12855        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12856        assert_eq!(forge.calls(), ["view"]);
12857    }
12858
12859    #[tokio::test]
12860    async fn land_sync_recovery_forces_fresh_e2e_and_gate_even_when_head_unchanged() {
12861        let (tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
12862        let home = home.as_path();
12863
12864        // Create marker-writing commands for gate and e2e so we prove both execute freshly
12865        // even when HEAD does not change (origin/main is already an ancestor of winner).
12866        let gate_marker = tmp.path().join("fresh-gate-ran");
12867        let e2e_marker = tmp.path().join("fresh-e2e-ran");
12868        state.config.verify.gate = vec![format!(
12869            "git rev-parse HEAD > \"{}\"",
12870            gate_marker.display().to_string().replace('\\', "/")
12871        )];
12872        state.config.verify.e2e = vec![format!(
12873            "git rev-parse HEAD > \"{}\"",
12874            e2e_marker.display().to_string().replace('\\', "/")
12875        )];
12876        let questions = ask::Questions::at(home.join("questions"));
12877        let mut old_q = ask::Question::new(
12878            state.id.clone(),
12879            APPROVAL_NODE.into(),
12880            "owner".into(),
12881            "prior approval on same head".into(),
12882            String::new(),
12883            vec![APPROVE.into()],
12884        );
12885        old_q
12886            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12887            .unwrap();
12888        questions.put(&mut old_q).unwrap();
12889        state.land_approval = Some(LandApproval {
12890            question: old_q.id.clone(),
12891            head: old.clone(),
12892        });
12893        state.save_under(home).unwrap();
12894
12895        let pr_url = state.pr.as_ref().unwrap().url.clone();
12896        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12897            url: pr_url.clone(),
12898            number: 42,
12899            open: true,
12900            head: old.clone(),
12901            base_branch: Some("main".to_owned()),
12902        });
12903        crate::land_sync_recovery_control::recover_with(
12904            &queue,
12905            home,
12906            crate::land_sync_recovery_control::Request {
12907                run: state.id.clone(),
12908                head: old.clone(),
12909                actor: "cli".into(),
12910                request: "req-same-head".into(),
12911            },
12912            &observer,
12913        )
12914        .await
12915        .unwrap();
12916
12917        let mut run = RunState::load_under(&state.id, home).unwrap();
12918        let mut forge = Scripted::for_pr(
12919            &pr_url,
12920            vec![
12921                seen(&old, Checks::Green, "CLEAN", false),
12922                seen(&old, Checks::Green, "CLEAN", false),
12923                seen(&old, Checks::Green, "CLEAN", false),
12924            ],
12925        );
12926        forge.public_repo = Some(run.repo.clone());
12927        land_with(&mut run, &pr_url, &forge).await.unwrap();
12928
12929        assert!(
12930            gate_marker.exists(),
12931            "fresh gate must run even on unchanged HEAD"
12932        );
12933        assert!(
12934            e2e_marker.exists(),
12935            "fresh E2E must run even on unchanged HEAD"
12936        );
12937        assert!(
12938            run.parked,
12939            "old approval before recovery must not be reused"
12940        );
12941        assert_ne!(run.land_approval.as_ref().unwrap().question, old_q.id);
12942    }
12943
12944    #[tokio::test]
12945    async fn land_sync_recovery_resumes_after_gate_repair_before_push() {
12946        let (_tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
12947        landing_gate_fixer(
12948            &mut state,
12949            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
12950        );
12951        state.config.verify.gate =
12952            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
12953        state.save_under(&home).unwrap();
12954        let pr_url = state.pr.as_ref().unwrap().url.clone();
12955        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12956            url: pr_url.clone(),
12957            number: 42,
12958            open: true,
12959            head: old.clone(),
12960            base_branch: Some("main".into()),
12961        });
12962        crate::land_sync_recovery_control::recover_with(
12963            &queue,
12964            &home,
12965            crate::land_sync_recovery_control::Request {
12966                run: state.id.clone(),
12967                head: old.clone(),
12968                actor: "cli".into(),
12969                request: "req-interrupted-gate-repair".into(),
12970            },
12971            &observer,
12972        )
12973        .await
12974        .unwrap();
12975        let mut run = RunState::load_under(&state.id, &home).unwrap();
12976        let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "CLEAN", false)]);
12977        assert!(matches!(
12978            prepare_land_sync_recovery(&mut run, &pr_url, &forge)
12979                .await
12980                .unwrap(),
12981            LandSyncPrep::Continue(Some(_))
12982        ));
12983        // Interrupt at the publication check, after the real gate fixer commits.
12984        let changed = Scripted::for_pr(
12985            &pr_url,
12986            vec![seen("different", Checks::Green, "CLEAN", false)],
12987        );
12988        let error = resume_landing_head(&mut run, &old, &pr_url, &changed, None)
12989            .await
12990            .unwrap_err();
12991        assert!(
12992            error.to_string().contains("PR head changed while gating"),
12993            "{error}"
12994        );
12995        let repaired = git::rev_parse(&run.repo, "HEAD").await.unwrap();
12996        assert_ne!(repaired, old);
12997        assert_eq!(run.gate_fixes.len(), 1);
12998        assert!(run.gate_fixes[0].committed);
12999        assert_eq!(
13000            git::remote_head(&run.repo, "origin", "task-head")
13001                .await
13002                .unwrap(),
13003            Some(old.clone())
13004        );
13005
13006        run.status = RunStatus::Blocked;
13007        run.save().unwrap();
13008        let mut resumed = RunState::load_under(&run.id, &home).unwrap();
13009        assert_eq!(resumed.land_sync_attempts, 5);
13010        assert!(resumed.land_sync_pending);
13011        assert!(!resumed.land_sync_exhausted());
13012        assert!(!resumed.land_sync_unstarted_grant());
13013        assert!(matches!(
13014            prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
13015                .await
13016                .unwrap(),
13017            LandSyncPrep::Continue(None)
13018        ));
13019        assert_eq!(
13020            resume_landing_head(&mut resumed, &old, &pr_url, &forge, None)
13021                .await
13022                .unwrap(),
13023            repaired
13024        );
13025        assert_eq!(resumed.land_sync_attempts, 5);
13026        assert_eq!(resumed.gate_fixes.len(), 1);
13027        assert!(!resumed.land_sync_pending);
13028        assert!(
13029            resumed.land_sync_recovery.authorizations[0]
13030                .invalidated
13031                .is_none()
13032        );
13033        assert_eq!(
13034            git::remote_head(&resumed.repo, "origin", "task-head")
13035                .await
13036                .unwrap(),
13037            Some(repaired)
13038        );
13039    }
13040
13041    #[tokio::test]
13042    async fn land_sync_recovery_repeated_exhaustion_is_bounded_by_lifetime_cap() {
13043        let (_tmp, home, queue, task, mut state, mut head) =
13044            legacy_exhausted_landing_fixture().await;
13045        let home = home.as_path();
13046        state.config.graph.land_approval = false;
13047        state.save_under(home).unwrap();
13048
13049        let pr_url = state.pr.as_ref().unwrap().url.clone();
13050        let mut base_step = 0usize;
13051        let advance_step = |repo: PathBuf, step: usize| async move {
13052            git::git(&repo, &["checkout", "main"]).await.unwrap();
13053            std::fs::write(repo.join(format!("advance-{step}")), format!("step-{step}")).unwrap();
13054            git::git(&repo, &["add", "."]).await.unwrap();
13055            git::git(&repo, &["commit", "-m", &format!("advance base {step}")])
13056                .await
13057                .unwrap();
13058            git::git(&repo, &["push", "origin", "main"]).await.unwrap();
13059            git::git(&repo, &["checkout", "winner"]).await.unwrap();
13060        };
13061        for grant_num in 1..=crate::land_sync_recovery::MAX_GRANTS {
13062            base_step += 1;
13063            advance_step(state.repo.clone(), base_step).await;
13064            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13065                url: pr_url.clone(),
13066                number: 42,
13067                open: true,
13068                head: head.clone(),
13069                base_branch: Some("main".to_owned()),
13070            });
13071            crate::land_sync_recovery_control::recover_with(
13072                &queue,
13073                home,
13074                crate::land_sync_recovery_control::Request {
13075                    run: state.id.clone(),
13076                    head: head.clone(),
13077                    actor: "cli".into(),
13078                    request: format!("req-cap-{grant_num}"),
13079                },
13080                &observer,
13081            )
13082            .await
13083            .unwrap();
13084
13085            // Simulate execution consuming grant, spending the 1 attempt, and hitting exhaustion again.
13086            state = RunState::load_under(&state.id, home).unwrap();
13087            let mut forge = Scripted::for_pr(
13088                &pr_url,
13089                vec![
13090                    seen(&head, Checks::Green, "BEHIND", false),
13091                    seen(&head, Checks::Green, "BEHIND", false),
13092                    seen("@published", Checks::Green, "BEHIND", false),
13093                ],
13094            );
13095            forge.public_repo = Some(state.repo.clone());
13096            let prep = prepare_land_sync_recovery(&mut state, &pr_url, &forge)
13097                .await
13098                .unwrap();
13099            assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
13100            head = resume_landing_head(&mut state, &head, &pr_url, &forge, None)
13101                .await
13102                .unwrap();
13103            assert_eq!(state.land_sync_attempts, 4 + grant_num);
13104            assert_eq!(state.land_sync_recovery.extra_attempts, grant_num);
13105
13106            // Re-exhaust on another base advance.
13107            base_step += 1;
13108            advance_step(state.repo.clone(), base_step).await;
13109            let err = rebase_landing_worktree(&mut state, "origin/main")
13110                .await
13111                .unwrap_err();
13112            assert!(err.to_string().contains("budget exhausted"), "{err:#}");
13113            state.status = RunStatus::Blocked;
13114            state.save_under(home).unwrap();
13115            assert!(state.land_sync_exhausted());
13116
13117            // Put task back to Held so the next explicit authorization can queue it.
13118            let mut t = queue.get(&task.id).unwrap();
13119            t.hold_machine(Some("re-exhausted".into()));
13120            queue.put(&mut t).unwrap();
13121        }
13122
13123        assert_eq!(
13124            state.land_sync_attempts,
13125            4 + crate::land_sync_recovery::MAX_GRANTS
13126        );
13127        assert_eq!(state.land_sync_grants_remaining(), 0);
13128        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13129            url: pr_url,
13130            number: 42,
13131            open: true,
13132            head: head.clone(),
13133            base_branch: Some("main".to_owned()),
13134        });
13135        let err = crate::land_sync_recovery_control::recover_with(
13136            &queue,
13137            home,
13138            crate::land_sync_recovery_control::Request {
13139                run: state.id.clone(),
13140                head,
13141                actor: "cli".into(),
13142                request: "req-cap-overflow".into(),
13143            },
13144            &observer,
13145        )
13146        .await
13147        .unwrap_err();
13148        assert!(
13149            err.to_string()
13150                .contains("lifetime landing base-sync recovery limit reached"),
13151            "{err:#}"
13152        );
13153    }
13154
13155    #[tokio::test]
13156    async fn land_sync_recovery_execution_revalidation_refuses_stale_pr_head_and_rewritten_base() {
13157        // Case A: PR head moves externally between admission and execution.
13158        {
13159            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13160            let pr_url = state.pr.as_ref().unwrap().url.clone();
13161            let home = home.as_path();
13162            advance_landing_base(&state).await;
13163            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13164                url: pr_url.clone(),
13165                number: 42,
13166                open: true,
13167                head: old.clone(),
13168                base_branch: Some("main".to_owned()),
13169            });
13170            crate::land_sync_recovery_control::recover_with(
13171                &queue,
13172                home,
13173                crate::land_sync_recovery_control::Request {
13174                    run: state.id.clone(),
13175                    head: old.clone(),
13176                    actor: "cli".into(),
13177                    request: "req-stale-pr".into(),
13178                },
13179                &observer,
13180            )
13181            .await
13182            .unwrap();
13183
13184            let mut run = RunState::load_under(&state.id, home).unwrap();
13185            let foreign_head = "f".repeat(40);
13186            let forge = Scripted::for_pr(
13187                &pr_url,
13188                vec![seen(&foreign_head, Checks::Green, "BEHIND", false)],
13189            );
13190            land_with(&mut run, &pr_url, &forge).await.unwrap();
13191            assert_eq!(run.status, RunStatus::Blocked);
13192            assert_eq!(run.land_sync_recovery.extra_attempts, 0);
13193            assert_eq!(run.land_sync_attempts, 4);
13194            let auth = run.land_sync_recovery.authorizations.last().unwrap();
13195            assert!(auth.consumed);
13196            assert!(
13197                auth.invalidated
13198                    .as_deref()
13199                    .is_some_and(|why| why.contains("published PR head changed")),
13200                "{:?}",
13201                auth.invalidated
13202            );
13203            assert_eq!(run.pr_pushed_head.as_deref(), Some(old.as_str()));
13204        }
13205
13206        // Case B: origin/main rewritten (non-fast-forward) between admission and execution.
13207        {
13208            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13209            let pr_url = state.pr.as_ref().unwrap().url.clone();
13210            let home = home.as_path();
13211            advance_landing_base(&state).await;
13212            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13213                url: pr_url.clone(),
13214                number: 42,
13215                open: true,
13216                head: old.clone(),
13217                base_branch: Some("main".to_owned()),
13218            });
13219            crate::land_sync_recovery_control::recover_with(
13220                &queue,
13221                home,
13222                crate::land_sync_recovery_control::Request {
13223                    run: state.id.clone(),
13224                    head: old.clone(),
13225                    actor: "cli".into(),
13226                    request: "req-rewritten-base".into(),
13227                },
13228                &observer,
13229            )
13230            .await
13231            .unwrap();
13232
13233            // Persist consumption before the rewrite, as if the driver crashed
13234            // between granting the attempt and starting the rebase.
13235            let mut consumed = RunState::load_under(&state.id, home).unwrap();
13236            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13237            assert!(matches!(
13238                prepare_land_sync_recovery(&mut consumed, &pr_url, &forge)
13239                    .await
13240                    .unwrap(),
13241                LandSyncPrep::Continue(Some(_))
13242            ));
13243            assert_eq!(consumed.land_sync_attempts, 4);
13244
13245            // Rewrite origin/main by amending the latest base commit and force-pushing.
13246            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13247            std::fs::write(state.repo.join("advance"), "rewritten").unwrap();
13248            git::git(&state.repo, &["add", "."]).await.unwrap();
13249            git::git(&state.repo, &["commit", "--amend", "-m", "rewritten base"])
13250                .await
13251                .unwrap();
13252            git::git(&state.repo, &["push", "--force", "origin", "main"])
13253                .await
13254                .unwrap();
13255            git::git(&state.repo, &["checkout", "winner"])
13256                .await
13257                .unwrap();
13258
13259            let mut run = RunState::load_under(&state.id, home).unwrap();
13260            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13261            land_with(&mut run, &pr_url, &forge).await.unwrap();
13262            assert_eq!(run.status, RunStatus::Blocked);
13263            assert_eq!(run.land_sync_recovery.extra_attempts, 1);
13264            assert_eq!(run.land_sync_attempts, 4);
13265            assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
13266            let auth = run.land_sync_recovery.authorizations.last().unwrap();
13267            assert!(auth.consumed);
13268            assert!(
13269                auth.invalidated
13270                    .as_deref()
13271                    .is_some_and(|why| why.contains("does not fast-forward")),
13272                "{:?}",
13273                auth.invalidated
13274            );
13275            assert!(run.land_sync_exhausted());
13276            assert_eq!(run.land_sync_budget(), 4);
13277            let mut held = queue
13278                .list()
13279                .into_iter()
13280                .find(|t| t.execution_runs().last() == Some(&run.id))
13281                .unwrap();
13282            held.hold_machine(Some("recovery scope changed".into()));
13283            queue.put(&mut held).unwrap();
13284            crate::land_sync_recovery_control::recover_with(
13285                &queue,
13286                home,
13287                crate::land_sync_recovery_control::Request {
13288                    run: run.id.clone(),
13289                    head: old.clone(),
13290                    actor: "cli".into(),
13291                    request: "req-rewritten-base-new-approval".into(),
13292                },
13293                &observer,
13294            )
13295            .await
13296            .unwrap();
13297            let mut resumed = RunState::load_under(&run.id, home).unwrap();
13298            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13299            assert!(matches!(
13300                prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
13301                    .await
13302                    .unwrap(),
13303                LandSyncPrep::Continue(Some(_))
13304            ));
13305            assert_eq!(resumed.land_sync_recovery.extra_attempts, 2);
13306            assert_eq!(resumed.land_sync_budget(), 5);
13307            assert_eq!(resumed.land_sync_attempts, 4);
13308            assert!(
13309                resumed.land_sync_recovery.authorizations[0]
13310                    .invalidated
13311                    .is_some()
13312            );
13313        }
13314    }
13315
13316    #[tokio::test]
13317    async fn land_sync_recovery_restart_after_consume_continues_without_double_grant() {
13318        let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13319        let home = home.as_path();
13320        let pr_url = state.pr.as_ref().unwrap().url.clone();
13321        advance_landing_base(&state).await;
13322        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13323            url: pr_url.clone(),
13324            number: 42,
13325            open: true,
13326            head: old.clone(),
13327            base_branch: Some("main".to_owned()),
13328        });
13329        crate::land_sync_recovery_control::recover_with(
13330            &queue,
13331            home,
13332            crate::land_sync_recovery_control::Request {
13333                run: state.id.clone(),
13334                head: old.clone(),
13335                actor: "cli".into(),
13336                request: "req-crash-after-consume".into(),
13337            },
13338            &observer,
13339        )
13340        .await
13341        .unwrap();
13342
13343        // Simulate consuming the authorization and crashing right before rebase starts.
13344        let mut crashed = RunState::load_under(&state.id, home).unwrap();
13345        let initial_forge =
13346            Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13347        let prep = prepare_land_sync_recovery(&mut crashed, &pr_url, &initial_forge)
13348            .await
13349            .unwrap();
13350        assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
13351        assert_eq!(crashed.land_sync_recovery.extra_attempts, 1);
13352        assert_eq!(crashed.land_sync_attempts, 4);
13353        assert!(crashed.land_sync_recovery.authorizations[0].consumed);
13354
13355        // An unreadable base is not proof that the authorized lineage changed.
13356        let remote = git::git(&state.repo, &["remote", "get-url", "origin"])
13357            .await
13358            .unwrap();
13359        git::git(
13360            &state.repo,
13361            &["remote", "set-url", "origin", "missing-local-origin"],
13362        )
13363        .await
13364        .unwrap();
13365        let mut interrupted = RunState::load_under(&state.id, home).unwrap();
13366        let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13367        assert!(matches!(
13368            prepare_land_sync_recovery(&mut interrupted, &pr_url, &forge)
13369                .await
13370                .unwrap(),
13371            LandSyncPrep::Stop(_)
13372        ));
13373        assert!(
13374            interrupted.land_sync_recovery.authorizations[0]
13375                .invalidated
13376                .is_none()
13377        );
13378        assert_eq!(interrupted.land_sync_attempts, 4);
13379        git::git(&state.repo, &["remote", "set-url", "origin", remote.trim()])
13380            .await
13381            .unwrap();
13382        let mut held = queue
13383            .list()
13384            .into_iter()
13385            .find(|t| t.execution_runs().last() == Some(&state.id))
13386            .unwrap();
13387        held.hold_machine(Some("base observation failed".into()));
13388        queue.put(&mut held).unwrap();
13389        assert!(crate::resume::pin_queued(&queue, &state.id, None, None).unwrap());
13390        let queued = queue.get(&held.id).unwrap();
13391        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, .. } =
13392            crate::land_sync_recovery::dispatch_check_with(&queue, home, &queued, &observer).await
13393        {
13394            panic!("dispatch refused recovery: {reason}");
13395        }
13396
13397        // Reload after restart and run land_with: uses the 1 already-granted attempt, never double-grants.
13398        let mut restarted = RunState::load_under(&state.id, home).unwrap();
13399        let mut forge = Scripted::for_pr(
13400            &pr_url,
13401            vec![
13402                seen(&old, Checks::Green, "BEHIND", false),
13403                seen(&old, Checks::Green, "BEHIND", false),
13404                seen("@published", Checks::Green, "CLEAN", false),
13405            ],
13406        );
13407        forge.public_repo = Some(restarted.repo.clone());
13408        land_with(&mut restarted, &pr_url, &forge).await.unwrap();
13409        assert_eq!(restarted.land_sync_recovery.extra_attempts, 1);
13410        assert_eq!(restarted.land_sync_attempts, 5);
13411        assert_eq!(restarted.land_sync_recovery.authorizations.len(), 1);
13412        assert!(!restarted.land_sync_pending);
13413    }
13414
13415    #[tokio::test]
13416    async fn land_sync_recovery_dispatch_revalidation_refuses_stale_and_superseded_state() {
13417        // 1. Without authorization, dispatch holds without spending budget.
13418        let (_tmp, home, queue, task, state, old) = legacy_exhausted_landing_fixture().await;
13419        let home = home.as_path();
13420        let pr_url = state.pr.as_ref().unwrap().url.clone();
13421        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13422            url: pr_url,
13423            number: 42,
13424            open: true,
13425            head: old.clone(),
13426            base_branch: Some("main".to_owned()),
13427        });
13428        assert!(matches!(
13429            crate::land_sync_recovery::dispatch_check_with(&queue, home, &task, &observer).await,
13430            crate::land_sync_recovery::DispatchDecision::Hold { .. }
13431        ));
13432
13433        // 2. Admit authorization, then supersede with a newer owner decision before dispatch.
13434        crate::land_sync_recovery_control::recover_with(
13435            &queue,
13436            home,
13437            crate::land_sync_recovery_control::Request {
13438                run: state.id.clone(),
13439                head: old.clone(),
13440                actor: "cli".into(),
13441                request: "req-dispatch-superseded".into(),
13442            },
13443            &observer,
13444        )
13445        .await
13446        .unwrap();
13447        let mut t = queue.get(&task.id).unwrap();
13448        t.operator_decided_at = Some(
13449            t.operator_decided_at.unwrap_or_else(jiff::Timestamp::now)
13450                + jiff::SignedDuration::from_secs(10),
13451        );
13452        queue.put(&mut t).unwrap();
13453        let decision =
13454            crate::land_sync_recovery::dispatch_check_with(&queue, home, &t, &observer).await;
13455        match decision {
13456            crate::land_sync_recovery::DispatchDecision::Hold {
13457                reason,
13458                state: updated,
13459            } => {
13460                assert!(
13461                    reason.contains("newer owner decision superseded"),
13462                    "{reason}"
13463                );
13464                let auth = updated.land_sync_recovery.authorizations.last().unwrap();
13465                assert!(auth.consumed);
13466                assert!(auth.invalidated.is_some());
13467                assert_eq!(updated.land_sync_recovery.extra_attempts, 0);
13468            }
13469            crate::land_sync_recovery::DispatchDecision::Proceed => {
13470                panic!("superseded authorization must be refused at dispatch");
13471            }
13472        }
13473    }
13474}