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 repair interrupted after publication but before saving the
4352/// successful push. The caller has already checked the clean, gated local head.
4353pub(crate) async fn repair_publication_observed(
4354    state: &RunState,
4355    publication: &crate::run::PrPublication,
4356) -> Result<bool> {
4357    if state.pr_publication.as_ref() != Some(publication) {
4358        return Ok(false);
4359    }
4360    let winner = state.winner().context("repair has no winner")?;
4361    let remote = git::remote_head(
4362        &winner.worktree,
4363        &state.config.merge.remote,
4364        &publication.branch,
4365    )
4366    .await?;
4367    Ok(remote.as_deref() == Some(publication.head.as_str()))
4368}
4369
4370/// Whether `observed` is the forge's stale view of this run's own completed
4371/// repair push. Proven only by the pre-push checkpoint: the observation is the
4372/// leased previous head, and the saved lease, retained HEAD and public ref all
4373/// name the checkpoint's commit. A third commit, a divergent or remote-only
4374/// update, or a missing checkpoint is not self-publication.
4375async fn lagging_self_publication(state: &RunState, observed: &str) -> Result<bool> {
4376    let Some(published) = &state.pr_publication else {
4377        return Ok(false);
4378    };
4379    let Some(winner) = state.winner() else {
4380        return Ok(false);
4381    };
4382    if !observed.eq_ignore_ascii_case(&published.previous)
4383        || observed.eq_ignore_ascii_case(&published.head)
4384        || state.pr_branch().unwrap_or(&winner.branch) != published.branch
4385        || !state
4386            .pr_pushed_head
4387            .as_deref()
4388            .is_some_and(|saved| saved.eq_ignore_ascii_case(&published.head))
4389        || state.gate_head.as_deref() != Some(published.head.as_str())
4390        || !state.gate_allows_progress()
4391    {
4392        return Ok(false);
4393    }
4394    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4395    if !local.eq_ignore_ascii_case(&published.head) || !git::is_clean(&winner.worktree).await? {
4396        return Ok(false);
4397    }
4398    let public =
4399        git::remote_head(&state.repo, &state.config.merge.remote, &published.branch).await?;
4400    Ok(public.is_some_and(|head| head.eq_ignore_ascii_case(&published.head)))
4401}
4402
4403/// Reconcile a stopped landing before changing its branch. This also handles
4404/// old records whose graph status or merge detail no longer identifies land.
4405async fn resume_landing_head<F: Forge>(
4406    state: &mut RunState,
4407    observed: &str,
4408    pr_url: &str,
4409    forge: &F,
4410    reason: Option<Blocking>,
4411) -> Result<String> {
4412    crate::pr_head::ensure_owner(state)?;
4413    let winner = state.winner().cloned().context("landing has no winner")?;
4414    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4415    let expected = state
4416        .pr_pushed_head
4417        .as_deref()
4418        .or(state.gate_head.as_deref())
4419        .context("missing public head lease")?;
4420    anyhow::ensure!(
4421        observed == expected
4422            || (observed == local
4423                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4424                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4425        "public head moved outside this run; refusing to sync"
4426    );
4427    // An operator may have extended and published the winner while approval
4428    // was pending. Matching local/public history can be adopted as the lease,
4429    // but publish_landing_head must gate its new SHA before proceeding. A
4430    // remote-only or divergent update still cannot be overwritten.
4431    // Save reconciliation before rebasing again; a prior push may have reached
4432    // the remote immediately before the previous driver's last save.
4433    state.pr_pushed_head = Some(observed.to_owned());
4434    state.save()?;
4435    restore_landing_worktree(state).await?;
4436    // Recover a rebase that finished before its completion checkpoint was
4437    // saved. Restoration above has already reconciled its files and ancestry.
4438    let scratch = state.dir().join("rebase");
4439    if let Some(target) = state.land_sync_target.clone()
4440        && !crate::rebase::checked_progress(state, &scratch, "").await?
4441        && git::ancestry(&winner.worktree, &target, &local).await?
4442    {
4443        state.land_sync_target = None;
4444        state.save()?;
4445    }
4446    let remote = state.config.merge.remote.clone();
4447    let base = state.base_branch.clone();
4448    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4449    anyhow::ensure!(
4450        fetched.ok(),
4451        "cannot fetch landing base: {}",
4452        fetched.stderr
4453    );
4454    anyhow::ensure!(
4455        !owner_requested_stop(state)?,
4456        "owner requested stop before base synchronization"
4457    );
4458    let onto = format!("{remote}/{base}");
4459    let tip = git::rev_parse(&state.repo, &onto).await?;
4460    if state.land_sync_unstarted_grant() {
4461        let auth = state
4462            .land_sync_recovery
4463            .authorizations
4464            .last()
4465            .context("missing recovery grant")?;
4466        anyhow::ensure!(
4467            auth.invalidated.is_none()
4468                && git::ancestry(&state.repo, &auth.scope.tip, &tip).await?
4469                && git::ancestry(&state.repo, &auth.stop.tip, &tip).await?,
4470            "fetched landing base is outside the authorized recovery lineage"
4471        );
4472    }
4473    let contains_base = git::ancestry(&state.repo, &tip, &local)
4474        .await
4475        .context("could not determine whether the landing head contains the fetched base")?;
4476    anyhow::ensure!(
4477        reason != Some(Blocking::Behind) || !contains_base,
4478        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4479    );
4480    if !contains_base || reason == Some(Blocking::Conflict) {
4481        match rebase_landing_worktree(state, &tip).await? {
4482            crate::rebase::Rebased::Applied => {}
4483            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4484        }
4485    }
4486    if reason == Some(Blocking::Behind) {
4487        anyhow::ensure!(
4488            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4489            "BEHIND synchronization left the head unchanged"
4490        );
4491    }
4492    publish_landing_head(state, observed, pr_url, forge).await
4493}
4494
4495/// Share the synchronization path with structured evidence retained after a refusal.
4496async fn synchronize_landing<F: Forge>(
4497    state: &mut RunState,
4498    pr: &mut PrState,
4499    observed: &str,
4500    pr_url: &str,
4501    forge: &F,
4502) -> Result<Option<String>> {
4503    if owner_stop(state, pr, forge).await? {
4504        return Ok(None);
4505    }
4506    state.event(
4507        "land",
4508        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4509    );
4510    state.save()?;
4511    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4512    if owner_stop(state, pr, forge).await? {
4513        return Ok(None);
4514    }
4515    match synced {
4516        Ok(head) => {
4517            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4518                crate::graph::refresh_reviewed_commits(state, &branch).await;
4519            }
4520            Ok(Some(head))
4521        }
4522        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4523        Err(e) => {
4524            let repo = state.repo.clone();
4525            stop(
4526                state,
4527                &repo,
4528                pr,
4529                &format!("could not synchronize landing base: {e:#}"),
4530            )
4531            .await?;
4532            Ok(None)
4533        }
4534    }
4535}
4536
4537enum LandSyncPrep {
4538    Continue(Option<Seen>),
4539    Stop(PrState),
4540}
4541
4542/// Revalidate and durably consume a pending landing base-sync recovery
4543/// authorization under the live execution lease before mutating landing status
4544/// or adopting any observed PR head.
4545async fn prepare_land_sync_recovery<F: Forge>(
4546    state: &mut RunState,
4547    pr_url: &str,
4548    forge: &F,
4549) -> Result<LandSyncPrep> {
4550    let has_unconsumed = state.has_unconsumed_land_sync_authorization();
4551    let unstarted = state.land_sync_unstarted_grant();
4552    let exhausted = state.land_sync_exhausted();
4553    if !has_unconsumed && !exhausted && !unstarted {
4554        return Ok(LandSyncPrep::Continue(None));
4555    }
4556    let repo = state.repo.clone();
4557    let seen = forge.view(&repo, pr_url).await?;
4558    if seen.pr.state != PrLifecycle::Open {
4559        anyhow::ensure!(
4560            state
4561                .pr
4562                .as_ref()
4563                .is_some_and(|pr| pr.url == seen.pr.url && pr.number == seen.pr.number),
4564            "terminal pull request does not match the retained run"
4565        );
4566        return Ok(LandSyncPrep::Continue(Some(seen)));
4567    }
4568    if !has_unconsumed && !unstarted {
4569        bail!(
4570            "{}; explicit recover-land-sync authorization required",
4571            crate::land_sync_recovery::EXHAUSTED_DETAIL
4572        );
4573    }
4574    let observed = crate::land_sync_recovery::ObservedPr {
4575        url: seen.pr.url.clone(),
4576        number: seen.pr.number,
4577        open: seen.pr.state == PrLifecycle::Open,
4578        head: seen.head.clone(),
4579        base_branch: (!seen.base.is_empty()).then(|| seen.base.clone()),
4580    };
4581    let home = crate::run::home();
4582    let validation = if owner_requested_stop(state)? {
4583        Err("owner requested stop before landing base-sync recovery".into())
4584    } else {
4585        crate::land_sync_recovery::validate_pending_authorization(
4586            &home,
4587            state,
4588            None,
4589            Some(&observed),
4590            &crate::land_sync_recovery::GhPrObserver,
4591        )
4592        .await
4593    };
4594    match validation {
4595        Ok((local_head, pr_head)) => {
4596            if unstarted {
4597                return Ok(LandSyncPrep::Continue(Some(seen)));
4598            }
4599            if let Err(reason) = state.consume_land_sync_recovery(&local_head, &pr_head) {
4600                state.status = RunStatus::Blocked;
4601                state.event("land-sync-recovery", format!("refused: {reason}"));
4602                state.save()?;
4603                return Ok(LandSyncPrep::Stop(seen.pr));
4604            }
4605            state.event(
4606                "land-sync-recovery",
4607                format!(
4608                    "consumed recovery grant {}/{}: authorized {} landing sync attempt ({}/{}); prior verification archived, fresh E2E and gate required",
4609                    state.land_sync_recovery.extra_attempts,
4610                    crate::land_sync_recovery::MAX_GRANTS,
4611                    crate::land_sync_recovery::GRANT_ATTEMPTS,
4612                    state.land_sync_attempts,
4613                    state.land_sync_budget()
4614                ),
4615            );
4616            state.save()?;
4617            Ok(LandSyncPrep::Continue(Some(seen)))
4618        }
4619        Err(failure) => {
4620            let reason = failure.reason;
4621            if !failure.observation_failed
4622                && let Some(auth) = state
4623                    .land_sync_recovery
4624                    .authorizations
4625                    .iter_mut()
4626                    .rev()
4627                    .find(|a| {
4628                        a.invalidated.is_none()
4629                            && (!a.consumed || unstarted && a.archived_verification.is_some())
4630                    })
4631            {
4632                auth.refuse(&reason);
4633            }
4634            state.status = RunStatus::Blocked;
4635            state.event("land-sync-recovery", format!("refused: {reason}"));
4636            state.save()?;
4637            Ok(LandSyncPrep::Stop(seen.pr))
4638        }
4639    }
4640}
4641
4642async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4643    crate::pr_head::ensure_owner(state)?;
4644    anyhow::ensure!(
4645        state.unfinished_instruction_revision().is_none(),
4646        "instruction revision repair did not complete; explicitly recover and review the revised instruction before landing"
4647    );
4648    let mut initial_seen = match prepare_land_sync_recovery(state, pr_url, forge).await? {
4649        LandSyncPrep::Continue(seen) => seen,
4650        LandSyncPrep::Stop(pr) => return Ok(pr),
4651    };
4652    state.land_unrelated = None;
4653    let reopening_hold = crate::merge_decision::resumable_hold(state);
4654    let repo = state.repo.clone();
4655    let budget = state.config.graph.land_rounds;
4656    let mut round = 0usize;
4657    let ci = state.config.merge.ci.expectation();
4658    if ci == CiExpectation::Absent {
4659        state.event(
4660            "land",
4661            "CI not expected ([merge] ci = \"none\"); check status ignored",
4662        );
4663    }
4664    let mut waited = Duration::ZERO;
4665    // Comment bodies the fixer has already been shown. A comment is
4666    // outstanding until it has been handed over once; after that it is a
4667    // recorded decision, not an open question, and re-feeding it would loop the
4668    // budget away on a comment the fixer already declined with an argument.
4669    let mut shown: BTreeSet<String> = BTreeSet::new();
4670    // Await the last successfully published head, including across resumes.
4671    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4672    // Whether a settled-checks refusal has already been given its one re-look.
4673    let mut rechecked = false;
4674
4675    // Marks the run resumable through exactly this function, not through a
4676    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4677    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4678    // status specifically to know a resumed run belongs back in `land`
4679    // rather than at a second `gh pr create`. Set on every entry - fresh or
4680    // resumed - because a resume that parked here again must keep reading
4681    // `Landing`, not whatever a first pass through `merge` left behind.
4682    state.status = RunStatus::Landing;
4683    state.event("land", format!("watching {pr_url}"));
4684    state.save()?;
4685
4686    // An armed merge recorded by an earlier pass may or may not have reached
4687    // the forge (the record is written before the call). It is taken back on
4688    // the first observation, where a pull request is known to stop with.
4689    let mut resumed_armed = state.land_armed_head.is_some();
4690
4691    'landing: loop {
4692        let seen = match initial_seen.take() {
4693            Some(seen) => seen,
4694            None => forge.view(&repo, pr_url).await?,
4695        };
4696        let mut pr = seen.pr.clone();
4697        pr.review_comments.retain(|c| !shown.contains(&c.body));
4698        state.pr = Some(crate::run::PrRecord {
4699            url: pr.url.clone(),
4700            number: pr.number,
4701            state: pr.state.as_str().to_owned(),
4702            checks: pr.checks.as_str().to_owned(),
4703            round,
4704            rounds: budget,
4705            red_at_merge: Vec::new(),
4706        });
4707        state.save()?;
4708
4709        if pr.state == PrLifecycle::Open {
4710            state.observe_branch_owner_holds(&seen.head).await;
4711            state.save()?;
4712        }
4713        crate::pr_head::ensure_owner(state)?;
4714        if reopening_hold {
4715            anyhow::ensure!(
4716                pr.state == PrLifecycle::Open,
4717                "held PR is no longer open; cannot request a fresh decision"
4718            );
4719            // An explicit resume authorizes a fresh question only. Preserve the
4720            // answered card, and never enter repair/rebase/merge on this pass.
4721            disarm(forge, state, &repo, pr.number)
4722                .await
4723                .map_err(anyhow::Error::msg)?;
4724            let previous = state.merge_decision.take();
4725            let binding = state.land_approval.take();
4726            state.config.graph.land_approval = true;
4727            let subject = merge_subject(
4728                crate::graph::landing_title(state, &seen.title),
4729                &crate::graph::landing_subject_source(state),
4730            );
4731            let contested = contested_to_ask(state);
4732            if let Err(error) =
4733                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4734            {
4735                state.merge_decision = previous;
4736                state.land_approval = binding;
4737                return Err(error);
4738            }
4739            state.end_pass_parked(crate::run::ParkCause::Question);
4740            state.parked = true;
4741            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()));
4742            state.save()?;
4743            return Ok(pr);
4744        }
4745        if owner_stop(state, &mut pr, forge).await? {
4746            return Ok(pr);
4747        }
4748
4749        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4750            // An approval already given for the same head is reused, so
4751            // nothing is asked twice. A failed disable
4752            // stops the run with the record kept: pushing on could change the
4753            // head under an arm that is still live.
4754            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4755                let why = format!(
4756                    "a previous pass may have armed auto-merge and it could not be disabled \
4757                     on resume: {e}"
4758                );
4759                stop(state, &repo, &pr, &why).await?;
4760                return Ok(pr);
4761            }
4762        }
4763
4764        // The head moved away from the one auto-merge was armed on, by
4765        // someone other than this loop. The arm is pinned and would refuse to
4766        // merge the new commit, but the approval was for the old one: take it
4767        // back and go through the normal path again.
4768        if pr.state == PrLifecycle::Open
4769            && !seen.head.is_empty()
4770            && state
4771                .land_armed_head
4772                .as_deref()
4773                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4774        {
4775            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4776                let why = format!(
4777                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4778                );
4779                stop(state, &repo, &pr, &why).await?;
4780                return Ok(pr);
4781            }
4782        }
4783
4784        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4785            // Disarming can outlive an owner answer. Consume it before our
4786            // own rebase invalidates the head shown on the decision card.
4787            if owner_stop(state, &mut pr, forge).await? {
4788                return Ok(pr);
4789            }
4790            if lagging_self_publication(state, &seen.head).await? {
4791                if waited < WAIT_CEILING {
4792                    waited += POLL;
4793                    forge.poll().await;
4794                    continue;
4795                }
4796                let why = format!(
4797                    "forge did not observe the published repair head {} (still showing {})",
4798                    state.pr_pushed_head.as_deref().unwrap_or_default(),
4799                    seen.head
4800                );
4801                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4802                return Ok(pr);
4803            }
4804            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4805                binding.head.eq_ignore_ascii_case(&seen.head)
4806                    && ask::Questions::open()
4807                        .get_for_effects(&binding.question)
4808                        .is_ok_and(|q| {
4809                            q.run == state.id
4810                                && q.node == APPROVAL_NODE
4811                                && q.status == ask::QuestionStatus::Answered
4812                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4813                        })
4814            });
4815            if repair_answer {
4816                let subject = merge_subject(
4817                    crate::graph::landing_title(state, &seen.title),
4818                    &crate::graph::landing_subject_source(state),
4819                );
4820                let contested = contested_to_ask(state);
4821                if matches!(
4822                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4823                    ApprovalGate::Repair
4824                ) {
4825                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4826                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4827                        state.save()?;
4828                    }
4829                    return Ok(pr);
4830                }
4831            }
4832            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4833            // A stop detected before publication must apply its durable
4834            // decision, even when verification returned an error meanwhile.
4835            if owner_stop(state, &mut pr, forge).await? {
4836                return Ok(pr);
4837            }
4838            let head = synced?;
4839            awaiting_head = Some(head);
4840            waited = Duration::ZERO;
4841            rechecked = false;
4842            // Read CI and approvals afresh, never from the pre-push observation.
4843            continue;
4844        }
4845
4846        // A stale base is independent of the CI rollup. Keep the public-head
4847        // lease, but synchronize before waiting for checks on the old tree.
4848        if pr.state == PrLifecycle::Open
4849            && pr.blocking == Blocking::Behind
4850            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4851        {
4852            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4853            let Some(head) = synced else {
4854                return Ok(pr);
4855            };
4856            awaiting_head = Some(head);
4857            rechecked = false;
4858            waited = Duration::ZERO;
4859            continue;
4860        }
4861
4862        if pr.state == PrLifecycle::Open {
4863            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4864                if waited >= WAIT_CEILING {
4865                    let want = awaiting_head.as_deref().unwrap_or_default();
4866                    let why = format!(
4867                        "the pull request's checks were still not about one readable head after \
4868                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4869                         someone may have pushed over it",
4870                        WAIT_CEILING.as_secs() / 60,
4871                        if want.is_empty() { "any" } else { want },
4872                        if seen.head.is_empty() {
4873                            "nothing readable"
4874                        } else {
4875                            &seen.head
4876                        },
4877                        if seen.rollup_head.is_empty() {
4878                            "nothing readable"
4879                        } else {
4880                            &seen.rollup_head
4881                        },
4882                    );
4883                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4884                    return Ok(pr);
4885                }
4886                waited += POLL;
4887                forge.poll().await;
4888                continue;
4889            }
4890            // Reset once, when the awaited head first shows up; resetting on
4891            // every re-observation would let a standing refusal wait forever.
4892            if awaiting_head.take().is_some() {
4893                // The checks now being read belong to the new head; give them
4894                // the same grace a fresh pull request gets.
4895                waited = Duration::ZERO;
4896            }
4897        }
4898
4899        // The merge-state grace is head-bound and durable. Reruns reset the
4900        // checks clock, but must not extend this deadline across resumes.
4901        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4902            let first = state
4903                .land_unsaid
4904                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4905            if !first.0.eq_ignore_ascii_case(&seen.head) {
4906                *first = (seen.head.clone(), forge.now());
4907            }
4908            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4909            state.save()?;
4910            elapsed
4911        } else {
4912            waited
4913        };
4914        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4915        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4916            if waited >= WAIT_CEILING {
4917                stop_disarmed(
4918                    forge,
4919                    state,
4920                    &repo,
4921                    &pr,
4922                    "merge state remained unreadable; refusing to merge on a guess",
4923                )
4924                .await?;
4925                return Ok(pr);
4926            }
4927            waited += POLL;
4928            forge.poll().await;
4929            continue;
4930        }
4931
4932        // A failed workflow run is rerun once, judged by its own run rather
4933        // than by the rollup's aggregate: another run still pending, or a fix
4934        // budget already spent, must not keep a flaky failure from its one
4935        // rerun. It spends no round and no attempt.
4936        if ci == CiExpectation::Expected
4937            && pr.state == PrLifecycle::Open
4938            && state.config.graph.rerun_flaky_checks
4939        {
4940            let include_optional = pr.checks == Checks::Red
4941                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4942            let failing = rerunnable_with(&seen.contexts, include_optional);
4943            let now = forge.now();
4944            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4945                RerunStep::Rerun(runs) => {
4946                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4947                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4948                        *rec = LandReruns {
4949                            head: seen.head.clone(),
4950                            runs: BTreeMap::new(),
4951                        };
4952                    }
4953                    for run in &runs {
4954                        rec.runs.insert(run.clone(), now);
4955                    }
4956                    // Durable before the call: a restart must not
4957                    // rerun the same run twice. A save that fails
4958                    // means no rerun.
4959                    state.save()?;
4960                    let mut any = false;
4961                    for run in &runs {
4962                        let names = failing
4963                            .iter()
4964                            .filter(|(_, r)| r.as_deref() == Some(run))
4965                            .map(|(l, _)| l.as_str())
4966                            .collect::<Vec<_>>()
4967                            .join(", ");
4968                        match forge.rerun(&repo, run).await {
4969                            Ok(()) => {
4970                                any = true;
4971                                state.event(
4972                                    "land",
4973                                    format!("reran failed check(s) {names} (run {run})"),
4974                                );
4975                            }
4976                            // Stays recorded: never a retry loop.
4977                            Err(e) => state.event(
4978                                "land",
4979                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4980                            ),
4981                        }
4982                    }
4983                    state.save()?;
4984                    if any {
4985                        waited = Duration::ZERO;
4986                        forge.poll().await;
4987                        continue;
4988                    }
4989                }
4990                RerunStep::Grace => {
4991                    if waited >= WAIT_CEILING {
4992                        let why = format!(
4993                            "checks were still failing after a rerun and {} minutes",
4994                            WAIT_CEILING.as_secs() / 60
4995                        );
4996                        stop(state, &repo, &pr, &why).await?;
4997                        return Ok(pr);
4998                    }
4999                    waited += POLL;
5000                    forge.poll().await;
5001                    continue;
5002                }
5003                RerunStep::Fix => {}
5004            }
5005        }
5006
5007        let step = proposed;
5008        // Armed on exactly this head: the forge is doing the waiting. A
5009        // decision to merge (or keep waiting) is only watched, never re-armed
5010        // and never re-approved; anything else - a red check, a comment, a
5011        // conflict - falls through to its own arm, which disarms first.
5012        let armed_here = state
5013            .land_armed_head
5014            .as_deref()
5015            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
5016        if armed_here && matches!(step, Step::Merge | Step::Wait) {
5017            if waited >= WAIT_CEILING {
5018                let required = if seen.base.is_empty() {
5019                    None
5020                } else {
5021                    forge.required_contexts(&repo, &seen.base).await
5022                };
5023                let why = format!(
5024                    "auto-merge was armed on {} but the pull request did not merge within {} \
5025                     minutes ({})",
5026                    seen.head,
5027                    WAIT_CEILING.as_secs() / 60,
5028                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
5029                );
5030                stop_disarmed(forge, state, &repo, &pr, &why).await?;
5031                return Ok(pr);
5032            }
5033            waited += POLL;
5034            forge.poll().await;
5035            continue;
5036        }
5037        if armed_here && !matches!(step, Step::Done { .. }) {
5038            // Not merging or waiting any more: whatever is next may change the
5039            // head or give up, and neither may leave the arm standing.
5040            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
5041                let why = format!("auto-merge could not be disabled: {e}");
5042                stop(state, &repo, &pr, &why).await?;
5043                return Ok(pr);
5044            }
5045        }
5046        if pr.checks == Checks::Red
5047            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
5048            && pr.review_comments.is_empty()
5049            && let Some(evidence) = forge.attribution(state, &seen).await
5050            && evidence.unrelated(&seen.head, &pr.failing)
5051        {
5052            if owner_stop(state, &mut pr, forge).await? {
5053                return Ok(pr);
5054            }
5055            // Attribution does not authorize action against an unseen push.
5056            let fresh = forge.view(&repo, pr_url).await?;
5057            if fresh.head != seen.head
5058                || fresh.rollup_head != seen.rollup_head
5059                || fresh.pr.state != PrLifecycle::Open
5060                || fresh.pr.checks != Checks::Red
5061                || fresh.pr.failing != pr.failing
5062                || fresh
5063                    .pr
5064                    .review_comments
5065                    .iter()
5066                    .any(|c| !shown.contains(&c.body))
5067            {
5068                continue;
5069            }
5070            hold_unrelated(state, &pr, evidence).await?;
5071            return Ok(pr);
5072        }
5073        match step {
5074            Step::Wait => {
5075                if waited >= WAIT_CEILING {
5076                    let why = format!(
5077                        "checks were still running after {} minutes",
5078                        WAIT_CEILING.as_secs() / 60
5079                    );
5080                    stop(state, &repo, &pr, &why).await?;
5081                    return Ok(pr);
5082                }
5083                waited += POLL;
5084                forge.poll().await;
5085            }
5086            Step::Done { merged } => {
5087                if merged {
5088                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
5089                }
5090                // Auto-merge is pinned to the approved head, but the forge's
5091                // own handling of a later push is not something magi can
5092                // see: if the pull request merged on another commit, say so
5093                // loudly rather than record a clean landing.
5094                if let Some(armed) = state.land_armed_head.take() {
5095                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
5096                        let msg = format!(
5097                            "{} merged on {} but the owner approved {armed}; review what landed",
5098                            pr.url, seen.head
5099                        );
5100                        tracing::warn!("{msg}");
5101                        state.event("land", msg);
5102                        // Only an arm left by an older build can get here.
5103                        // The wording is fixed so a repeat does not relight
5104                        // the notice.
5105                        crate::notices::raise_with(
5106                            crate::notices::Notice::warn(
5107                                &format!("merged-unapproved-head:{}", state.id),
5108                                "A pull request merged on a commit the owner did not approve; \
5109                                 review what landed",
5110                            )
5111                            .link(crate::notices::Link::Run {
5112                                id: state.id.clone(),
5113                            }),
5114                            &state.config.notify,
5115                        );
5116                    }
5117                }
5118                state.status = if merged {
5119                    RunStatus::Merged
5120                } else {
5121                    RunStatus::Ready
5122                };
5123                let detail = if merged {
5124                    format!("{} was merged", pr.url)
5125                } else {
5126                    format!("{} was closed without merging", pr.url)
5127                };
5128                state.merge = Some(MergeOutcome {
5129                    mode: MergeMode::Pr,
5130                    ok: merged,
5131                    detail: detail.clone(),
5132                    empty: false,
5133                });
5134                state.event("land", detail);
5135                state.save()?;
5136                write_pr_state_through(state, pr.state);
5137                return Ok(pr);
5138            }
5139            Step::Merge => {
5140                state.check_delivery_evidence(&seen.head)?;
5141                let subject = merge_subject(
5142                    crate::graph::landing_title(state, &seen.title),
5143                    &crate::graph::landing_subject_source(state),
5144                );
5145                // The owner sees the panel before the one irreversible step,
5146                // and an unanswered question is a hold: silence never merges.
5147                //
5148                // The dedicated policy includes existing consent and post-repair
5149                // decisions; repair choice availability never grants merge authority.
5150                let contested = contested_to_ask(state);
5151                if !approval_reasons(state).is_empty() {
5152                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
5153                        .await?
5154                    {
5155                        ApprovalGate::Approved => {}
5156                        ApprovalGate::Repair => {
5157                            // The driver consumes the saved request under the existing
5158                            // run/task claim. No merge, no second run or task.
5159                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
5160                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
5161                                state.save()?;
5162                            }
5163                            return Ok(pr);
5164                        }
5165                        ApprovalGate::Held => {
5166                            // Another entry point may have saved a stop after
5167                            // the first read above. Apply its durable action.
5168                            if owner_stop(state, &mut pr, forge).await? {
5169                                return Ok(pr);
5170                            }
5171                            stop(
5172                                state,
5173                                &repo,
5174                                &pr,
5175                                "the owner did not approve the merge (held or unanswered)",
5176                            )
5177                            .await?;
5178                            return Ok(pr);
5179                        }
5180                        // Filed (or still standing from an earlier visit) and
5181                        // not yet answered. Park here rather than wait: the
5182                        // question survives on disk, the daemon hands this
5183                        // run's slot to something else, and a later resume
5184                        // re-enters `land`, finds the same question, and
5185                        // either merges or stops depending on what it says
5186                        // by then.
5187                        ApprovalGate::Pending => {
5188                            state.end_pass_parked(crate::run::ParkCause::Question);
5189                            state.parked = true;
5190                            state.event(
5191                                "land",
5192                                "parked awaiting merge approval - resumes once answered",
5193                            );
5194                            state.save()?;
5195                            return Ok(pr);
5196                        }
5197                    }
5198                }
5199                // Open and past the gate above, so `seen.head` is the commit
5200                // the checks were bound to and the owner approved.
5201                //
5202                // Merge directly, bound to that commit. Auto-merge is not
5203                // armed any more: the forge checks `--match-head-commit` only
5204                // when the request is made, so an arm outlives the head it
5205                // was made for, and a push of another commit whose
5206                // requirements are met first would merge without approval.
5207                // A direct merge is checked by the forge at the moment it
5208                // happens, so only the approved head can land.
5209                let observed_head = seen.head.clone();
5210                // Read the pull request again just before: the state seen
5211                // above can be a moment old.
5212                {
5213                    let fresh = forge.view(&repo, pr_url).await.ok();
5214                    if fresh.as_ref().is_some_and(|current| {
5215                        current.pr.state == PrLifecycle::Open
5216                            && current.head.eq_ignore_ascii_case(&observed_head)
5217                            && Blocking::of(&current.merge_state) == Blocking::Behind
5218                    }) {
5219                        pr.blocking = Blocking::Behind;
5220                        let synced =
5221                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5222                                .await?;
5223                        let Some(head) = synced else {
5224                            return Ok(pr);
5225                        };
5226                        awaiting_head = Some(head);
5227                        rechecked = false;
5228                        waited = Duration::ZERO;
5229                        continue 'landing;
5230                    }
5231                    if !direct_merge_is_safe(
5232                        fresh.as_ref(),
5233                        &observed_head,
5234                        &shown,
5235                        round,
5236                        budget,
5237                        waited,
5238                        ci,
5239                    ) {
5240                        if waited >= WAIT_CEILING {
5241                            let why = "the pull request did not settle on the approved head \
5242                                       before it could be merged";
5243                            stop(state, &repo, &pr, why).await?;
5244                            return Ok(pr);
5245                        }
5246                        state.event(
5247                            "land",
5248                            "the pull request changed before merging; looking again",
5249                        );
5250                        waited += POLL;
5251                        forge.poll().await;
5252                        continue;
5253                    }
5254                }
5255                let argv = merge_argv_at(pr.number, &subject, &observed_head);
5256                let out = {
5257                    let merge_lock = repo_merge_lock(&repo);
5258                    let _merge_slot = merge_lock.lock().await;
5259                    crate::pr_head::ensure_owner(state)?;
5260                    if let Some(task_id) = state
5261                        .origin
5262                        .as_ref()
5263                        .and_then(|origin| origin.task.as_ref())
5264                    {
5265                        let task = crate::queue::Queue::open()
5266                            .get(task_id)
5267                            .context("cannot verify the task owner immediately before merge")?;
5268                        if task.execution_runs().last() != Some(&state.id)
5269                            || task.operator_held()
5270                            || task.status == crate::queue::TaskStatus::Done
5271                        {
5272                            bail!(
5273                                "task ownership or an operator hold superseded this merge approval"
5274                            );
5275                        }
5276                    }
5277                    if let Some(binding) = &state.land_approval {
5278                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
5279                        if merge_consent_superseded(state, &current)?
5280                            || current.run != state.id
5281                            || !binding.head.eq_ignore_ascii_case(&observed_head)
5282                            || approval(current.resolution().as_deref()) != Approval::Merge
5283                            || current.merge_target.as_ref().is_some_and(|t| {
5284                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
5285                            })
5286                        {
5287                            bail!(
5288                                "merge decision is stale or no longer authorizes the reviewed head"
5289                            );
5290                        }
5291                    }
5292                    forge.merge(&repo, &argv).await?
5293                };
5294                if out.0 {
5295                    // Exit 0 is not proof of a merge: with a merge queue `gh`
5296                    // enqueues (or reports the pull request already queued)
5297                    // and succeeds while it is still open. Ask the forge; an
5298                    // unreadable answer is not a confirmation either, so it
5299                    // is looked at again rather than recorded as merged.
5300                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
5301                        if c.pr.state == PrLifecycle::Merged {
5302                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
5303                            true
5304                        } else {
5305                            false
5306                        }
5307                    });
5308                    if !confirmed {
5309                        if waited >= WAIT_CEILING {
5310                            let why = "the merge request succeeded but the pull request \
5311                                       could not be confirmed merged after waiting";
5312                            stop(state, &repo, &pr, why).await?;
5313                            return Ok(pr);
5314                        }
5315                        state.event(
5316                            "land",
5317                            "merge accepted but the pull request is not confirmed merged yet; waiting",
5318                        );
5319                        state.save()?;
5320                        waited += POLL;
5321                        forge.poll().await;
5322                        continue;
5323                    }
5324                    pr.state = PrLifecycle::Merged;
5325                    state.status = RunStatus::Merged;
5326                    state.merge = Some(MergeOutcome {
5327                        mode: MergeMode::Pr,
5328                        ok: true,
5329                        detail: format!("gh {}", argv.join(" ")),
5330                        empty: false,
5331                    });
5332                    // The last `state.pr` snapshot is whatever the poll before
5333                    // this merge observed - still `open` - and nothing below
5334                    // refreshes it from GitHub again, so the UI's round rail
5335                    // would otherwise keep animating a merged run forever.
5336                    if let Some(pr_record) = state.pr.as_mut() {
5337                        pr_record.state = pr.state.as_str().to_owned();
5338                    }
5339                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5340                    announce_red_merge(state, &pr).await;
5341                    state.save()?;
5342                    write_pr_state_through(state, pr.state);
5343                    return Ok(pr);
5344                }
5345                let after_seen = forge.view(&repo, pr_url).await.ok();
5346                let after = after_seen.as_ref().map(|s| s.pr.state);
5347                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
5348                    state.pr_merged_head = after_seen
5349                        .as_ref()
5350                        .map(|s| s.head.clone())
5351                        .filter(|h| !h.is_empty());
5352                    pr.state = PrLifecycle::Merged;
5353                    state.status = RunStatus::Merged;
5354                    state.merge = Some(outcome);
5355                    if let Some(pr_record) = state.pr.as_mut() {
5356                        pr_record.state = pr.state.as_str().to_owned();
5357                    }
5358                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5359                    announce_red_merge(state, &pr).await;
5360                    state.save()?;
5361                    write_pr_state_through(state, pr.state);
5362                    return Ok(pr);
5363                }
5364                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
5365                match verdict {
5366                    Refused::Behind => {
5367                        pr.blocking = Blocking::Behind;
5368                        let synced =
5369                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5370                                .await?;
5371                        let Some(head) = synced else {
5372                            return Ok(pr);
5373                        };
5374                        awaiting_head = Some(head);
5375                        rechecked = false;
5376                        waited = Duration::ZERO;
5377                        continue 'landing;
5378                    }
5379                    Refused::Final => {
5380                        let merge_state = after_seen
5381                            .as_ref()
5382                            .map(|s| s.merge_state.as_str())
5383                            .filter(|m| !m.is_empty())
5384                            .unwrap_or("unknown");
5385                        // Which refusal this was decides what a person has to
5386                        // do about it, so the two are worded apart; both carry
5387                        // the forge's own message.
5388                        let why = format!(
5389                            "the merge was refused: {} (merge state: {merge_state})",
5390                            out.1
5391                        );
5392                        stop(state, &repo, &pr, &why).await?;
5393                        return Ok(pr);
5394                    }
5395                    verdict => {
5396                        // Back to the top, which re-decides and passes the
5397                        // approval gate again, a poll later. `waited` is not
5398                        // reset here: only a pushed fix restarts it, or a
5399                        // standing refusal would wait forever.
5400                        if waited >= WAIT_CEILING {
5401                            let why = format!(
5402                                "the merge was still refused after {} minutes: {}",
5403                                WAIT_CEILING.as_secs() / 60,
5404                                out.1
5405                            );
5406                            stop(state, &repo, &pr, &why).await?;
5407                            return Ok(pr);
5408                        }
5409                        if verdict == Refused::Recheck {
5410                            rechecked = true;
5411                        }
5412                        state.event(
5413                            "land",
5414                            "merge refused while the branch policy is not satisfied yet; waiting",
5415                        );
5416                        state.save()?;
5417                        waited += POLL;
5418                        forge.poll().await;
5419                    }
5420                }
5421            }
5422            Step::Rebase => {
5423                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
5424                let Some(head) = synced else {
5425                    return Ok(pr);
5426                };
5427                awaiting_head = Some(head);
5428                rechecked = false;
5429                waited = Duration::ZERO;
5430                continue 'landing;
5431            }
5432            Step::GiveUp { reason } => {
5433                stop(state, &repo, &pr, &reason).await?;
5434                return Ok(pr);
5435            }
5436            Step::Fix { reason } => {
5437                round += 1;
5438                waited = Duration::ZERO;
5439                for c in &pr.review_comments {
5440                    shown.insert(c.body.clone());
5441                }
5442                state.event("land", format!("round {round}: {reason}"));
5443                state.save()?;
5444
5445                let logs = failing_logs(&repo, &seen.failing_urls).await;
5446                let was_red = pr.checks == Checks::Red;
5447                if owner_stop(state, &mut pr, forge).await? {
5448                    return Ok(pr);
5449                }
5450                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
5451                if owner_stop(state, &mut pr, forge).await? {
5452                    return Ok(pr);
5453                }
5454                match fixed {
5455                    Fixed::Committed { head } => {
5456                        // Whatever the next look shows may still be the
5457                        // previous head; see `awaiting_new_head`.
5458                        state.pr_pushed_head = Some(head.clone());
5459                        awaiting_head = Some(head);
5460                        rechecked = false;
5461                        waited = Duration::ZERO;
5462                        forge.poll().await;
5463                    }
5464                    Fixed::Declined if was_red => {
5465                        // Review comments may have required this round even
5466                        // when CI was unrelated. Once the fixer has read them,
5467                        // use the same structural attribution before charging
5468                        // a no-commit stop to the task.
5469                        if let Some(evidence) = forge.attribution(state, &seen).await
5470                            && evidence.unrelated(&seen.head, &pr.failing)
5471                        {
5472                            let fresh = forge.view(&repo, pr_url).await?;
5473                            if fresh.head != seen.head
5474                                || fresh.rollup_head != seen.rollup_head
5475                                || fresh.pr.state != PrLifecycle::Open
5476                                || fresh.pr.checks != Checks::Red
5477                                || fresh.pr.failing != pr.failing
5478                                || fresh
5479                                    .pr
5480                                    .review_comments
5481                                    .iter()
5482                                    .any(|c| !shown.contains(&c.body))
5483                            {
5484                                continue;
5485                            }
5486                            if owner_stop(state, &mut pr, forge).await? {
5487                                return Ok(pr);
5488                            }
5489                            hold_unrelated(state, &pr, evidence).await?;
5490                            return Ok(pr);
5491                        }
5492                        let why = format!(
5493                            "the fixer produced no commit while {} check(s) were failing \
5494                             ({}); stopping instead of looping on an unchanged tree",
5495                            pr.failing.len(),
5496                            pr.failing.join(", ")
5497                        );
5498                        stop(state, &repo, &pr, &why).await?;
5499                        return Ok(pr);
5500                    }
5501                    // Comment-driven round with no commit: the fixer read the
5502                    // comments and changed nothing, which is a decision it is
5503                    // allowed to make. The comments are recorded as shown, so
5504                    // the next observation sees a clean pull request.
5505                    Fixed::Declined => state.event(
5506                        "land",
5507                        format!("round {round}: fixer declined the comments, nothing committed"),
5508                    ),
5509                    Fixed::Deferred => {
5510                        // No fixer was available to judge these comments or
5511                        // checks. Keep the previous completed-round count and
5512                        // return without handing the PR off as a task failure.
5513                        state.status = RunStatus::Blocked;
5514                        state.save()?;
5515                        return Ok(pr);
5516                    }
5517                    Fixed::Failed(why) => {
5518                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5519                        return Ok(pr);
5520                    }
5521                }
5522                state.save()?;
5523            }
5524        }
5525    }
5526}
5527
5528/// Owner decision for a CI failure independently reproduced on the base.
5529pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5530
5531/// Durable machine-hold evidence, bound to one observed PR head.
5532#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5533pub struct CiHold {
5534    /// Head that exhibited the independently reproduced failures.
5535    pub head: String,
5536    /// Typed owner question controlling resumption.
5537    pub question: String,
5538    /// Complete structured facts used to attribute the failures.
5539    pub evidence: CiEvidence,
5540}
5541
5542/// Only structured forge annotations are compared, never log prose.
5543#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5544struct CiFailure {
5545    path: String,
5546    start_line: u64,
5547    end_line: u64,
5548    title: String,
5549    message: String,
5550}
5551
5552#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5553struct CiCheckEvidence {
5554    label: String,
5555    head_check: u64,
5556    base_check: u64,
5557    app: u64,
5558    run: String,
5559    base_run: String,
5560    head_failures: Vec<CiFailure>,
5561    base_failures: Vec<CiFailure>,
5562    rerun_exhausted: bool,
5563}
5564
5565/// Pinned Git diff and forge failure annotations used for CI attribution.
5566#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5567pub struct CiEvidence {
5568    head: String,
5569    base: String,
5570    changed: Vec<String>,
5571    checks: Vec<CiCheckEvidence>,
5572}
5573
5574impl CiEvidence {
5575    /// Every red check must have the same located failure on the base, outside
5576    /// the diff. Changes to CI/build configuration invalidate this inference.
5577    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5578        if self.head != head
5579            || self.base.is_empty()
5580            || failing.is_empty()
5581            || self.changed.iter().any(|p| {
5582                p.starts_with(".github/")
5583                    || p.starts_with(".config/")
5584                    || p.starts_with(".cargo/")
5585                    || matches!(
5586                        p.rsplit('/').next().unwrap_or(p),
5587                        "Cargo.toml"
5588                            | "Cargo.lock"
5589                            | "Makefile.toml"
5590                            | "build.rs"
5591                            | "rust-toolchain.toml"
5592                    )
5593            })
5594        {
5595            return false;
5596        }
5597        failing.iter().all(|label| {
5598            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5599            matches.len() == 1
5600                && matches[0].rerun_exhausted
5601                && !matches[0].head_failures.is_empty()
5602                && matches[0].head_failures.iter().all(|f| {
5603                    // Workflow-level exit-code annotations do not identify a
5604                    // failing test or source file, and prove nothing here.
5605                    !f.path.is_empty()
5606                        && !f.path.starts_with('.')
5607                        && !f.path.contains("..")
5608                        && !f.path.starts_with('/')
5609                        && !self.changed.contains(&f.path)
5610                        && matches[0].base_failures.contains(f)
5611                })
5612        })
5613    }
5614}
5615
5616async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5617    let out = gh(repo, &["api".into(), endpoint]).await.ok()?;
5618    if !out.ok {
5619        return None;
5620    }
5621    serde_json::from_str(&out.stdout).ok()
5622}
5623
5624async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5625    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5626    if count == 0 || count >= 100 {
5627        return None;
5628    }
5629    let id = check.get("id")?.as_u64()?;
5630    let value = ci_json(
5631        repo,
5632        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5633    )
5634    .await?;
5635    let annotations = value.as_array()?;
5636    if annotations.len() != count as usize {
5637        return None;
5638    }
5639    annotations
5640        .iter()
5641        .filter(|a| a["annotation_level"] == "failure")
5642        .map(|a| {
5643            Some(CiFailure {
5644                path: a["path"].as_str()?.into(),
5645                start_line: a["start_line"].as_u64()?,
5646                end_line: a["end_line"].as_u64()?,
5647                title: a["title"].as_str()?.into(),
5648                message: a["message"].as_str()?.into(),
5649            })
5650        })
5651        .collect()
5652}
5653
5654async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5655    let value = ci_json(
5656        repo,
5657        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5658    )
5659    .await?;
5660    let runs = value["check_runs"].as_array()?;
5661    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5662        return None;
5663    }
5664    Some(runs.clone())
5665}
5666
5667async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5668    let repo = &state.repo;
5669    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5670    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5671        .await
5672        .ok()?;
5673    if !base.ok() {
5674        return None;
5675    }
5676    let range = format!("{}...{}", base.stdout, seen.head);
5677    // No rename detection: both old and new paths must count as changed.
5678    let diff = git::git_raw(
5679        repo,
5680        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5681    )
5682    .await
5683    .ok()?;
5684    if !diff.ok() {
5685        return None;
5686    }
5687    let head_runs = ci_runs(repo, &seen.head).await?;
5688    let base_runs = ci_runs(repo, &base.stdout).await?;
5689    let mut checks = Vec::new();
5690    for label in &seen.pr.failing {
5691        let matching = |runs: &[serde_json::Value]| {
5692            runs.iter()
5693                .filter(|r| r["name"].as_str() == Some(label))
5694                .cloned()
5695                .collect::<Vec<_>>()
5696        };
5697        let heads = matching(&head_runs);
5698        let bases = matching(&base_runs);
5699        if heads.len() != 1 || bases.len() != 1 {
5700            return None;
5701        }
5702        let h = &heads[0];
5703        let b = &bases[0];
5704        if h["conclusion"] != "failure"
5705            || b["conclusion"] != "failure"
5706            || h["status"] != "completed"
5707            || b["status"] != "completed"
5708            || h["head_sha"].as_str()? != seen.head
5709            || b["head_sha"].as_str()? != base.stdout
5710            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5711        {
5712            return None;
5713        }
5714        let run = run_of(h["details_url"].as_str()?)?;
5715        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5716        if contexts.len() != 1
5717            || contexts[0].run.as_ref() != Some(&run)
5718            || contexts[0].verdict != Verdict::Fail
5719        {
5720            return None;
5721        }
5722        // A persisted request alone is not a completed rerun: require the
5723        // workflow's structured attempt number as well.
5724        let workflow =
5725            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5726        let base_run = run_of(b["details_url"].as_str()?)?;
5727        let base_workflow = ci_json(
5728            repo,
5729            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5730        )
5731        .await?;
5732        if base_workflow["head_sha"].as_str()? != base.stdout
5733            || base_workflow["head_branch"].as_str()? != seen.base
5734            || base_workflow["status"] != "completed"
5735            || base_workflow["conclusion"] != "failure"
5736            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5737        {
5738            return None;
5739        }
5740        let exhausted = state
5741            .land_reruns
5742            .as_ref()
5743            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5744            && workflow["head_sha"].as_str()? == seen.head
5745            && workflow["run_attempt"].as_u64()? > 1
5746            && workflow["status"] == "completed";
5747        checks.push(CiCheckEvidence {
5748            label: label.clone(),
5749            head_check: h["id"].as_u64()?,
5750            base_check: b["id"].as_u64()?,
5751            app: h.pointer("/app/id")?.as_u64()?,
5752            run,
5753            base_run,
5754            head_failures: ci_annotations(repo, h).await?,
5755            base_failures: ci_annotations(repo, b).await?,
5756            rerun_exhausted: exhausted,
5757        });
5758    }
5759    Some(CiEvidence {
5760        head: seen.head.clone(),
5761        base: base.stdout,
5762        changed: diff
5763            .stdout
5764            .split('\0')
5765            .filter(|p| !p.is_empty())
5766            .map(str::to_owned)
5767            .collect(),
5768        checks,
5769    })
5770}
5771
5772async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5773    let detail = serde_json::to_string(&evidence)?;
5774    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5775    let hold = "operator: 保留して後で判断する".to_owned();
5776    let mut q = ask::Question::new(
5777        state.id.clone(),
5778        CI_HOLD_NODE.into(),
5779        "land".into(),
5780        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5781        format!(
5782            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5783        ),
5784        vec![resume.clone(), hold.clone()],
5785    );
5786    q.actions.insert(
5787        resume,
5788        ask::ChoiceAction::Resume {
5789            run: state.id.clone(),
5790        },
5791    );
5792    q.actions.insert(hold, ask::ChoiceAction::Hold);
5793    ask::Questions::open().put_executable(&mut q)?;
5794    state.land_unrelated = Some(CiHold {
5795        head: evidence.head.clone(),
5796        question: q.id.clone(),
5797        evidence,
5798    });
5799    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5800    state.end_pass_parked(crate::run::ParkCause::Question);
5801    state.parked = true;
5802    state.save()?;
5803    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5804        tracing::warn!("could not notify about CI hold: {e:#}");
5805    }
5806    // A durable question and evidence are sufficient even if commenting fails.
5807    let body = stop_comment(
5808        &state.id,
5809        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5810    );
5811    let (_, body) = crate::github_text::prepare(state, "", &body);
5812    gh(
5813        &state.repo,
5814        &[
5815            "pr".into(),
5816            "comment".into(),
5817            pr.number.to_string(),
5818            "--body".into(),
5819            body,
5820        ],
5821    )
5822    .await
5823    .ok();
5824    Ok(())
5825}
5826
5827/// One observation, plus the two things [`PrState`] deliberately does not carry:
5828/// the title (needed for the squash subject) and where the failing checks'
5829/// logs live.
5830#[derive(Clone)]
5831struct Seen {
5832    pr: PrState,
5833    title: String,
5834    failing_urls: Vec<(String, String)>,
5835    /// `headRefOid`: the commit this observation, checks included, is about.
5836    head: String,
5837    /// The commit the checks belong to, read from the same GraphQL node as
5838    /// the checks themselves. Empty when unreadable.
5839    rollup_head: String,
5840    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5841    /// and DRAFT together, and a stop reason has to say which.
5842    merge_state: String,
5843    /// Every check of the rollup, for naming what an armed merge waits on.
5844    contexts: Vec<CheckInfo>,
5845    /// `baseRefName`, to look up which contexts the base requires.
5846    base: String,
5847}
5848
5849/// One check of the rollup as far as a stop reason needs it.
5850#[derive(Clone)]
5851struct CheckInfo {
5852    label: String,
5853    verdict: Verdict,
5854    required: Option<bool>,
5855    /// The workflow run the check belongs to; `None` for an external status.
5856    run: Option<String>,
5857}
5858
5859/// What to do with a red head before a fix round is spent on it.
5860#[derive(Debug, Clone, PartialEq, Eq)]
5861enum RerunStep {
5862    /// Rerun these workflow runs (each not yet rerun for this head).
5863    Rerun(Vec<String>),
5864    /// Reran already and the forge may still report the old failure: wait.
5865    Grace,
5866    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5867    Fix,
5868}
5869
5870/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5871/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5872/// pending checks in another run do not delay this run's rerun.
5873#[cfg(test)]
5874fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5875    rerunnable_with(contexts, false)
5876}
5877
5878fn rerunnable_with(
5879    contexts: &[CheckInfo],
5880    include_optional: bool,
5881) -> Vec<(String, Option<String>)> {
5882    contexts
5883        .iter()
5884        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5885        // `gh run rerun --failed` refuses a run with a job still going.
5886        .filter(|c| {
5887            c.run.as_ref().is_none_or(|r| {
5888                !contexts.iter().any(|o| {
5889                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5890                        && o.run.as_ref() == Some(r)
5891                })
5892            })
5893        })
5894        .map(|c| (c.label.clone(), c.run.clone()))
5895        .collect()
5896}
5897
5898/// Pure: rerun once per run id, wait out the grace, then hand over.
5899fn rerun_step(
5900    failing: &[(String, Option<String>)],
5901    record: Option<&LandReruns>,
5902    head: &str,
5903    now: i64,
5904) -> RerunStep {
5905    // A failure with no workflow run (an external status) cannot be rerun, and
5906    // the fixer's push re-runs everything anyway.
5907    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5908        return RerunStep::Fix;
5909    }
5910    // Reruns belong to the head they were made on.
5911    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5912    let mut fresh: Vec<String> = Vec::new();
5913    let mut recent = false;
5914    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5915        match record.and_then(|r| r.runs.get(run)) {
5916            None => {
5917                if !fresh.iter().any(|f| f == run) {
5918                    fresh.push(run.to_owned());
5919                }
5920            }
5921            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5922            Some(_) => {}
5923        }
5924    }
5925    if !fresh.is_empty() {
5926        RerunStep::Rerun(fresh)
5927    } else if recent {
5928        RerunStep::Grace
5929    } else {
5930        RerunStep::Fix
5931    }
5932}
5933
5934/// Read minimal live PR metadata (`url`, `number`, `state`, `headRefOid`,
5935/// `baseRefName`) for landing base-sync recovery admission and dispatch checks.
5936pub(crate) async fn observe_pr_summary(
5937    repo: &Path,
5938    pr_url: &str,
5939) -> Result<crate::land_sync_recovery::ObservedPr> {
5940    #[derive(serde::Deserialize)]
5941    struct Summary {
5942        #[serde(default)]
5943        url: String,
5944        #[serde(default)]
5945        number: u64,
5946        #[serde(default)]
5947        state: String,
5948        #[serde(default, rename = "headRefOid")]
5949        head_ref_oid: String,
5950        #[serde(default, rename = "baseRefName")]
5951        base_ref_name: String,
5952    }
5953    let view = gh(
5954        repo,
5955        &[
5956            "pr".to_owned(),
5957            "view".to_owned(),
5958            pr_url.to_owned(),
5959            "--json".to_owned(),
5960            "url,number,state,headRefOid,baseRefName".to_owned(),
5961        ],
5962    )
5963    .await?;
5964    if !view.ok {
5965        bail!("gh pr view {pr_url}: {}", view.combined());
5966    }
5967    let parsed: Summary = serde_json::from_str(&view.stdout).context("parse pull request json")?;
5968    Ok(crate::land_sync_recovery::ObservedPr {
5969        url: parsed.url,
5970        number: parsed.number,
5971        open: parsed.state.eq_ignore_ascii_case("OPEN"),
5972        head: parsed.head_ref_oid,
5973        base_branch: (!parsed.base_ref_name.is_empty()).then_some(parsed.base_ref_name),
5974    })
5975}
5976
5977/// Read the pull request: `gh pr view` for the top-level thread and merge
5978/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5979/// inline review comments `gh pr view` does not report.
5980async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5981    let view = gh(
5982        repo,
5983        &[
5984            "pr".to_owned(),
5985            "view".to_owned(),
5986            pr_url.to_owned(),
5987            "--json".to_owned(),
5988            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5989                .to_owned(),
5990        ],
5991    )
5992    .await?;
5993    if !view.ok {
5994        bail!("gh pr view {pr_url}: {}", view.combined());
5995    }
5996    let number = parse_pr(&view.stdout)?.number;
5997    let node = last_commit_node(repo, number).await;
5998    let mut seen = seen_from(&view.stdout, node.as_deref())?;
5999
6000    let inline = gh(
6001        repo,
6002        &[
6003            "api".to_owned(),
6004            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
6005        ],
6006    )
6007    .await?;
6008    if inline.ok {
6009        match parse_inline_comments(&inline.stdout) {
6010            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
6011            // An unreadable inline thread must not end a landing: the rollup
6012            // and the top-level thread are still real signal.
6013            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
6014        }
6015    } else {
6016        tracing::warn!(
6017            "gh api pulls/{}/comments: {}",
6018            seen.pr.number,
6019            inline.combined()
6020        );
6021    }
6022    Ok(seen)
6023}
6024
6025/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
6026/// response. No I/O.
6027///
6028/// The commit oid and the checks are read from the *same* node, so the rollup
6029/// is bound to the commit it belongs to by construction; two reads that agree
6030/// before and after another response prove nothing about what that response
6031/// held. The view's own rollup is never used. A node that is missing,
6032/// unreadable, carries GraphQL errors, or whose checks run past the page
6033/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
6034/// as "look again" and never as a reason to merge.
6035fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
6036    let mut pr = parse_pr(view_json)?;
6037    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
6038
6039    let mut rollup_head = String::new();
6040    let mut failing_urls = Vec::new();
6041    let mut contexts = Vec::new();
6042    let mut checks = Checks::Unknown;
6043    let mut failing = Vec::new();
6044    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
6045        (checks, failing) = rollup_verdict(&rollup);
6046        failing_urls = rollup
6047            .iter()
6048            .filter(|c| c.verdict() == Verdict::Fail)
6049            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
6050            .collect();
6051        contexts = rollup
6052            .iter()
6053            .map(|c| CheckInfo {
6054                label: c.label(),
6055                verdict: c.verdict(),
6056                required: c.is_required,
6057                run: c.url().and_then(run_of),
6058            })
6059            .collect();
6060        rollup_head = oid;
6061    }
6062    pr.checks = checks;
6063    pr.failing = failing;
6064
6065    Ok(Seen {
6066        pr,
6067        title: raw.title,
6068        failing_urls,
6069        head: raw.head_ref_oid,
6070        rollup_head,
6071        merge_state: raw.merge_state_status,
6072        contexts,
6073        base: raw.base_ref_name,
6074    })
6075}
6076
6077/// The last commit's oid and its checks from one GraphQL response, `None`
6078/// when anything about it cannot be trusted.
6079fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
6080    let v: serde_json::Value = serde_json::from_str(json).ok()?;
6081    if v.get("errors").is_some_and(|e| !e.is_null()) {
6082        return None;
6083    }
6084    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
6085    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
6086    let contexts = commit.pointer("/statusCheckRollup/contexts");
6087    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
6088        // No rollup at all: the commit has no checks.
6089        return Some((oid.to_owned(), Vec::new()));
6090    };
6091    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
6092        return None;
6093    }
6094    let nodes = contexts.get("nodes")?.as_array()?;
6095    let rollup = nodes
6096        .iter()
6097        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
6098        .collect::<Result<Vec<_>, _>>()
6099        .ok()?;
6100    Some((oid.to_owned(), rollup))
6101}
6102
6103/// The pull request's last commit and its checks, in one response. `None`
6104/// when the forge could not be asked.
6105async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
6106    let out = gh(
6107        repo,
6108        &[
6109            "api".to_owned(),
6110            "graphql".to_owned(),
6111            "-F".to_owned(),
6112            "owner={owner}".to_owned(),
6113            "-F".to_owned(),
6114            "repo={repo}".to_owned(),
6115            "-F".to_owned(),
6116            format!("number={number}"),
6117            "-f".to_owned(),
6118            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
6119             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
6120             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
6121             ... on CheckRun{name status conclusion detailsUrl \
6122             isRequired(pullRequestNumber:$number)} \
6123             ... on StatusContext{context state targetUrl \
6124             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
6125                .to_owned(),
6126        ],
6127    )
6128    .await
6129    .ok()?;
6130    out.ok.then_some(out.stdout)
6131}
6132
6133/// What a fix round did.
6134#[doc(hidden)]
6135#[derive(Debug, PartialEq)]
6136pub enum Fixed {
6137    /// The fixer committed something, and this is the head that was pushed.
6138    Committed {
6139        /// The commit now at the tip of the pushed branch.
6140        head: String,
6141    },
6142    /// The fixer ran and chose to change nothing.
6143    Declined,
6144    /// Machine availability prevented a result; retry this round on resume.
6145    Deferred,
6146    /// The fixer could not run, or said nothing usable.
6147    Failed(String),
6148}
6149
6150/// Hand the failures and the comments to the fixer, then commit and push.
6151///
6152/// The fixer works in the winner's own worktree so its commits land on the
6153/// branch the pull request is built from, and it runs with `allow_write` for
6154/// the same reason.
6155#[doc(hidden)]
6156pub async fn fix_round(
6157    state: &mut RunState,
6158    pr: &PrState,
6159    round: usize,
6160    budget: usize,
6161    reason: &str,
6162    logs: &str,
6163) -> Result<Fixed> {
6164    let winner = state
6165        .winner()
6166        .cloned()
6167        .context("landing needs a winning candidate; none is recorded on this run")?;
6168    let roles = state
6169        .config
6170        .resolve_roles()
6171        .context("resolve the roster for the fix round")?;
6172    // Same chain as the review loop (see `crate::fixer`): the configured
6173    // fixers in order, otherwise the winner's own author continuing its own
6174    // conversation - the competition is over, so its context is pure benefit.
6175    let attempts = crate::fixer::attempts(state, &roles, &winner);
6176    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
6177
6178    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
6179    let mut artifacts = agent::artifacts_dir(&state.dir());
6180    if let Some(request) = state
6181        .merge_repairs
6182        .last()
6183        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
6184    {
6185        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
6186    }
6187    let prompt =
6188        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
6189            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
6190        } else {
6191            prompt
6192        };
6193    // Read before the fixer runs: it normally commits for itself, so HEAD has
6194    // already moved by the time it returns and a later read would see no
6195    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
6196    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
6197    // Each id at most once, forward only: the next one is asked only when the
6198    // call advances, and only the last attempt's result is judged below, so an
6199    // exhausted chain ends as a single failed fixer does.
6200    let mut last = None;
6201    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
6202        if owner_requested_stop(state)? {
6203            return Ok(Fixed::Declined);
6204        }
6205        let mut seat = seat_of(state, &seat_key, &spec.id);
6206        let stem = if i == 0 {
6207            format!("land-{round}")
6208        } else {
6209            format!("land-{round}-{}", spec.id)
6210        };
6211        let out = agent::invoke(
6212            &spec,
6213            &mut seat,
6214            &Invocation {
6215                coordination: state.config.coordination.as_ref(),
6216                fetched_base: state.fetched_base.as_ref(),
6217                cwd: &winner.worktree,
6218                prompt: &prompt,
6219                timeout: Duration::from_secs(state.config.graph.timeout_fix),
6220                allow_write: true,
6221                sessions: state.config.graph.sessions,
6222                artifacts: &artifacts,
6223                stem: &stem,
6224                run: &state.id,
6225                node: "land",
6226                cache_dir: state.config.cache_dir().as_deref(),
6227                attachments: &[],
6228                writable: &[],
6229            },
6230        )
6231        .await;
6232        state.seats.insert(seat.key.clone(), seat);
6233        if let Some(next) = ids.get(i + 1)
6234            && agent::chain_advances(&out)
6235        {
6236            let (class, why) = crate::fixer::failure_of(&out);
6237            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
6238            continue;
6239        }
6240        last = Some((seat_key, out));
6241        break;
6242    }
6243    let (seat_key, out) = last.expect("the fixer chain always has an entry");
6244
6245    match out {
6246        Ok(o) if o.quota_exhausted() => {
6247            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
6248            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
6249            state.quota.push(loss);
6250            state.status = RunStatus::Blocked;
6251            state.save()?;
6252            // Keep partial edits reachable on the winner branch and leave a
6253            // clean tree for resume_landing_head. The resumed landing gates
6254            // this new commit before it can publish it; no push happens here.
6255            let inherited = crate::repo_lock::WaitPolicy::current();
6256            let wait = crate::repo_lock::WaitPolicy::new(
6257                Duration::from_secs(state.config.graph.timeout_resource_wait),
6258                move || inherited.cancelled(),
6259            );
6260            let _coordination = crate::repo_lock::SeatLease::operation_with(
6261                &winner.worktree,
6262                state.config.coordination.as_ref(),
6263                &wait,
6264            )
6265            .await?;
6266            let rescue = git::rescue_commit(
6267                &winner.worktree,
6268                &format!("magi: deferred land round {round} (uncommitted work)"),
6269            )
6270            .await?;
6271            state.note_withheld("land", &rescue.withheld);
6272            state.save()?;
6273            return Ok(Fixed::Deferred);
6274        }
6275        Ok(o) if !o.usable() => {
6276            return Ok(Fixed::Failed(format!(
6277                "the fixer produced nothing usable ({})",
6278                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
6279            )));
6280        }
6281        Ok(_) => {}
6282        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
6283        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
6284    }
6285
6286    if owner_requested_stop(state)? {
6287        return Ok(Fixed::Declined);
6288    }
6289
6290    // An agent that edited files but never committed would otherwise push
6291    // nothing and look like a refusal.
6292    let wait = crate::repo_lock::WaitPolicy::new(
6293        Duration::from_secs(state.config.graph.timeout_resource_wait),
6294        || false,
6295    );
6296    let coordination = crate::repo_lock::SeatLease::operation_with(
6297        &winner.worktree,
6298        state.config.coordination.as_ref(),
6299        &wait,
6300    )
6301    .await?;
6302    match git::rescue_commit(
6303        &winner.worktree,
6304        &format!("magi: land round {round} fixes (uncommitted work)"),
6305    )
6306    .await
6307    {
6308        Ok(r) => state.note_withheld("land", &r.withheld),
6309        Err(e)
6310            if state
6311                .merge_repairs
6312                .last()
6313                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
6314        {
6315            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
6316        }
6317        Err(_) => {}
6318    }
6319    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
6320    drop(coordination);
6321    if after == before {
6322        return Ok(Fixed::Declined);
6323    }
6324
6325    if owner_requested_stop(state)? {
6326        return Ok(Fixed::Declined);
6327    }
6328    crate::pr_head::ensure_owner(state)?;
6329    let remote = state.config.merge.remote.clone();
6330    anyhow::ensure!(
6331        crate::foreign_checkout::write_back(state, &after).await?,
6332        "foreign checkout delivery is blocked; see the run events"
6333    );
6334    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
6335    let push = if state.pr_head.is_some() {
6336        let expected = state
6337            .pr_pushed_head
6338            .as_deref()
6339            .context("missing public head lease")?;
6340        git::push_as(
6341            &winner.worktree,
6342            &remote,
6343            &winner.branch,
6344            &public_head,
6345            expected,
6346        )
6347        .await?
6348    } else {
6349        git::push(&winner.worktree, &remote, &winner.branch).await?
6350    };
6351    if !push.ok() {
6352        return Ok(Fixed::Failed(format!(
6353            "pushing {} to {remote} failed: {}",
6354            public_head, push.stderr
6355        )));
6356    }
6357    state.event(
6358        "land",
6359        format!("round {round}: pushed a fix to {public_head}"),
6360    );
6361    state.pr_pushed_head = Some(after.clone());
6362    state.save()?;
6363    Ok(Fixed::Committed { head: after })
6364}
6365
6366/// Fetch or create a seat, keeping its conversation across nodes.
6367pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
6368    crate::fixer::seat_for(state, key, agent)
6369}
6370
6371/// Recheck the live PR and local worktree before spending the requested fix.
6372/// A moved/closed PR is held, never repaired using obsolete evidence.
6373pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
6374    let seen = observe(&state.repo, url).await?;
6375    let winner = state.winner().context("no winning branch to repair")?;
6376    if seen.pr.state != PrLifecycle::Open || seen.head != head {
6377        anyhow::bail!(
6378            "PR is closed or its head changed; review the current head before requesting repair again"
6379        );
6380    }
6381    if git::rev_parse(&winner.worktree, "HEAD").await? != head
6382        || !git::is_clean(&winner.worktree).await?
6383    {
6384        anyhow::bail!(
6385            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
6386        );
6387    }
6388    // Always disable any forge-side reservation, including one not recorded
6389    // by this run. A repair request is never merge authorization.
6390    let view = gh(
6391        &state.repo,
6392        &[
6393            "pr".into(),
6394            "view".into(),
6395            url.into(),
6396            "--json".into(),
6397            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
6398        ],
6399    )
6400    .await?;
6401    if !view.ok {
6402        bail!("cannot check auto-merge: {}", view.combined());
6403    }
6404    let live: serde_json::Value = serde_json::from_str(&view.stdout)?;
6405    let public = state.pr_branch().unwrap_or(&winner.branch);
6406    if live["state"] != "OPEN"
6407        || live["headRefOid"] != head
6408        || live["headRefName"] != public
6409        || live["baseRefName"] != state.base_branch
6410        || live["isCrossRepository"] != false
6411    {
6412        bail!("PR changed during repair preflight; review its current head explicitly");
6413    }
6414    let auto_merge = live
6415        .get("autoMergeRequest")
6416        .context("cannot read the PR auto-merge reservation; repair held")?;
6417    if !auto_merge.is_null() {
6418        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
6419        if !out.ok {
6420            bail!("cannot disable auto-merge; repair held: {}", out.combined());
6421        }
6422    }
6423    Ok(seen.pr)
6424}
6425
6426pub(crate) fn merge_repair_reason(
6427    state: &RunState,
6428    request: &crate::run::MergeRepair,
6429) -> Result<String> {
6430    let evidence = serde_json::to_string_pretty(request)?;
6431    Ok(
6432        if state
6433            .instruction_revisions
6434            .iter()
6435            .any(|r| r.repair == request.question)
6436        {
6437            format!(
6438                "The owner revised the task instruction. Implement the current task, even when it conflicts with previous findings or requires changes not raised by checks or comments. The following evidence is historical, not a list of requirements; retain only findings still applicable to the revised task. Do not merge or approve the PR.\n\n{evidence}"
6439            )
6440        } else {
6441            format!(
6442                "The owner requested fix findings and re-review, without merging. Address the unresolved Major findings and final rejecting votes in this exact review evidence. Do not merge or approve the PR.\n\n{evidence}"
6443            )
6444        },
6445    )
6446}
6447
6448/// What the fixer is told.
6449fn fix_prompt(
6450    state: &RunState,
6451    pr: &PrState,
6452    round: usize,
6453    budget: usize,
6454    reason: &str,
6455    logs: &str,
6456) -> String {
6457    let mut s = format!(
6458        "Your patch is open as a pull request and it is not landing. Land round \
6459         {round} of {budget}.\n\n\
6460         Pull request: {}\n\n\
6461         What is holding it: {reason}\n\n\
6462         # The task\n\n{}\n",
6463        pr.url, state.instruction
6464    );
6465
6466    if pr.failing.is_empty() {
6467        s.push_str("\n# Failing checks\n\n(none)\n");
6468    } else {
6469        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
6470        if logs.trim().is_empty() {
6471            s.push_str(
6472                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
6473            );
6474        } else {
6475            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
6476        }
6477    }
6478
6479    if pr.review_comments.is_empty() {
6480        s.push_str("\n# Review comments\n\n(none)\n");
6481    } else {
6482        s.push_str("\n# Review comments\n");
6483        for c in &pr.review_comments {
6484            let where_ = match (&c.path, c.line) {
6485                (Some(p), Some(l)) => format!(" ({p}:{l})"),
6486                (Some(p), None) => format!(" ({p})"),
6487                _ => String::new(),
6488            };
6489            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
6490        }
6491    }
6492
6493    let revision_repair = state.merge_repairs.last().is_some_and(|repair| {
6494        repair.phase == crate::run::MergeRepairPhase::Fixing
6495            && state
6496                .instruction_revisions
6497                .iter()
6498                .any(|r| r.repair == repair.question)
6499    });
6500    s.push_str(
6501        "\n# Rules\n\n\
6502         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
6503            failing test; do not silence a lint with an allow attribute; do not \
6504            stretch a timeout to hide a race. If the check is right, the code is \
6505            wrong.\n",
6506    );
6507    if revision_repair {
6508        s.push_str("2. Implement the revised task. Old findings, checks, and comments are historical evidence; address them only where applicable to the current task. Avoid unrelated changes.\n");
6509    } else {
6510        s.push_str(
6511            "2. Change nothing the checks and the comments did not raise. A \
6512            drive-by refactor turns a one-line fix into a pull request that \
6513            needs reviewing again.\n",
6514        );
6515    }
6516    s.push_str(
6517        "\
6518         3. If a comment is wrong, say so with a checkable argument and change \
6519            nothing for it. A declined comment with a reason is a correct \
6520            outcome; a change made to appease a reviewer is not.\n\
6521         4. Commit in this worktree. magi pushes to the pull request's branch \
6522            for you; do not push, merge, or close anything yourself.\n\
6523         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
6524         # Output\n\n\
6525         Say what you changed and why, and what you declined and why.",
6526    );
6527
6528    let language = &state.config.graph.language;
6529    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
6530        let _ = write!(s, "\n\nWrite all prose in {language}.");
6531    }
6532    // After the language line, so the exception is the last word on it.
6533    s.push_str(&crate::prompt::github_rule(
6534        language,
6535        &state.config.graph.github_language,
6536    ));
6537    if let Some(overlay) = state.config.prompts.overlay("fix") {
6538        let _ = write!(s, "\n\n{overlay}");
6539    }
6540    s.push('\n');
6541    s.push_str(crate::prompt::child_run_ownership());
6542    s
6543}
6544
6545/// Failing log tails, the way the operator collects them by hand:
6546/// `gh run view --log-failed`.
6547async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6548    let mut out = String::new();
6549    for (name, url) in failing.iter().take(MAX_LOGS) {
6550        let args = match (job_of(url), run_of(url)) {
6551            (Some(job), _) => vec![
6552                "run".to_owned(),
6553                "view".to_owned(),
6554                "--log-failed".to_owned(),
6555                "--job".to_owned(),
6556                job,
6557            ],
6558            (None, Some(run)) => vec![
6559                "run".to_owned(),
6560                "view".to_owned(),
6561                run,
6562                "--log-failed".to_owned(),
6563            ],
6564            // Not a GitHub Actions check - an external status has no log here.
6565            (None, None) => continue,
6566        };
6567        let (ok, body) = match gh(repo, &args).await {
6568            Ok(v) => (v.ok, v.combined()),
6569            Err(e) => (false, format!("{e:#}")),
6570        };
6571        if !ok && body.trim().is_empty() {
6572            continue;
6573        }
6574        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6575    }
6576    out
6577}
6578
6579/// Job id out of a check's `detailsUrl`
6580/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
6581fn job_of(details_url: &str) -> Option<String> {
6582    let after = details_url.split("/job/").nth(1)?;
6583    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6584    (!id.is_empty()).then_some(id)
6585}
6586
6587/// Workflow run id out of a check's `detailsUrl`.
6588pub(crate) fn run_of(details_url: &str) -> Option<String> {
6589    let after = details_url.split("/actions/runs/").nth(1)?;
6590    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6591    (!id.is_empty()).then_some(id)
6592}
6593
6594/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6595/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6596/// it to that.
6597fn stop_comment(run_id: &str, why: &str) -> String {
6598    format!(
6599        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6600         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6601    )
6602}
6603
6604/// Leave the pull request open, say why on it, and mark the run blocked.
6605///
6606/// The comment is what makes an unattended stop actionable: the operator wakes
6607/// up to a pull request that explains itself rather than to a silent queue.
6608async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6609    let body = stop_comment(&state.id, why);
6610    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6611    if !body.contains(MARKER) {
6612        body = format!("{MARKER}\n{body}");
6613    }
6614    let posted = gh(
6615        repo,
6616        &[
6617            "pr".to_owned(),
6618            "comment".to_owned(),
6619            pr.number.to_string(),
6620            "--body".to_owned(),
6621            body,
6622        ],
6623    )
6624    .await;
6625    match posted {
6626        Ok(out) if out.ok => {}
6627        Ok(out) => tracing::warn!("could not comment on {}: {}", pr.url, out.combined()),
6628        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6629    }
6630    state.status = RunStatus::Blocked;
6631    state.merge = Some(MergeOutcome {
6632        mode: MergeMode::Pr,
6633        ok: false,
6634        detail: why.to_owned(),
6635        empty: false,
6636    });
6637    state.event("land", format!("stopped: {why}"));
6638    state.save()?;
6639    Ok(())
6640}
6641
6642/// Output of a `gh` subprocess, keeping machine-readable `stdout` separate from
6643/// diagnostic `stderr`.
6644///
6645/// Newer `gh` releases (for example `gh` 2.105.0) can emit advisory hints on
6646/// `stderr` even when a read-only `--json` or API command succeeds with exit
6647/// status 0. Appending `stderr` onto `stdout` before deserialization breaks
6648/// strict JSON parsing (for example `trailing characters at line 2 column 1`).
6649///
6650/// Output contract:
6651/// - **Successful structured reads** (`--json`, REST `gh api`, GraphQL, etc.):
6652///   check [`Self::ok`], then pass [`Self::stdout`] straight to a strict parser.
6653///   Never fall back to [`Self::stderr`] when `stdout` is empty, and never strip
6654///   specific hint text or heuristically extract JSON substrings.
6655/// - **Failed invocations (`!ok`)**: use [`Self::combined`] so both `stdout`
6656///   and `stderr` diagnostics stay actionable (for example `404` detection and
6657///   refused-merge details).
6658/// - **Human-facing or mutating commands** (`pr merge`, `pr close`, `pr edit`,
6659///   `pr comment`, `run rerun`, `run view --log-failed`): use
6660///   [`Self::combined`] for failure diagnostics or human-readable output.
6661#[derive(Debug, Clone, PartialEq, Eq)]
6662pub(crate) struct GhOutput {
6663    /// Whether `gh` exited with status 0.
6664    pub(crate) ok: bool,
6665    /// Process `stdout`, decoded lossily as UTF-8.
6666    pub(crate) stdout: String,
6667    /// Process `stderr`, decoded lossily as UTF-8.
6668    pub(crate) stderr: String,
6669}
6670
6671impl GhOutput {
6672    /// Build from a completed subprocess output and log non-empty `stderr`
6673    /// emitted on exit status 0 at debug level without logging command
6674    /// arguments.
6675    pub(crate) fn from_output(output: std::process::Output) -> Self {
6676        let parsed = Self {
6677            ok: output.status.success(),
6678            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
6679            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
6680        };
6681        if parsed.ok && !parsed.stderr.trim().is_empty() {
6682            tracing::debug!(
6683                stderr = parsed.stderr.trim(),
6684                "gh exited successfully with stderr diagnostics"
6685            );
6686        }
6687        parsed
6688    }
6689
6690    /// Combined trimmed `stdout` and `stderr` for failure diagnostics and
6691    /// human-facing commands.
6692    pub(crate) fn combined(&self) -> String {
6693        let out = self.stdout.trim();
6694        let err = self.stderr.trim();
6695        match (out.is_empty(), err.is_empty()) {
6696            (true, true) => String::new(),
6697            (false, true) => out.to_owned(),
6698            (true, false) => err.to_owned(),
6699            (false, false) => format!("{out}\n{err}"),
6700        }
6701    }
6702}
6703
6704/// Run `gh` in `cwd`, returning exit status with separated `stdout` and
6705/// `stderr` in [`GhOutput`].
6706///
6707/// Structured callers must check [`GhOutput::ok`] and parse [`GhOutput::stdout`]
6708/// strictly without substituting [`GhOutput::stderr`]. Failed invocations and
6709/// human-facing or mutating commands should use [`GhOutput::combined`] so both
6710/// streams remain available as diagnostics.
6711///
6712/// `GH_REPO` is stripped from the child's environment: every call site here
6713/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6714/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6715/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6716/// `GH_REPO` the operator happens to have exported for an unrelated script
6717/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6718/// below) to a different repository than the one actually on disk - which
6719/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6720/// could be made to agree with whatever repository a forged `--merged` URL
6721/// claims, defeating it entirely.
6722pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<GhOutput> {
6723    gh_with(Path::new("gh"), cwd, args).await
6724}
6725
6726pub(crate) async fn gh_with(program: &Path, cwd: &Path, args: &[String]) -> Result<GhOutput> {
6727    let out = tokio::process::Command::new(program)
6728        .args(args)
6729        .current_dir(cwd)
6730        .env_remove("GH_REPO")
6731        .quiet()
6732        .stdin(std::process::Stdio::null())
6733        .output()
6734        .await
6735        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6736    Ok(GhOutput::from_output(out))
6737}
6738
6739/// Verdict of one entry in the status rollup.
6740#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6741pub(crate) enum Verdict {
6742    Pass,
6743    Fail,
6744    Pending,
6745    Unknown,
6746}
6747
6748impl Verdict {
6749    /// Short operator-facing check result.
6750    pub(crate) fn label(self) -> &'static str {
6751        match self {
6752            Self::Pass => "passed",
6753            Self::Fail => "failed",
6754            Self::Pending => "pending",
6755            Self::Unknown => "unknown",
6756        }
6757    }
6758}
6759
6760#[derive(Debug, Deserialize)]
6761#[serde(rename_all = "camelCase")]
6762struct GhPr {
6763    #[serde(default)]
6764    url: String,
6765    #[serde(default)]
6766    number: u64,
6767    #[serde(default)]
6768    state: String,
6769    #[serde(default)]
6770    title: String,
6771    #[serde(default)]
6772    status_check_rollup: Vec<GhCheck>,
6773    /// GitHub's own verdict on whether the pull request can be merged.
6774    ///
6775    /// Worth asking for because it is the only place the *required* check set
6776    /// is applied: the rollup lists every check equally, so a repository that
6777    /// deliberately does not require `coverage` still looks red here. See
6778    /// [`Blocking`].
6779    #[serde(default)]
6780    merge_state_status: String,
6781    /// The commit the pull request currently points at. Compared with the
6782    /// commit a fix round pushed, it is how the loop knows the forge has moved
6783    /// on and the rollup belongs to the new head.
6784    #[serde(default)]
6785    head_ref_oid: String,
6786    #[serde(default)]
6787    base_ref_name: String,
6788    #[serde(default)]
6789    reviews: Vec<GhReview>,
6790    #[serde(default)]
6791    comments: Vec<GhComment>,
6792}
6793
6794/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6795/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6796/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6797/// conclusion at all.
6798#[derive(Debug, Deserialize)]
6799#[serde(rename_all = "camelCase")]
6800struct GhCheck {
6801    #[serde(default)]
6802    name: Option<String>,
6803    #[serde(default)]
6804    context: Option<String>,
6805    #[serde(default)]
6806    status: Option<String>,
6807    #[serde(default)]
6808    conclusion: Option<String>,
6809    #[serde(default)]
6810    state: Option<String>,
6811    #[serde(default)]
6812    details_url: Option<String>,
6813    #[serde(default)]
6814    target_url: Option<String>,
6815    /// Whether the base branch requires this check. Only the GraphQL node
6816    /// carries it; `None` is "not read", never "not required".
6817    #[serde(default)]
6818    is_required: Option<bool>,
6819}
6820
6821impl GhCheck {
6822    /// Name to show a human and hand to the fixer.
6823    fn label(&self) -> String {
6824        self.name
6825            .clone()
6826            .or_else(|| self.context.clone())
6827            .unwrap_or_else(|| "(unnamed check)".to_owned())
6828    }
6829
6830    /// Where this check's logs live, when it has any.
6831    fn url(&self) -> Option<&str> {
6832        self.details_url
6833            .as_deref()
6834            .or(self.target_url.as_deref())
6835            .filter(|u| !u.is_empty())
6836    }
6837
6838    /// Did it pass?
6839    ///
6840    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6841    /// skips release and bot pull requests by design, and a skip that blocked
6842    /// landing would block exactly the pull requests that need no review.
6843    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6844    /// merging over one is merging over a check that never ran.
6845    fn verdict(&self) -> Verdict {
6846        if let Some(status) = self.status.as_deref() {
6847            if !status.eq_ignore_ascii_case("COMPLETED") {
6848                return Verdict::Pending;
6849            }
6850        }
6851        let outcome = self
6852            .conclusion
6853            .as_deref()
6854            .or(self.state.as_deref())
6855            .unwrap_or("");
6856        match outcome.to_ascii_uppercase().as_str() {
6857            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6858            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6859            | "ACTION_REQUIRED" => Verdict::Fail,
6860            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6861                Verdict::Pending
6862            }
6863            _ => Verdict::Unknown,
6864        }
6865    }
6866}
6867
6868#[derive(Debug, Deserialize)]
6869struct GhAuthor {
6870    #[serde(default)]
6871    login: String,
6872}
6873
6874#[derive(Debug, Deserialize)]
6875struct GhReview {
6876    #[serde(default)]
6877    author: GhAuthor,
6878    #[serde(default)]
6879    body: String,
6880}
6881
6882#[derive(Debug, Deserialize)]
6883struct GhComment {
6884    #[serde(default)]
6885    author: GhAuthor,
6886    #[serde(default)]
6887    body: String,
6888}
6889
6890#[derive(Debug, Deserialize)]
6891struct GhUser {
6892    #[serde(default)]
6893    login: String,
6894}
6895
6896#[derive(Debug, Deserialize)]
6897struct GhInline {
6898    #[serde(default)]
6899    user: GhUser,
6900    #[serde(default)]
6901    path: Option<String>,
6902    #[serde(default)]
6903    line: Option<u64>,
6904    #[serde(default)]
6905    body: String,
6906}
6907
6908impl Default for GhAuthor {
6909    fn default() -> Self {
6910        Self {
6911            login: "(unknown)".to_owned(),
6912        }
6913    }
6914}
6915
6916impl Default for GhUser {
6917    fn default() -> Self {
6918        Self {
6919            login: "(unknown)".to_owned(),
6920        }
6921    }
6922}
6923
6924#[cfg(test)]
6925pub(crate) mod tests {
6926    use super::*;
6927    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6928
6929    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6930        format!(
6931            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6932        )
6933    }
6934
6935    #[test]
6936    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6937        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6938        assert_eq!(
6939            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6940            Ok(())
6941        );
6942        for (json, why) in [
6943            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6944            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6945            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6946            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6947            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6948            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6949        ] {
6950            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6951                .unwrap_err()
6952                .why;
6953            assert!(err.contains(why), "{json}: {err}");
6954        }
6955        // A head that moved on past what was verified is left alone.
6956        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6957        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6958        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6959        assert!(
6960            !closable(
6961                &head_json("x", "main", "OPEN", false),
6962                "magi/27b2/A",
6963                "main",
6964                &[]
6965            )
6966            .unwrap_err()
6967            .retry
6968        );
6969        assert!(is_forge_url("https://github.com/o/r.git"));
6970        assert!(is_forge_url("git@github.com:o/r.git"));
6971        assert!(!is_forge_url("/tmp/origin.git"));
6972        assert!(!is_forge_url("C:\\work\\origin.git"));
6973        assert!(!is_forge_url("file:///tmp/origin.git"));
6974        assert!(forge_unavailable(
6975            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6976        ));
6977        assert!(!forge_unavailable(
6978            "gh pr list failed: error connecting to api.github.com"
6979        ));
6980        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6981        // A record that does not say whether it is a fork is not trusted.
6982        assert!(
6983            closable(
6984                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6985                "b",
6986                "main",
6987                &["aaa".to_owned()]
6988            )
6989            .is_err()
6990        );
6991    }
6992
6993    #[test]
6994    fn the_close_comment_names_the_commit_on_the_base() {
6995        let e = crate::already::Evidence {
6996            proof: crate::already::Proof::PatchId,
6997            tip: "1234567890".to_owned(),
6998            commits: vec!["0e368de0000".to_owned()],
6999        };
7000        let c = superseded_comment("main", &e);
7001        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
7002    }
7003
7004    /// 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.
7005    const GREEN_OPEN: &str = r####"{
7006  "url": "https://github.com/yukimemi/magi/pull/10",
7007  "number": 10,
7008  "state": "OPEN",
7009  "mergeStateStatus": "CLEAN",
7010  "statusCheckRollup": [
7011    {
7012      "__typename": "CheckRun",
7013      "conclusion": "SKIPPED",
7014      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
7015      "name": "review",
7016      "status": "COMPLETED",
7017      "workflowName": "claude-review"
7018    },
7019    {
7020      "__typename": "CheckRun",
7021      "conclusion": "SUCCESS",
7022      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
7023      "name": "check (ubuntu-latest)",
7024      "status": "COMPLETED",
7025      "workflowName": "CI"
7026    },
7027    {
7028      "__typename": "CheckRun",
7029      "conclusion": "SUCCESS",
7030      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
7031      "name": "rustfmt",
7032      "status": "COMPLETED",
7033      "workflowName": "CI"
7034    },
7035    {
7036      "__typename": "StatusContext",
7037      "context": "CodeRabbit",
7038      "state": "SUCCESS",
7039      "targetUrl": ""
7040    }
7041  ],
7042  "reviews": [],
7043  "comments": [
7044    {
7045      "author": {
7046        "login": "coderabbitai"
7047      },
7048      "authorAssociation": "NONE",
7049      "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"
7050    }
7051  ]
7052}"####;
7053
7054    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
7055    const RED_OPEN: &str = r####"{
7056  "url": "https://github.com/yukimemi/magi/pull/9",
7057  "number": 9,
7058  "state": "OPEN",
7059  "mergeStateStatus": "UNSTABLE",
7060  "statusCheckRollup": [
7061    {
7062      "__typename": "CheckRun",
7063      "conclusion": "SUCCESS",
7064      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
7065      "name": "check (ubuntu-latest)",
7066      "status": "COMPLETED",
7067      "workflowName": "CI"
7068    },
7069    {
7070      "__typename": "CheckRun",
7071      "conclusion": "SUCCESS",
7072      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
7073      "name": "rustfmt",
7074      "status": "COMPLETED",
7075      "workflowName": "CI"
7076    },
7077    {
7078      "__typename": "CheckRun",
7079      "conclusion": "FAILURE",
7080      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
7081      "name": "editorconfig",
7082      "status": "COMPLETED",
7083      "workflowName": "CI"
7084    },
7085    {
7086      "__typename": "StatusContext",
7087      "context": "CodeRabbit",
7088      "state": "SUCCESS",
7089      "targetUrl": ""
7090    }
7091  ],
7092  "reviews": [],
7093  "comments": [
7094    {
7095      "author": {
7096        "login": "coderabbitai"
7097      },
7098      "authorAssociation": "NONE",
7099      "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"
7100    }
7101  ]
7102}"####;
7103
7104    /// 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.
7105    const PENDING_OPEN: &str = r####"{
7106  "url": "https://github.com/yukimemi/magi/pull/9",
7107  "number": 9,
7108  "state": "OPEN",
7109  "statusCheckRollup": [
7110    {
7111      "__typename": "CheckRun",
7112      "conclusion": "SUCCESS",
7113      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
7114      "name": "check (ubuntu-latest)",
7115      "status": "COMPLETED",
7116      "workflowName": "CI"
7117    },
7118    {
7119      "__typename": "CheckRun",
7120      "conclusion": "SUCCESS",
7121      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
7122      "name": "rustfmt",
7123      "status": "COMPLETED",
7124      "workflowName": "CI"
7125    },
7126    {
7127      "__typename": "CheckRun",
7128      "conclusion": null,
7129      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
7130      "name": "editorconfig",
7131      "status": "IN_PROGRESS",
7132      "workflowName": "CI"
7133    },
7134    {
7135      "__typename": "StatusContext",
7136      "context": "CodeRabbit",
7137      "state": "SUCCESS",
7138      "targetUrl": ""
7139    }
7140  ],
7141  "reviews": [],
7142  "comments": []
7143}"####;
7144
7145    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
7146    const MERGED: &str = r####"{
7147  "url": "https://github.com/yukimemi/magi/pull/16",
7148  "number": 16,
7149  "state": "MERGED",
7150  "statusCheckRollup": [
7151    {
7152      "__typename": "CheckRun",
7153      "conclusion": "SUCCESS",
7154      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
7155      "name": "check (ubuntu-latest)",
7156      "status": "COMPLETED",
7157      "workflowName": "CI"
7158    },
7159    {
7160      "__typename": "CheckRun",
7161      "conclusion": "SUCCESS",
7162      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
7163      "name": "review",
7164      "status": "COMPLETED",
7165      "workflowName": "claude-review"
7166    }
7167  ],
7168  "reviews": [],
7169  "comments": []
7170}"####;
7171
7172    /// 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.
7173    const REVIEWED_OPEN: &str = r####"{
7174  "url": "https://github.com/yukimemi/magi/pull/12",
7175  "number": 12,
7176  "state": "OPEN",
7177  "statusCheckRollup": [
7178    {
7179      "__typename": "CheckRun",
7180      "conclusion": "SUCCESS",
7181      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
7182      "name": "check (ubuntu-latest)",
7183      "status": "COMPLETED",
7184      "workflowName": "CI"
7185    },
7186    {
7187      "__typename": "CheckRun",
7188      "conclusion": "SUCCESS",
7189      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
7190      "name": "review",
7191      "status": "COMPLETED",
7192      "workflowName": "claude-review"
7193    }
7194  ],
7195  "reviews": [
7196    {
7197      "author": {
7198        "login": "claude"
7199      },
7200      "state": "COMMENTED",
7201      "body": ""
7202    }
7203  ],
7204  "comments": [
7205    {
7206      "author": {
7207        "login": "coderabbitai"
7208      },
7209      "authorAssociation": "NONE",
7210      "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"
7211    },
7212    {
7213      "author": {
7214        "login": "claude"
7215      },
7216      "authorAssociation": "NONE",
7217      "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"
7218    }
7219  ]
7220}"####;
7221
7222    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
7223    const INLINE: &str = r####"[
7224  {
7225    "user": {
7226      "login": "claude[bot]"
7227    },
7228    "path": "src/graph.rs",
7229    "line": 231,
7230    "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"
7231  }
7232]"####;
7233
7234    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
7235    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
7236<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
7237
7238> [!IMPORTANT]
7239> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
7240> 
7241> This repository does not receive automatic reviews because it has fewer than 10 stars.
7242> 
7243> <details>
7244> <summary>⚙️ Run configuration</summary>
7245> 
7246> **Configuration used**: defaults
7247> 
7248> **Review profile**: CHILL
7249> 
7250> **Plan**: Team
7251> 
7252> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
7253> 
7254> </details>
7255
7256<!-- end of auto-generated comment: skip review by coderabbit.ai -->
7257
7258<!-- tips_start -->
7259
7260---
7261
7262Thanks 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.
7263
7264<details>
7265<summary>❤️ Share</summary>
7266
7267- [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"####;
7268
7269    /// 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.
7270    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
7271
7272---
7273### Reviewing PR #16
7274
7275- [x] Read AGENTS.md conventions
7276- [x] Review `src/daemon.rs` changes
7277- [x] Review `src/main.rs` changes (new `doctor` reporting)
7278- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
7279- [x] Check test coverage for new behavior
7280- [x] Run verification commands (blocked — see note)
7281- [x] Post findings"####;
7282
7283    /// The same job's real comment on pull request #12 once it had something to say.
7284    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
7285
7286---
7287### Review: `magi review <branch>` — cheap-half-only graph
7288
7289Read 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.
7290
7291**Correctness**
7292
7293- 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"####;
7294
7295    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
7296        PrState {
7297            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
7298            number: 16,
7299            state: PrLifecycle::Open,
7300            checks,
7301            // These tests are about red-means-fix, so a red here is one the
7302            // forge gates on. Without saying so they would assert the new
7303            // "merge past a check nobody requires" path by accident.
7304            blocking: if matches!(checks, Checks::Red) {
7305                Blocking::Yes
7306            } else {
7307                Blocking::No
7308            },
7309            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
7310            review_comments: (0..comments)
7311                .map(|i| ReviewComment {
7312                    author: "coderabbitai".to_owned(),
7313                    path: Some("src/graph.rs".to_owned()),
7314                    line: Some(231),
7315                    body: format!("finding {i}"),
7316                })
7317                .collect(),
7318        }
7319    }
7320
7321    #[test]
7322    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
7323        use CiExpectation::{Absent, Expected};
7324        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
7325            let p = pr(checks, &["x"], 0);
7326            for waited in [Duration::ZERO, CHECKS_GRACE] {
7327                assert_eq!(
7328                    decide_with(&p, 0, 4, waited, Expected),
7329                    decide(&p, 0, 4, waited)
7330                );
7331            }
7332        }
7333        // Nothing will ever report: no wait, no give-up, no fix round.
7334        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
7335            let p = pr(checks, &["x"], 0);
7336            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
7337            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
7338        }
7339        // Third-party statuses never change the review decision, even at budget.
7340        for comments in [0, 1] {
7341            for round in [0, 4] {
7342                let absent = decide_with(
7343                    &pr(Checks::Unknown, &[], comments),
7344                    round,
7345                    4,
7346                    CHECKS_GRACE,
7347                    Absent,
7348                );
7349                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
7350                    assert_eq!(
7351                        decide_with(
7352                            &pr(checks, &["third-party"], comments),
7353                            round,
7354                            4,
7355                            Duration::ZERO,
7356                            Absent
7357                        ),
7358                        absent
7359                    );
7360                }
7361                if comments != 0 {
7362                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
7363                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
7364                }
7365            }
7366        }
7367        let empty = pr(Checks::Unknown, &[], 0);
7368        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
7369            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
7370        }
7371        assert_eq!(
7372            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
7373            Step::Wait
7374        );
7375        assert_eq!(
7376            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
7377            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
7378        );
7379        // A conflict is not a check: it still wants the rebase.
7380        let mut p = pr(Checks::Unknown, &[], 0);
7381        p.blocking = Blocking::Conflict;
7382        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
7383        // And a pull request that left our hands is still done.
7384        p.state = PrLifecycle::Merged;
7385        assert_eq!(
7386            decide_with(&p, 0, 4, Duration::ZERO, Absent),
7387            Step::Done { merged: true }
7388        );
7389    }
7390
7391    #[test]
7392    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
7393        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
7394        assert_eq!(state.number, 10);
7395        assert_eq!(state.state, PrLifecycle::Open);
7396        assert_eq!(state.checks, Checks::Green);
7397        assert!(state.failing.is_empty());
7398        assert!(
7399            state.review_comments.is_empty(),
7400            "the only comment is CodeRabbit's trigger notice: {:?}",
7401            state.review_comments
7402        );
7403        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
7404    }
7405
7406    #[test]
7407    fn a_failing_check_parses_as_red_and_is_named() {
7408        let state = parse_pr(RED_OPEN).expect("red fixture parses");
7409        assert_eq!(state.checks, Checks::Red);
7410        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
7411        // The captured payload says `UNSTABLE` - mergeable, with a check
7412        // nobody requires red - which is exactly the shape that had to be
7413        // merged by hand. Asserted separately, in
7414        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
7415        // test is about is that a red check is *named*, so the reason a fixer
7416        // is handed says which one; so it asks the blocking question here.
7417        let mut blocking = state.clone();
7418        blocking.blocking = Blocking::Yes;
7419        match decide(&blocking, 0, 4, Duration::ZERO) {
7420            Step::Fix { reason } => {
7421                assert!(reason.contains("editorconfig"), "reason: {reason}");
7422                assert!(reason.contains("failing"), "reason: {reason}");
7423            }
7424            other => panic!("expected a fix round, got {other:?}"),
7425        }
7426    }
7427
7428    #[test]
7429    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
7430        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
7431        assert_eq!(state.checks, Checks::Pending);
7432        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
7433    }
7434
7435    #[test]
7436    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
7437        let state = parse_pr(MERGED).expect("merged fixture parses");
7438        assert_eq!(state.state, PrLifecycle::Merged);
7439        assert_eq!(
7440            decide(&state, 0, 4, Duration::ZERO),
7441            Step::Done { merged: true }
7442        );
7443    }
7444
7445    #[test]
7446    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
7447        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
7448        assert_eq!(state.checks, Checks::Green);
7449        let authors: Vec<&str> = state
7450            .review_comments
7451            .iter()
7452            .map(|c| c.author.as_str())
7453            .collect();
7454        assert_eq!(
7455            authors,
7456            vec!["claude"],
7457            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
7458        );
7459        match decide(&state, 0, 4, Duration::ZERO) {
7460            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
7461            other => panic!("expected a fix round, got {other:?}"),
7462        }
7463    }
7464
7465    #[test]
7466    fn inline_review_comments_keep_their_file_and_line() {
7467        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
7468        assert_eq!(comments.len(), 1);
7469        assert_eq!(comments[0].author, "claude[bot]");
7470        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
7471        assert_eq!(comments[0].line, Some(231));
7472        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
7473    }
7474
7475    #[test]
7476    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
7477        assert!(
7478            is_noise(CODERABBIT_TRIGGER),
7479            "CodeRabbit's trigger notice declares itself not a review"
7480        );
7481        assert!(
7482            is_noise(CLAUDE_CHECKLIST),
7483            "a progress checklist asks for nothing"
7484        );
7485        assert!(
7486            !is_noise(CLAUDE_FINDING),
7487            "a review that names a bug is input, not noise"
7488        );
7489
7490        let mut clean = pr(Checks::Green, &[], 0);
7491        clean.review_comments.push(ReviewComment {
7492            author: "coderabbitai".to_owned(),
7493            path: None,
7494            line: None,
7495            body: CODERABBIT_TRIGGER.to_owned(),
7496        });
7497        clean.review_comments.retain(|c| !is_noise(&c.body));
7498        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
7499
7500        let mut found = pr(Checks::Green, &[], 0);
7501        found.review_comments.push(ReviewComment {
7502            author: "claude".to_owned(),
7503            path: None,
7504            line: None,
7505            body: CLAUDE_FINDING.to_owned(),
7506        });
7507        found.review_comments.retain(|c| !is_noise(&c.body));
7508        assert!(matches!(
7509            decide(&found, 0, 4, Duration::ZERO),
7510            Step::Fix { .. }
7511        ));
7512    }
7513
7514    #[test]
7515    fn the_policy_table_holds_for_every_combination_that_matters() {
7516        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
7517            (
7518                "pending checks are waited for, even on the last round",
7519                pr(Checks::Pending, &[], 0),
7520                4,
7521                4,
7522                Duration::ZERO,
7523                Step::Wait,
7524            ),
7525            (
7526                "red checks are fixed",
7527                pr(Checks::Red, &["editorconfig"], 0),
7528                0,
7529                4,
7530                Duration::ZERO,
7531                Step::Fix {
7532                    reason: "1 check(s) failing: editorconfig".to_owned(),
7533                },
7534            ),
7535            (
7536                "green with comments is fixed, not merged",
7537                pr(Checks::Green, &[], 2),
7538                1,
7539                4,
7540                Duration::ZERO,
7541                Step::Fix {
7542                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
7543                        .to_owned(),
7544                },
7545            ),
7546            (
7547                "green and clean merges",
7548                pr(Checks::Green, &[], 0),
7549                3,
7550                4,
7551                Duration::ZERO,
7552                Step::Merge,
7553            ),
7554            (
7555                "an unreadable rollup is waited on while the grace lasts",
7556                pr(Checks::Unknown, &[], 0),
7557                0,
7558                4,
7559                Duration::ZERO,
7560                Step::Wait,
7561            ),
7562            (
7563                "an unreadable rollup is never merged once the grace is spent",
7564                pr(Checks::Unknown, &[], 0),
7565                0,
7566                4,
7567                CHECKS_GRACE,
7568                Step::GiveUp {
7569                    reason: "no check status is readable on the pull request after 3 minute(s); \
7570                             refusing to merge on a guess"
7571                        .to_owned(),
7572                },
7573            ),
7574        ];
7575        for (what, state, round, budget, waited, want) in cases {
7576            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
7577        }
7578    }
7579
7580    #[test]
7581    fn the_forge_verdict_survives_the_round_trip_from_gh() {
7582        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
7583        // requested but never parsed is the kind of thing that looks wired up
7584        // and answers `Unsaid` forever.
7585        let green = parse_pr(GREEN_OPEN).expect("parse");
7586        assert_eq!(green.blocking, Blocking::No);
7587        let red = parse_pr(RED_OPEN).expect("parse");
7588        assert_eq!(
7589            red.blocking,
7590            Blocking::No,
7591            "`UNSTABLE` is mergeable: the red check is one nobody requires"
7592        );
7593        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
7594        // A payload from an older `gh` has no such field at all.
7595        let quiet =
7596            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
7597        assert_eq!(quiet.blocking, Blocking::Unsaid);
7598    }
7599
7600    #[test]
7601    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
7602        // Pull request 37's only red check was `editorconfig`, failing
7603        // because the action could not fetch its own binary after
7604        // editorconfig-checker v4 renamed its release assets. The repository
7605        // does not require it. magi answered by asking a fixer to repair a
7606        // change that was fine, and the pull request had to be merged by hand.
7607        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7608        nonblocking.blocking = Blocking::No;
7609        assert_eq!(
7610            decide(&nonblocking, 0, 4, Duration::ZERO),
7611            Step::Merge,
7612            "the forge says nothing is in the way, so nothing is"
7613        );
7614
7615        // The same red, gated on: that is a fix round, as before.
7616        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7617        blocking.blocking = Blocking::Yes;
7618        assert!(matches!(
7619            decide(&blocking, 0, 4, Duration::ZERO),
7620            Step::Fix { .. }
7621        ));
7622
7623        // A review comment still outranks green-enough: a non-required red
7624        // must not become a way to merge past an unanswered reviewer.
7625        let mut commented = pr(Checks::Red, &["coverage"], 1);
7626        commented.blocking = Blocking::No;
7627        assert!(matches!(
7628            decide(&commented, 0, 4, Duration::ZERO),
7629            Step::Fix { .. }
7630        ));
7631
7632        // And silence from the forge is not consent.
7633        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7634        unsaid.blocking = Blocking::Unsaid;
7635        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7636        assert!(matches!(
7637            decide(&unsaid, 0, 4, CHECKS_GRACE),
7638            Step::Fix { .. }
7639        ));
7640    }
7641
7642    #[test]
7643    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7644        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7645        red.blocking = Blocking::No;
7646        assert_eq!(
7647            decide(&red, 0, 4, Duration::ZERO),
7648            Step::Merge,
7649            "announcing must not change the decision"
7650        );
7651        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7652        assert!(said.contains("yukimemi/magi"), "{said}");
7653        assert!(said.contains("#16"), "{said}");
7654        assert!(
7655            said.contains("https://github.com/yukimemi/magi/pull/16"),
7656            "{said}"
7657        );
7658        assert!(
7659            said.contains("test (windows-latest)") && said.contains("coverage"),
7660            "{said}"
7661        );
7662
7663        // `failing` can be left over on a green observation; only `checks` counts.
7664        let green = pr(Checks::Green, &["stale"], 0);
7665        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7666    }
7667
7668    #[test]
7669    fn red_merge_notices_omit_empty_check_details() {
7670        for checks in [vec![], vec!["", "  "]] {
7671            let red = pr(Checks::Red, &checks, 0);
7672            let summary = red_merge_summary("owner/repo", &red).unwrap();
7673            let notice = crate::notices::merged_red("run-1", &summary);
7674            assert_eq!(
7675                notice.message,
7676                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7677            );
7678            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7679        }
7680        let red = pr(Checks::Red, &["", " test ", " "], 0);
7681        let summary = red_merge_summary("owner/repo", &red).unwrap();
7682        assert!(summary.contains("with red checks: test ("), "{summary}");
7683    }
7684
7685    #[test]
7686    fn the_repo_label_comes_from_the_pull_request_url() {
7687        let p = Path::new("/tmp/checkout");
7688        assert_eq!(
7689            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7690            "yukimemi/magi"
7691        );
7692        assert_eq!(repo_label(p, "not a url"), "checkout");
7693    }
7694
7695    #[test]
7696    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7697        // Pull requests 35 and 37 were both rebased by hand: a competition
7698        // that runs for two hours against a repository merging pull requests
7699        // all day conflicts on the way in, and that is arithmetic rather
7700        // than a defect in the change.
7701        let mut conflicted = pr(Checks::Green, &[], 0);
7702        conflicted.blocking = Blocking::Conflict;
7703        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7704
7705        // Decided before the checks, and even with the rounds spent: every
7706        // check on a branch that cannot land is an answer about a state that
7707        // cannot land, and a conflict is not the change's fault.
7708        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7709        red.blocking = Blocking::Conflict;
7710        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7711
7712        // The lifecycle still wins over everything, conflict included.
7713        let mut merged = pr(Checks::Red, &[], 0);
7714        merged.blocking = Blocking::Conflict;
7715        merged.state = PrLifecycle::Merged;
7716        assert_eq!(
7717            decide(&merged, 0, 4, Duration::ZERO),
7718            Step::Done { merged: true }
7719        );
7720    }
7721
7722    #[test]
7723    fn the_forge_verdict_is_read_off_merge_state_status() {
7724        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7725        // matters: mergeable, with a non-required check red or still running.
7726        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7727            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7728            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7729        }
7730        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7731        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7732        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7733        // An older `gh`, or a token without the scope, says nothing - and
7734        // refusing to guess is the rule everywhere else in this module.
7735        for quiet in ["", "UNKNOWN"] {
7736            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7737            assert!(Blocking::of(quiet).stops_a_merge());
7738        }
7739    }
7740
7741    #[test]
7742    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7743        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7744        // The exact stderr from run ec12, in a jj-colocated repository.
7745        let jj = "could not determine current branch: failed to run git: not on any branch";
7746
7747        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7748            .expect("the forge says merged, so it merged");
7749        assert!(landed.ok);
7750        assert!(
7751            landed.detail.contains("but the pull request is merged"),
7752            "the record must not read as a clean success: {}",
7753            landed.detail
7754        );
7755        assert!(
7756            landed.detail.contains("not on any branch"),
7757            "and it must keep what the command actually said: {}",
7758            landed.detail
7759        );
7760
7761        // A pull request still open means the merge really failed.
7762        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7763        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7764        // And an unreadable answer is not evidence of success.
7765        assert!(merged_after_all(&argv, jj, None).is_none());
7766    }
7767
7768    #[test]
7769    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7770        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7771        state.state = PrLifecycle::Closed;
7772        assert_eq!(
7773            decide(&state, 0, 4, Duration::ZERO),
7774            Step::Done { merged: false },
7775            "a human closing the pull request ends the loop, whatever CI says"
7776        );
7777    }
7778
7779    #[test]
7780    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7781        let red = decide(
7782            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7783            4,
7784            4,
7785            Duration::ZERO,
7786        );
7787        match red {
7788            Step::GiveUp { reason } => {
7789                assert!(reason.contains("editorconfig"), "reason: {reason}");
7790                assert!(reason.contains("test (macos)"), "reason: {reason}");
7791                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7792            }
7793            other => panic!("expected a give-up, got {other:?}"),
7794        }
7795
7796        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7797        match commented {
7798            Step::GiveUp { reason } => {
7799                assert!(reason.contains("unresolved"), "reason: {reason}");
7800                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7801            }
7802            other => panic!("expected a give-up, got {other:?}"),
7803        }
7804    }
7805
7806    #[test]
7807    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7808        let candidate_commit = "magi: candidate A (uncommitted work)";
7809        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7810        let argv = merge_argv(16, &subject);
7811
7812        assert!(argv.contains(&"--squash".to_owned()));
7813        assert!(argv.contains(&"--delete-branch".to_owned()));
7814        assert!(argv.contains(&"--subject".to_owned()));
7815        assert_eq!(
7816            argv.last().map(String::as_str),
7817            Some("add retries to the uploader"),
7818            "the subject must not be the candidate commit message"
7819        );
7820        assert_ne!(subject, candidate_commit);
7821    }
7822
7823    #[test]
7824    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7825        assert_eq!(
7826            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7827            "feat: a queue, an unattended loop, and a phone UI"
7828        );
7829        assert_eq!(
7830            merge_subject("", "# port the retry logic\n\ndetails"),
7831            "port the retry logic",
7832            "an empty title falls back to the task's first line, heading marks stripped"
7833        );
7834    }
7835
7836    #[test]
7837    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7838        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7839        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7840        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7841        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7842        assert_eq!(run_of(""), None);
7843    }
7844
7845    #[test]
7846    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7847        let mut out = Vec::new();
7848        push_if_outstanding(
7849            &mut out,
7850            ReviewComment {
7851                author: "yukimemi".to_owned(),
7852                path: None,
7853                line: None,
7854                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7855            },
7856        );
7857        assert!(out.is_empty());
7858    }
7859
7860    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7861    /// falls back to the repository - which keeps these tests free of a
7862    /// worktree, a `git` invocation and a network.
7863    fn run_state() -> RunState {
7864        let mut state = RunState::new(
7865            std::path::PathBuf::from("/repo/magi"),
7866            "main".to_owned(),
7867            "abcdef1234".to_owned(),
7868            "add retries to the uploader".to_owned(),
7869            crate::config::Config::default(),
7870        );
7871        // These fixtures test execution flow, independent of host disk capacity.
7872        state.config.disk.min_free_bytes = 0;
7873        // Tests run in parallel against one persistent home and the ids
7874        // `RunState::new` draws from the clock can repeat, so two tests would
7875        // share a run's questions. The home also outlives the process, so the
7876        // counter alone would reuse an earlier run's ids.
7877        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7878        let nanos = std::time::SystemTime::now()
7879            .duration_since(std::time::UNIX_EPOCH)
7880            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7881        state.id = format!(
7882            "20261004-{nanos:06}-{:04x}",
7883            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7884        );
7885        state
7886    }
7887
7888    fn green_pr() -> PrState {
7889        PrState {
7890            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7891            number: 42,
7892            state: PrLifecycle::Open,
7893            checks: Checks::Green,
7894            // The forge sees nothing in the way unless a test says otherwise.
7895            blocking: Blocking::No,
7896            failing: Vec::new(),
7897            review_comments: vec![ReviewComment {
7898                author: "coderabbitai".to_owned(),
7899                path: Some("src/land.rs".to_owned()),
7900                line: Some(212),
7901                body: "this branch never checks the exit code".to_owned(),
7902            }],
7903        }
7904    }
7905
7906    #[test]
7907    fn land_fixer_defers_review_and_verification_without_a_cache() {
7908        let state = run_state();
7909        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7910        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7911        assert!(p.contains("Commit in this worktree"), "{p}");
7912    }
7913
7914    #[test]
7915    fn github_facing_land_text_is_english_whatever_the_language() {
7916        let mut state = run_state();
7917        state.config.graph.language = "ja".to_owned();
7918        let comment = stop_comment(&state.id, "checks are still red");
7919        assert!(crate::github_text::check("", &comment).is_empty());
7920        assert!(comment.is_ascii(), "{comment}");
7921        assert!(comment.starts_with(MARKER));
7922
7923        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7924        let ja_at = p.find("Write all prose in ja").unwrap();
7925        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7926        assert!(ja_at < rule_at, "{p}");
7927        assert!(p.contains("stays in Japanese"), "{p}");
7928
7929        state.config.graph.language = "en".to_owned();
7930        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7931        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7932        assert!(!p.contains("does not apply"), "{p}");
7933    }
7934
7935    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7936
7937    fn panel() -> String {
7938        approval_panel(
7939            &run_state(),
7940            &green_pr(),
7941            NUMSTAT,
7942            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7943            &[
7944                "land: ask before merging".to_owned(),
7945                "land: colour the diff".to_owned(),
7946            ],
7947            "feat: merge approval from the phone",
7948        )
7949    }
7950
7951    #[test]
7952    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7953        let html = panel();
7954        for needle in [
7955            "42",
7956            "main",
7957            "src/land.rs",
7958            "src/web.rs",
7959            "assets/logo.png",
7960            "feat: merge approval from the phone",
7961            "land: ask before merging",
7962            "land: colour the diff",
7963            "coderabbitai",
7964            "this branch never checks the exit code",
7965            "green",
7966        ] {
7967            assert!(html.contains(needle), "the panel must state `{needle}`");
7968        }
7969    }
7970
7971    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7972        crate::run::pin_test_home();
7973        let tmp = tempfile::tempdir().unwrap();
7974        let repo = tmp.path().join("repo");
7975        let remote = tmp.path().join("remote.git");
7976        std::fs::create_dir(&repo).unwrap();
7977        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7978            .await
7979            .unwrap();
7980        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7981        git::git(&repo, &["config", "user.name", "Test"])
7982            .await
7983            .unwrap();
7984        git::git(&repo, &["config", "user.email", "test@example.test"])
7985            .await
7986            .unwrap();
7987        std::fs::write(repo.join("base"), "base").unwrap();
7988        git::git(&repo, &["add", "."]).await.unwrap();
7989        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7990        git::git(
7991            &repo,
7992            &["remote", "add", "origin", remote.to_str().unwrap()],
7993        )
7994        .await
7995        .unwrap();
7996        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7997        git::git(&repo, &["checkout", "-b", "winner"])
7998            .await
7999            .unwrap();
8000        std::fs::write(repo.join("change"), "change").unwrap();
8001        git::git(&repo, &["add", "."]).await.unwrap();
8002        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
8003        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
8004        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
8005            .await
8006            .unwrap();
8007        let mut state = run_state();
8008        state.repo = repo.clone();
8009        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
8010        state.config.graph.land = true;
8011        state.config.graph.land_approval = true;
8012        state.pr_head = Some("task-head".into());
8013        state.pr_pushed_head = Some(head.clone());
8014        state.candidates = vec![winning_candidate("change")];
8015        state.candidates[0].worktree = repo;
8016        state.candidates[0].branch = "winner".into();
8017        state.tally = Some(uncontested_tally());
8018        state.gate_ran = true;
8019        state.gate_head = Some(head.clone());
8020        state.land_sync_pending = true;
8021        state.save().unwrap();
8022        (tmp, state, head)
8023    }
8024
8025    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
8026        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
8027        resume_landing_head(state, head, &green_pr().url, &forge, None).await
8028    }
8029
8030    async fn advance_landing_base(state: &RunState) {
8031        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8032        std::fs::write(state.repo.join("advance"), "advance").unwrap();
8033        git::git(&state.repo, &["add", "."]).await.unwrap();
8034        git::git(&state.repo, &["commit", "-m", "advance base"])
8035            .await
8036            .unwrap();
8037        git::git(&state.repo, &["push", "origin", "main"])
8038            .await
8039            .unwrap();
8040        git::git(&state.repo, &["checkout", "winner"])
8041            .await
8042            .unwrap();
8043    }
8044
8045    #[tokio::test]
8046    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
8047        let (_tmp, mut state, head) = landing_git_fixture().await;
8048        advance_landing_base(&state).await;
8049        let scratch = state.dir().join("rebase");
8050        std::fs::create_dir_all(&scratch).unwrap();
8051        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
8052        let attempts = state.land_sync_attempts;
8053        let error = rebase_landing_worktree(&mut state, "origin/main")
8054            .await
8055            .unwrap_err();
8056        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8057        assert_eq!(state.land_sync_attempts, attempts);
8058        assert!(state.land_sync_target.is_none());
8059        assert!(state.rebase_fixes.is_empty());
8060        assert!(
8061            state
8062                .base_sync
8063                .as_ref()
8064                .is_none_or(|sync| sync.conflict.is_none())
8065        );
8066        let block = state.resource_block.as_ref().unwrap();
8067        assert_eq!(block.kind, crate::rebase::SEQUENCER_INFRASTRUCTURE);
8068        assert!(
8069            block.detail.contains("inspect scratch Git backlink"),
8070            "{}",
8071            block.detail
8072        );
8073        assert_eq!(
8074            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
8075            "keep"
8076        );
8077        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
8078        std::fs::remove_dir_all(&scratch).unwrap();
8079        state.resource_block = None;
8080        assert_eq!(
8081            rebase_landing_worktree(&mut state, "origin/main")
8082                .await
8083                .unwrap(),
8084            crate::rebase::Rebased::Applied
8085        );
8086        assert_eq!(state.land_sync_attempts, attempts + 1);
8087        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
8088        assert!(git::is_clean(&state.repo).await.unwrap());
8089        assert!(state.rebase_fixes.is_empty());
8090    }
8091
8092    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
8093    {
8094        let (tmp, mut state, old) = landing_git_fixture().await;
8095        let path = tmp.path().join("foreign");
8096        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
8097            .await
8098            .unwrap();
8099        state.foreign_checkout = Some(
8100            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
8101                .await
8102                .unwrap(),
8103        );
8104        state.config.merge.mode = crate::config::MergeMode::Pr;
8105        state.save().unwrap();
8106        (tmp, state, old, path)
8107    }
8108
8109    #[tokio::test]
8110    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
8111        for phase in 0..4 {
8112            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
8113            advance_landing_base(&state).await;
8114            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
8115            if phase == 0 {
8116                // The live Step::Rebase path uses this same synchronization
8117                // and publication pair, without going through resume.
8118                assert_eq!(
8119                    rebase_landing_worktree(&mut state, "origin/main")
8120                        .await
8121                        .unwrap(),
8122                    crate::rebase::Rebased::Applied
8123                );
8124            } else {
8125                interrupt_landing_rebase(&mut state).await;
8126                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
8127                if phase == 2 {
8128                    git::sync_to_head(&state.repo).await.unwrap();
8129                } else if phase == 3 {
8130                    // Crash after joining history, before clearing its saved
8131                    // start. Repeating restoration must not add another merge.
8132                    restore_landing_worktree(&mut state).await.unwrap();
8133                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8134                    state.land_rebase_from = Some(old.clone());
8135                    state.save().unwrap();
8136                    restore_landing_worktree(&mut state).await.unwrap();
8137                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
8138                }
8139                state.save().unwrap();
8140                state = RunState::load(&state.id).unwrap();
8141                restore_landing_worktree(&mut state).await.unwrap();
8142                assert_eq!(
8143                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
8144                    repaired_tree
8145                );
8146            }
8147            let head = if phase == 0 {
8148                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
8149                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
8150                    .await
8151                    .unwrap()
8152            } else {
8153                resume_observed_head(&mut state, &old).await.unwrap()
8154            };
8155            assert!(git::is_ancestor(&state.repo, &old, &head).await);
8156            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
8157            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
8158            assert_eq!(
8159                git::remote_head(&state.repo, "origin", "task-head")
8160                    .await
8161                    .unwrap(),
8162                Some(head.clone())
8163            );
8164            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8165            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
8166            assert!(state.gate_allows_progress());
8167            assert!(state.land_rebase_from.is_none());
8168            assert!(!state.land_sync_pending);
8169            assert!(git::is_clean(&path).await.unwrap());
8170        }
8171    }
8172
8173    #[tokio::test]
8174    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
8175        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
8176        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8177        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8178        git::commit_all(&state.repo, "conflicting base")
8179            .await
8180            .unwrap();
8181        git::git(&state.repo, &["push", "origin", "main"])
8182            .await
8183            .unwrap();
8184        git::git(&state.repo, &["checkout", "winner"])
8185            .await
8186            .unwrap();
8187        landing_gate_fixer(
8188            &mut state,
8189            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
8190        );
8191        state.config.graph.gate_fix_rounds = 0;
8192        state.config.verify.gate = vec!["exit 1".into()];
8193        assert!(resume_observed_head(&mut state, &old).await.is_err());
8194        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
8195        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8196        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
8197        assert_eq!(
8198            std::fs::read_to_string(state.repo.join("change")).unwrap(),
8199            "resolved"
8200        );
8201        // A red gate must neither deliver nor publish the repaired tree.
8202        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
8203        assert_eq!(
8204            git::remote_head(&state.repo, "origin", "task-head")
8205                .await
8206                .unwrap(),
8207            Some(old.clone())
8208        );
8209        state = RunState::load(&state.id).unwrap();
8210        state.config.verify.gate = vec!["grep -q resolved change".into()];
8211        let head = resume_observed_head(&mut state, &old).await.unwrap();
8212        assert_eq!(head, repaired);
8213        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
8214        assert_eq!(
8215            std::fs::read_to_string(path.join("change")).unwrap(),
8216            "resolved"
8217        );
8218        assert_eq!(
8219            git::remote_head(&state.repo, "origin", "task-head")
8220                .await
8221                .unwrap(),
8222            Some(head.clone())
8223        );
8224        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8225        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
8226        assert!(git::is_clean(&path).await.unwrap());
8227    }
8228
8229    #[tokio::test]
8230    async fn landing_resume_completes_the_last_charged_sync_attempt() {
8231        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
8232            let (_tmp, mut state, old) = landing_git_fixture().await;
8233            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8234            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8235            git::commit_all(&state.repo, "conflicting base")
8236                .await
8237                .unwrap();
8238            git::git(&state.repo, &["push", "origin", "main"])
8239                .await
8240                .unwrap();
8241            git::git(&state.repo, &["checkout", "winner"])
8242                .await
8243                .unwrap();
8244            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
8245            state.config.graph.land_rounds = 1;
8246            state.land_sync_attempts = 1;
8247            state.land_sync_target = saved_target.then(|| target.clone());
8248            state.land_rebase_from = Some(old.clone());
8249            landing_gate_fixer(
8250                &mut state,
8251                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
8252            );
8253            state.config.verify.gate = vec!["grep -q resolved change".into()];
8254            state.save().unwrap();
8255            // Simulate interruption before the scratch start and at a conflict.
8256            if scratch_started {
8257                assert!(matches!(
8258                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
8259                        .await
8260                        .unwrap(),
8261                    git::RebaseStart::Conflicted(_)
8262                ));
8263            }
8264            state = RunState::load(&state.id).unwrap();
8265            let head = resume_observed_head(&mut state, &old).await.unwrap();
8266            assert_ne!(head, old);
8267            assert_eq!(state.land_sync_attempts, 1);
8268            assert!(state.land_sync_target.is_none());
8269            assert!(state.land_rebase_from.is_none());
8270            assert!(!state.land_sync_pending);
8271            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8272            assert!(state.gate_allows_progress());
8273            assert_eq!(
8274                git::remote_head(&state.repo, "origin", "task-head")
8275                    .await
8276                    .unwrap(),
8277                Some(head)
8278            );
8279            assert!(
8280                rebase_landing_worktree(&mut state, "origin/main")
8281                    .await
8282                    .unwrap_err()
8283                    .to_string()
8284                    .contains("budget exhausted")
8285            );
8286        }
8287    }
8288
8289    #[tokio::test]
8290    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
8291        let (_tmp, mut state, old) = landing_git_fixture().await;
8292        advance_landing_base(&state).await;
8293        state.config.verify.gate = vec!["test -f advance".into()];
8294        let head = resume_observed_head(&mut state, &old).await.unwrap();
8295        assert_ne!(head, old);
8296        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8297        assert!(state.gate_allows_progress());
8298        assert_eq!(
8299            git::remote_head(&state.repo, "origin", "task-head")
8300                .await
8301                .unwrap(),
8302            Some(head.clone())
8303        );
8304        assert_eq!(state.pr_pushed_head, Some(head));
8305        assert!(!state.land_sync_pending);
8306        assert!(state.config.graph.land_approval);
8307    }
8308
8309    fn landing_gate_fixer(state: &mut RunState, script: &str) {
8310        state.config.disk.min_free_bytes = 0;
8311        state.config.graph.gate_fix_rounds = 1;
8312        state.config.agents = vec![crate::config::AgentSpec {
8313            id: "mock".into(),
8314            kind: crate::config::AgentKind::Command,
8315            model: None,
8316            command: vec!["sh".into(), "-c".into(), script.into()],
8317            extra_args: Vec::new(),
8318            env: Default::default(),
8319            prompt_delivery: None,
8320            max_turn_secs: None,
8321        }];
8322        state.candidates[0].agent = "mock".into();
8323    }
8324
8325    #[tokio::test]
8326    async fn rebase_fixer_invocation_cap_survives_fallback_and_reload() {
8327        let (tmp, mut state, original) = landing_git_fixture().await;
8328        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8329        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8330        git::commit_all(&state.repo, "conflicting base")
8331            .await
8332            .unwrap();
8333        let target = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8334        git::git(&state.repo, &["checkout", "winner"])
8335            .await
8336            .unwrap();
8337        let scratch = state.dir().join("rebase");
8338        let counter = tmp.path().join("calls");
8339        landing_gate_fixer(
8340            &mut state,
8341            "echo \"$REBASE_AGENT\" >> \"$REBASE_COUNTER\"; exit 1",
8342        );
8343        let template = state.config.agents[0].clone();
8344        let ids = ["mock", "fallback1", "fallback2", "fallback3"].map(str::to_owned);
8345        state.config.agents = ids
8346            .iter()
8347            .map(|id| {
8348                let mut spec = template.clone();
8349                spec.id.clone_from(id);
8350                spec.env.insert("REBASE_AGENT".into(), id.clone());
8351                spec.env
8352                    .insert("REBASE_COUNTER".into(), git::path_arg(&counter));
8353                spec
8354            })
8355            .collect();
8356        state.config.roles.fixer = Some(crate::config::AgentChoice::Chain(ids.to_vec()));
8357        state.config.graph.review_rounds = 3;
8358        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8359        state.config.graph.timeout_resource_wait = 0;
8360        let started = git::rebase_start(&state.repo, &scratch, "winner", &target)
8361            .await
8362            .unwrap();
8363        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
8364        let home = crate::run::home();
8365        let cache = crate::build_target::resolve(&home, &scratch).unwrap();
8366        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", &scratch, &original);
8367        let crate::cache::AcquireOutcome::Acquired(lease) =
8368            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
8369        else {
8370            panic!("test target was already leased");
8371        };
8372        let error = crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8373            .await
8374            .unwrap_err();
8375        assert!(error.is::<crate::agent::IsolatedSeatWait>(), "{error:#}");
8376        assert!(!counter.exists());
8377        assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), ["change"]);
8378        drop(lease);
8379        state = RunState::load(&state.id).unwrap();
8380        for _ in 0..2 {
8381            let crate::rebase::Rebased::Stopped(why) =
8382                crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8383                    .await
8384                    .unwrap()
8385            else {
8386                panic!("the unresolved conflict must stop");
8387            };
8388            assert!(why.contains("after 3 of 3 fixer round(s)"), "{why}");
8389            assert_eq!(
8390                std::fs::read_to_string(&counter)
8391                    .unwrap()
8392                    .lines()
8393                    .collect::<Vec<_>>(),
8394                ["mock", "fallback1", "fallback2"]
8395            );
8396            assert_eq!(
8397                git::rev_parse(&state.repo, "winner").await.unwrap(),
8398                original
8399            );
8400            state = RunState::load(&state.id).unwrap();
8401        }
8402    }
8403
8404    #[tokio::test]
8405    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
8406        let (_tmp, mut state, old) = landing_git_fixture().await;
8407        std::fs::write(state.repo.join("change"), "operator update").unwrap();
8408        git::commit_all(&state.repo, "extend winner").await.unwrap();
8409        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8410        git::git(
8411            &state.repo,
8412            &["push", "origin", "HEAD:refs/heads/task-head"],
8413        )
8414        .await
8415        .unwrap();
8416        state.config.verify.gate = vec!["exit 1".into()];
8417        state.config.graph.gate_fix_rounds = 0;
8418        assert!(resume_observed_head(&mut state, &updated).await.is_err());
8419        assert_ne!(old, updated);
8420        assert_eq!(state.gate_head.as_ref(), Some(&updated));
8421        assert!(!state.gate_allows_progress());
8422        assert!(state.land_sync_pending);
8423        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
8424        let head = resume_observed_head(&mut state, &updated).await.unwrap();
8425        assert_eq!(head, updated);
8426        assert!(state.gate_allows_progress());
8427        assert!(!state.land_sync_pending);
8428        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8429        land_with(&mut state, &green_pr().url, &forge)
8430            .await
8431            .unwrap();
8432        assert!(state.parked);
8433        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8434        assert!(forge.argvs().is_empty());
8435    }
8436
8437    #[tokio::test]
8438    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
8439        for divergent in [false, true] {
8440            let (_tmp, mut state, old) = landing_git_fixture().await;
8441            if divergent {
8442                git::git(&state.repo, &["reset", "--hard", "origin/main"])
8443                    .await
8444                    .unwrap();
8445            }
8446            std::fs::write(state.repo.join("external"), "external").unwrap();
8447            git::commit_all(&state.repo, "external update")
8448                .await
8449                .unwrap();
8450            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8451            git::git(
8452                &state.repo,
8453                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
8454            )
8455            .await
8456            .unwrap();
8457            if !divergent {
8458                git::git(&state.repo, &["reset", "--hard", &old])
8459                    .await
8460                    .unwrap();
8461            }
8462            let error = resume_observed_head(&mut state, &external)
8463                .await
8464                .unwrap_err();
8465            assert!(
8466                error
8467                    .to_string()
8468                    .contains("public head moved outside this run")
8469            );
8470            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
8471            assert_eq!(
8472                git::remote_head(&state.repo, "origin", "task-head")
8473                    .await
8474                    .unwrap(),
8475                Some(external)
8476            );
8477        }
8478    }
8479
8480    #[test]
8481    fn fixer_prompt_carries_the_adopted_instruction_not_the_obsolete_one() {
8482        let mut state = repair_state(true, true);
8483        state.reviews[0].reviews[0].findings[0].detail = "require teravars 0.7.0".into();
8484        state.instruction = "use teravars 0.7.0".into();
8485        crate::instruction_revision_control::adopt_into_run(
8486            &mut state,
8487            "cli/r",
8488            "instruction-cli-r",
8489            "use teravars 0.8.0",
8490            1,
8491            "h",
8492            &green_pr().url,
8493        );
8494        state.merge_repairs[0].phase = crate::run::MergeRepairPhase::Fixing;
8495        let reason = merge_repair_reason(&state, &state.merge_repairs[0]).unwrap();
8496        let prompt = fix_prompt(&state, &green_pr(), 1, 4, &reason, "");
8497        assert!(prompt.contains("# The task\n\nuse teravars 0.8.0"));
8498        assert!(prompt.contains("require teravars 0.7.0"));
8499        assert!(prompt.contains("evidence is historical, not a list of requirements"));
8500        assert!(prompt.contains("Implement the revised task"));
8501        assert!(!prompt.contains("Address the unresolved Major findings"));
8502        assert!(!prompt.contains("Change nothing the checks and the comments did not raise"));
8503    }
8504
8505    /// A repair publication leaves a checkpoint; a forge still showing the
8506    /// leased head is then this run's own lagging view, and nothing else is.
8507    #[tokio::test]
8508    async fn only_a_checkpointed_self_push_counts_as_a_lagging_observation() {
8509        let (_tmp, mut state, old) = landing_git_fixture().await;
8510        let repo = state.repo.clone();
8511        std::fs::write(repo.join("repair"), "repair").unwrap();
8512        git::git(&repo, &["add", "."]).await.unwrap();
8513        git::git(&repo, &["commit", "-m", "repair"]).await.unwrap();
8514        let new = git::rev_parse(&repo, "HEAD").await.unwrap();
8515        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
8516            .await
8517            .unwrap();
8518        state.pr_pushed_head = Some(new.clone());
8519        // Without the pre-push checkpoint the refusal path is untouched.
8520        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8521        state.pr_publication = Some(crate::run::PrPublication {
8522            previous: old.clone(),
8523            head: new.clone(),
8524            branch: "task-head".into(),
8525        });
8526        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8527        state.gate_head = Some(new.clone());
8528        assert!(lagging_self_publication(&state, &old).await.unwrap());
8529        state.gate_ran = false;
8530        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8531        state.gate_ran = true;
8532        std::fs::write(repo.join("dirty"), "unverified").unwrap();
8533        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8534        std::fs::remove_file(repo.join("dirty")).unwrap();
8535        // The new head itself is not stale, and a third commit never is.
8536        assert!(!lagging_self_publication(&state, &new).await.unwrap());
8537        assert!(
8538            !lagging_self_publication(&state, &"d".repeat(40))
8539                .await
8540                .unwrap()
8541        );
8542        // The saved lease must name the checkpointed commit.
8543        let mut unsaved = state.clone();
8544        unsaved.pr_pushed_head = Some(old.clone());
8545        assert!(!lagging_self_publication(&unsaved, &old).await.unwrap());
8546        let checkpoint = unsaved.pr_publication.clone().unwrap();
8547        assert!(
8548            repair_publication_observed(&unsaved, &checkpoint)
8549                .await
8550                .unwrap()
8551        );
8552        let mut other = checkpoint.clone();
8553        other.previous = "other lease".into();
8554        assert!(!repair_publication_observed(&unsaved, &other).await.unwrap());
8555        unsaved.pr_publication = None;
8556        assert!(
8557            !repair_publication_observed(&unsaved, &checkpoint)
8558                .await
8559                .unwrap()
8560        );
8561        unsaved.pr_publication = Some(checkpoint.clone());
8562        // A remote-only update after the push is not self-publication.
8563        git::git(&repo, &["commit", "--allow-empty", "-m", "external"])
8564            .await
8565            .unwrap();
8566        git::git(
8567            &repo,
8568            &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
8569        )
8570        .await
8571        .unwrap();
8572        git::git(&repo, &["reset", "--hard", &new]).await.unwrap();
8573        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8574        assert!(
8575            !repair_publication_observed(&unsaved, &checkpoint)
8576                .await
8577                .unwrap()
8578        );
8579        // The existing refusal for a foreign head is retained.
8580        assert!(
8581            resume_observed_head(&mut state, &"d".repeat(40))
8582                .await
8583                .is_err()
8584        );
8585    }
8586
8587    #[tokio::test]
8588    async fn repair_publication_lag_binds_fresh_approval() {
8589        let (_tmp, mut state, old) = landing_git_fixture().await;
8590        advance_landing_base(&state).await;
8591        let new = resume_observed_head(&mut state, &old).await.unwrap();
8592        state.pr_publication = Some(crate::run::PrPublication {
8593            previous: old.clone(),
8594            head: new.clone(),
8595            branch: "task-head".into(),
8596        });
8597        state.land_sync_pending = true;
8598        state.save().unwrap();
8599        let mut state = RunState::load(&state.id).unwrap();
8600        let forge = Scripted::new(
8601            vec![
8602                seen(&old, Checks::Green, "CLEAN", false),
8603                seen(&new, Checks::Green, "CLEAN", false),
8604            ],
8605            vec![],
8606        );
8607        land_with(&mut state, &green_pr().url, &forge)
8608            .await
8609            .unwrap();
8610        assert!(forge.calls().contains(&"poll"));
8611        assert_eq!(state.land_approval.as_ref().unwrap().head, new);
8612        assert!(forge.argvs().is_empty());
8613    }
8614
8615    #[tokio::test]
8616    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
8617        let (_tmp, mut state, old) = landing_git_fixture().await;
8618        advance_landing_base(&state).await;
8619        landing_gate_fixer(
8620            &mut state,
8621            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8622        );
8623        state.config.verify.gate =
8624            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8625        state.config.verify.e2e = vec!["test -f advance".into()];
8626        // First save a red gate without spending a fixer round. Resume must
8627        // still offer the remaining budget for this exact same failed head.
8628        state.config.graph.gate_fix_rounds = 0;
8629        assert!(resume_observed_head(&mut state, &old).await.is_err());
8630        assert_eq!(
8631            git::remote_head(&state.repo, "origin", "task-head")
8632                .await
8633                .unwrap(),
8634            Some(old.clone())
8635        );
8636        state.config.graph.gate_fix_rounds = 1;
8637        let head = resume_observed_head(&mut state, &old).await.unwrap();
8638        assert_eq!(state.gate_fixes.len(), 1);
8639        assert!(state.gate_fixes[0].committed);
8640        assert!(state.gate_allows_progress());
8641        assert_eq!(state.gate_head.as_ref(), Some(&head));
8642        assert_eq!(
8643            git::remote_head(&state.repo, "origin", "task-head")
8644                .await
8645                .unwrap(),
8646            Some(head.clone())
8647        );
8648        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8649        land_with(&mut state, &green_pr().url, &forge)
8650            .await
8651            .unwrap();
8652        assert!(state.parked);
8653        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8654        assert!(forge.argvs().is_empty());
8655    }
8656
8657    #[tokio::test]
8658    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
8659        let (_tmp, mut state, old) = landing_git_fixture().await;
8660        advance_landing_base(&state).await;
8661        landing_gate_fixer(
8662            &mut state,
8663            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8664        );
8665        state.config.verify.gate = vec!["echo still red; exit 1".into()];
8666        for _ in 0..2 {
8667            assert!(resume_observed_head(&mut state, &old).await.is_err());
8668            assert_eq!(state.gate_fixes.len(), 1);
8669            assert_eq!(
8670                git::remote_head(&state.repo, "origin", "task-head")
8671                    .await
8672                    .unwrap(),
8673                Some(old.clone())
8674            );
8675        }
8676    }
8677
8678    #[tokio::test]
8679    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
8680        let (_tmp, mut state, old) = landing_git_fixture().await;
8681        advance_landing_base(&state).await;
8682        landing_gate_fixer(
8683            &mut state,
8684            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8685        );
8686        state.config.verify.gate =
8687            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8688        // The repair makes the gate green while breaking an e2e invariant.
8689        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
8690        let mut saved_comparison = None;
8691        for resume in 0..3 {
8692            assert!(resume_observed_head(&mut state, &old).await.is_err());
8693            state = RunState::load(&state.id).unwrap();
8694            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8695            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8696            assert_eq!(evidence.head, head);
8697            assert!(!evidence.passed);
8698            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
8699            let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
8700            if let Some(saved) = &saved_comparison {
8701                assert_eq!(comparison, saved);
8702            } else {
8703                saved_comparison = Some(comparison.clone());
8704            }
8705            assert_eq!(state.gate_fixes.len(), 1);
8706            assert_eq!(
8707                git::remote_head(&state.repo, "origin", "task-head")
8708                    .await
8709                    .unwrap(),
8710                Some(old.clone())
8711            );
8712            if resume > 0 {
8713                assert!(
8714                    state.gate_allows_progress(),
8715                    "a green gate must not bypass red e2e"
8716                );
8717            }
8718        }
8719        // A changed command is not new evidence about the already checked SHA.
8720        state.config.verify.e2e = vec!["grep -q fixed change".into()];
8721        assert!(resume_observed_head(&mut state, &old).await.is_err());
8722        assert_eq!(
8723            state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
8724            saved_comparison
8725        );
8726    }
8727
8728    #[tokio::test]
8729    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
8730        for phase in 0..3 {
8731            let (_tmp, mut state, old) = landing_git_fixture().await;
8732            advance_landing_base(&state).await;
8733            let head = resume_observed_head(&mut state, &old).await.unwrap();
8734            // Persist the shapes left by interruption, resource deferral,
8735            // and a successful check for a different (older) SHA.
8736            state.land_sync_pending = true;
8737            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
8738            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8739                if phase == 2 {
8740                    old.clone()
8741                } else {
8742                    head.clone()
8743                },
8744                phase == 2,
8745                if phase == 1 {
8746                    vec![crate::run::CommandOutcome {
8747                        command: state.config.verify.e2e[0].clone(),
8748                        code: None,
8749                        output_tail: "verification resource unavailable".into(),
8750                        duration_ms: 0,
8751                        resource_blocked: true,
8752                        ..Default::default()
8753                    }]
8754                } else {
8755                    Vec::new()
8756                },
8757            ));
8758            state.save().unwrap();
8759            for _ in 0..2 {
8760                state = RunState::load(&state.id).unwrap();
8761                assert!(resume_observed_head(&mut state, &head).await.is_err());
8762                let evidence = state.gate_repair_e2e.as_ref().unwrap();
8763                assert_eq!(evidence.head, head);
8764                assert!(!evidence.passed);
8765                assert!(!evidence.outcomes.is_empty());
8766                assert_eq!(
8767                    git::remote_head(&state.repo, "origin", "task-head")
8768                        .await
8769                        .unwrap(),
8770                    Some(head.clone())
8771                );
8772                assert!(state.land_sync_pending);
8773            }
8774        }
8775    }
8776
8777    #[tokio::test]
8778    async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
8779        for code in [None, Some(126), Some(127)] {
8780            let (_tmp, mut state, old) = landing_git_fixture().await;
8781            advance_landing_base(&state).await;
8782            let head = resume_observed_head(&mut state, &old).await.unwrap();
8783            state.land_sync_pending = true;
8784            state.config.verify.e2e = vec!["true".into()];
8785            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8786                head.clone(),
8787                false,
8788                vec![crate::run::CommandOutcome {
8789                    command: state.config.verify.e2e[0].clone(),
8790                    code,
8791                    output_tail: "verification command did not complete".into(),
8792                    ..Default::default()
8793                }],
8794            ));
8795            state.save().unwrap();
8796            state = RunState::load(&state.id).unwrap();
8797            assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
8798            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8799            assert_eq!(evidence.head, head);
8800            assert!(evidence.passed);
8801            assert_eq!(evidence.outcomes[0].code, Some(0));
8802        }
8803    }
8804
8805    async fn interrupt_landing_rebase(state: &mut RunState) {
8806        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
8807        state.save().unwrap();
8808        let scratch = state.dir().join("rebase");
8809        assert_eq!(
8810            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
8811                .await
8812                .unwrap(),
8813            crate::rebase::Rebased::Applied
8814        );
8815        assert!(!git::is_clean(&state.repo).await.unwrap());
8816    }
8817
8818    async fn landing_setup(state: &mut RunState) {
8819        git::git(
8820            &state.repo,
8821            &["config", "extensions.worktreeConfig", "true"],
8822        )
8823        .await
8824        .unwrap();
8825        state.config.worktree.setup =
8826            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8827        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8828            .await
8829            .unwrap();
8830        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8831    }
8832
8833    #[tokio::test]
8834    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8835        let (tmp, mut state, head) = landing_git_fixture().await;
8836        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8837        git::acquire_worktree_config(&state.repo).await.unwrap();
8838        let winner = tmp.path().join("landing");
8839        git::worktree_add_existing(&state.repo, &winner, "winner", false)
8840            .await
8841            .unwrap();
8842        state.candidates[0].worktree = winner.clone();
8843        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8844        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8845        state.config.disk.min_free_bytes = 0;
8846        state.config.worktree.setup = vec![crate::config::SetupStep {
8847            run: Some("touch setup-completed".into()),
8848            ..Default::default()
8849        }];
8850        #[cfg(unix)]
8851        {
8852            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8853            state.config.coordination = Some(crate::config::Coordination {
8854                contract_file: "fixture-contract".into(),
8855                contract_token: "fixture-v1".into(),
8856                lock_file: "fixture-lock".into(),
8857            });
8858        }
8859        state.land_rebase_from = Some(head);
8860        let restore = restore_landing_worktree(&mut state);
8861        // Only the registered Unix fixture can deadlock by reacquiring its
8862        // own operation lease. Don't time the whole Git/setup path elsewhere.
8863        #[cfg(unix)]
8864        let restore = async {
8865            tokio::time::timeout(Duration::from_secs(15), restore)
8866                .await
8867                .expect("landing setup must not wait for its own repository operation")
8868        };
8869        restore.await.unwrap();
8870        assert!(winner.join("setup-completed").is_file());
8871        assert!(git::is_clean(&winner).await.unwrap());
8872        assert!(state.land_rebase_from.is_none());
8873    }
8874
8875    #[tokio::test]
8876    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8877        for phase in 0..3 {
8878            let (_tmp, mut state, old) = landing_git_fixture().await;
8879            advance_landing_base(&state).await;
8880            landing_setup(&mut state).await;
8881            if phase > 0 {
8882                interrupt_landing_rebase(&mut state).await;
8883                if phase == 2 {
8884                    // Crash after clean removed setup products, before setup.
8885                    git::sync_to_head(&state.repo).await.unwrap();
8886                    assert!(!state.repo.join(".env").exists());
8887                }
8888                state = RunState::load(&state.id).unwrap();
8889            }
8890            let head = resume_observed_head(&mut state, &old).await.unwrap();
8891            assert_ne!(head, old);
8892            assert!(state.gate_allows_progress());
8893            assert!(state.land_rebase_from.is_none());
8894            assert_eq!(
8895                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8896                "secret"
8897            );
8898            assert!(git::is_clean(&state.repo).await.unwrap());
8899            assert!(
8900                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8901                    .await
8902                    .unwrap()
8903                    .contains(".env")
8904            );
8905        }
8906    }
8907
8908    #[tokio::test]
8909    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8910        let (_tmp, mut state, _) = landing_git_fixture().await;
8911        advance_landing_base(&state).await;
8912        landing_setup(&mut state).await;
8913        interrupt_landing_rebase(&mut state).await;
8914        // Exercise unusual names without asking Windows to create an invalid
8915        // control-character filename. Unix also covers embedded newlines.
8916        let locals = [
8917            "local notes",
8918            #[cfg(unix)]
8919            "local\nnotes",
8920        ];
8921        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8922            .await
8923            .unwrap();
8924        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8925        for local in locals {
8926            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8927            assert!(
8928                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8929                    .await
8930                    .unwrap()
8931                    .ok()
8932            );
8933        }
8934        restore_landing_worktree(&mut state).await.unwrap();
8935        for local in locals {
8936            assert_eq!(
8937                std::fs::read_to_string(state.repo.join(local)).unwrap(),
8938                "keep these notes"
8939            );
8940        }
8941        assert_eq!(
8942            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8943            "secret"
8944        );
8945        assert!(git::is_clean(&state.repo).await.unwrap());
8946        assert!(state.land_rebase_from.is_none());
8947    }
8948
8949    #[tokio::test]
8950    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8951        for local in ["advance", "advance/notes", "new-directory"] {
8952            let (_tmp, mut state, _) = landing_git_fixture().await;
8953            advance_landing_base(&state).await;
8954            // Also cover a local file blocking a new tracked directory.
8955            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8956            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8957            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8958            git::git(&state.repo, &["add", "."]).await.unwrap();
8959            git::git(&state.repo, &["commit", "-m", "add directory"])
8960                .await
8961                .unwrap();
8962            git::git(&state.repo, &["push", "origin", "main"])
8963                .await
8964                .unwrap();
8965            git::git(&state.repo, &["checkout", "winner"])
8966                .await
8967                .unwrap();
8968            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8969                .await
8970                .unwrap();
8971            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8972            let path = state.repo.join(local);
8973            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8974            std::fs::write(&path, "local notes").unwrap();
8975            interrupt_landing_rebase(&mut state).await;
8976            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8977            let checkpoint = state.land_rebase_from.clone();
8978            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8979            assert!(
8980                error.to_string().contains("conflicting with HEAD"),
8981                "{error:#}"
8982            );
8983            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8984            assert_eq!(
8985                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8986                before
8987            );
8988            assert_eq!(state.land_rebase_from, checkpoint);
8989        }
8990    }
8991
8992    #[tokio::test]
8993    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8994        for interrupted in [false, true] {
8995            let (_tmp, mut state, old) = landing_git_fixture().await;
8996            assert!(state.config.worktree.setup.is_empty());
8997            // A gate product exists before the base moves, without setup metadata.
8998            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8999                .await
9000                .unwrap();
9001            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
9002            state.config.verify.gate =
9003                vec!["mkdir -p target && printf artifact > target/probe".into()];
9004            state.gate_ran = false;
9005            resume_observed_head(&mut state, &old).await.unwrap();
9006            assert_eq!(
9007                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
9008                "artifact"
9009            );
9010            advance_landing_base(&state).await;
9011            if interrupted {
9012                interrupt_landing_rebase(&mut state).await;
9013                state = RunState::load(&state.id).unwrap();
9014            }
9015            state.config.verify.gate =
9016                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
9017            let head = resume_observed_head(&mut state, &old).await.unwrap();
9018            assert_ne!(head, old);
9019            assert!(state.gate_allows_progress());
9020            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
9021            assert_eq!(
9022                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
9023                "artifact"
9024            );
9025            assert!(state.land_rebase_from.is_none());
9026            assert_eq!(
9027                git::remote_head(&state.repo, "origin", "task-head")
9028                    .await
9029                    .unwrap(),
9030                Some(head.clone())
9031            );
9032            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
9033            land_with(&mut state, &green_pr().url, &forge)
9034                .await
9035                .unwrap();
9036            assert!(state.parked);
9037            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
9038            assert!(forge.argvs().is_empty());
9039        }
9040    }
9041
9042    #[tokio::test]
9043    #[cfg(unix)]
9044    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
9045        use std::os::fd::AsRawFd as _;
9046
9047        for interrupted in [false, true] {
9048            let (_tmp, mut state, _) = landing_git_fixture().await;
9049            advance_landing_base(&state).await;
9050            landing_setup(&mut state).await;
9051            if interrupted {
9052                interrupt_landing_rebase(&mut state).await;
9053            }
9054            state.config.worktree.setup =
9055                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
9056            let common = crate::repo_lock::common_dir(&state.repo)
9057                .await
9058                .unwrap()
9059                .unwrap();
9060            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
9061            state.config.coordination = crate::config::test_coordination();
9062            state.config.graph.timeout_resource_wait = 0;
9063            let external = std::fs::OpenOptions::new()
9064                .read(true)
9065                .write(true)
9066                .create(true)
9067                .truncate(false)
9068                .open(common.join("updater.lock"))
9069                .unwrap();
9070            // SAFETY: the descriptor belongs to `external` and remains open.
9071            let locked =
9072                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
9073            assert_eq!(locked, 0);
9074            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
9075            let checkpoint = state.land_rebase_from.clone();
9076            let error = restore_landing_worktree(&mut state).await.unwrap_err();
9077            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
9078            assert_eq!(
9079                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
9080                before
9081            );
9082            assert_eq!(state.land_rebase_from, checkpoint);
9083            assert_eq!(
9084                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
9085                "secret"
9086            );
9087
9088            drop(external);
9089            state.config.graph.timeout_resource_wait = 2;
9090            restore_landing_worktree(&mut state).await.unwrap();
9091            assert!(git::is_clean(&state.repo).await.unwrap());
9092            assert!(state.land_rebase_from.is_none());
9093            assert_eq!(
9094                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
9095                "restored"
9096            );
9097        }
9098    }
9099
9100    #[tokio::test]
9101    #[cfg(unix)]
9102    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
9103        use std::sync::atomic::{AtomicBool, Ordering};
9104
9105        let (_tmp, mut state, _) = landing_git_fixture().await;
9106        advance_landing_base(&state).await;
9107        landing_setup(&mut state).await;
9108        interrupt_landing_rebase(&mut state).await;
9109        let common = crate::repo_lock::common_dir(&state.repo)
9110            .await
9111            .unwrap()
9112            .unwrap();
9113        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
9114        state.config.coordination = crate::config::test_coordination();
9115        let holder = crate::repo_lock::SeatLease::for_checkout(
9116            &state.repo,
9117            true,
9118            state.config.coordination.as_ref(),
9119        )
9120        .await
9121        .unwrap();
9122        assert!(holder.is_some());
9123        let cancelled = Arc::new(AtomicBool::new(false));
9124        let signal = cancelled.clone();
9125        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
9126            signal.load(Ordering::SeqCst)
9127        });
9128        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
9129        let checkpoint = state.land_rebase_from.clone();
9130        let (result, ()) = tokio::join!(
9131            tokio::time::timeout(
9132                Duration::from_secs(2),
9133                wait.scope(restore_landing_worktree(&mut state)),
9134            ),
9135            async {
9136                tokio::time::sleep(Duration::from_millis(100)).await;
9137                cancelled.store(true, Ordering::SeqCst);
9138            }
9139        );
9140        let error = result
9141            .expect("cancellation must release the waiting driver")
9142            .unwrap_err();
9143        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
9144        assert_eq!(
9145            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
9146            before
9147        );
9148        assert_eq!(state.land_rebase_from, checkpoint);
9149        assert_eq!(
9150            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
9151            "secret"
9152        );
9153        drop(holder);
9154        restore_landing_worktree(&mut state).await.unwrap();
9155        assert!(state.land_rebase_from.is_none());
9156        assert!(git::is_clean(&state.repo).await.unwrap());
9157    }
9158
9159    #[tokio::test]
9160    #[cfg(unix)]
9161    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
9162        use std::sync::atomic::{AtomicBool, Ordering};
9163
9164        for e2e in [false, true] {
9165            let (_tmp, mut state, head) = landing_git_fixture().await;
9166            let common = crate::repo_lock::common_dir(&state.repo)
9167                .await
9168                .unwrap()
9169                .unwrap();
9170            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
9171            state.config.coordination = crate::config::test_coordination();
9172            if e2e {
9173                state.config.verify.e2e = vec!["true".into()];
9174                state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9175                    head.clone(),
9176                    false,
9177                    Vec::new(),
9178                ));
9179            } else {
9180                state.config.verify.gate = vec!["true".into()];
9181                state.gate_ran = false;
9182            }
9183            let holder = crate::repo_lock::SeatLease::for_checkout(
9184                &state.repo,
9185                true,
9186                state.config.coordination.as_ref(),
9187            )
9188            .await
9189            .unwrap();
9190            assert!(holder.is_some());
9191            let cancelled = Arc::new(AtomicBool::new(false));
9192            let signal = cancelled.clone();
9193            let waiting = Arc::new(tokio::sync::Notify::new());
9194            let observed = waiting.clone();
9195            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
9196                observed.notify_one();
9197                signal.load(Ordering::SeqCst)
9198            });
9199            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
9200            let url = green_pr().url;
9201            let result = {
9202                let mut publishing =
9203                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
9204                // Git and fixture I/O precede local coordination. Start the
9205                // cancellation deadline only once the inherited wait policy
9206                // is polled, rather than timing those unrelated subprocesses.
9207                tokio::time::timeout(Duration::from_secs(30), async {
9208                    tokio::select! {
9209                        result = &mut publishing => panic!(
9210                            "verification must wait behind the held seat: {result:?}"
9211                        ),
9212                        () = waiting.notified() => {}
9213                    }
9214                })
9215                .await
9216                .expect("verification must reach the inherited coordination wait");
9217                cancelled.store(true, Ordering::SeqCst);
9218                tokio::time::timeout(Duration::from_secs(2), publishing).await
9219            };
9220            let error = result
9221                .expect("cancellation must release the verification waiter")
9222                .unwrap_err();
9223            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
9224            assert!(error.to_string().contains("cancelled"), "{error:#}");
9225            assert!(forge.argvs().is_empty());
9226            assert_eq!(
9227                git::remote_head(&state.repo, "origin", "task-head")
9228                    .await
9229                    .unwrap(),
9230                Some(head.clone())
9231            );
9232            drop(holder);
9233            // Cancellation must release its reservation so another attempt can verify.
9234            assert_eq!(
9235                publish_landing_head(&mut state, &head, &url, &forge)
9236                    .await
9237                    .unwrap(),
9238                head
9239            );
9240        }
9241    }
9242
9243    #[tokio::test]
9244    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
9245        for staged in [false, true] {
9246            let (_tmp, mut state, old) = landing_git_fixture().await;
9247            advance_landing_base(&state).await;
9248            interrupt_landing_rebase(&mut state).await;
9249            std::fs::write(state.repo.join("change"), "user edit").unwrap();
9250            if staged {
9251                git::git(&state.repo, &["add", "change"]).await.unwrap();
9252            }
9253            assert!(resume_observed_head(&mut state, &old).await.is_err());
9254            assert_eq!(
9255                std::fs::read_to_string(state.repo.join("change")).unwrap(),
9256                "user edit"
9257            );
9258            assert_eq!(
9259                git::remote_head(&state.repo, "origin", "task-head")
9260                    .await
9261                    .unwrap(),
9262                Some(old)
9263            );
9264        }
9265    }
9266
9267    #[tokio::test]
9268    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
9269        let (_tmp, mut state, head) = landing_git_fixture().await;
9270        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
9271        let id = state.id.clone();
9272        let pr = land_with(&mut state, &green_pr().url, &forge)
9273            .await
9274            .unwrap();
9275        assert_eq!(pr.state, PrLifecycle::Open);
9276        assert_eq!(state.id, id);
9277        assert!(state.parked);
9278        assert_eq!(state.status, RunStatus::Landing);
9279        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
9280        assert!(forge.argvs().is_empty());
9281
9282        state.land_sync_pending = true;
9283        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
9284        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
9285        closed.pr.state = PrLifecycle::Closed;
9286        let forge = Scripted::new(vec![closed], vec![]);
9287        assert_eq!(
9288            land_with(&mut state, &green_pr().url, &forge)
9289                .await
9290                .unwrap()
9291                .state,
9292            PrLifecycle::Closed
9293        );
9294        assert_eq!(
9295            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
9296            "do not touch"
9297        );
9298        assert!(forge.argvs().is_empty());
9299    }
9300
9301    #[tokio::test]
9302    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
9303        let (_tmp, mut state, old) = landing_git_fixture().await;
9304        advance_landing_base(&state).await;
9305        state.config.verify.gate = vec!["exit 1".into()];
9306        assert!(resume_observed_head(&mut state, &old).await.is_err());
9307        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
9308        assert!(!state.gate_allows_progress());
9309        assert_eq!(
9310            git::remote_head(&state.repo, "origin", "task-head")
9311                .await
9312                .unwrap(),
9313            Some(old)
9314        );
9315        assert!(state.land_sync_pending);
9316    }
9317
9318    #[tokio::test]
9319    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
9320        let (_tmp, mut state, old) = landing_git_fixture().await;
9321        advance_landing_base(&state).await;
9322        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
9323        // Model a crash after the push but before saving its published SHA.
9324        state.pr_pushed_head = Some(old.clone());
9325        state.land_sync_pending = true;
9326        assert_eq!(
9327            resume_observed_head(&mut state, &pushed).await.unwrap(),
9328            pushed
9329        );
9330        // A writer races the observed PR snapshot: the explicit remote lease
9331        // must reject the push even though preflight saw our expected head.
9332        git::git(
9333            &state.repo,
9334            &["push", "--force", "origin", "main:refs/heads/task-head"],
9335        )
9336        .await
9337        .unwrap();
9338        assert!(
9339            publish_landing_head(
9340                &mut state,
9341                &pushed,
9342                &green_pr().url,
9343                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
9344            )
9345            .await
9346            .unwrap_err()
9347            .to_string()
9348            .contains("publishing gated")
9349        );
9350        assert!(
9351            resume_observed_head(&mut state, "foreign-head")
9352                .await
9353                .is_err()
9354        );
9355    }
9356    #[tokio::test]
9357    async fn landing_publication_refuses_a_pr_closed_during_gate() {
9358        let (_tmp, mut state, head) = landing_git_fixture().await;
9359        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
9360        closed.pr.state = PrLifecycle::Closed;
9361        let forge = Scripted::new(vec![closed], vec![]);
9362        assert!(
9363            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
9364                .await
9365                .unwrap_err()
9366                .to_string()
9367                .contains("PR closed or merged")
9368        );
9369    }
9370
9371    /// A candidate selected by the uncontested tally.
9372    fn winning_candidate(summary: &str) -> Candidate {
9373        Candidate {
9374            index: 0,
9375            label: 'A',
9376            agent: "opus".to_owned(),
9377            branch: "magi/x/A".to_owned(),
9378            worktree: PathBuf::from("/wt/A"),
9379            summary: summary.to_owned(),
9380            stat: String::new(),
9381            files: 1,
9382            commits: 1,
9383            empty: false,
9384            failed: None,
9385            verified_noop: None,
9386            duration_ms: 0,
9387            folded: false,
9388        }
9389    }
9390
9391    fn uncontested_tally() -> Tally {
9392        Tally {
9393            first_choice: BTreeMap::from([('A', 1)]),
9394            borda: BTreeMap::new(),
9395            winner: 'A',
9396            rankings: 1,
9397            unanimous_initial: true,
9398            deliberated: false,
9399            changed_votes: 0,
9400            unanimous_final: true,
9401            tie_break: None,
9402            judges: 1,
9403            present: 1,
9404            quorum: 1,
9405            met_quorum: true,
9406            uncontested: None,
9407        }
9408    }
9409
9410    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
9411        ReviewRecord {
9412            attempts: 0,
9413            reviewer,
9414            agent: agent.to_owned(),
9415            summary: summary.to_owned(),
9416            findings: Vec::new(),
9417            vote: None,
9418            failed: None,
9419            duration_ms: 0,
9420        }
9421    }
9422
9423    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
9424        let answered = reviews.len();
9425        ReviewRound {
9426            round,
9427            head: "abc1234".to_owned(),
9428            verified_head: None,
9429            verified_at: None,
9430            reviews,
9431            e2e: Vec::new(),
9432            verify_retried: false,
9433            e2e_deferred: false,
9434            e2e_defer_reason: None,
9435            fix: None,
9436            blocking: 0,
9437            answered,
9438            expected: answered,
9439            clean: true,
9440            progressed: false,
9441            vote_split: false,
9442            reconsideration: Vec::new(),
9443            verdict: None,
9444        }
9445    }
9446
9447    #[test]
9448    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
9449        let en = panel();
9450        assert!(en.contains("Task"), "{en}");
9451        assert!(en.contains("add retries to the uploader"), "{en}");
9452
9453        let mut state = run_state();
9454        state.config.graph.language = "ja".to_owned();
9455        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9456        assert!(ja.contains("タスク"), "{ja}");
9457        assert!(
9458            ja.contains("add retries to the uploader"),
9459            "the task itself is not translated: {ja}"
9460        );
9461    }
9462
9463    #[test]
9464    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
9465        // `run_state()` has no candidates, no tally and no reviews - exactly
9466        // the shape a run has before anything has judged or reviewed it, and
9467        // the panel must not print an empty box for either.
9468        let html = panel();
9469        assert!(!html.contains("What changed"), "{html}");
9470        assert!(!html.contains("Review verdict"), "{html}");
9471    }
9472
9473    #[test]
9474    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
9475        let mut state = run_state();
9476        state.candidates = vec![winning_candidate("")];
9477        state.tally = Some(uncontested_tally());
9478        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9479        assert!(
9480            !html.contains("What changed"),
9481            "an empty summary must not render an empty box: {html}"
9482        );
9483    }
9484
9485    #[test]
9486    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
9487        let mut state = run_state();
9488        state.candidates = vec![winning_candidate(
9489            "Added a retry loop around the uploader PUT call.",
9490        )];
9491        state.tally = Some(uncontested_tally());
9492        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9493        assert!(en.contains("What changed"), "{en}");
9494        assert!(
9495            en.contains("Added a retry loop around the uploader PUT call."),
9496            "{en}"
9497        );
9498
9499        state.config.graph.language = "ja".to_owned();
9500        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9501        assert!(ja.contains("変更内容"), "{ja}");
9502        assert!(
9503            ja.contains("Added a retry loop around the uploader PUT call."),
9504            "{ja}"
9505        );
9506    }
9507
9508    #[test]
9509    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
9510        let mut state = run_state();
9511        state.reviews = vec![
9512            review_round(
9513                1,
9514                vec![review_record(1, "alpha", "found a race, sent back")],
9515            ),
9516            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
9517        ];
9518        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9519        assert!(en.contains("Review verdict"), "{en}");
9520        assert!(en.contains("race is fixed, clean"), "{en}");
9521        assert!(
9522            !en.contains("found a race, sent back"),
9523            "only the round that actually cleared the merge should show: {en}"
9524        );
9525
9526        state.config.graph.language = "ja".to_owned();
9527        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9528        assert!(ja.contains("レビューの結論"), "{ja}");
9529        assert!(ja.contains("レビュアー"), "{ja}");
9530        assert!(ja.contains("race is fixed, clean"), "{ja}");
9531    }
9532
9533    /// The `incomplete_review = "warn"` policy (see
9534    /// `graph::Runner::review_loop`) can push a `clean` round to
9535    /// `state.reviews` while one seat's own record still has `failed: Some`
9536    /// and an empty `summary` - a seat that never answered, not one that
9537    /// answered with nothing to say.
9538    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
9539        ReviewRecord {
9540            attempts: 0,
9541            reviewer,
9542            agent: agent.to_owned(),
9543            summary: String::new(),
9544            findings: Vec::new(),
9545            vote: None,
9546            failed: Some(reason.to_owned()),
9547            duration_ms: 0,
9548        }
9549    }
9550
9551    #[test]
9552    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
9553        let mut state = run_state();
9554        state.reviews = vec![review_round(
9555            1,
9556            vec![
9557                review_record(1, "alpha", "clean, nothing to add"),
9558                unanswered_review_record(2, "beta", "timed out"),
9559            ],
9560        )];
9561        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9562        assert!(en.contains("clean, nothing to add"), "{en}");
9563        assert!(
9564            en.contains("produced no answer: timed out"),
9565            "a seat that never answered must say so, not render a blank box: {en}"
9566        );
9567        assert!(
9568            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
9569            "no reviewer box may be left empty: {en}"
9570        );
9571
9572        state.config.graph.language = "ja".to_owned();
9573        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9574        assert!(ja.contains("回答なし: timed out"), "{ja}");
9575    }
9576
9577    #[test]
9578    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
9579        let html = panel();
9580        assert!(!html.contains("<script"), "no script survives the csp");
9581        assert!(!html.contains("<form"), "form-action is 'none'");
9582        let pr = green_pr();
9583        assert_eq!(
9584            html.matches("http").count(),
9585            html.matches(pr.url.as_str()).count(),
9586            "the only http url in the panel is the pull request's own link"
9587        );
9588        assert!(
9589            html.contains("target=\"_blank\""),
9590            "the PR link must open in a new tab so it escapes the iframe"
9591        );
9592        assert!(
9593            html.contains("rel=\"noopener noreferrer\""),
9594            "external links opening in new tabs must carry noopener noreferrer"
9595        );
9596    }
9597
9598    #[test]
9599    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
9600        let html = panel();
9601        assert!(
9602            html.contains(">+</span>"),
9603            "an added line carries a `+` in the gutter, not only a background"
9604        );
9605        assert!(
9606            html.contains(">-</span>"),
9607            "a removed line carries a `-` in the gutter, not only a background"
9608        );
9609        assert!(
9610            html.contains(">new line</span>"),
9611            "the marker is moved to the gutter, so the body is printed once without it"
9612        );
9613    }
9614
9615    #[test]
9616    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
9617        let total = DIFF_MAX_LINES + 100;
9618        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
9619        let html = approval_panel(
9620            &run_state(),
9621            &green_pr(),
9622            NUMSTAT,
9623            &diff,
9624            &[],
9625            "feat: something long",
9626        );
9627        assert!(
9628            html.contains(&format!("100 of {total} diff lines omitted")),
9629            "the note must say exactly how much was cut"
9630        );
9631        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
9632        assert!(
9633            !html.contains(&format!("line {DIFF_MAX_LINES}")),
9634            "nothing past the threshold is rendered"
9635        );
9636        assert!(
9637            html.contains("/repo/magi"),
9638            "the note says where the rest is"
9639        );
9640    }
9641
9642    #[test]
9643    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
9644        let html = approval_panel(
9645            &run_state(),
9646            &green_pr(),
9647            "1\t2\tsrc/<b>&\"x\"'.rs",
9648            "",
9649            &[],
9650            "subject",
9651        );
9652        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
9653        assert!(
9654            !html.contains("<b>"),
9655            "an agent-influenced path must never become markup"
9656        );
9657    }
9658
9659    #[tokio::test]
9660    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
9661        let a = std::path::PathBuf::from("/repo/a");
9662        let b = std::path::PathBuf::from("/repo/b");
9663
9664        let held = repo_merge_lock(&a).lock_owned().await;
9665
9666        // A second, concurrent land run against the *same* repository must
9667        // wait - `try_lock` fails while `held` is alive.
9668        assert!(
9669            repo_merge_lock(&a).try_lock().is_err(),
9670            "a second merge into the same repository must not proceed concurrently"
9671        );
9672
9673        // A run against a *different* repository must not be blocked by it -
9674        // this is what keeps a slow rebase or `gh pr merge` in one
9675        // repository from also stalling a land-approval resume in another.
9676        assert!(
9677            repo_merge_lock(&b).try_lock().is_ok(),
9678            "a different repository's merge lock must be independent"
9679        );
9680
9681        drop(held);
9682        assert!(
9683            repo_merge_lock(&a).try_lock().is_ok(),
9684            "the lock is released once the holder is done"
9685        );
9686    }
9687
9688    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
9689        let mut state = landing_state();
9690        let mut rec = review_record(1, "alpha", "precise rejection reason");
9691        rec.vote = Some(if reject {
9692            crate::verdict::ReviewVote::Reject
9693        } else {
9694            crate::verdict::ReviewVote::Approve
9695        });
9696        if major {
9697            rec.findings = contested().findings;
9698        }
9699        let mut round = review_round(1, vec![rec]);
9700        round.clean = false;
9701        round.blocking = usize::from(major);
9702        state.reviews.push(round);
9703        state.config.graph.review_rounds = 1;
9704        state
9705    }
9706
9707    #[test]
9708    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
9709        for every in [false, true] {
9710            for contested in [false, true] {
9711                for major in [false, true] {
9712                    for reject in [false, true] {
9713                        let mut state = repair_state(major, reject);
9714                        state.config.graph.land_approval = every;
9715                        state.config.graph.hold_contested_merge = contested;
9716                        let reasons = approval_reasons(&state);
9717                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
9718                        assert_eq!(
9719                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
9720                            contested && major
9721                        );
9722                        assert_eq!(
9723                            reasons.contains(&ApprovalReason::FinalReject),
9724                            contested && reject
9725                        );
9726                        assert_eq!(
9727                            reasons.len(),
9728                            usize::from(every)
9729                                + usize::from(contested && major)
9730                                + usize::from(contested && reject)
9731                        );
9732                    }
9733                }
9734            }
9735        }
9736    }
9737
9738    #[test]
9739    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
9740        use crate::verdict::ReviewVote::{Approve, Reject};
9741        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
9742            let mut state = repair_state(false, initial_reject);
9743            state.reviews[0]
9744                .reconsideration
9745                .push(crate::run::ReviewRevoteRecord {
9746                    reviewer: 1,
9747                    agent: "alpha".into(),
9748                    vote: Some(final_vote),
9749                    reason: "changed after reading the panel <evidence>".into(),
9750                    failed: None,
9751                });
9752            assert_eq!(
9753                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9754                final_vote == Reject
9755            );
9756            for language in ["en", "ja"] {
9757                state.config.graph.language = language.into();
9758                let evidence = approval_evidence(&state);
9759                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
9760                assert!(evidence.contains("changed after reading the panel <evidence>"));
9761                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9762                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
9763                assert!(!html.contains("<evidence>"));
9764            }
9765            state.reviews[0].reconsideration[0].vote = None;
9766            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
9767            assert_eq!(
9768                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9769                initial_reject
9770            );
9771            assert!(approval_evidence(&state).contains("timed out"));
9772        }
9773    }
9774
9775    #[tokio::test]
9776    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
9777        for every in [false, true] {
9778            for contested in [false, true] {
9779                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
9780                {
9781                    let mut state = repair_state(major, reject);
9782                    state.config.graph.land_approval = every;
9783                    state.config.graph.hold_contested_merge = contested;
9784                    let forge = Scripted::new(
9785                        vec![seen("abc", Checks::Green, "CLEAN", false)],
9786                        vec![(true, "")],
9787                    );
9788                    land_with(&mut state, URL, &forge).await.unwrap();
9789                    let expected = every || (contested && (major || reject));
9790                    assert_eq!(state.land_approval.is_some(), expected);
9791                    assert_eq!(forge.calls().contains(&"merge"), !expected);
9792                    if expected {
9793                        assert!(state.parked);
9794                    }
9795                }
9796            }
9797        }
9798    }
9799
9800    #[tokio::test]
9801    async fn reviewed_branch_hold_is_read_before_landing_decision() {
9802        for (base, control) in [
9803            (false, "land_approval"),
9804            (true, "land_approval"),
9805            (false, "hold_contested_merge"),
9806        ] {
9807            let (_tmp, mut state, _) = landing_git_fixture().await;
9808            state.config.graph.land_approval = base;
9809            state.config.graph.hold_contested_merge = false;
9810            state.reviewed_commits = Some(Vec::new());
9811            if control == "hold_contested_merge" {
9812                state.reviews = repair_state(false, true).reviews;
9813            }
9814            std::fs::write(
9815                state.repo.join("magi.toml"),
9816                format!("[graph]\n{control} = {}\n", !base),
9817            )
9818            .unwrap();
9819            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
9820            git::git(&state.repo, &["commit", "-m", "approval policy"])
9821                .await
9822                .unwrap();
9823            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9824            state.land_sync_pending = false;
9825            state.pr_pushed_head = Some(head.clone());
9826            state.gate_head = Some(head.clone());
9827            let forge = Scripted::new(
9828                vec![seen(&head, Checks::Green, "CLEAN", false)],
9829                vec![(true, "")],
9830            );
9831            land_with(&mut state, URL, &forge).await.unwrap();
9832            assert!(
9833                state.land_approval.is_some(),
9834                "base={base}, control={control}"
9835            );
9836            assert!(!forge.calls().contains(&"merge"));
9837            if !base {
9838                let question = ask::Questions::open()
9839                    .get(&state.land_approval.as_ref().unwrap().question)
9840                    .unwrap();
9841                assert!(question.detail.contains(&format!(
9842                    "{control}=true from the reviewed branch's magi.toml"
9843                )));
9844            }
9845        }
9846    }
9847
9848    #[tokio::test]
9849    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9850        for file in ["magi.toml", ".magi/config.toml"] {
9851            for control in crate::config::OwnerHold::ALL {
9852                let (_tmp, mut state, _) = landing_git_fixture().await;
9853                state.config.graph.land_approval = false;
9854                state.config.graph.hold_contested_merge = false;
9855                state.reviewed_commits = Some(Vec::new());
9856                if control == crate::config::OwnerHold::HoldContestedMerge {
9857                    state.reviews = repair_state(false, true).reviews;
9858                }
9859                let config = state.repo.join(file);
9860                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9861                std::fs::write(
9862                    &config,
9863                    format!(
9864                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9865                        control.key()
9866                    ),
9867                )
9868                .unwrap();
9869                git::git(&state.repo, &["add", file]).await.unwrap();
9870                git::git(&state.repo, &["commit", "-m", "require approval"])
9871                    .await
9872                    .unwrap();
9873                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9874                let gate = state.config.verify.gate.clone();
9875                state.observe_branch_owner_holds(&head).await;
9876                assert_eq!(state.config.verify.gate, gate);
9877                assert!(state.owner_hold(control));
9878                let holds = state.branch_owner_holds.clone();
9879                git::git(&state.repo, &["rm", file]).await.unwrap();
9880                git::git(&state.repo, &["commit", "-m", "remove config"])
9881                    .await
9882                    .unwrap();
9883                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9884                state.save().unwrap();
9885                state = RunState::load(&state.id).unwrap();
9886                state.observe_branch_owner_holds(&later).await;
9887                assert_eq!(state.branch_owner_holds, holds);
9888                assert_eq!(state.branch_owner_holds[0].head, head);
9889                state.land_sync_pending = false;
9890                state.pr_pushed_head = Some(later.clone());
9891                state.gate_head = Some(later.clone());
9892                let forge = Scripted::new(
9893                    vec![seen(&later, Checks::Green, "CLEAN", false)],
9894                    vec![(true, "")],
9895                );
9896                land_with(&mut state, URL, &forge).await.unwrap();
9897                assert!(!forge.calls().contains(&"merge"));
9898                assert!(state.parked);
9899                let question = ask::Questions::open()
9900                    .get(&state.land_approval.as_ref().unwrap().question)
9901                    .unwrap();
9902                assert!(question.detail.contains("Approval required because:"));
9903                assert!(question.detail.contains(&format!(
9904                    "{}=true from the reviewed branch's {file}",
9905                    control.key()
9906                )));
9907                assert_eq!(state.branch_owner_holds, holds);
9908                state.save().unwrap();
9909                let resumed = RunState::load(&state.id).unwrap();
9910                assert!(resumed.owner_hold(control));
9911                assert_eq!(resumed.branch_owner_holds, holds);
9912                assert_eq!(
9913                    resumed.land_approval.unwrap().question,
9914                    state.land_approval.unwrap().question
9915                );
9916            }
9917        }
9918    }
9919
9920    #[tokio::test]
9921    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9922        let mut state = repair_state(false, true);
9923        state.reviews[0].clean = true;
9924        let mut finding = contested().findings.remove(0);
9925        finding.severity = crate::verdict::Severity::Minor;
9926        state.reviews[0].reviews[0].findings.push(finding);
9927        assert!(state.open_findings().is_empty());
9928        let mut pr = green_pr();
9929        pr.review_comments.clear();
9930        for language in ["en", "ja"] {
9931            state.config.graph.language = language.into();
9932            let html = approval_panel(&state, &pr, "", "", &[], "subject");
9933            assert!(html.contains("[R3-1-1] minor"));
9934            assert!(html.contains(if language == "ja" {
9935                "内部指摘の解決を意味するものではありません"
9936            } else {
9937                "This does not mean internal findings are resolved"
9938            }));
9939            assert!(
9940                html.find(if language == "ja" {
9941                    "承認が必要な理由:"
9942                } else {
9943                    "Approval required because:"
9944                })
9945                .unwrap()
9946                    < html.find("[R3-1-1]").unwrap()
9947            );
9948        }
9949        state.config.graph.language = "en".into();
9950        let observed = seen("abc", Checks::Green, "CLEAN", false);
9951        assert_eq!(
9952            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9953                .await
9954                .unwrap(),
9955            ApprovalGate::Pending
9956        );
9957        let id = state.land_approval.as_ref().unwrap().question.clone();
9958        let q = ask::Questions::open().get(&id).unwrap();
9959        assert!(q.detail.starts_with("Approval required because:"));
9960        assert!(q.detail.contains("final reviewer reject"));
9961        assert!(q.detail.contains("[R3-1-1] minor"));
9962        assert!(
9963            q.detail
9964                .contains("No adoption or resolution evidence recorded")
9965        );
9966        state.config.graph.land_approval = false;
9967        state.config.graph.hold_contested_merge = false;
9968        state.reviews.clear();
9969        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9970        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9971        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9972        let forge = Scripted::new(vec![observed], vec![]);
9973        land_with(&mut state, URL, &forge).await.unwrap();
9974        assert!(!forge.calls().contains(&"merge"));
9975        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9976        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9977    }
9978
9979    #[tokio::test]
9980    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9981        let mut state = repair_state(false, true);
9982        state.config.graph.land_approval = false;
9983        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9984        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9985        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9986        state.reviews[0].reviews[0].summary = long_reason.clone();
9987        for i in 1..=10 {
9988            let mut finding = contested().findings.remove(0);
9989            finding.id = format!("R1-1-{i}");
9990            finding.severity = if i == 9 {
9991                crate::verdict::Severity::Major
9992            } else {
9993                crate::verdict::Severity::Minor
9994            };
9995            finding.title = long_title.clone();
9996            finding.detail = long_detail.clone();
9997            state.reviews[0].reviews[0].findings.push(finding);
9998        }
9999        state.reviews[0].fix = Some(crate::run::FixRecord {
10000            agent: "fixer".into(),
10001            addressed: vec!["R1-1-9".into()],
10002            rejected: vec![crate::verdict::Rejection {
10003                id: "R1-1-10".into(),
10004                why: long_reason.clone(),
10005            }],
10006            notes: long_detail.clone(),
10007            committed: false,
10008            failed: None,
10009            duration_ms: 0,
10010            continuation: None,
10011        });
10012        assert_eq!(
10013            approval_reasons(&state),
10014            [
10015                ApprovalReason::OpenBlockingFindings,
10016                ApprovalReason::FinalReject
10017            ]
10018        );
10019        let excerpt = approval_excerpt(&long_reason, 300);
10020        assert_eq!(excerpt.chars().count(), 300);
10021        assert!(excerpt.ends_with('…'));
10022        let boundary = "拒".repeat(300);
10023        assert_eq!(approval_excerpt(&boundary, 300), boundary);
10024        for language in ["en", "ja"] {
10025            state.config.graph.language = language.into();
10026            for revote in [
10027                None,
10028                Some(crate::verdict::ReviewVote::Reject),
10029                Some(crate::verdict::ReviewVote::Approve),
10030            ] {
10031                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
10032                state.reviews[0].reconsideration.clear();
10033                if let Some(vote) = revote {
10034                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
10035                    state.reviews[0]
10036                        .reconsideration
10037                        .push(crate::run::ReviewRevoteRecord {
10038                            reviewer: 1,
10039                            agent: "alpha".into(),
10040                            vote: Some(vote),
10041                            reason: long_reason.clone(),
10042                            failed: None,
10043                        });
10044                }
10045                let evidence = approval_evidence(&state);
10046                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
10047                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
10048                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
10049                assert_eq!(
10050                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
10051                    final_vote == crate::verdict::ReviewVote::Reject
10052                );
10053                assert!(evidence.contains(&excerpt));
10054                assert!(evidence.contains("[R1-1-8] minor"));
10055                assert!(evidence.contains("[R1-1-9] major"));
10056                assert!(evidence.contains("[R1-1-10] minor"));
10057                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
10058                    assert!(!evidence.contains(tail));
10059                }
10060                assert!(evidence.contains(if language == "ja" {
10061                    "採用申告(解決未確認)"
10062                } else {
10063                    "claimed addressed (resolution unconfirmed)"
10064                }));
10065                assert!(evidence.contains(if language == "ja" {
10066                    "不採用理由"
10067                } else {
10068                    "declined"
10069                }));
10070                let major_evidence = evidence
10071                    .split("[R1-1-9] major")
10072                    .nth(1)
10073                    .unwrap()
10074                    .split("[R1-1-10]")
10075                    .next()
10076                    .unwrap();
10077                assert!(major_evidence.contains(if language == "ja" {
10078                    "採用申告(解決未確認)"
10079                } else {
10080                    "claimed addressed (resolution unconfirmed)"
10081                }));
10082                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
10083                assert!(last_evidence.contains(if language == "ja" {
10084                    "不採用理由"
10085                } else {
10086                    "declined"
10087                }));
10088                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
10089                assert!(html.contains(&esc(&evidence)));
10090                assert_eq!(
10091                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
10092                        .await
10093                        .unwrap(),
10094                    ApprovalGate::Pending
10095                );
10096                let id = &state.land_approval.take().unwrap().question;
10097                let q = ask::Questions::open().get(id).unwrap();
10098                assert!(q.detail.starts_with(&evidence));
10099            }
10100            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
10101        }
10102    }
10103
10104    #[test]
10105    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
10106        for (major, reject) in [(true, false), (false, true), (true, true)] {
10107            let state = repair_state(major, reject);
10108            assert!(repair_available(&state));
10109            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
10110        }
10111        assert!(!repair_available(&repair_state(false, false)));
10112        let mut clean = repair_state(true, false);
10113        clean.reviews[0].clean = true;
10114        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
10115        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
10116    }
10117
10118    #[tokio::test]
10119    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
10120        let mut state = repair_state(true, false);
10121        let pr = green_pr();
10122        approval_gate(&mut state, &pr, "feat: x", None, "abc")
10123            .await
10124            .unwrap();
10125        let store = ask::Questions::open();
10126        let id = state.land_approval.as_ref().unwrap().question.clone();
10127        // Simulate an unanswered two-choice question created by an older build.
10128        store
10129            .update(&id, |q| {
10130                q.choices = vec![APPROVE.into(), HOLD.into()];
10131                Ok(())
10132            })
10133            .unwrap();
10134        let upgraded = store.get(&id).unwrap();
10135        assert_eq!(upgraded.choices, approval_choices(&state));
10136        assert!(!upgraded.actions.contains_key(HOLD));
10137        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
10138        assert!(
10139            store
10140                .list()
10141                .iter()
10142                .any(|q| q.id == id && q.choices == upgraded.choices)
10143        );
10144        assert!(
10145            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
10146        );
10147        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
10148        store
10149            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
10150            .unwrap();
10151        // An earlier build may have recorded the repair answer and stopped
10152        // before any driver consumed it. Reconcile that durable decision too.
10153        store
10154            .update(&id, |q| {
10155                q.actions.clear();
10156                Ok(())
10157            })
10158            .unwrap();
10159        assert_eq!(
10160            store.get(&id).unwrap().chosen_action(),
10161            Some(&ask::ChoiceAction::Resume {
10162                run: state.id.clone()
10163            })
10164        );
10165        let binding = state.land_approval.clone();
10166        assert_eq!(
10167            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10168                .await
10169                .unwrap(),
10170            ApprovalGate::Repair
10171        );
10172        assert!(state.land_approval.is_none());
10173        assert_eq!(state.merge_repairs.len(), 1);
10174        let request = &state.merge_repairs[0];
10175        assert_eq!(request.question, id);
10176        assert_eq!(request.head, "abc");
10177        assert_eq!(request.pr, pr.url);
10178        assert_eq!(
10179            request.reviews[0].reviews[0].summary,
10180            "precise rejection reason"
10181        );
10182        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
10183        assert_eq!(
10184            request.reviews[0].reviews[0].findings[0].detail,
10185            state.reviews[0].reviews[0].findings[0].detail
10186        );
10187        // A repeated consumption of the same answer never dispatches another repair.
10188        state.land_approval = binding;
10189        assert_eq!(
10190            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10191                .await
10192                .unwrap(),
10193            ApprovalGate::Repair
10194        );
10195        assert_eq!(state.merge_repairs.len(), 1);
10196        state.land_approval = None;
10197        state.config.graph.land_approval = false;
10198        state.config.graph.hold_contested_merge = false;
10199        state.reviews.clear();
10200        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
10201        assert_eq!(
10202            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10203                .await
10204                .unwrap(),
10205            ApprovalGate::Pending
10206        );
10207        let fresh_id = &state.land_approval.as_ref().unwrap().question;
10208        assert_ne!(fresh_id, &id);
10209        let fresh = store.get(fresh_id).unwrap();
10210        assert!(
10211            fresh
10212                .detail
10213                .contains("fresh owner approval after merge repair")
10214        );
10215        assert!(fresh.detail.contains("No review recorded"));
10216        assert!(!fresh.detail.contains("precise rejection reason"));
10217    }
10218
10219    #[tokio::test]
10220    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
10221        for choice in [REPAIR, HOLD] {
10222            let mut state = repair_state(false, true);
10223            let observed = seen("abc", Checks::Green, "CLEAN", false);
10224            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
10225                .await
10226                .unwrap();
10227            let id = state.land_approval.as_ref().unwrap().question.clone();
10228            ask::Questions::open()
10229                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
10230                .unwrap();
10231            let forge = Scripted::new(vec![observed], vec![(true, "")]);
10232            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10233                .await
10234                .unwrap();
10235            assert!(
10236                forge
10237                    .argvs()
10238                    .iter()
10239                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
10240            );
10241            assert!(!forge.calls().contains(&"fix"));
10242            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
10243            assert_ne!(state.status, RunStatus::Merged);
10244        }
10245    }
10246
10247    #[test]
10248    fn only_the_merge_choice_merges_and_silence_holds() {
10249        let table = [
10250            (None, Approval::Hold),
10251            (Some("merge"), Approval::Merge),
10252            (Some(" merge\n"), Approval::Merge),
10253            (Some("hold"), Approval::Hold),
10254            (Some(""), Approval::Hold),
10255            (Some("yes"), Approval::Hold),
10256        ];
10257        for (answer, want) in table {
10258            assert_eq!(
10259                approval(answer),
10260                want,
10261                "answer {answer:?} must resolve to {want:?}"
10262            );
10263        }
10264    }
10265
10266    #[tokio::test]
10267    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
10268        let mut state = landing_state();
10269        state.config.graph.land_approval = true;
10270        let pr = green_pr();
10271
10272        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
10273            .await
10274            .unwrap();
10275        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
10276        assert!(
10277            !state.parked,
10278            "approval_gate itself never sets `parked`; only its caller does"
10279        );
10280
10281        let store = ask::Questions::open();
10282        let filed: Vec<_> = store
10283            .list()
10284            .into_iter()
10285            .filter(|q| q.run == state.id)
10286            .collect();
10287        assert_eq!(filed.len(), 1, "exactly one question is filed");
10288        assert_eq!(filed[0].node, APPROVAL_NODE);
10289        assert_eq!(filed[0].choices, approval_choices(&state));
10290        assert!(filed[0].status.open());
10291
10292        // A second visit - standing in for a resumed run whose slot the
10293        // daemon handed to something else while nobody had answered - must
10294        // find the same question rather than filing a second one.
10295        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
10296            .await
10297            .unwrap();
10298        assert_eq!(again, ApprovalGate::Pending);
10299        let still_one = store
10300            .list()
10301            .into_iter()
10302            .filter(|q| q.run == state.id)
10303            .count();
10304        assert_eq!(
10305            still_one, 1,
10306            "asking twice must not double-file the question"
10307        );
10308    }
10309
10310    #[tokio::test]
10311    async fn approving_the_existing_question_is_read_back_as_approved() {
10312        crate::run::pin_test_home();
10313        let mut state = run_state();
10314        state.config.graph.land_approval = true;
10315        let pr = green_pr();
10316        assert_eq!(
10317            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10318                .await
10319                .unwrap(),
10320            ApprovalGate::Pending
10321        );
10322
10323        let store = ask::Questions::open();
10324        let mut q = store
10325            .list()
10326            .into_iter()
10327            .find(|q| q.run == state.id)
10328            .expect("filed above");
10329        let talks = crate::talk::Talks::open();
10330        let cfg = crate::config::Config {
10331            agents: vec![crate::config::AgentSpec {
10332                id: "mock".into(),
10333                kind: crate::config::AgentKind::Command,
10334                model: None,
10335                command: vec!["true".into()],
10336                extra_args: Vec::new(),
10337                env: Default::default(),
10338                prompt_delivery: None,
10339                max_turn_secs: None,
10340            }],
10341            ..crate::config::Config::default()
10342        };
10343        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
10344        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
10345        crate::talk::drain(&mut talk, &talks).unwrap();
10346        assert_eq!(
10347            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10348                .await
10349                .unwrap(),
10350            ApprovalGate::Pending,
10351            "consultation cannot approve or hold the merge"
10352        );
10353        q = store.get(&q.id).unwrap();
10354        assert!(q.answer.is_none());
10355        // The owner's merge answer (from the chat or the card) is the approval.
10356        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10357        store.put(&mut q).unwrap();
10358
10359        assert_eq!(
10360            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10361                .await
10362                .unwrap(),
10363            ApprovalGate::Approved
10364        );
10365    }
10366
10367    #[tokio::test]
10368    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
10369        crate::run::pin_test_home();
10370        let store = ask::Questions::open();
10371        for via_list in [false, true] {
10372            let mut state = repair_state(false, true);
10373            let pr = green_pr();
10374            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10375                .await
10376                .unwrap();
10377            let id = state.land_approval.as_ref().unwrap().question.clone();
10378            store
10379                .update(&id, |q| {
10380                    q.actions.insert(
10381                        HOLD.to_owned(),
10382                        ask::ChoiceAction::Resume {
10383                            run: state.id.clone(),
10384                        },
10385                    );
10386                    Ok(())
10387                })
10388                .unwrap();
10389            let q = if via_list {
10390                store.list().into_iter().find(|q| q.id == id).unwrap()
10391            } else {
10392                store.get(&id).unwrap()
10393            };
10394            assert!(!q.actions.contains_key(HOLD));
10395            store
10396                .update(&id, |q| {
10397                    // Check the persisted migration, without another read upgrade.
10398                    assert!(!q.actions.contains_key(HOLD));
10399                    assert!(!upgrade_repair_choice(q, &state));
10400                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
10401                })
10402                .unwrap();
10403            assert!(store.get(&id).unwrap().chosen_action().is_none());
10404            assert_eq!(
10405                approval_gate(&mut state, &pr, "feat: x", None, "abc")
10406                    .await
10407                    .unwrap(),
10408                ApprovalGate::Held
10409            );
10410        }
10411    }
10412
10413    #[tokio::test]
10414    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
10415        crate::run::pin_test_home();
10416        let store = ask::Questions::open();
10417
10418        let mut held_state = run_state();
10419        held_state.config.graph.land_approval = true;
10420        let pr = green_pr();
10421        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
10422            .await
10423            .unwrap();
10424        let mut q = store
10425            .list()
10426            .into_iter()
10427            .find(|q| q.run == held_state.id)
10428            .expect("filed above");
10429        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
10430        store.put(&mut q).unwrap();
10431        assert_eq!(
10432            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
10433                .await
10434                .unwrap(),
10435            ApprovalGate::Held
10436        );
10437
10438        let mut abandoned_state = run_state();
10439        abandoned_state.config.graph.land_approval = true;
10440        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
10441            .await
10442            .unwrap();
10443        let mut q = store
10444            .list()
10445            .into_iter()
10446            .find(|q| q.run == abandoned_state.id)
10447            .expect("filed above");
10448        q.abandon("no answer within the timeout");
10449        store.put(&mut q).unwrap();
10450        assert_eq!(
10451            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
10452                .await
10453                .unwrap(),
10454            ApprovalGate::Pending,
10455            "an expired approval must ask again without merging"
10456        );
10457        assert_eq!(
10458            store.get(&q.id).unwrap().status,
10459            ask::QuestionStatus::Abandoned
10460        );
10461        assert_ne!(
10462            abandoned_state.land_approval.as_ref().unwrap().question,
10463            q.id
10464        );
10465    }
10466
10467    fn contested() -> ContestedHandoff {
10468        let finding = |id: &str, n: u32| crate::verdict::Finding {
10469            id: id.to_owned(),
10470            severity: crate::verdict::Severity::Major,
10471            file: Some("src/a.rs".to_owned()),
10472            line: Some(n),
10473            title: format!("problem {id}"),
10474            detail: String::new(),
10475        };
10476        ContestedHandoff {
10477            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
10478            rejecters: vec![(1, "alpha".to_owned())],
10479        }
10480    }
10481
10482    #[test]
10483    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
10484        let mut state = run_state();
10485        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
10486        state.contested_handoff = Some(contested());
10487        assert!(contested_to_ask(&state).is_some());
10488        state.config.graph.hold_contested_merge = false;
10489        assert!(
10490            contested_to_ask(&state).is_none(),
10491            "the switch restores today"
10492        );
10493    }
10494
10495    #[test]
10496    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
10497        let q = ask::Question::new(
10498            "run-1".to_owned(),
10499            APPROVAL_NODE.to_owned(),
10500            "land".to_owned(),
10501            "Merge?".to_owned(),
10502            String::new(),
10503            vec![APPROVE.to_owned(), HOLD.to_owned()],
10504        );
10505        let none = deputy_brief(&q, None);
10506        assert!(none.contains("could not be read"), "{none}");
10507        assert!(none.contains("Silence is a hold"), "{none}");
10508
10509        let mut state = run_state();
10510        state.pr = Some(crate::run::PrRecord {
10511            url: "https://example.test/pull/7".to_owned(),
10512            number: 7,
10513            state: "open".to_owned(),
10514            checks: "green".to_owned(),
10515            round: 0,
10516            rounds: 3,
10517            red_at_merge: Vec::new(),
10518        });
10519        state.contested_handoff = Some(contested());
10520        let b = deputy_brief(&q, Some(&state));
10521        assert!(b.contains("https://example.test/pull/7"), "{b}");
10522        assert!(b.contains("not recorded in this legacy question"), "{b}");
10523        assert!(!b.contains("This question was filed although"));
10524        state.contested_handoff = None;
10525        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
10526    }
10527
10528    #[test]
10529    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
10530        for lang in ["en", "ja"] {
10531            let mut cfg = crate::config::Config::default();
10532            cfg.graph.language = lang.to_owned();
10533            let w = words(&cfg.graph.language);
10534            let text = w.approval_detail(
10535                "https://github.com/yukimemi/magi/pull/42",
10536                "main",
10537                "feat: x",
10538                Some(&contested()),
10539            );
10540            assert!(text.contains("pull/42"), "{text}");
10541            assert!(
10542                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
10543                "{text}"
10544            );
10545            assert!(text.contains("R3-1-5"), "{text}");
10546            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
10547            assert!(text.contains("2"), "the rest are counted: {text}");
10548            assert!(text.contains("#1 (alpha)"), "{text}");
10549        }
10550        let plain = words("en").approval_detail("u", "main", "s", None);
10551        assert!(!plain.contains("reject"), "{plain}");
10552    }
10553
10554    #[tokio::test]
10555    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
10556        crate::run::pin_test_home();
10557        let mut state = run_state();
10558        state.config.graph.land_approval = false;
10559        state.contested_handoff = Some(contested());
10560        let pr = green_pr();
10561        let c = contested_to_ask(&state);
10562        assert_eq!(
10563            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10564                .await
10565                .unwrap(),
10566            ApprovalGate::Pending,
10567            "silence is a hold"
10568        );
10569        let store = ask::Questions::open();
10570        let filed: Vec<_> = store
10571            .list()
10572            .into_iter()
10573            .filter(|q| q.run == state.id)
10574            .collect();
10575        assert_eq!(filed.len(), 1);
10576        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
10577
10578        assert_eq!(
10579            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10580                .await
10581                .unwrap(),
10582            ApprovalGate::Pending
10583        );
10584        let mut q = store
10585            .list()
10586            .into_iter()
10587            .find(|q| q.run == state.id)
10588            .unwrap();
10589        assert_eq!(q.id, filed[0].id, "the same question after a resume");
10590        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10591        store.put(&mut q).unwrap();
10592        assert_eq!(
10593            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10594                .await
10595                .unwrap(),
10596            ApprovalGate::Approved
10597        );
10598    }
10599
10600    #[test]
10601    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
10602        let rows = parse_numstat(NUMSTAT);
10603        assert_eq!(
10604            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
10605            ["src/web.rs", "src/land.rs", "assets/logo.png"]
10606        );
10607        assert_eq!(rows[2].added, None, "a binary file has no line counts");
10608    }
10609    #[test]
10610    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
10611        // Reported from a real run: the merge question arrived in English on a
10612        // repository with `language = "ja"`. magi's own strings have to follow
10613        // that setting too - "it is a literal in Rust" is not an answer.
10614        let mut state = run_state();
10615        state.config.graph.language = "ja".to_owned();
10616        let pr = green_pr();
10617        let commits = ["c1".to_owned()];
10618
10619        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10620        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
10621        assert!(ja.contains("squash されるコミット"), "{ja}");
10622        assert!(ja.contains("レビューコメント"), "{ja}");
10623        assert!(ja.contains("差分"), "{ja}");
10624        assert!(
10625            !ja.contains("Commits being squashed"),
10626            "no English left over"
10627        );
10628
10629        let w = words("ja");
10630        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
10631        assert!(
10632            w.approval_detail("http://x/1", "main", "feat: x", None)
10633                .contains("パネル")
10634        );
10635
10636        // The evidence itself is language-neutral and must survive either way.
10637        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
10638        assert!(ja.contains("feat: x"), "nor is the merge subject");
10639
10640        // English stays the default, and a language magi cannot check falls
10641        // back to it rather than shipping a guess.
10642        state.config.graph.language = "en".to_owned();
10643        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10644        assert!(en.contains("Commits being squashed"), "{en}");
10645        assert_eq!(words("Klingon").html_lang, "en");
10646    }
10647
10648    /// A `gh pr list` result naming exactly one pull request whose base and
10649    /// merge time both fit the run is exactly the case
10650    /// [`find_external_merge`] exists to act on.
10651    #[test]
10652    fn pick_open_pr_classifies_by_count_and_base() {
10653        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
10654        assert_eq!(
10655            pick_open_pr(one, "main").unwrap(),
10656            OpenPr::One {
10657                url: "https://x/pull/58".into(),
10658                title: "t".into()
10659            }
10660        );
10661        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
10662        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
10663        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
10664                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
10665        assert_eq!(
10666            pick_open_pr(two, "main").unwrap(),
10667            OpenPr::Many(vec!["u1".into(), "u2".into()])
10668        );
10669        // A fork's same-named branch is not a pull request for this head.
10670        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
10671        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
10672        assert!(pick_open_pr("not json", "main").is_err());
10673        // An incomplete record is an error, never "nothing open".
10674        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
10675        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
10676    }
10677
10678    #[test]
10679    fn pick_merged_pr_picks_the_unique_match() {
10680        let json = r#"[
10681            {"url": "https://github.com/o/r/pull/42", "number": 42,
10682             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
10683        ]"#;
10684        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10685        let found = pick_merged_pr(json, "main", created_at)
10686            .expect("valid json")
10687            .expect("one unambiguous match");
10688        assert_eq!(found.url, "https://github.com/o/r/pull/42");
10689        assert_eq!(found.number, 42);
10690    }
10691
10692    /// Two candidates surviving the filter is exactly as uninformative as
10693    /// zero — a branch name can be reused across runs — so neither is
10694    /// preferred over the other and nothing is recorded automatically.
10695    #[test]
10696    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
10697        let json = r#"[
10698            {"url": "https://github.com/o/r/pull/42", "number": 42,
10699             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
10700            {"url": "https://github.com/o/r/pull/43", "number": 43,
10701             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
10702        ]"#;
10703        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10704        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10705        let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
10706        assert!(error.to_string().contains("ambiguous"), "{error:#}");
10707    }
10708
10709    /// A pull request that targets a different base branch cannot be this
10710    /// run's, whatever its head branch is named — a reused branch name from
10711    /// an unrelated task must not be recorded as this run's merge.
10712    #[test]
10713    fn pick_merged_pr_ignores_a_different_base_branch() {
10714        let json = r#"[
10715            {"url": "https://github.com/o/r/pull/42", "number": 42,
10716             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
10717        ]"#;
10718        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10719        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10720    }
10721
10722    /// A pull request merged before this run was even created cannot be this
10723    /// run's winner, no matter how its head branch is spelled.
10724    #[test]
10725    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
10726        let json = r#"[
10727            {"url": "https://github.com/o/r/pull/42", "number": 42,
10728             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
10729        ]"#;
10730        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10731        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10732    }
10733
10734    #[test]
10735    fn slug_of_pr_url_reads_host_owner_and_repo() {
10736        assert_eq!(
10737            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
10738            Some("github.com/yukimemi/shun")
10739        );
10740    }
10741
10742    #[test]
10743    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
10744        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
10745        assert_eq!(slug_of_pr_url("not a url at all"), None);
10746        assert_eq!(slug_of_pr_url("https://github.com"), None);
10747    }
10748
10749    #[test]
10750    fn slug_of_repo_url_reads_host_owner_and_repo() {
10751        assert_eq!(
10752            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
10753            Some("github.com/yukimemi/magi")
10754        );
10755        assert_eq!(slug_of_repo_url("https://github.com"), None);
10756    }
10757
10758    #[test]
10759    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
10760        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
10761            .expect("same repo, different case");
10762    }
10763
10764    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
10765    /// own in-progress run and rewrote its status from a pull request in a
10766    /// completely different repository. This is the guard that must catch
10767    /// that even when an explicit (but wrong) id is given.
10768    #[test]
10769    fn ensure_same_repo_refuses_a_different_repo() {
10770        let err =
10771            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
10772        let msg = format!("{err:#}");
10773        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10774        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
10775    }
10776
10777    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
10778    /// instance mirroring a `github.com` repository's name, say) must not be
10779    /// treated as the same repository just because the trailing path
10780    /// matches.
10781    #[test]
10782    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
10783        let err = ensure_same_repo(
10784            "github.com/yukimemi/magi",
10785            "github.example.com/yukimemi/magi",
10786        )
10787        .unwrap_err();
10788        let msg = format!("{err:#}");
10789        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10790        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
10791    }
10792
10793    /// No winner decided yet means there is no branch to ask GitHub about at
10794    /// all — `find_external_merge` must return `None` without ever spawning
10795    /// `gh`, which this proves by never providing a real repository to spawn
10796    /// it in.
10797    #[tokio::test]
10798    async fn find_external_merge_returns_none_without_a_winner() {
10799        let state = RunState::new(
10800            PathBuf::from("/no/such/repo"),
10801            "main".to_owned(),
10802            "0000000000000000000000000000000000000000".to_owned(),
10803            "irrelevant".to_owned(),
10804            crate::config::Config::default(),
10805        );
10806        assert_eq!(find_external_merge(&state).await.unwrap(), None);
10807    }
10808
10809    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
10810        let mut run = RunState::new(
10811            PathBuf::from(repo),
10812            "main".to_owned(),
10813            "abcdef1234".to_owned(),
10814            "x".to_owned(),
10815            crate::config::Config::default(),
10816        );
10817        run.id = id.to_owned();
10818        run.status = status;
10819        run.driver_exited = true;
10820        run.pr = Some(crate::run::PrRecord {
10821            number: url.rsplit('/').next().unwrap().parse().unwrap(),
10822            url: url.to_owned(),
10823            state: state.to_owned(),
10824            checks: "red".to_owned(),
10825            round: 0,
10826            rounds: 2,
10827            red_at_merge: Vec::new(),
10828        });
10829        run.save_under(home).unwrap();
10830    }
10831
10832    fn recorded(home: &Path, id: &str) -> String {
10833        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10834        serde_json::from_str::<RunState>(&body)
10835            .unwrap()
10836            .pr
10837            .unwrap()
10838            .state
10839    }
10840
10841    const PR: &str = "https://github.com/o/r/pull/7";
10842
10843    #[test]
10844    fn write_through_updates_predecessors_and_siblings_only() {
10845        let tmp = tempfile::tempdir().unwrap();
10846        let h = tmp.path();
10847        pr_run(
10848            h,
10849            "20261004-100000-aaaa",
10850            "/repo/r",
10851            RunStatus::Superseded,
10852            PR,
10853            "open",
10854        );
10855        pr_run(
10856            h,
10857            "20261004-100100-bbbb",
10858            "/repo/r",
10859            RunStatus::Blocked,
10860            PR,
10861            "open",
10862        );
10863        // Not terminal: a driver may be writing it.
10864        pr_run(
10865            h,
10866            "20261004-100200-cccc",
10867            "/repo/r",
10868            RunStatus::Landing,
10869            PR,
10870            "open",
10871        );
10872        // Another repository's pull request with the same number.
10873        pr_run(
10874            h,
10875            "20261004-100300-dddd",
10876            "/repo/other",
10877            RunStatus::Blocked,
10878            "https://github.com/o/other/pull/7",
10879            "open",
10880        );
10881        // A different pull request of the same repository.
10882        pr_run(
10883            h,
10884            "20261004-100400-eeee",
10885            "/repo/r",
10886            RunStatus::Blocked,
10887            "https://github.com/o/r/pull/8",
10888            "open",
10889        );
10890        pr_run(
10891            h,
10892            "20261004-100500-ffff",
10893            "/repo/r",
10894            RunStatus::Merged,
10895            PR,
10896            "open",
10897        );
10898        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10899
10900        assert_eq!(
10901            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10902            2
10903        );
10904        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10905        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10906        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10907        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10908        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10909        // The source's own record is the caller's to write.
10910        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10911        // Idempotent.
10912        assert_eq!(
10913            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10914            0
10915        );
10916        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10917        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10918    }
10919
10920    #[test]
10921    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10922        let home = tempfile::tempdir().unwrap();
10923        let live_id = "20261004-100000-aaaa";
10924        let unknown_id = "20261004-100100-bbbb";
10925        for id in [live_id, unknown_id] {
10926            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10927            let mut s = RunState::load_under(id, home.path()).unwrap();
10928            s.driver_exited = false;
10929            // Model legacy driver evidence, not a newly reserved unstarted run.
10930            s.driver_claimed = None;
10931            if id == live_id {
10932                s.driver_pid = Some(std::process::id());
10933                s.driver_started_at = crate::proc::process_started_at(std::process::id());
10934            }
10935            s.save_under(home.path()).unwrap();
10936            if id == unknown_id {
10937                assert_eq!(
10938                    s.liveness_under(home.path(), false),
10939                    crate::run::Liveness::Unknown
10940                );
10941            }
10942        }
10943        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10944        assert_eq!(apply_pr_states(home.path(), &known), 0);
10945        for id in [live_id, unknown_id] {
10946            assert_eq!(recorded(home.path(), id), "open");
10947        }
10948    }
10949
10950    #[test]
10951    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10952        let tmp = tempfile::tempdir().unwrap();
10953        let h = tmp.path();
10954        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10955        pr_run(
10956            h,
10957            "20261004-100000-aaaa",
10958            "/repo/r",
10959            RunStatus::Superseded,
10960            &url(1),
10961            "open",
10962        );
10963        pr_run(
10964            h,
10965            "20261004-100100-bbbb",
10966            "/repo/r",
10967            RunStatus::Blocked,
10968            &url(2),
10969            "open",
10970        );
10971        pr_run(
10972            h,
10973            "20261004-100200-cccc",
10974            "/repo/r",
10975            RunStatus::Ready,
10976            &url(3),
10977            "open",
10978        );
10979        pr_run(
10980            h,
10981            "20261004-100300-dddd",
10982            "/repo/r",
10983            RunStatus::Ready,
10984            &url(4),
10985            "open",
10986        );
10987        pr_run(
10988            h,
10989            "20261004-100400-eeee",
10990            "/repo/r",
10991            RunStatus::Implementing,
10992            &url(1),
10993            "open",
10994        );
10995        assert_eq!(stale_open_prs(h).len(), 4);
10996
10997        let mut known = BTreeMap::new();
10998        known.insert(url(1), PrLifecycle::Merged);
10999        known.insert(url(2), PrLifecycle::Closed);
11000        known.insert(url(3), PrLifecycle::Open);
11001        // #4: the forge could not be read, so it has no answer.
11002        assert_eq!(apply_pr_states(h, &known), 2);
11003        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
11004        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
11005        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
11006        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
11007        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
11008        assert_eq!(apply_pr_states(h, &known), 0);
11009    }
11010
11011    // --- the land loop against a scripted forge -------------------------
11012
11013    use std::collections::VecDeque;
11014    use std::sync::Mutex;
11015
11016    /// Answers views from a script (the last one repeats), merges from a
11017    /// queue, and records every call so a test can assert the order.
11018    struct Scripted {
11019        public_repo: Option<PathBuf>,
11020        evidence: Mutex<Option<CiEvidence>>,
11021        views: Mutex<VecDeque<Seen>>,
11022        merges: Mutex<VecDeque<(bool, String)>>,
11023        fix: Mutex<Option<Fixed>>,
11024        log: Mutex<Vec<&'static str>>,
11025        argvs: Mutex<Vec<Vec<String>>>,
11026        required: Mutex<Option<BTreeSet<String>>>,
11027        /// Set once a merge answered ok: the forge then reports `merged`,
11028        /// unless `queued` says the merge only entered a queue.
11029        merged: Mutex<bool>,
11030        queued: Mutex<bool>,
11031        /// Views fail once a merge answered ok.
11032        unreadable_after_merge: Mutex<bool>,
11033        /// Workflow runs asked to rerun, and whether that call fails.
11034        reruns: Mutex<Vec<String>>,
11035        rerun_fails: Mutex<bool>,
11036        /// Unix seconds; every poll moves it on by `POLL`.
11037        clock: Mutex<i64>,
11038    }
11039
11040    impl Scripted {
11041        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
11042            Self {
11043                public_repo: None,
11044                evidence: Mutex::new(None),
11045                views: Mutex::new(views.into()),
11046                merges: Mutex::new(
11047                    merges
11048                        .into_iter()
11049                        .map(|(ok, m)| (ok, m.to_owned()))
11050                        .collect(),
11051                ),
11052                fix: Mutex::new(None),
11053                log: Mutex::new(Vec::new()),
11054                argvs: Mutex::new(Vec::new()),
11055                required: Mutex::new(None),
11056                merged: Mutex::new(false),
11057                queued: Mutex::new(false),
11058                unreadable_after_merge: Mutex::new(false),
11059                reruns: Mutex::new(Vec::new()),
11060                rerun_fails: Mutex::new(false),
11061                clock: Mutex::new(1_000),
11062            }
11063        }
11064        fn for_pr(url: &str, mut views: Vec<Seen>) -> Self {
11065            for view in &mut views {
11066                view.pr.url = url.to_owned();
11067            }
11068            Self::new(views, vec![])
11069        }
11070        fn argvs(&self) -> Vec<Vec<String>> {
11071            self.argvs.lock().unwrap().clone()
11072        }
11073        fn calls(&self) -> Vec<&'static str> {
11074            self.log.lock().unwrap().clone()
11075        }
11076    }
11077
11078    impl Forge for Scripted {
11079        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
11080            self.evidence.lock().unwrap().clone()
11081        }
11082        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
11083            self.log.lock().unwrap().push("view");
11084            if *self.unreadable_after_merge.lock().unwrap()
11085                && !self.argvs.lock().unwrap().is_empty()
11086            {
11087                anyhow::bail!("forge unreachable");
11088            }
11089            let mut seen = {
11090                let mut v = self.views.lock().unwrap();
11091                if v.len() > 1 {
11092                    v.pop_front().unwrap()
11093                } else {
11094                    v[0].clone()
11095                }
11096            };
11097            if seen.head == "@published" {
11098                let head =
11099                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
11100                        .await?
11101                        .context("missing published head")?;
11102                seen.head.clone_from(&head);
11103                seen.rollup_head = head;
11104            }
11105            if *self.merged.lock().unwrap() {
11106                seen.pr.state = PrLifecycle::Merged;
11107            }
11108            Ok(seen)
11109        }
11110        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
11111            self.log.lock().unwrap().push("merge");
11112            self.argvs.lock().unwrap().push(argv.to_vec());
11113            let out = self
11114                .merges
11115                .lock()
11116                .unwrap()
11117                .pop_front()
11118                .expect("unscripted merge");
11119            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
11120            {
11121                *self.merged.lock().unwrap() = true;
11122            }
11123            Ok(out)
11124        }
11125        async fn poll(&self) {
11126            self.log.lock().unwrap().push("poll");
11127            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
11128        }
11129        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
11130            self.log.lock().unwrap().push("rerun");
11131            self.reruns.lock().unwrap().push(run.to_owned());
11132            if *self.rerun_fails.lock().unwrap() {
11133                anyhow::bail!("gh run rerun: no");
11134            }
11135            Ok(())
11136        }
11137        fn now(&self) -> i64 {
11138            *self.clock.lock().unwrap()
11139        }
11140        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
11141            self.required.lock().unwrap().clone()
11142        }
11143        async fn fix(
11144            &self,
11145            _state: &mut RunState,
11146            _pr: &PrState,
11147            _round: usize,
11148            _budget: usize,
11149            _reason: &str,
11150            _logs: &str,
11151        ) -> Result<Fixed> {
11152            self.log.lock().unwrap().push("fix");
11153            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
11154        }
11155    }
11156
11157    const REFUSED: &str =
11158        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
11159
11160    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
11161        let mut pr = green_pr();
11162        pr.checks = checks;
11163        pr.blocking = Blocking::of(merge_state);
11164        if !comments {
11165            pr.review_comments.clear();
11166        }
11167        Seen {
11168            pr,
11169            title: "feat: x".to_owned(),
11170            failing_urls: Vec::new(),
11171            head: head.to_owned(),
11172            rollup_head: head.to_owned(),
11173            merge_state: merge_state.to_owned(),
11174            contexts: Vec::new(),
11175            base: "main".to_owned(),
11176        }
11177    }
11178
11179    fn landing_state() -> RunState {
11180        crate::run::pin_test_home();
11181        let mut state = run_state();
11182        state.config.graph.land_approval = false;
11183        state
11184    }
11185
11186    #[test]
11187    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
11188        assert!(!awaiting_new_head(None, "aaa"));
11189        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
11190        assert!(awaiting_new_head(Some("abc123"), "def456"));
11191        assert!(awaiting_new_head(Some("abc123"), ""));
11192    }
11193
11194    #[test]
11195    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
11196        let open = |c, m: &str| seen("a", c, m, false);
11197        let table = [
11198            (None, false, Refused::Pending),
11199            (
11200                Some(open(Checks::Pending, "BLOCKED")),
11201                false,
11202                Refused::Pending,
11203            ),
11204            (
11205                Some(open(Checks::Unknown, "BLOCKED")),
11206                false,
11207                Refused::Pending,
11208            ),
11209            (
11210                Some(open(Checks::Green, "UNKNOWN")),
11211                false,
11212                Refused::Pending,
11213            ),
11214            (Some(open(Checks::Green, "")), false, Refused::Pending),
11215            (
11216                Some(open(Checks::Green, "BLOCKED")),
11217                false,
11218                Refused::Recheck,
11219            ),
11220            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
11221        ];
11222        for (after, rechecked, want) in table {
11223            assert_eq!(
11224                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
11225                want
11226            );
11227        }
11228        let mut closed = open(Checks::Green, "CLEAN");
11229        closed.pr.state = PrLifecycle::Closed;
11230        assert_eq!(
11231            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
11232            Refused::Final
11233        );
11234    }
11235
11236    #[test]
11237    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
11238        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
11239            let pr = seen("a", checks, "BEHIND", false).pr;
11240            assert_eq!(
11241                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
11242                Step::Rebase
11243            );
11244        }
11245        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
11246            let current = seen("a", Checks::Green, status, false);
11247            assert_ne!(
11248                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
11249                Step::Rebase
11250            );
11251            assert_ne!(
11252                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
11253                Refused::Behind
11254            );
11255        }
11256        let mut current = seen("a", Checks::Pending, "BEHIND", false);
11257        current.rollup_head = "old".into();
11258        assert_eq!(
11259            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
11260            Refused::Behind
11261        );
11262        assert_eq!(
11263            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
11264            Refused::Pending
11265        );
11266        current.pr.state = PrLifecycle::Closed;
11267        assert_eq!(
11268            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
11269            Refused::Final
11270        );
11271    }
11272
11273    #[tokio::test]
11274    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
11275        for boundary in ["initial", "premerge", "refusal"] {
11276            let (_tmp, mut state, old) = landing_git_fixture().await;
11277            state.land_sync_pending = false;
11278            advance_landing_base(&state).await;
11279            state.config.verify.gate = vec!["test -f advance".into()];
11280            state.config.verify.e2e = vec!["test -f advance".into()];
11281            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
11282                .await
11283                .unwrap();
11284            let old_binding = state.land_approval.clone().unwrap();
11285            let store = ask::Questions::open();
11286            let mut question = store.get(&old_binding.question).unwrap();
11287            question
11288                .answer(ask::Answer::Choice(APPROVE.to_owned()))
11289                .unwrap();
11290            store.put(&mut question).unwrap();
11291            let mut views = Vec::new();
11292            if boundary != "initial" {
11293                views.push(seen(&old, Checks::Green, "CLEAN", false));
11294            }
11295            if boundary == "refusal" {
11296                views.push(seen(&old, Checks::Green, "CLEAN", false));
11297            }
11298            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
11299            behind.rollup_head = "old-ci-head".into();
11300            views.push(behind);
11301            // Publication checks the PR lease while verification has completed.
11302            views.push(seen(&old, Checks::Green, "CLEAN", false));
11303            views.push(seen("@published", Checks::Pending, "CLEAN", false));
11304            views.push(seen("@published", Checks::Green, "CLEAN", false));
11305            let merges = if boundary == "refusal" {
11306                vec![(false, REFUSED)]
11307            } else {
11308                vec![]
11309            };
11310            let mut forge = Scripted::new(views, merges);
11311            forge.public_repo = Some(state.repo.clone());
11312            let run = state.id.clone();
11313            land_with(&mut state, URL, &forge).await.unwrap();
11314            let head = state.pr_pushed_head.clone().unwrap();
11315            assert_ne!(head, old, "{boundary}");
11316            assert_eq!(state.id, run);
11317            assert_eq!(state.pr_branch(), Some("task-head"));
11318            assert_eq!(state.winner().unwrap().branch, "winner");
11319            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
11320            assert!(state.gate_allows_progress());
11321            let e2e = state.head_e2e.as_ref().unwrap();
11322            assert_eq!(e2e.head, head);
11323            assert!(e2e.passed);
11324            assert_eq!(state.land_sync_attempts, 1);
11325            assert!(!state.land_sync_pending);
11326            assert!(state.parked);
11327            let binding = state.land_approval.as_ref().unwrap();
11328            assert_eq!(binding.head, head);
11329            assert_ne!(binding.question, old_binding.question);
11330            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
11331            // The new question authorizes only the synchronized head on resume.
11332            let mut question = store.get(&binding.question).unwrap();
11333            question
11334                .answer(ask::Answer::Choice(APPROVE.to_owned()))
11335                .unwrap();
11336            store.put(&mut question).unwrap();
11337            let forge = Scripted::new(
11338                vec![seen(&head, Checks::Green, "CLEAN", false)],
11339                vec![(true, "")],
11340            );
11341            land_with(&mut state, URL, &forge).await.unwrap();
11342            assert_eq!(state.status, RunStatus::Merged);
11343            assert_eq!(
11344                value_of(&forge.argvs()[0], "--match-head-commit"),
11345                Some(head.as_str())
11346            );
11347        }
11348    }
11349
11350    #[tokio::test]
11351    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
11352        let (_tmp, mut state, old) = landing_git_fixture().await;
11353        state.land_sync_pending = false;
11354        state.config.graph.land_approval = false;
11355        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
11356        advance_landing_base(&state).await;
11357        let mut forge = Scripted::new(
11358            vec![
11359                seen(&old, Checks::Green, "CLEAN", false),
11360                seen(&old, Checks::Green, "CLEAN", false),
11361                seen(&old, Checks::Green, "BEHIND", false),
11362                // The next observation is the publication lease check. The
11363                // refusal's evidence still applies to exactly this old head.
11364                seen(&old, Checks::Green, "CLEAN", false),
11365                seen("@published", Checks::Green, "CLEAN", false),
11366            ],
11367            vec![(false, REFUSED), (true, "")],
11368        );
11369        forge.public_repo = Some(state.repo.clone());
11370        land_with(&mut state, URL, &forge).await.unwrap();
11371        let head = state.pr_pushed_head.as_deref().unwrap();
11372        assert_ne!(head, old);
11373        assert_eq!(state.land_sync_attempts, 1);
11374        assert_eq!(state.gate_head.as_deref(), Some(head));
11375        assert_eq!(state.status, RunStatus::Merged);
11376        let requests = forge.argvs();
11377        assert_eq!(requests.len(), 2);
11378        assert_eq!(
11379            value_of(&requests[0], "--match-head-commit"),
11380            Some(old.as_str())
11381        );
11382        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
11383    }
11384
11385    #[tokio::test]
11386    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
11387        let (tmp, mut state, old) = landing_git_fixture().await;
11388        state.land_sync_pending = false;
11389        // A damaged history must not be interpreted as a missing base. Keep
11390        // the head's tree intact so worktree restoration itself can succeed.
11391        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
11392        let commit = tmp.path().join("broken-commit");
11393        std::fs::write(
11394            &commit,
11395            format!(
11396                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
11397                "f".repeat(40)
11398            ),
11399        )
11400        .unwrap();
11401        let replacement = git::git(
11402            &state.repo,
11403            &[
11404                "hash-object",
11405                "-t",
11406                "commit",
11407                "-w",
11408                commit.to_str().unwrap(),
11409            ],
11410        )
11411        .await
11412        .unwrap();
11413        git::git(&state.repo, &["replace", &old, replacement.trim()])
11414            .await
11415            .unwrap();
11416        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11417        land_with(&mut state, URL, &forge).await.unwrap();
11418        assert_eq!(state.land_sync_attempts, 0);
11419        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
11420        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
11421        assert!(forge.argvs().is_empty());
11422        assert!(
11423            state.events.iter().any(|e| e.message.contains(
11424                "could not determine whether the landing head contains the fetched base"
11425            ))
11426        );
11427    }
11428
11429    #[tokio::test]
11430    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
11431        let (_tmp, mut state, old) = landing_git_fixture().await;
11432        state.land_sync_pending = false;
11433        git::git(
11434            &state.repo,
11435            &["remote", "set-url", "origin", "missing-remote"],
11436        )
11437        .await
11438        .unwrap();
11439        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11440        land_with(&mut state, URL, &forge).await.unwrap();
11441        assert_eq!(state.land_sync_attempts, 0);
11442        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
11443        assert!(
11444            state
11445                .events
11446                .iter()
11447                .any(|e| e.message.contains("cannot fetch landing base"))
11448        );
11449        assert!(forge.argvs().is_empty());
11450    }
11451
11452    #[tokio::test]
11453    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
11454        let (_tmp, mut state, old) = landing_git_fixture().await;
11455        state.land_sync_pending = false;
11456        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11457        land_with(&mut state, URL, &forge).await.unwrap();
11458        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
11459        assert_eq!(state.land_sync_attempts, 0);
11460        assert!(
11461            state
11462                .events
11463                .iter()
11464                .any(|e| e.message.contains("already included"))
11465        );
11466        advance_landing_base(&state).await;
11467        state.land_sync_attempts = state.config.graph.land_rounds;
11468        state.land_sync_pending = true;
11469        state.save().unwrap();
11470        let mut restored = RunState::load(&state.id).unwrap();
11471        assert!(
11472            resume_observed_head(&mut restored, &old)
11473                .await
11474                .unwrap_err()
11475                .to_string()
11476                .contains("budget exhausted")
11477        );
11478        assert_eq!(
11479            git::remote_head(&state.repo, "origin", "task-head")
11480                .await
11481                .unwrap(),
11482            Some(old)
11483        );
11484    }
11485
11486    #[tokio::test]
11487    async fn a_normal_landing_merges_on_the_first_look() {
11488        let mut state = landing_state();
11489        let forge = Scripted::new(
11490            vec![seen("a", Checks::Green, "CLEAN", false)],
11491            vec![(true, "")],
11492        );
11493        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11494            .await
11495            .unwrap();
11496        // One fresh read, then the head-bound merge.
11497        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11498        assert_eq!(state.status, RunStatus::Merged);
11499    }
11500
11501    #[tokio::test]
11502    async fn landing_refuses_unfinished_instruction_revision_before_observing_pr() {
11503        let mut state = landing_state();
11504        let url = "https://github.com/o/r/pull/42";
11505        crate::instruction_revision_control::adopt_into_run(
11506            &mut state,
11507            "cli/revision",
11508            "revision-repair",
11509            "revised task",
11510            1,
11511            "a",
11512            url,
11513        );
11514        for phase in [
11515            crate::run::MergeRepairPhase::Requested,
11516            crate::run::MergeRepairPhase::Fixing,
11517            crate::run::MergeRepairPhase::Reviewing,
11518            crate::run::MergeRepairPhase::Failed,
11519        ] {
11520            state.merge_repairs[0].phase = phase;
11521            let forge = Scripted::new(
11522                vec![seen("a", Checks::Green, "CLEAN", false)],
11523                vec![(true, "")],
11524            );
11525            let error = land_with(&mut state, url, &forge).await.unwrap_err();
11526            assert!(
11527                error
11528                    .to_string()
11529                    .contains("instruction revision repair did not complete")
11530            );
11531            assert!(forge.calls().is_empty());
11532            assert!(state.land_approval.is_none());
11533        }
11534        state.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
11535        assert!(state.unfinished_instruction_revision().is_none());
11536    }
11537
11538    #[tokio::test]
11539    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
11540        let mut state = landing_state();
11541        let forge = Scripted::new(
11542            vec![seen("a", Checks::Green, "CLEAN", false)],
11543            std::iter::repeat_n((true, ""), 100).collect(),
11544        );
11545        *forge.queued.lock().unwrap() = true;
11546        let task = async {
11547            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11548                .await
11549                .unwrap();
11550        };
11551        // Still open after the command succeeded: it keeps watching and
11552        // never records a merge (it stops at the wait ceiling instead).
11553        task.await;
11554        assert_ne!(state.status, RunStatus::Merged);
11555    }
11556
11557    #[tokio::test]
11558    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
11559        let mut state = landing_state();
11560        let forge = Scripted::new(
11561            vec![seen("a", Checks::Green, "CLEAN", false)],
11562            std::iter::repeat_n((true, ""), 100).collect(),
11563        );
11564        *forge.unreadable_after_merge.lock().unwrap() = true;
11565        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11566            .await
11567            .ok();
11568        assert_ne!(state.status, RunStatus::Merged);
11569    }
11570
11571    #[tokio::test]
11572    async fn a_task_public_head_is_awaited_on_land_entry() {
11573        let mut state = landing_state();
11574        state.pr_head = Some("magi/task-abcd-1234".into());
11575        state.pr_pushed_head = Some("new".into());
11576        let forge = Scripted::new(
11577            vec![
11578                seen("old", Checks::Green, "CLEAN", false),
11579                seen("new", Checks::Green, "CLEAN", false),
11580            ],
11581            vec![(true, "")],
11582        );
11583        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11584            .await
11585            .unwrap();
11586        assert_eq!(
11587            forge.calls(),
11588            ["view", "poll", "view", "view", "merge", "view"]
11589        );
11590        assert_eq!(state.status, RunStatus::Merged);
11591    }
11592
11593    #[tokio::test]
11594    async fn a_superseded_public_head_owner_cannot_reenter_land() {
11595        let mut state = landing_state();
11596        state.pr_taken_over_by = Some("next".into());
11597        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
11598        assert!(
11599            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11600                .await
11601                .is_err()
11602        );
11603        assert!(forge.calls().is_empty());
11604    }
11605
11606    #[tokio::test]
11607    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
11608        let mut state = landing_state();
11609        let forge = Scripted::new(
11610            vec![
11611                seen("old", Checks::Green, "CLEAN", true),
11612                // The forge has not moved to the new head yet: still green.
11613                seen("old", Checks::Green, "CLEAN", true),
11614                seen("new", Checks::Pending, "BLOCKED", true),
11615                seen("new", Checks::Green, "CLEAN", true),
11616            ],
11617            vec![(true, "")],
11618        );
11619        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11620            head: "NEW".to_owned(),
11621        });
11622        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11623            .await
11624            .unwrap();
11625        assert_eq!(
11626            forge.calls(),
11627            [
11628                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
11629                "view"
11630            ]
11631        );
11632        assert_eq!(state.status, RunStatus::Merged);
11633    }
11634
11635    #[tokio::test]
11636    async fn a_head_that_never_arrives_stops_naming_both_commits() {
11637        let mut state = landing_state();
11638        let forge = Scripted::new(
11639            vec![
11640                seen("old", Checks::Green, "CLEAN", true),
11641                seen("someone-elses", Checks::Green, "CLEAN", true),
11642            ],
11643            vec![],
11644        );
11645        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11646            head: "mine".to_owned(),
11647        });
11648        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11649            .await
11650            .unwrap();
11651        assert!(!forge.calls().contains(&"merge"));
11652        let why = state.merge.as_ref().unwrap().detail.clone();
11653        assert!(
11654            why.contains("mine") && why.contains("someone-elses"),
11655            "{why}"
11656        );
11657        assert_eq!(state.status, RunStatus::Blocked);
11658    }
11659
11660    #[tokio::test]
11661    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
11662        let mut state = landing_state();
11663        let forge = Scripted::new(
11664            vec![
11665                seen("a", Checks::Green, "CLEAN", false),
11666                seen("a", Checks::Green, "CLEAN", false),
11667                seen("a", Checks::Pending, "BLOCKED", false),
11668                seen("a", Checks::Pending, "BLOCKED", false),
11669                seen("a", Checks::Green, "CLEAN", false),
11670            ],
11671            vec![(false, REFUSED), (true, "")],
11672        );
11673        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11674            .await
11675            .unwrap();
11676        assert_eq!(
11677            forge.calls(),
11678            [
11679                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
11680                "view"
11681            ]
11682        );
11683        assert_eq!(state.status, RunStatus::Merged);
11684    }
11685
11686    #[tokio::test]
11687    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
11688        let mut state = landing_state();
11689        let forge = Scripted::new(
11690            vec![
11691                seen("a", Checks::Green, "CLEAN", false),
11692                seen("a", Checks::Green, "BLOCKED", false),
11693            ],
11694            vec![(false, REFUSED), (false, REFUSED)],
11695        );
11696        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11697            .await
11698            .unwrap();
11699        // One re-look is allowed for the forge's own lag, then it is final.
11700        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
11701        let why = state.merge.as_ref().unwrap().detail.clone();
11702        assert!(
11703            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
11704            "{why}"
11705        );
11706        assert_eq!(state.status, RunStatus::Blocked);
11707    }
11708
11709    #[test]
11710    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
11711        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
11712        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
11713        // The pull request is still on the commit before the push.
11714        assert_eq!(bound_head("old", "old", Some("new")), None);
11715        // The checks are the previous commit's.
11716        assert_eq!(bound_head("new", "old", Some("new")), None);
11717        assert_eq!(bound_head("new", "old", None), None);
11718        // Nothing readable.
11719        assert_eq!(bound_head("", "", None), None);
11720        assert_eq!(bound_head("", "", Some("new")), None);
11721        assert_eq!(bound_head("abc", "", None), None);
11722    }
11723
11724    fn view_json(head: &str) -> String {
11725        format!(
11726            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
11727            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
11728            "reviews":[],"comments":[]}}"#
11729        )
11730    }
11731
11732    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
11733        format!(
11734            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
11735            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
11736            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
11737            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
11738        )
11739    }
11740
11741    #[test]
11742    fn rollup_is_bound_to_the_commit_in_the_same_node() {
11743        // The view already points at the new head, but the node still answers
11744        // for the old commit with its red check: the head stays unbound.
11745        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
11746        assert_eq!(s.rollup_head, "old");
11747        assert_eq!(s.pr.checks, Checks::Red);
11748        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
11749        assert_eq!(s.failing_urls.len(), 1);
11750    }
11751
11752    #[test]
11753    fn checks_come_from_the_node_not_the_view() {
11754        let view = view_json("new").replace(
11755            r#""reviews""#,
11756            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
11757        );
11758        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
11759        assert_eq!(s.pr.checks, Checks::Green);
11760        assert!(s.pr.failing.is_empty());
11761        assert_eq!(
11762            bound_head(&s.head, &s.rollup_head, Some("new")),
11763            Some("new")
11764        );
11765    }
11766
11767    #[test]
11768    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
11769        for node in [
11770            None,
11771            Some("not json".to_owned()),
11772            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
11773            Some(node_json("new", "SUCCESS", true)),
11774        ] {
11775            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
11776            assert!(s.rollup_head.is_empty());
11777            assert_eq!(s.pr.checks, Checks::Unknown);
11778            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
11779        }
11780    }
11781
11782    #[test]
11783    fn the_merge_command_is_pinned_to_the_observed_head() {
11784        let argv = merge_argv_at(7, "feat: x", "deadbeef");
11785        let at = argv
11786            .iter()
11787            .position(|a| a == "--match-head-commit")
11788            .unwrap();
11789        assert_eq!(argv[at + 1], "deadbeef");
11790    }
11791
11792    #[tokio::test]
11793    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
11794        let mut state = landing_state();
11795        // The pull request is on the pushed head but the rollup is still the
11796        // previous commit's red, non-required result.
11797        let mut stale = seen("new", Checks::Red, "CLEAN", false);
11798        stale.rollup_head = "old".to_owned();
11799        let forge = Scripted::new(
11800            vec![seen("old", Checks::Green, "CLEAN", true), stale],
11801            vec![],
11802        );
11803        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11804            head: "new".to_owned(),
11805        });
11806        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11807            .await
11808            .unwrap();
11809        assert!(!forge.calls().contains(&"merge"));
11810        assert_eq!(state.status, RunStatus::Blocked);
11811        let why = state.merge.as_ref().unwrap().detail.clone();
11812        assert!(why.contains("new") && why.contains("old"), "{why}");
11813    }
11814
11815    #[test]
11816    fn a_refusal_read_against_another_commits_checks_is_pending() {
11817        let mut after = seen("a", Checks::Green, "BLOCKED", false);
11818        after.rollup_head = "old".to_owned();
11819        assert_eq!(
11820            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
11821            Refused::Pending
11822        );
11823    }
11824
11825    #[tokio::test]
11826    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
11827        let mut state = landing_state();
11828        state.config.merge.ci = crate::config::MergeCi::None;
11829        state.config.graph.land_approval = true;
11830        let forge = Scripted::new(
11831            vec![seen("a", Checks::Unknown, "CLEAN", false)],
11832            vec![(true, "")],
11833        );
11834        land_with(&mut state, URL, &forge).await.unwrap();
11835        assert!(state.parked);
11836        assert_eq!(forge.calls(), ["view"]);
11837        let store = ask::Questions::open();
11838        let mut q = store
11839            .get(&state.land_approval.as_ref().unwrap().question)
11840            .unwrap();
11841        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11842        store.put(&mut q).unwrap();
11843
11844        land_with(&mut state, URL, &forge).await.unwrap();
11845        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
11846        assert_eq!(state.status, RunStatus::Merged);
11847        assert_eq!(
11848            value_of(&forge.argvs()[0], "--match-head-commit"),
11849            Some("a")
11850        );
11851    }
11852
11853    #[tokio::test]
11854    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
11855        let mut state = landing_state();
11856        state.config.merge.ci = crate::config::MergeCi::None;
11857        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
11858        land_with(&mut state, URL, &forge).await.unwrap();
11859        assert!(forge.reruns.lock().unwrap().is_empty());
11860        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11861        assert_eq!(state.status, RunStatus::Merged);
11862    }
11863
11864    #[test]
11865    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
11866        let shown = BTreeSet::new();
11867        let guard = |s: Option<&Seen>| {
11868            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11869        };
11870        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11871        assert!(guard(Some(&fresh)));
11872        assert!(!guard(None));
11873        fresh.rollup_head = "old".to_owned();
11874        assert!(!guard(Some(&fresh)));
11875        fresh.rollup_head = "a".to_owned();
11876        fresh.head = "b".to_owned();
11877        assert!(!guard(Some(&fresh)));
11878        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11879        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11880    }
11881
11882    #[test]
11883    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11884        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11885            let after = seen("a", checks, "BLOCKED", false);
11886            assert_eq!(
11887                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11888                Refused::Recheck
11889            );
11890            assert_eq!(
11891                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11892                Refused::Final
11893            );
11894        }
11895    }
11896
11897    #[tokio::test]
11898    async fn a_matching_head_with_red_non_required_checks_still_merges() {
11899        let mut state = landing_state();
11900        let forge = Scripted::new(
11901            vec![seen("a", Checks::Red, "CLEAN", false)],
11902            vec![(true, "")],
11903        );
11904        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11905            .await
11906            .unwrap();
11907        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11908        assert_eq!(state.status, RunStatus::Merged);
11909    }
11910
11911    #[tokio::test]
11912    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11913        let mut state = landing_state();
11914        let forge = Scripted::new(
11915            vec![
11916                seen("a", Checks::Green, "CLEAN", false),
11917                seen("a", Checks::Green, "CLEAN", false),
11918                // Re-viewed after the refusal: someone pushed.
11919                seen("b", Checks::Green, "BLOCKED", false),
11920                seen("b", Checks::Green, "CLEAN", false),
11921            ],
11922            vec![(false, REFUSED), (true, "")],
11923        );
11924        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11925            .await
11926            .unwrap();
11927        assert_eq!(
11928            forge.calls(),
11929            [
11930                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
11931            ]
11932        );
11933        assert_eq!(state.status, RunStatus::Merged);
11934    }
11935
11936    fn merged_view(head: &str) -> Seen {
11937        let mut m = seen(head, Checks::Green, "CLEAN", false);
11938        m.pr.state = PrLifecycle::Merged;
11939        m
11940    }
11941
11942    fn has(argv: &[String], flag: &str) -> bool {
11943        argv.iter().any(|a| a == flag)
11944    }
11945
11946    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11947        let at = argv.iter().position(|a| a == flag)?;
11948        argv.get(at + 1).map(String::as_str)
11949    }
11950
11951    const URL: &str = "https://github.com/o/r/pull/42";
11952
11953    #[tokio::test]
11954    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11955        let mut state = landing_state();
11956        let forge = Scripted::new(
11957            vec![
11958                seen("abc", Checks::Green, "CLEAN", false),
11959                seen("abc", Checks::Green, "CLEAN", false),
11960            ],
11961            vec![(true, "")],
11962        );
11963        land_with(&mut state, URL, &forge).await.unwrap();
11964        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11965        let argv = &forge.argvs()[0];
11966        assert!(has(argv, "--squash") && has(argv, "--subject"));
11967        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11968        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11969        assert_eq!(state.status, RunStatus::Merged);
11970        assert!(state.land_armed_head.is_none());
11971    }
11972
11973    #[tokio::test]
11974    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11975        let mut state = landing_state();
11976        state.land_armed_head = Some("a".to_owned());
11977        let forge = Scripted::new(
11978            vec![seen("a", Checks::Green, "CLEAN", false)],
11979            vec![(true, ""), (true, "")],
11980        );
11981        land_with(&mut state, URL, &forge).await.unwrap();
11982        let argvs = forge.argvs();
11983        assert!(has(&argvs[0], "--disable-auto"));
11984        assert!(!has(&argvs[1], "--auto"));
11985        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11986        assert_eq!(state.status, RunStatus::Merged);
11987        assert!(state.land_armed_head.is_none());
11988    }
11989
11990    #[tokio::test]
11991    async fn an_approval_never_carries_over_to_a_new_head() {
11992        crate::run::pin_test_home();
11993        let mut state = run_state();
11994        state.config.graph.land_approval = true;
11995        let pr = green_pr();
11996        let store = ask::Questions::open();
11997
11998        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11999            .await
12000            .unwrap();
12001        let mut q = store
12002            .list()
12003            .into_iter()
12004            .find(|q| q.run == state.id)
12005            .unwrap();
12006        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
12007        store.put(&mut q).unwrap();
12008        assert_eq!(
12009            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
12010                .await
12011                .unwrap(),
12012            ApprovalGate::Approved,
12013            "the same head keeps its approval"
12014        );
12015
12016        // A new head is a new question, not the old word.
12017        assert_eq!(
12018            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
12019                .await
12020                .unwrap(),
12021            ApprovalGate::Pending
12022        );
12023        let all: Vec<_> = store
12024            .list()
12025            .into_iter()
12026            .filter(|q| q.run == state.id)
12027            .collect();
12028        assert_eq!(all.len(), 2);
12029
12030        // A question recorded before heads were tracked is not reused either.
12031        state.land_approval = None;
12032        assert_eq!(
12033            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
12034                .await
12035                .unwrap(),
12036            ApprovalGate::Pending
12037        );
12038        let open = store
12039            .list()
12040            .into_iter()
12041            .filter(|q| q.run == state.id && q.status.open())
12042            .count();
12043        assert_eq!(open, 1, "the superseded question was retired");
12044    }
12045
12046    #[tokio::test]
12047    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
12048        let mut state = landing_state();
12049        let forge = Scripted::new(
12050            vec![
12051                seen("a", Checks::Green, "CLEAN", false),
12052                // The fresh read before the merge: someone pushed.
12053                seen("b", Checks::Green, "CLEAN", false),
12054            ],
12055            vec![(true, "")],
12056        );
12057        land_with(&mut state, URL, &forge).await.unwrap();
12058        let argvs = forge.argvs();
12059        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
12060        assert!(!has(&argvs[0], "--auto"));
12061        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
12062        assert_eq!(state.status, RunStatus::Merged);
12063    }
12064
12065    fn passing(label: &str) -> CheckInfo {
12066        CheckInfo {
12067            label: label.to_owned(),
12068            verdict: Verdict::Pass,
12069            required: Some(false),
12070            run: None,
12071        }
12072    }
12073
12074    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
12075        (label.to_owned(), run.map(str::to_owned))
12076    }
12077
12078    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
12079        LandReruns {
12080            head: head.to_owned(),
12081            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
12082        }
12083    }
12084
12085    #[test]
12086    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
12087        let f = [failing("test (macos)", Some("7"))];
12088        assert_eq!(
12089            rerun_step(&f, None, "h", 100),
12090            RerunStep::Rerun(vec!["7".to_owned()])
12091        );
12092        let rec = reran("h", &[("7", 100)]);
12093        let grace = crate::release_watch::RERUN_GRACE;
12094        assert_eq!(
12095            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
12096            RerunStep::Grace
12097        );
12098        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
12099    }
12100
12101    #[test]
12102    fn a_failure_without_a_run_id_goes_to_the_fixer() {
12103        let f = [failing("a", Some("7")), failing("ci/external", None)];
12104        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
12105        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
12106    }
12107
12108    #[test]
12109    fn a_moved_head_forgets_the_reruns() {
12110        let f = [failing("a", Some("7"))];
12111        let rec = reran("old", &[("7", 100)]);
12112        assert_eq!(
12113            rerun_step(&f, Some(&rec), "new", 101),
12114            RerunStep::Rerun(vec!["7".to_owned()])
12115        );
12116    }
12117
12118    #[test]
12119    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
12120        let f = [
12121            failing("a", Some("7")),
12122            failing("b", Some("7")),
12123            failing("c", Some("8")),
12124        ];
12125        assert_eq!(
12126            rerun_step(&f, None, "h", 0),
12127            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
12128        );
12129        let rec = reran("h", &[("7", 0)]);
12130        assert_eq!(
12131            rerun_step(&f, Some(&rec), "h", 1),
12132            RerunStep::Rerun(vec!["8".to_owned()])
12133        );
12134    }
12135
12136    #[test]
12137    fn only_blocking_failures_are_candidates_for_a_rerun() {
12138        let check = |label: &str, verdict, required, run: &str| CheckInfo {
12139            label: label.to_owned(),
12140            verdict,
12141            required,
12142            run: Some(run.to_owned()),
12143        };
12144        let got = rerunnable(&[
12145            check("passed", Verdict::Pass, Some(true), "1"),
12146            check("optional", Verdict::Fail, Some(false), "2"),
12147            check("required", Verdict::Fail, Some(true), "3"),
12148            check("unknown", Verdict::Fail, None, "4"),
12149        ]);
12150        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
12151        assert_eq!(labels, ["required", "unknown"]);
12152    }
12153
12154    fn unrelated_ci_fixture() -> CiEvidence {
12155        let failure = CiFailure {
12156            path: "tests/web_render.rs".into(),
12157            start_line: 42,
12158            end_line: 42,
12159            title: "question_identity_disclosure_copy_and_live_updates".into(),
12160            message: "assertion failed".into(),
12161        };
12162        CiEvidence {
12163            head: "a".into(),
12164            base: "base-sha".into(),
12165            changed: vec![
12166                "AGENTS.md".into(),
12167                "src/talk.rs".into(),
12168                "tests/consult_investigation.rs".into(),
12169            ],
12170            checks: vec![CiCheckEvidence {
12171                label: "coverage".into(),
12172                head_check: 70,
12173                base_check: 60,
12174                app: 1,
12175                run: "7".into(),
12176                base_run: "6".into(),
12177                head_failures: vec![failure.clone()],
12178                base_failures: vec![failure],
12179                rerun_exhausted: true,
12180            }],
12181        }
12182    }
12183
12184    #[test]
12185    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
12186        let good = unrelated_ci_fixture();
12187        let red = vec!["coverage".into()];
12188        assert!(good.unrelated("a", &red));
12189        assert!(!good.unrelated("another-head", &red));
12190        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
12191        assert!(!good.unrelated("a", &[]));
12192        for mutation in 0..8 {
12193            let mut bad = good.clone();
12194            match mutation {
12195                0 => bad.checks[0].rerun_exhausted = false,
12196                1 => bad.checks[0].base_failures.clear(),
12197                2 => bad.checks[0].head_failures.clear(),
12198                3 => bad.changed.push("tests/web_render.rs".into()),
12199                4 => bad.changed.push(".github/workflows/ci.yml".into()),
12200                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
12201                6 => bad.checks.push(bad.checks[0].clone()),
12202                _ => bad.base.clear(),
12203            }
12204            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
12205        }
12206    }
12207
12208    #[test]
12209    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
12210        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
12211        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
12212        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
12213        assert!(matches!(
12214            decide(&pr, 2, 2, CHECKS_GRACE),
12215            Step::GiveUp { .. }
12216        ));
12217        let optional = CheckInfo {
12218            label: "coverage".into(),
12219            verdict: Verdict::Fail,
12220            required: Some(false),
12221            run: Some("7".into()),
12222        };
12223        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
12224        assert_eq!(
12225            rerunnable_with(&[optional], true),
12226            vec![("coverage".into(), Some("7".into()))]
12227        );
12228    }
12229
12230    #[tokio::test]
12231    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
12232        let mut state = landing_state();
12233        let mut red = coverage_unknown();
12234        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
12235        red.pr.failing = vec!["coverage".into()];
12236        let forge = Scripted::new(vec![red], vec![]);
12237        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
12238        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12239        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12240        assert!(forge.calls().contains(&"fix"));
12241        assert!(state.land_unrelated.is_some());
12242        assert!(state.parked);
12243        assert!(
12244            !state
12245                .events
12246                .iter()
12247                .any(|e| e.message.contains("fixer produced no commit"))
12248        );
12249    }
12250
12251    fn coverage_unknown() -> Seen {
12252        let mut s = red("a", Some("7"));
12253        s.pr.blocking = Blocking::Unsaid;
12254        s.merge_state = "UNKNOWN".into();
12255        s.pr.failing = vec!["coverage".into()];
12256        s.contexts[0].label = "coverage".into();
12257        s.contexts[0].required = Some(false);
12258        s
12259    }
12260
12261    #[tokio::test]
12262    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
12263        let mut state = landing_state();
12264        let unknown = coverage_unknown();
12265        let mut unstable = unknown.clone();
12266        unstable.pr.blocking = Blocking::of("UNSTABLE");
12267        unstable.merge_state = "UNSTABLE".into();
12268        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
12269        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12270        assert!(!forge.calls().contains(&"fix"));
12271        assert!(!forge.calls().contains(&"rerun"));
12272        assert_eq!(state.status, RunStatus::Merged);
12273        assert_eq!(state.pr.unwrap().round, 0);
12274    }
12275
12276    #[tokio::test]
12277    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
12278        let mut state = landing_state();
12279        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
12280        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
12281        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12282        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12283        assert!(!forge.calls().contains(&"fix"));
12284        assert!(state.parked);
12285        assert_eq!(state.status, RunStatus::Landing);
12286        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12287        let hold = state.land_unrelated.as_ref().unwrap();
12288        let q = ask::Questions::open().get(&hold.question).unwrap();
12289        assert!(
12290            q.actions
12291                .values()
12292                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
12293        );
12294        assert!(
12295            state
12296                .events
12297                .iter()
12298                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
12299        );
12300        let first = state.land_unsaid.clone();
12301        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
12302        state.parked = false;
12303        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12304        assert_eq!(state.land_unsaid, first);
12305        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12306    }
12307
12308    fn red(head: &str, run: Option<&str>) -> Seen {
12309        let mut s = seen(head, Checks::Red, "BLOCKED", false);
12310        s.pr.failing = vec!["test (macos)".to_owned()];
12311        s.contexts = vec![CheckInfo {
12312            label: "test (macos)".to_owned(),
12313            verdict: Verdict::Fail,
12314            required: Some(true),
12315            run: run.map(str::to_owned),
12316        }];
12317        s
12318    }
12319
12320    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
12321
12322    #[tokio::test]
12323    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
12324        let mut state = landing_state();
12325        let forge = Scripted::new(
12326            vec![
12327                red("a", Some("7")),
12328                seen("a", Checks::Pending, "BLOCKED", false),
12329                seen("a", Checks::Green, "CLEAN", false),
12330            ],
12331            vec![(true, "")],
12332        );
12333        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12334        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12335        assert!(!forge.calls().contains(&"fix"));
12336        assert_eq!(state.status, RunStatus::Merged);
12337        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12338        let argvs = forge.argvs();
12339        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
12340        assert!(
12341            state
12342                .events
12343                .iter()
12344                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
12345        );
12346    }
12347
12348    #[tokio::test]
12349    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
12350        let mut state = landing_state();
12351        let forge = Scripted::new(
12352            vec![
12353                red("a", Some("7")),
12354                seen("a", Checks::Green, "CLEAN", false),
12355            ],
12356            vec![(true, "")],
12357        );
12358        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12359        // The red view repeats for the grace, then the fixer is asked once.
12360        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12361        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
12362        let calls = forge.calls();
12363        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
12364        let fix_at = calls.iter().position(|c| *c == "fix");
12365        assert!(fix_at.is_none_or(|f| f > rerun_at));
12366    }
12367
12368    #[tokio::test]
12369    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
12370        let mut state = landing_state();
12371        let mut v = red("a", Some("7"));
12372        v.pr.checks = Checks::Pending;
12373        v.contexts.push(CheckInfo {
12374            label: "slow".to_owned(),
12375            verdict: Verdict::Pending,
12376            required: Some(true),
12377            run: Some("8".to_owned()),
12378        });
12379        let forge = Scripted::new(
12380            vec![v, seen("a", Checks::Green, "CLEAN", false)],
12381            vec![(true, "")],
12382        );
12383        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12384        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12385        assert_eq!(state.status, RunStatus::Merged);
12386    }
12387
12388    #[test]
12389    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
12390        let mut v = red("a", Some("7"));
12391        v.contexts.push(CheckInfo {
12392            label: "same run, still going".to_owned(),
12393            verdict: Verdict::Pending,
12394            required: Some(true),
12395            run: Some("7".to_owned()),
12396        });
12397        assert!(rerunnable(&v.contexts).is_empty());
12398    }
12399
12400    #[tokio::test]
12401    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
12402        let mut state = landing_state();
12403        state.config.graph.land_rounds = 0;
12404        let forge = Scripted::new(
12405            vec![
12406                red("a", Some("7")),
12407                seen("a", Checks::Green, "CLEAN", false),
12408            ],
12409            vec![(true, "")],
12410        );
12411        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12412        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12413        assert_eq!(state.status, RunStatus::Merged);
12414        assert!(!forge.calls().contains(&"fix"));
12415        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12416    }
12417
12418    #[tokio::test]
12419    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
12420        let mut state = landing_state();
12421        state.config.graph.land_rounds = 1;
12422        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
12423        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
12424        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12425        assert_eq!(pr.state, PrLifecycle::Open);
12426        assert_eq!(state.status, RunStatus::Blocked);
12427        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12428        assert!(
12429            state.merge_decision.is_none(),
12430            "no ordinary failure handoff"
12431        );
12432        assert!(forge.argvs().is_empty(), "no merge on outage");
12433
12434        let recovered = Scripted::new(
12435            vec![
12436                seen("a", Checks::Green, "CLEAN", true),
12437                seen("b", Checks::Green, "CLEAN", false),
12438            ],
12439            vec![(true, "")],
12440        );
12441        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
12442        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
12443        assert_eq!(state.status, RunStatus::Merged);
12444        assert_eq!(state.pr.as_ref().unwrap().round, 1);
12445        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
12446    }
12447
12448    #[tokio::test]
12449    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
12450        let mut state = landing_state();
12451        state.config.graph.land_rounds = 1;
12452        let forge = Scripted::new(
12453            vec![
12454                seen("a", Checks::Green, "CLEAN", true),
12455                red("b", Some("7")),
12456                seen("b", Checks::Green, "CLEAN", false),
12457            ],
12458            vec![(true, "")],
12459        );
12460        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
12461            head: "b".to_owned(),
12462        });
12463        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12464        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12465        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
12466        assert_eq!(state.pr.as_ref().unwrap().round, 1);
12467        assert_eq!(state.status, RunStatus::Merged);
12468        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
12469        assert_eq!(
12470            value_of(&forge.argvs()[0], "--match-head-commit"),
12471            Some("b")
12472        );
12473    }
12474
12475    #[tokio::test]
12476    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
12477        let mut state = landing_state();
12478        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12479        *forge.rerun_fails.lock().unwrap() = true;
12480        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12481        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12482        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
12483        assert_eq!(
12484            forge.calls().iter().filter(|c| **c == "fix").count(),
12485            1,
12486            "{:?}",
12487            forge.calls()
12488        );
12489    }
12490
12491    #[tokio::test]
12492    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
12493        let mut state = landing_state();
12494        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12495        // The record was written just before the previous pass died.
12496        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
12497        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12498        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12499        assert!(forge.reruns.lock().unwrap().is_empty());
12500    }
12501
12502    #[tokio::test]
12503    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
12504        let mut state = landing_state();
12505        state.config.graph.rerun_flaky_checks = false;
12506        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12507        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12508        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12509        assert!(forge.reruns.lock().unwrap().is_empty());
12510        assert!(forge.calls().contains(&"fix"));
12511
12512        let mut state = landing_state();
12513        let forge = Scripted::new(vec![red("a", None)], vec![]);
12514        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12515        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12516        assert!(forge.reruns.lock().unwrap().is_empty());
12517        assert!(forge.calls().contains(&"fix"));
12518    }
12519
12520    fn names(xs: &[&str]) -> BTreeSet<String> {
12521        xs.iter().map(|x| (*x).to_owned()).collect()
12522    }
12523
12524    #[test]
12525    fn a_required_check_the_rollup_never_listed_is_named() {
12526        let req = names(&["build"]);
12527        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
12528        assert!(why.contains("never reported: build"), "{why}");
12529        assert!(!why.contains("probably waiting for a review"), "{why}");
12530    }
12531
12532    #[test]
12533    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
12534        let why = waiting_on("BLOCKED", &[passing("review")], None);
12535        assert!(why.contains("could not be read"), "{why}");
12536        assert!(!why.contains("probably waiting for a review"), "{why}");
12537    }
12538
12539    #[test]
12540    fn all_required_reported_keeps_the_review_guess() {
12541        let req = names(&["build"]);
12542        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12543        assert!(why.contains("probably waiting for a review"), "{why}");
12544        assert!(!why.contains("never reported"), "{why}");
12545    }
12546
12547    #[test]
12548    fn required_names_match_the_rollup_ignoring_case_only() {
12549        let req = names(&["Build"]);
12550        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12551        assert!(!why.contains("never reported"), "{why}");
12552    }
12553
12554    #[test]
12555    fn required_contexts_are_read_from_protection_and_rulesets() {
12556        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
12557        assert_eq!(
12558            parse_classic_required(classic),
12559            Some(names(&["build", "lint"]))
12560        );
12561        let rules = r#"[{"type":"pull_request","parameters":{}},
12562            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
12563        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
12564        assert_eq!(parse_ruleset_required("nope"), None);
12565        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
12566    }
12567
12568    #[test]
12569    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
12570        let shown = BTreeSet::new();
12571        let ok = seen("a", Checks::Green, "CLEAN", false);
12572        let guard = |s: Option<&Seen>| {
12573            direct_merge_is_safe(
12574                s,
12575                "A",
12576                &shown,
12577                0,
12578                4,
12579                Duration::ZERO,
12580                CiExpectation::Expected,
12581            )
12582        };
12583        assert!(guard(Some(&ok)));
12584        assert!(!guard(None));
12585        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
12586        let mut stale = ok.clone();
12587        stale.rollup_head = "old".to_owned();
12588        assert!(!guard(Some(&stale)));
12589        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
12590        assert!(!guard(Some(&merged_view("a"))));
12591    }
12592
12593    #[test]
12594    fn the_rollup_node_carries_whether_each_check_is_required() {
12595        let node = node_json("new", "SUCCESS", false)
12596            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
12597        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
12598        assert_eq!(s.contexts.len(), 1);
12599        assert_eq!(s.contexts[0].required, Some(true));
12600        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
12601        assert_eq!(s.contexts[0].required, None);
12602    }
12603
12604    #[tokio::test]
12605    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
12606        let mut state = landing_state();
12607        state.land_armed_head = Some("a".to_owned());
12608        let forge = Scripted::new(
12609            vec![seen("a", Checks::Green, "CLEAN", true)],
12610            vec![(false, "disable exploded")],
12611        );
12612        land_with(&mut state, URL, &forge).await.unwrap();
12613        assert!(!forge.calls().contains(&"fix"));
12614        assert_eq!(state.status, RunStatus::Blocked);
12615        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
12616        let why = state.merge.as_ref().unwrap().detail.clone();
12617        assert!(why.contains("disable exploded"), "{why}");
12618    }
12619
12620    /// Create a cross-platform fake `gh` executable in `dir` backed by exact
12621    /// fixture files, avoiding shell quoting differences and global `PATH`
12622    /// mutation.
12623    pub(crate) fn fake_gh_script(
12624        dir: &Path,
12625        name: &str,
12626        stdout: &str,
12627        stderr: &str,
12628        exit_code: i32,
12629    ) -> PathBuf {
12630        let out_path = dir.join(format!("{name}.stdout"));
12631        let err_path = dir.join(format!("{name}.stderr"));
12632        std::fs::write(&out_path, stdout).unwrap();
12633        std::fs::write(&err_path, stderr).unwrap();
12634        #[cfg(windows)]
12635        {
12636            let script = dir.join(format!("{name}.cmd"));
12637            let mut body = String::from("@echo off\r\n");
12638            if !stdout.is_empty() {
12639                body.push_str(&format!("type \"{}\"\r\n", out_path.display()));
12640            }
12641            if !stderr.is_empty() {
12642                body.push_str(&format!("type \"{}\" 1>&2\r\n", err_path.display()));
12643            }
12644            body.push_str(&format!("exit /b {exit_code}\r\n"));
12645            std::fs::write(&script, body).unwrap();
12646            script
12647        }
12648        #[cfg(unix)]
12649        {
12650            use std::os::unix::fs::PermissionsExt as _;
12651            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
12652            let script = dir.join(name);
12653            let mut body = String::from("#!/bin/sh\n");
12654            if !stdout.is_empty() {
12655                body.push_str(&format!("cat {}\n", quote(&out_path)));
12656            }
12657            if !stderr.is_empty() {
12658                body.push_str(&format!("cat {} >&2\n", quote(&err_path)));
12659            }
12660            body.push_str(&format!("exit {exit_code}\n"));
12661            let status = std::process::Command::new("sh")
12662                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
12663                .arg(&script)
12664                .arg(&body)
12665                .status()
12666                .unwrap();
12667            assert!(status.success());
12668            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
12669            script
12670        }
12671    }
12672
12673    #[test]
12674    fn gh_output_combined_preserves_and_separates_both_streams() {
12675        let mk = |ok, stdout: &str, stderr: &str| GhOutput {
12676            ok,
12677            stdout: stdout.into(),
12678            stderr: stderr.into(),
12679        };
12680        assert_eq!(mk(true, "  ", "\n").combined(), "");
12681        assert_eq!(mk(true, "  only out \n", " \t ").combined(), "only out");
12682        assert_eq!(mk(false, "", "  only err\n").combined(), "only err");
12683        assert_eq!(
12684            mk(false, "{\"status\":\"404\"}", "gh: Not Found (HTTP 404)\n").combined(),
12685            "{\"status\":\"404\"}\ngh: Not Found (HTTP 404)"
12686        );
12687    }
12688
12689    #[tokio::test]
12690    async fn gh_separates_json_stdout_from_stderr_diagnostics() {
12691        let tmp = tempfile::tempdir().unwrap();
12692        let hint = "hint: to listen to pull request events, run `gh pr view --web`\n";
12693        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"}"#;
12694        let valid_list = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: test","baseRefName":"main","isCrossRepository":false}]"#;
12695
12696        // Valid JSON stdout + nonempty stderr hint on exit 0: structured reads
12697        // parse stdout cleanly while stderr remains available via `combined()`.
12698        let ok_view = fake_gh_script(tmp.path(), "ok-view", &format!("{valid_view}\n"), hint, 0);
12699        let out = gh_with(&ok_view, tmp.path(), &["pr".into(), "view".into()])
12700            .await
12701            .unwrap();
12702        assert!(out.ok);
12703        assert_eq!(parse_pr(&out.stdout).unwrap().state, PrLifecycle::Open);
12704        assert!(out.stderr.contains("listen to pull request events"));
12705        assert!(out.combined().contains("listen to pull request events"));
12706        assert!(out.combined().contains("feat: test"));
12707
12708        let ok_list = fake_gh_script(tmp.path(), "ok-list", &format!("{valid_list}\n"), hint, 0);
12709        assert_eq!(
12710            find_open_pr_with(&ok_list, tmp.path(), "magi/task-t", "main")
12711                .await
12712                .unwrap(),
12713            OpenPr::One {
12714                url: "https://github.com/example/repo/pull/1".into(),
12715                title: "feat: test".into(),
12716            }
12717        );
12718
12719        // Malformed stdout with trailing characters still fails strict JSON parsing.
12720        let malformed = fake_gh_script(
12721            tmp.path(),
12722            "malformed",
12723            &format!("{valid_view}\ntrailing garbage\n"),
12724            "",
12725            0,
12726        );
12727        let out = gh_with(&malformed, tmp.path(), &["pr".into(), "view".into()])
12728            .await
12729            .unwrap();
12730        assert!(out.ok);
12731        let err = parse_pr(&out.stdout).unwrap_err();
12732        assert!(
12733            format!("{err:#}").contains("trailing characters"),
12734            "{err:#}"
12735        );
12736
12737        // Empty stdout + nonempty stderr on exit 0 never substitutes stderr.
12738        let empty = fake_gh_script(tmp.path(), "empty", "", hint, 0);
12739        let out = gh_with(&empty, tmp.path(), &["pr".into(), "view".into()])
12740            .await
12741            .unwrap();
12742        assert!(out.ok);
12743        assert!(out.stdout.trim().is_empty());
12744        assert!(parse_pr(&out.stdout).is_err());
12745
12746        // Non-zero exit with valid JSON on stdout and error on stderr reports
12747        // failure and preserves both streams in `combined()`.
12748        let failed = fake_gh_script(
12749            tmp.path(),
12750            "failed",
12751            &format!("{valid_view}\n"),
12752            "gh: HTTP 404 Not Found\n",
12753            1,
12754        );
12755        let out = gh_with(&failed, tmp.path(), &["pr".into(), "view".into()])
12756            .await
12757            .unwrap();
12758        assert!(!out.ok);
12759        let diag = out.combined();
12760        assert!(diag.contains("HTTP 404 Not Found"), "{diag}");
12761        assert!(diag.contains("feat: test"), "{diag}");
12762        let list_err = find_open_pr_with(&failed, tmp.path(), "magi/task-t", "main")
12763            .await
12764            .unwrap_err()
12765            .to_string();
12766        assert!(list_err.contains("HTTP 404 Not Found"), "{list_err}");
12767    }
12768
12769    struct StaticPrObserver(crate::land_sync_recovery::ObservedPr);
12770
12771    impl crate::land_sync_recovery::PrObserver for StaticPrObserver {
12772        async fn observe_pr(
12773            &self,
12774            _repo: &Path,
12775            _pr_url: &str,
12776        ) -> Result<crate::land_sync_recovery::ObservedPr> {
12777            Ok(self.0.clone())
12778        }
12779    }
12780
12781    const FIXTURE_PR_PREFIX: &str = "https://github.com/example/landing-sync-";
12782
12783    /// Tests share a process-wide home, so each recovery fixture needs a unique
12784    /// PR URL to prevent another test's `write_pr_state_through` from settling it.
12785    fn fixture_pr_url(state: &RunState) -> String {
12786        format!("{FIXTURE_PR_PREFIX}{}/pull/42", state.id)
12787    }
12788
12789    /// Build a real-shaped legacy landing base-sync exhaustion fixture backed by
12790    /// an isolated temp Git repo, bare origin, queue task, and open PR metadata.
12791    async fn legacy_exhausted_landing_fixture() -> (
12792        tempfile::TempDir,
12793        PathBuf,
12794        crate::queue::Queue,
12795        crate::queue::Task,
12796        RunState,
12797        String,
12798    ) {
12799        let (tmp, mut state, old) = landing_git_fixture().await;
12800        crate::run::pin_test_home();
12801        let home = crate::run::home();
12802        // Move run state under this isolated home so load_under/save_under match.
12803        state.config.graph.land_rounds = 4;
12804        state.config.graph.land_approval = true;
12805        state.config.verify.gate = vec!["git rev-parse HEAD".into()];
12806        state.config.verify.e2e = vec!["git rev-parse HEAD".into()];
12807        state.status = RunStatus::Blocked;
12808        state.driver_exited = true;
12809        state.pr = Some(crate::run::PrRecord {
12810            url: fixture_pr_url(&state),
12811            number: 42,
12812            state: "open".to_owned(),
12813            checks: "green".to_owned(),
12814            round: 0,
12815            rounds: 4,
12816            red_at_merge: Vec::new(),
12817        });
12818        state.merge = Some(MergeOutcome {
12819            mode: MergeMode::Pr,
12820            ok: false,
12821            detail:
12822                "could not synchronize landing base: landing base synchronization budget exhausted"
12823                    .to_owned(),
12824            empty: false,
12825        });
12826        state.reviews = vec![serde_json::from_value(serde_json::json!({
12827            "round": 1,
12828            "head": old,
12829            "expected": 2,
12830            "answered": 2,
12831            "reviews": [],
12832            "clean": true,
12833            "e2e": [{"command": "git rev-parse HEAD", "code": 0, "output_tail": old, "duration_ms": 10}],
12834            "verified_head": old,
12835            "verified_at": jiff::Timestamp::now(),
12836            "e2e_deferred": false
12837        }))
12838        .unwrap()];
12839        let pass_cmd: crate::run::CommandOutcome = serde_json::from_value(serde_json::json!({
12840            "command": "git rev-parse HEAD",
12841            "code": 0,
12842            "output_tail": old,
12843            "duration_ms": 10
12844        }))
12845        .unwrap();
12846        state.head_e2e = Some(crate::run::GateRepairE2e::new(
12847            old.clone(),
12848            true,
12849            vec![pass_cmd.clone()],
12850        ));
12851        state.gate = vec![pass_cmd];
12852        state.gate_ran = true;
12853        state.gate_head = Some(old.clone());
12854        state.land_sync_attempts = 4;
12855        state.land_sync_target = None;
12856        state.land_sync_pending = true;
12857        state.event(
12858            "land",
12859            "stopped: could not synchronize landing base: landing base synchronization budget exhausted",
12860        );
12861
12862        let queue = crate::queue::Queue::at(home.join("queue"));
12863        let mut task = crate::queue::Task::new(
12864            "landing sync".into(),
12865            state.instruction.clone(),
12866            state.repo.clone(),
12867            crate::queue::Source::Human,
12868        );
12869        task.link_run(&state.id);
12870        task.hold_machine(Some("landing base synchronization budget exhausted".into()));
12871        queue.put(&mut task).unwrap();
12872        state.origin = Some(crate::run::Origin::queue(&task.id));
12873        state.save_under(&home).unwrap();
12874        (tmp, home, queue, task, state, old)
12875    }
12876
12877    #[tokio::test]
12878    async fn land_sync_recovery_isolated_from_unrelated_pr_settlement() {
12879        let (_tmp, _home, _queue, _task, mut state, _old) =
12880            legacy_exhausted_landing_fixture().await;
12881        let home = tempfile::tempdir().unwrap();
12882        state.save_under(home.path()).unwrap();
12883        let mut source = run_state();
12884        source.pr = state.pr.clone();
12885        source.pr.as_mut().unwrap().url = green_pr().url;
12886        assert_eq!(
12887            write_pr_state_through_in(home.path(), &source, PrLifecycle::Merged),
12888            0
12889        );
12890        // The unrelated record must not be locked even during selection.
12891        assert_eq!(
12892            rewrite_open_prs(home.path(), &mut |candidate| {
12893                assert_eq!(candidate.id, state.id);
12894                let _owner = crate::pr_head::owner_lock(home.path(), &candidate.id)
12895                    .expect("unrelated PR scan must not hold the recovery owner lock");
12896                names_same_pr(
12897                    candidate,
12898                    &source.pr.as_ref().unwrap().url,
12899                    42,
12900                    &source.repo,
12901                )
12902                .then_some(PrLifecycle::Merged)
12903            }),
12904            0
12905        );
12906        let saved = RunState::load_under(&state.id, home.path()).unwrap();
12907        assert_eq!(saved.pr.as_ref().unwrap().state, "open");
12908        assert!(saved.land_sync_exhausted());
12909    }
12910
12911    #[tokio::test]
12912    async fn land_sync_recovery_continues_legacy_real_shaped_stop_on_existing_pr() {
12913        let (_tmp, home, queue, task, mut state, old) = legacy_exhausted_landing_fixture().await;
12914        let home = home.as_path();
12915
12916        // Advance origin/main once so landing rebase has real work to replay.
12917        advance_landing_base(&state).await;
12918
12919        state.pre_gate = vec![
12920            serde_json::from_value(serde_json::json!({
12921                "command": "prepare sources",
12922                "code": 0,
12923                "output_tail": "prepared",
12924                "duration_ms": 15
12925            }))
12926            .unwrap(),
12927        ];
12928        let pre_gate_commit = git::rev_parse(&state.repo, "HEAD^").await.unwrap();
12929        assert_ne!(pre_gate_commit, old);
12930        state.pre_gate_commit = Some(pre_gate_commit.clone());
12931        let pre_gate = serde_json::to_value(&state.pre_gate).unwrap();
12932        state.save_under(home).unwrap();
12933
12934        // Pre-recovery: legacy shape recognized, recover-base refused, ordinary resume/release refused.
12935        assert!(state.land_sync_exhausted());
12936        assert!(!state.base_sync_blocked());
12937        assert!(crate::land_sync_recovery::held_task(&queue, &task));
12938        let base_err = crate::graph::Runner::authorize_base_recovery(home, &state.id, &task.id)
12939            .await
12940            .unwrap_err();
12941        assert!(
12942            base_err.to_string().contains("run has no base-sync stop"),
12943            "{base_err:#}"
12944        );
12945        assert!(crate::handover::resume_refusal_under(&state, Some(home)).is_none());
12946        assert!(crate::base_sync_recovery::ensure_generic_release(&queue, &task).is_err());
12947
12948        // Ordinary land_with without authorization refuses without refilling budget.
12949        let pr_url = state.pr.as_ref().unwrap().url.clone();
12950        let blocked_forge =
12951            Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
12952        let err = land_with(&mut state, &pr_url, &blocked_forge)
12953            .await
12954            .unwrap_err();
12955        assert!(err.to_string().contains("budget exhausted"), "{err:#}");
12956        assert_eq!(state.land_sync_attempts, 4);
12957        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12958
12959        // Attach a prior head-bound approval on `old` to prove fresh approval is required after recovery.
12960        let questions = ask::Questions::at(home.join("questions"));
12961        let mut old_q = ask::Question::new(
12962            state.id.clone(),
12963            APPROVAL_NODE.into(),
12964            "owner".into(),
12965            "old head approval".into(),
12966            String::new(),
12967            vec![APPROVE.into()],
12968        );
12969        old_q
12970            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12971            .unwrap();
12972        questions.put(&mut old_q).unwrap();
12973        state.land_approval = Some(LandApproval {
12974            question: old_q.id.clone(),
12975            head: old.clone(),
12976        });
12977        state.save_under(home).unwrap();
12978
12979        // Admit explicit recover-land-sync via two-phase control.
12980        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12981            url: pr_url.clone(),
12982            number: 42,
12983            open: true,
12984            head: old.clone(),
12985            base_branch: Some("main".to_owned()),
12986        });
12987        let outcome = crate::land_sync_recovery_control::recover_with(
12988            &queue,
12989            home,
12990            crate::land_sync_recovery_control::Request {
12991                run: state.id.clone(),
12992                head: old.clone(),
12993                actor: "cli".into(),
12994                request: "req-legacy-1".into(),
12995            },
12996            &observer,
12997        )
12998        .await
12999        .unwrap();
13000        assert!(!outcome.repeated);
13001        assert_eq!(
13002            outcome
13003                .task
13004                .resume_override
13005                .as_ref()
13006                .and_then(|pin| pin.pinned_run.as_deref()),
13007            Some(state.id.as_str())
13008        );
13009
13010        // Ordinary fast-forward of origin/main between admission and dispatch is allowed.
13011        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13012        std::fs::write(state.repo.join("advance2"), "advance2").unwrap();
13013        git::git(&state.repo, &["add", "."]).await.unwrap();
13014        git::git(&state.repo, &["commit", "-m", "advance base again"])
13015            .await
13016            .unwrap();
13017        git::git(&state.repo, &["push", "origin", "main"])
13018            .await
13019            .unwrap();
13020        git::git(&state.repo, &["checkout", "winner"])
13021            .await
13022            .unwrap();
13023
13024        let reloaded_task = queue.get(&task.id).unwrap();
13025        assert!(matches!(
13026            crate::land_sync_recovery::dispatch_check_with(&queue, home, &reloaded_task, &observer)
13027                .await,
13028            crate::land_sync_recovery::DispatchDecision::Proceed
13029        ));
13030
13031        // Execute continuation on the existing PR using real rebase + fresh gate + fresh E2E.
13032        let mut run = RunState::load_under(&state.id, home).unwrap();
13033        assert!(run.land_sync_recovery_pending());
13034        let mut forge = Scripted::for_pr(
13035            &pr_url,
13036            vec![
13037                seen(&old, Checks::Green, "BEHIND", false),
13038                seen(&old, Checks::Green, "BEHIND", false),
13039                seen("@published", Checks::Green, "CLEAN", false),
13040            ],
13041        );
13042        forge.public_repo = Some(run.repo.clone());
13043        let pr = land_with(&mut run, &pr_url, &forge).await.unwrap();
13044        assert_eq!(pr.state, PrLifecycle::Open);
13045        assert!(run.parked, "must park awaiting fresh head-bound approval");
13046
13047        // Verify attempts preserved (4 -> 5), 1 grant consumed, fresh head published,
13048        // prior verification archived, fresh gate + E2E ran on new head, fresh approval asked.
13049        let new_head = git::rev_parse(&run.repo, "HEAD").await.unwrap();
13050        assert_ne!(new_head, old);
13051        assert_eq!(run.land_sync_attempts, 5);
13052        assert_eq!(run.land_sync_recovery.extra_attempts, 1);
13053        assert_eq!(run.land_sync_budget(), 5);
13054        assert!(!run.land_sync_pending);
13055        assert_eq!(run.pr_pushed_head.as_deref(), Some(new_head.as_str()));
13056        assert_eq!(
13057            git::remote_head(&run.repo, "origin", "task-head")
13058                .await
13059                .unwrap()
13060                .as_deref(),
13061            Some(new_head.as_str())
13062        );
13063        assert!(run.gate_ran);
13064        assert_eq!(run.gate_head.as_deref(), Some(new_head.as_str()));
13065        assert!(
13066            run.head_e2e
13067                .as_ref()
13068                .is_some_and(|e| e.head == new_head && e.passed)
13069        );
13070        assert_eq!(run.reviews.len(), 1);
13071        assert!(run.reviews[0].clean);
13072        assert_eq!(run.reviews[0].answered, 2);
13073        assert!(run.reviews[0].verified_head.is_none());
13074        assert!(!run.verification_history.is_empty());
13075        assert_eq!(run.land_sync_recovery.stops.len(), 1);
13076        assert_eq!(run.land_sync_recovery.authorizations.len(), 1);
13077        let auth = &run.land_sync_recovery.authorizations[0];
13078        assert!(auth.consumed);
13079        assert!(auth.invalidated.is_none());
13080        assert!(run.pre_gate.is_empty());
13081        assert!(run.pre_gate_commit.is_none());
13082        let saved = RunState::load_under(&run.id, home).unwrap();
13083        assert!(saved.pre_gate.is_empty());
13084        assert!(saved.pre_gate_commit.is_none());
13085        let archived = saved.land_sync_recovery.authorizations[0]
13086            .archived_verification
13087            .as_ref()
13088            .unwrap();
13089        assert_eq!(serde_json::to_value(&archived.pre_gate).unwrap(), pre_gate);
13090        assert_eq!(
13091            archived.pre_gate_commit.as_deref(),
13092            Some(pre_gate_commit.as_str())
13093        );
13094
13095        let mut legacy = serde_json::to_value(archived).unwrap();
13096        let fields = legacy.as_object_mut().unwrap();
13097        fields.remove("pre_gate");
13098        fields.remove("pre_gate_commit");
13099        let legacy: crate::land_sync_recovery::ArchivedVerification =
13100            serde_json::from_value(legacy).unwrap();
13101        assert!(legacy.pre_gate.is_empty());
13102        assert!(legacy.pre_gate_commit.is_none());
13103        let new_approval = run.land_approval.as_ref().unwrap();
13104        assert_ne!(new_approval.question, old_q.id);
13105        assert_eq!(new_approval.head, new_head);
13106    }
13107
13108    #[tokio::test]
13109    async fn land_sync_recovery_observes_external_merge_without_grant() {
13110        let (_tmp, home, queue, mut task, mut state, old) =
13111            legacy_exhausted_landing_fixture().await;
13112        let pr_url = state.pr.as_ref().unwrap().url.clone();
13113        task.resume_override = Some(crate::queue::OperatorResume {
13114            question_id: String::new(),
13115            at: jiff::Timestamp::now(),
13116            conductor_rehold: None,
13117            forced: true,
13118            pinned_run: Some(state.id.clone()),
13119        });
13120        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13121            url: pr_url.clone(),
13122            number: 42,
13123            open: false,
13124            head: old.clone(),
13125            base_branch: Some("main".into()),
13126        });
13127        assert!(matches!(
13128            crate::land_sync_recovery::dispatch_check_with(&queue, &home, &task, &observer).await,
13129            crate::land_sync_recovery::DispatchDecision::Proceed
13130        ));
13131        let forge = Scripted::for_pr(&pr_url, vec![merged_view(&old)]);
13132        land_with(&mut state, &pr_url, &forge).await.unwrap();
13133        assert_eq!(state.status, RunStatus::Merged);
13134        assert_eq!(state.land_sync_attempts, 4);
13135        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
13136        assert_eq!(forge.calls(), ["view"]);
13137    }
13138
13139    #[tokio::test]
13140    async fn land_sync_recovery_forces_fresh_e2e_and_gate_even_when_head_unchanged() {
13141        let (tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
13142        let home = home.as_path();
13143
13144        // Create marker-writing commands for gate and e2e so we prove both execute freshly
13145        // even when HEAD does not change (origin/main is already an ancestor of winner).
13146        let gate_marker = tmp.path().join("fresh-gate-ran");
13147        let e2e_marker = tmp.path().join("fresh-e2e-ran");
13148        state.config.verify.gate = vec![format!(
13149            "git rev-parse HEAD > \"{}\"",
13150            gate_marker.display().to_string().replace('\\', "/")
13151        )];
13152        state.config.verify.e2e = vec![format!(
13153            "git rev-parse HEAD > \"{}\"",
13154            e2e_marker.display().to_string().replace('\\', "/")
13155        )];
13156        let questions = ask::Questions::at(home.join("questions"));
13157        let mut old_q = ask::Question::new(
13158            state.id.clone(),
13159            APPROVAL_NODE.into(),
13160            "owner".into(),
13161            "prior approval on same head".into(),
13162            String::new(),
13163            vec![APPROVE.into()],
13164        );
13165        old_q
13166            .answer(ask::Answer::Choice(APPROVE.to_owned()))
13167            .unwrap();
13168        questions.put(&mut old_q).unwrap();
13169        state.land_approval = Some(LandApproval {
13170            question: old_q.id.clone(),
13171            head: old.clone(),
13172        });
13173        state.save_under(home).unwrap();
13174
13175        let pr_url = state.pr.as_ref().unwrap().url.clone();
13176        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13177            url: pr_url.clone(),
13178            number: 42,
13179            open: true,
13180            head: old.clone(),
13181            base_branch: Some("main".to_owned()),
13182        });
13183        crate::land_sync_recovery_control::recover_with(
13184            &queue,
13185            home,
13186            crate::land_sync_recovery_control::Request {
13187                run: state.id.clone(),
13188                head: old.clone(),
13189                actor: "cli".into(),
13190                request: "req-same-head".into(),
13191            },
13192            &observer,
13193        )
13194        .await
13195        .unwrap();
13196
13197        let mut run = RunState::load_under(&state.id, home).unwrap();
13198        let mut forge = Scripted::for_pr(
13199            &pr_url,
13200            vec![
13201                seen(&old, Checks::Green, "CLEAN", false),
13202                seen(&old, Checks::Green, "CLEAN", false),
13203                seen(&old, Checks::Green, "CLEAN", false),
13204            ],
13205        );
13206        forge.public_repo = Some(run.repo.clone());
13207        land_with(&mut run, &pr_url, &forge).await.unwrap();
13208
13209        assert!(
13210            gate_marker.exists(),
13211            "fresh gate must run even on unchanged HEAD"
13212        );
13213        assert!(
13214            e2e_marker.exists(),
13215            "fresh E2E must run even on unchanged HEAD"
13216        );
13217        assert!(
13218            run.parked,
13219            "old approval before recovery must not be reused"
13220        );
13221        assert_ne!(run.land_approval.as_ref().unwrap().question, old_q.id);
13222    }
13223
13224    #[tokio::test]
13225    async fn land_sync_recovery_resumes_after_gate_repair_before_push() {
13226        let (_tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
13227        landing_gate_fixer(
13228            &mut state,
13229            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
13230        );
13231        state.config.verify.gate =
13232            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
13233        state.save_under(&home).unwrap();
13234        let pr_url = state.pr.as_ref().unwrap().url.clone();
13235        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13236            url: pr_url.clone(),
13237            number: 42,
13238            open: true,
13239            head: old.clone(),
13240            base_branch: Some("main".into()),
13241        });
13242        crate::land_sync_recovery_control::recover_with(
13243            &queue,
13244            &home,
13245            crate::land_sync_recovery_control::Request {
13246                run: state.id.clone(),
13247                head: old.clone(),
13248                actor: "cli".into(),
13249                request: "req-interrupted-gate-repair".into(),
13250            },
13251            &observer,
13252        )
13253        .await
13254        .unwrap();
13255        let mut run = RunState::load_under(&state.id, &home).unwrap();
13256        let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "CLEAN", false)]);
13257        assert!(matches!(
13258            prepare_land_sync_recovery(&mut run, &pr_url, &forge)
13259                .await
13260                .unwrap(),
13261            LandSyncPrep::Continue(Some(_))
13262        ));
13263        // Interrupt at the publication check, after the real gate fixer commits.
13264        let changed = Scripted::for_pr(
13265            &pr_url,
13266            vec![seen("different", Checks::Green, "CLEAN", false)],
13267        );
13268        let error = resume_landing_head(&mut run, &old, &pr_url, &changed, None)
13269            .await
13270            .unwrap_err();
13271        assert!(
13272            error.to_string().contains("PR head changed while gating"),
13273            "{error}"
13274        );
13275        let repaired = git::rev_parse(&run.repo, "HEAD").await.unwrap();
13276        assert_ne!(repaired, old);
13277        assert_eq!(run.gate_fixes.len(), 1);
13278        assert!(run.gate_fixes[0].committed);
13279        assert_eq!(
13280            git::remote_head(&run.repo, "origin", "task-head")
13281                .await
13282                .unwrap(),
13283            Some(old.clone())
13284        );
13285
13286        run.status = RunStatus::Blocked;
13287        run.save().unwrap();
13288        let mut resumed = RunState::load_under(&run.id, &home).unwrap();
13289        assert_eq!(resumed.land_sync_attempts, 5);
13290        assert!(resumed.land_sync_pending);
13291        assert!(!resumed.land_sync_exhausted());
13292        assert!(!resumed.land_sync_unstarted_grant());
13293        assert!(matches!(
13294            prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
13295                .await
13296                .unwrap(),
13297            LandSyncPrep::Continue(None)
13298        ));
13299        assert_eq!(
13300            resume_landing_head(&mut resumed, &old, &pr_url, &forge, None)
13301                .await
13302                .unwrap(),
13303            repaired
13304        );
13305        assert_eq!(resumed.land_sync_attempts, 5);
13306        assert_eq!(resumed.gate_fixes.len(), 1);
13307        assert!(!resumed.land_sync_pending);
13308        assert!(
13309            resumed.land_sync_recovery.authorizations[0]
13310                .invalidated
13311                .is_none()
13312        );
13313        assert_eq!(
13314            git::remote_head(&resumed.repo, "origin", "task-head")
13315                .await
13316                .unwrap(),
13317            Some(repaired)
13318        );
13319    }
13320
13321    #[tokio::test]
13322    async fn land_sync_recovery_repeated_exhaustion_is_bounded_by_lifetime_cap() {
13323        let (_tmp, home, queue, task, mut state, mut head) =
13324            legacy_exhausted_landing_fixture().await;
13325        let home = home.as_path();
13326        state.config.graph.land_approval = false;
13327        state.save_under(home).unwrap();
13328
13329        let pr_url = state.pr.as_ref().unwrap().url.clone();
13330        let mut base_step = 0usize;
13331        let advance_step = |repo: PathBuf, step: usize| async move {
13332            git::git(&repo, &["checkout", "main"]).await.unwrap();
13333            std::fs::write(repo.join(format!("advance-{step}")), format!("step-{step}")).unwrap();
13334            git::git(&repo, &["add", "."]).await.unwrap();
13335            git::git(&repo, &["commit", "-m", &format!("advance base {step}")])
13336                .await
13337                .unwrap();
13338            git::git(&repo, &["push", "origin", "main"]).await.unwrap();
13339            git::git(&repo, &["checkout", "winner"]).await.unwrap();
13340        };
13341        for grant_num in 1..=crate::land_sync_recovery::MAX_GRANTS {
13342            base_step += 1;
13343            advance_step(state.repo.clone(), base_step).await;
13344            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13345                url: pr_url.clone(),
13346                number: 42,
13347                open: true,
13348                head: head.clone(),
13349                base_branch: Some("main".to_owned()),
13350            });
13351            crate::land_sync_recovery_control::recover_with(
13352                &queue,
13353                home,
13354                crate::land_sync_recovery_control::Request {
13355                    run: state.id.clone(),
13356                    head: head.clone(),
13357                    actor: "cli".into(),
13358                    request: format!("req-cap-{grant_num}"),
13359                },
13360                &observer,
13361            )
13362            .await
13363            .unwrap();
13364
13365            // Simulate execution consuming grant, spending the 1 attempt, and hitting exhaustion again.
13366            state = RunState::load_under(&state.id, home).unwrap();
13367            let mut forge = Scripted::for_pr(
13368                &pr_url,
13369                vec![
13370                    seen(&head, Checks::Green, "BEHIND", false),
13371                    seen(&head, Checks::Green, "BEHIND", false),
13372                    seen("@published", Checks::Green, "BEHIND", false),
13373                ],
13374            );
13375            forge.public_repo = Some(state.repo.clone());
13376            let prep = prepare_land_sync_recovery(&mut state, &pr_url, &forge)
13377                .await
13378                .unwrap();
13379            assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
13380            head = resume_landing_head(&mut state, &head, &pr_url, &forge, None)
13381                .await
13382                .unwrap();
13383            assert_eq!(state.land_sync_attempts, 4 + grant_num);
13384            assert_eq!(state.land_sync_recovery.extra_attempts, grant_num);
13385
13386            // Re-exhaust on another base advance.
13387            base_step += 1;
13388            advance_step(state.repo.clone(), base_step).await;
13389            let err = rebase_landing_worktree(&mut state, "origin/main")
13390                .await
13391                .unwrap_err();
13392            assert!(err.to_string().contains("budget exhausted"), "{err:#}");
13393            state.status = RunStatus::Blocked;
13394            state.save_under(home).unwrap();
13395            assert!(state.land_sync_exhausted());
13396
13397            // Put task back to Held so the next explicit authorization can queue it.
13398            let mut t = queue.get(&task.id).unwrap();
13399            t.hold_machine(Some("re-exhausted".into()));
13400            queue.put(&mut t).unwrap();
13401        }
13402
13403        assert_eq!(
13404            state.land_sync_attempts,
13405            4 + crate::land_sync_recovery::MAX_GRANTS
13406        );
13407        assert_eq!(state.land_sync_grants_remaining(), 0);
13408        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13409            url: pr_url,
13410            number: 42,
13411            open: true,
13412            head: head.clone(),
13413            base_branch: Some("main".to_owned()),
13414        });
13415        let err = crate::land_sync_recovery_control::recover_with(
13416            &queue,
13417            home,
13418            crate::land_sync_recovery_control::Request {
13419                run: state.id.clone(),
13420                head,
13421                actor: "cli".into(),
13422                request: "req-cap-overflow".into(),
13423            },
13424            &observer,
13425        )
13426        .await
13427        .unwrap_err();
13428        assert!(
13429            err.to_string()
13430                .contains("lifetime landing base-sync recovery limit reached"),
13431            "{err:#}"
13432        );
13433    }
13434
13435    #[tokio::test]
13436    async fn land_sync_recovery_execution_revalidation_refuses_stale_pr_head_and_rewritten_base() {
13437        // Case A: PR head moves externally between admission and execution.
13438        {
13439            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13440            let pr_url = state.pr.as_ref().unwrap().url.clone();
13441            let home = home.as_path();
13442            advance_landing_base(&state).await;
13443            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13444                url: pr_url.clone(),
13445                number: 42,
13446                open: true,
13447                head: old.clone(),
13448                base_branch: Some("main".to_owned()),
13449            });
13450            crate::land_sync_recovery_control::recover_with(
13451                &queue,
13452                home,
13453                crate::land_sync_recovery_control::Request {
13454                    run: state.id.clone(),
13455                    head: old.clone(),
13456                    actor: "cli".into(),
13457                    request: "req-stale-pr".into(),
13458                },
13459                &observer,
13460            )
13461            .await
13462            .unwrap();
13463
13464            let mut run = RunState::load_under(&state.id, home).unwrap();
13465            let foreign_head = "f".repeat(40);
13466            let forge = Scripted::for_pr(
13467                &pr_url,
13468                vec![seen(&foreign_head, Checks::Green, "BEHIND", false)],
13469            );
13470            land_with(&mut run, &pr_url, &forge).await.unwrap();
13471            assert_eq!(run.status, RunStatus::Blocked);
13472            assert_eq!(run.land_sync_recovery.extra_attempts, 0);
13473            assert_eq!(run.land_sync_attempts, 4);
13474            let auth = run.land_sync_recovery.authorizations.last().unwrap();
13475            assert!(auth.consumed);
13476            assert!(
13477                auth.invalidated
13478                    .as_deref()
13479                    .is_some_and(|why| why.contains("published PR head changed")),
13480                "{:?}",
13481                auth.invalidated
13482            );
13483            assert_eq!(run.pr_pushed_head.as_deref(), Some(old.as_str()));
13484        }
13485
13486        // Case B: origin/main rewritten (non-fast-forward) between admission and execution.
13487        {
13488            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13489            let pr_url = state.pr.as_ref().unwrap().url.clone();
13490            let home = home.as_path();
13491            advance_landing_base(&state).await;
13492            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13493                url: pr_url.clone(),
13494                number: 42,
13495                open: true,
13496                head: old.clone(),
13497                base_branch: Some("main".to_owned()),
13498            });
13499            crate::land_sync_recovery_control::recover_with(
13500                &queue,
13501                home,
13502                crate::land_sync_recovery_control::Request {
13503                    run: state.id.clone(),
13504                    head: old.clone(),
13505                    actor: "cli".into(),
13506                    request: "req-rewritten-base".into(),
13507                },
13508                &observer,
13509            )
13510            .await
13511            .unwrap();
13512
13513            // Persist consumption before the rewrite, as if the driver crashed
13514            // between granting the attempt and starting the rebase.
13515            let mut consumed = RunState::load_under(&state.id, home).unwrap();
13516            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13517            assert!(matches!(
13518                prepare_land_sync_recovery(&mut consumed, &pr_url, &forge)
13519                    .await
13520                    .unwrap(),
13521                LandSyncPrep::Continue(Some(_))
13522            ));
13523            assert_eq!(consumed.land_sync_attempts, 4);
13524
13525            // Rewrite origin/main by amending the latest base commit and force-pushing.
13526            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13527            std::fs::write(state.repo.join("advance"), "rewritten").unwrap();
13528            git::git(&state.repo, &["add", "."]).await.unwrap();
13529            git::git(&state.repo, &["commit", "--amend", "-m", "rewritten base"])
13530                .await
13531                .unwrap();
13532            git::git(&state.repo, &["push", "--force", "origin", "main"])
13533                .await
13534                .unwrap();
13535            git::git(&state.repo, &["checkout", "winner"])
13536                .await
13537                .unwrap();
13538
13539            let mut run = RunState::load_under(&state.id, home).unwrap();
13540            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13541            land_with(&mut run, &pr_url, &forge).await.unwrap();
13542            assert_eq!(run.status, RunStatus::Blocked);
13543            assert_eq!(run.land_sync_recovery.extra_attempts, 1);
13544            assert_eq!(run.land_sync_attempts, 4);
13545            assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
13546            let auth = run.land_sync_recovery.authorizations.last().unwrap();
13547            assert!(auth.consumed);
13548            assert!(
13549                auth.invalidated
13550                    .as_deref()
13551                    .is_some_and(|why| why.contains("does not fast-forward")),
13552                "{:?}",
13553                auth.invalidated
13554            );
13555            assert!(run.land_sync_exhausted());
13556            assert_eq!(run.land_sync_budget(), 4);
13557            let mut held = queue
13558                .list()
13559                .into_iter()
13560                .find(|t| t.execution_runs().last() == Some(&run.id))
13561                .unwrap();
13562            held.hold_machine(Some("recovery scope changed".into()));
13563            queue.put(&mut held).unwrap();
13564            crate::land_sync_recovery_control::recover_with(
13565                &queue,
13566                home,
13567                crate::land_sync_recovery_control::Request {
13568                    run: run.id.clone(),
13569                    head: old.clone(),
13570                    actor: "cli".into(),
13571                    request: "req-rewritten-base-new-approval".into(),
13572                },
13573                &observer,
13574            )
13575            .await
13576            .unwrap();
13577            let mut resumed = RunState::load_under(&run.id, home).unwrap();
13578            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13579            assert!(matches!(
13580                prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
13581                    .await
13582                    .unwrap(),
13583                LandSyncPrep::Continue(Some(_))
13584            ));
13585            assert_eq!(resumed.land_sync_recovery.extra_attempts, 2);
13586            assert_eq!(resumed.land_sync_budget(), 5);
13587            assert_eq!(resumed.land_sync_attempts, 4);
13588            assert!(
13589                resumed.land_sync_recovery.authorizations[0]
13590                    .invalidated
13591                    .is_some()
13592            );
13593        }
13594    }
13595
13596    #[tokio::test]
13597    async fn land_sync_recovery_restart_after_consume_continues_without_double_grant() {
13598        let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13599        let home = home.as_path();
13600        let pr_url = state.pr.as_ref().unwrap().url.clone();
13601        advance_landing_base(&state).await;
13602        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13603            url: pr_url.clone(),
13604            number: 42,
13605            open: true,
13606            head: old.clone(),
13607            base_branch: Some("main".to_owned()),
13608        });
13609        crate::land_sync_recovery_control::recover_with(
13610            &queue,
13611            home,
13612            crate::land_sync_recovery_control::Request {
13613                run: state.id.clone(),
13614                head: old.clone(),
13615                actor: "cli".into(),
13616                request: "req-crash-after-consume".into(),
13617            },
13618            &observer,
13619        )
13620        .await
13621        .unwrap();
13622
13623        // Simulate consuming the authorization and crashing right before rebase starts.
13624        let mut crashed = RunState::load_under(&state.id, home).unwrap();
13625        let initial_forge =
13626            Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13627        let prep = prepare_land_sync_recovery(&mut crashed, &pr_url, &initial_forge)
13628            .await
13629            .unwrap();
13630        assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
13631        assert_eq!(crashed.land_sync_recovery.extra_attempts, 1);
13632        assert_eq!(crashed.land_sync_attempts, 4);
13633        assert!(crashed.land_sync_recovery.authorizations[0].consumed);
13634
13635        // An unreadable base is not proof that the authorized lineage changed.
13636        let remote = git::git(&state.repo, &["remote", "get-url", "origin"])
13637            .await
13638            .unwrap();
13639        git::git(
13640            &state.repo,
13641            &["remote", "set-url", "origin", "missing-local-origin"],
13642        )
13643        .await
13644        .unwrap();
13645        let mut interrupted = RunState::load_under(&state.id, home).unwrap();
13646        let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13647        assert!(matches!(
13648            prepare_land_sync_recovery(&mut interrupted, &pr_url, &forge)
13649                .await
13650                .unwrap(),
13651            LandSyncPrep::Stop(_)
13652        ));
13653        assert!(
13654            interrupted.land_sync_recovery.authorizations[0]
13655                .invalidated
13656                .is_none()
13657        );
13658        assert_eq!(interrupted.land_sync_attempts, 4);
13659        git::git(&state.repo, &["remote", "set-url", "origin", remote.trim()])
13660            .await
13661            .unwrap();
13662        let mut held = queue
13663            .list()
13664            .into_iter()
13665            .find(|t| t.execution_runs().last() == Some(&state.id))
13666            .unwrap();
13667        held.hold_machine(Some("base observation failed".into()));
13668        queue.put(&mut held).unwrap();
13669        assert!(crate::resume::pin_queued(&queue, &state.id, None, None).unwrap());
13670        let queued = queue.get(&held.id).unwrap();
13671        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, .. } =
13672            crate::land_sync_recovery::dispatch_check_with(&queue, home, &queued, &observer).await
13673        {
13674            panic!("dispatch refused recovery: {reason}");
13675        }
13676
13677        // Reload after restart and run land_with: uses the 1 already-granted attempt, never double-grants.
13678        let mut restarted = RunState::load_under(&state.id, home).unwrap();
13679        let mut forge = Scripted::for_pr(
13680            &pr_url,
13681            vec![
13682                seen(&old, Checks::Green, "BEHIND", false),
13683                seen(&old, Checks::Green, "BEHIND", false),
13684                seen("@published", Checks::Green, "CLEAN", false),
13685            ],
13686        );
13687        forge.public_repo = Some(restarted.repo.clone());
13688        land_with(&mut restarted, &pr_url, &forge).await.unwrap();
13689        assert_eq!(restarted.land_sync_recovery.extra_attempts, 1);
13690        assert_eq!(restarted.land_sync_attempts, 5);
13691        assert_eq!(restarted.land_sync_recovery.authorizations.len(), 1);
13692        assert!(!restarted.land_sync_pending);
13693    }
13694
13695    #[tokio::test]
13696    async fn land_sync_recovery_dispatch_revalidation_refuses_stale_and_superseded_state() {
13697        // 1. Without authorization, dispatch holds without spending budget.
13698        let (_tmp, home, queue, task, state, old) = legacy_exhausted_landing_fixture().await;
13699        let home = home.as_path();
13700        let pr_url = state.pr.as_ref().unwrap().url.clone();
13701        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13702            url: pr_url,
13703            number: 42,
13704            open: true,
13705            head: old.clone(),
13706            base_branch: Some("main".to_owned()),
13707        });
13708        assert!(matches!(
13709            crate::land_sync_recovery::dispatch_check_with(&queue, home, &task, &observer).await,
13710            crate::land_sync_recovery::DispatchDecision::Hold { .. }
13711        ));
13712
13713        // 2. Admit authorization, then supersede with a newer owner decision before dispatch.
13714        crate::land_sync_recovery_control::recover_with(
13715            &queue,
13716            home,
13717            crate::land_sync_recovery_control::Request {
13718                run: state.id.clone(),
13719                head: old.clone(),
13720                actor: "cli".into(),
13721                request: "req-dispatch-superseded".into(),
13722            },
13723            &observer,
13724        )
13725        .await
13726        .unwrap();
13727        let mut t = queue.get(&task.id).unwrap();
13728        t.operator_decided_at = Some(
13729            t.operator_decided_at.unwrap_or_else(jiff::Timestamp::now)
13730                + jiff::SignedDuration::from_secs(10),
13731        );
13732        queue.put(&mut t).unwrap();
13733        let decision =
13734            crate::land_sync_recovery::dispatch_check_with(&queue, home, &t, &observer).await;
13735        match decision {
13736            crate::land_sync_recovery::DispatchDecision::Hold {
13737                reason,
13738                state: updated,
13739            } => {
13740                assert!(
13741                    reason.contains("newer owner decision superseded"),
13742                    "{reason}"
13743                );
13744                let auth = updated.land_sync_recovery.authorizations.last().unwrap();
13745                assert!(auth.consumed);
13746                assert!(auth.invalidated.is_some());
13747                assert_eq!(updated.land_sync_recovery.extra_attempts, 0);
13748            }
13749            crate::land_sync_recovery::DispatchDecision::Proceed => {
13750                panic!("superseded authorization must be refused at dispatch");
13751            }
13752        }
13753    }
13754}