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    /// An explicitly authorized landing synchronization recovery requires fresh approval.
650    AfterLandingRecovery,
651}
652
653/// Disabling fresh approval controls never bypasses an existing owner decision
654/// or the fresh decision owed after repair, even if repair kept the same head.
655pub fn approval_reasons(state: &RunState) -> Vec<ApprovalReason> {
656    let mut reasons = Vec::new();
657    if state.owner_hold(crate::config::OwnerHold::LandApproval) {
658        reasons.push(ApprovalReason::EveryMerge);
659    }
660    if state.owner_hold(crate::config::OwnerHold::HoldContestedMerge) {
661        if state.open_findings().iter().any(|f| f.severity.blocks()) {
662            reasons.push(ApprovalReason::OpenBlockingFindings);
663        }
664        if state.reviews.last().is_some_and(|r| {
665            r.final_votes()
666                .iter()
667                .any(|(_, _, v)| *v == crate::verdict::ReviewVote::Reject)
668        }) {
669            reasons.push(ApprovalReason::FinalReject);
670        }
671    }
672    if state.land_approval.is_some() {
673        reasons.push(ApprovalReason::ExistingDecision);
674    }
675    if !state.merge_repairs.is_empty() || !state.repair_grants.is_empty() {
676        reasons.push(ApprovalReason::AfterRepair);
677    }
678    if state
679        .land_sync_recovery
680        .authorizations
681        .iter()
682        .any(|auth| auth.consumed && auth.invalidated.is_none())
683    {
684        reasons.push(ApprovalReason::AfterLandingRecovery);
685    }
686    reasons
687}
688
689/// Bound free-form approval evidence by characters, including an explicit
690/// ellipsis when abbreviated. Keep UTF-8 text intact in questions and panels.
691fn approval_excerpt(text: &str, max_chars: usize) -> String {
692    if text.chars().count() <= max_chars {
693        text.to_owned()
694    } else {
695        let mut excerpt: String = text.chars().take(max_chars.saturating_sub(1)).collect();
696        excerpt.push('…');
697        excerpt
698    }
699}
700
701/// Persisted verbatim in the question and panel at creation. Deputies and
702/// resumed questions use that snapshot, never reconstruct past policy from
703/// today's settings. Fixer claims and successful gates are not resolutions.
704fn approval_evidence(state: &RunState) -> String {
705    const TITLE_CHARS: usize = 100;
706    const REASON_CHARS: usize = 300;
707    let reason = |text: &str| approval_excerpt(text, REASON_CHARS);
708    let ja = words(&state.config.graph.language).html_lang == "ja";
709    let mut s = if ja {
710        "承認が必要な理由:\n"
711    } else {
712        "Approval required because:\n"
713    }
714    .to_owned();
715    for reason in approval_reasons(state) {
716        let label = match (reason, ja) {
717            (ApprovalReason::EveryMerge, false) => {
718                "land_approval=true: owner approval for every merge"
719            }
720            (ApprovalReason::EveryMerge, true) => {
721                "land_approval=true: すべてのマージに所有者の承認が必要"
722            }
723            (ApprovalReason::OpenBlockingFindings, false) => {
724                "hold_contested_merge=true: open Major-or-above internal findings"
725            }
726            (ApprovalReason::OpenBlockingFindings, true) => {
727                "hold_contested_merge=true: Major 以上の内部指摘が未解決"
728            }
729            (ApprovalReason::FinalReject, false) => {
730                "hold_contested_merge=true: final reviewer reject after reconsideration (even without Major findings)"
731            }
732            (ApprovalReason::FinalReject, true) => {
733                "hold_contested_merge=true: 再考後の最終票が reject(Major 指摘がなくても承認が必要)"
734            }
735            (ApprovalReason::ExistingDecision, false) => {
736                "existing owner decision: changing controls cannot bypass it"
737            }
738            (ApprovalReason::ExistingDecision, true) => {
739                "既存の所有者判断: 設定変更では迂回できません"
740            }
741            (ApprovalReason::AfterRepair, false) => {
742                "fresh owner approval after merge repair, even with an unchanged head"
743            }
744            (ApprovalReason::AfterRepair, true) => {
745                "マージ修復後の新しい所有者承認(head に変更がなくても必要)"
746            }
747            (ApprovalReason::AfterLandingRecovery, false) => {
748                "fresh owner approval after landing synchronization recovery"
749            }
750            (ApprovalReason::AfterLandingRecovery, true) => {
751                "着地同期の復旧後に新しい所有者承認が必要"
752            }
753        };
754        let control = match reason {
755            ApprovalReason::EveryMerge => Some(crate::config::OwnerHold::LandApproval),
756            ApprovalReason::OpenBlockingFindings | ApprovalReason::FinalReject => {
757                Some(crate::config::OwnerHold::HoldContestedMerge)
758            }
759            _ => None,
760        };
761        let source = control
762            .filter(|c| !c.base_value(&state.config.graph))
763            .and_then(|c| state.branch_owner_holds.iter().find(|h| h.control == c));
764        if let Some(source) = source {
765            if ja {
766                let _ = writeln!(
767                    s,
768                    "- {}=true(レビュー対象ブランチの {} 由来, {})",
769                    source.control.key(),
770                    source.file,
771                    source.head
772                );
773            } else {
774                let _ = writeln!(
775                    s,
776                    "- {}=true from the reviewed branch's {} ({})",
777                    source.control.key(),
778                    source.file,
779                    source.head
780                );
781            }
782        }
783        let _ = writeln!(s, "- {label}");
784    }
785    s.push_str(if ja {
786        "\n再考後の各レビュアーの最終票:\n"
787    } else {
788        "\nFinal reviewer votes after reconsideration:\n"
789    });
790    if let Some(round) = state.reviews.last() {
791        let votes = round.final_votes();
792        for r in &round.reviews {
793            let vote = votes
794                .iter()
795                .find(|(seat, _, _)| *seat == r.reviewer)
796                .map(|(_, _, v)| v.label())
797                .unwrap_or(if ja { "記録なし" } else { "not recorded" });
798            let _ = writeln!(s, "#{} ({}): {vote}", r.reviewer, r.agent);
799            let rv = round
800                .reconsideration
801                .iter()
802                .find(|rv| rv.reviewer == r.reviewer);
803            if let Some(rv) = rv.filter(|rv| rv.vote.is_some()) {
804                let initial = r.vote.map(|v| v.label()).unwrap_or("?");
805                let _ = writeln!(
806                    s,
807                    "  {}: {initial} → {vote}",
808                    if ja { "再考" } else { "reconsideration" }
809                );
810                let _ = writeln!(
811                    s,
812                    "  {}: {}",
813                    if ja { "理由" } else { "reason" },
814                    reason(if rv.reason.trim().is_empty() {
815                        if ja { "記録なし" } else { "not recorded" }
816                    } else {
817                        &rv.reason
818                    })
819                );
820            } else {
821                let _ = writeln!(
822                    s,
823                    "  {}: {}",
824                    if ja {
825                        "初回票を保持・理由"
826                    } else {
827                        "initial vote retained; reason"
828                    },
829                    reason(if r.summary.trim().is_empty() {
830                        if ja { "記録なし" } else { "not recorded" }
831                    } else {
832                        &r.summary
833                    })
834                );
835                if let Some(rv) = rv {
836                    let _ = writeln!(
837                        s,
838                        "  {}: {}",
839                        if ja {
840                            "再投票の回答なし"
841                        } else {
842                            "no reconsideration vote"
843                        },
844                        reason(rv.failed.as_deref().unwrap_or(if ja {
845                            "理由の記録なし"
846                        } else {
847                            "reason not recorded"
848                        }))
849                    );
850                }
851            }
852            if let Some(failed) = &r.failed {
853                let _ = writeln!(
854                    s,
855                    "  {}: {}",
856                    if ja { "回答なし" } else { "no answer" },
857                    reason(failed)
858                );
859            }
860        }
861    } else {
862        s.push_str(if ja {
863            "レビュー記録なし\n"
864        } else {
865            "No review recorded\n"
866        });
867    }
868    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" });
869    let findings = state.last_round_findings();
870    for f in &findings {
871        let _ = writeln!(
872            s,
873            "[{}] {} {}:{}: {}\n{}",
874            f.id,
875            f.severity,
876            f.file.as_deref().unwrap_or("?"),
877            f.line.map(|l| l.to_string()).unwrap_or_else(|| "?".into()),
878            approval_excerpt(&f.title, TITLE_CHARS),
879            reason(&f.detail)
880        );
881        let mut evidence = false;
882        for fix in state.reviews.iter().filter_map(|r| r.fix.as_ref()).chain(
883            state
884                .operator_fixes
885                .iter()
886                .filter_map(|request| request.fix.as_ref()),
887        ) {
888            if fix.addressed.contains(&f.id) {
889                evidence = true;
890                let _ = writeln!(
891                    s,
892                    "  {} ({}): {}",
893                    if ja {
894                        "採用申告(解決未確認)"
895                    } else {
896                        "claimed addressed (resolution unconfirmed)"
897                    },
898                    fix.agent,
899                    reason(&fix.notes)
900                );
901            }
902            for rejection in fix.rejected.iter().filter(|r| r.id == f.id) {
903                evidence = true;
904                let _ = writeln!(
905                    s,
906                    "  {}: {}",
907                    if ja { "不採用理由" } else { "declined" },
908                    reason(&rejection.why)
909                );
910            }
911        }
912        if !evidence {
913            s.push_str(if ja {
914                "  採用・解決確認の記録なし\n"
915            } else {
916                "  No adoption or resolution evidence recorded\n"
917            });
918        }
919    }
920    if findings.is_empty() {
921        s.push_str(if ja {
922            "最終ラウンドに指摘の記録なし\n"
923        } else {
924            "No findings recorded in the last round\n"
925        });
926    }
927    s
928}
929
930/// Shared choices for web, CLI and consultation questions.
931pub fn approval_choices(state: &RunState) -> Vec<String> {
932    let mut choices = vec![
933        APPROVE.to_owned(),
934        HOLD.to_owned(),
935        REPAIR.to_owned(),
936        crate::merge_decision::WITHDRAW.to_owned(),
937        crate::merge_decision::DISMISS.to_owned(),
938    ];
939    choices.extend(
940        state
941            .config
942            .agents
943            .iter()
944            .map(|a| format!("{}{id}", crate::merge_decision::REIMPLEMENT, id = a.id)),
945    );
946    choices
947}
948
949/// Extend unanswered legacy cards in place. Answered cards keep their choices;
950/// a legacy repair answer gains only its missing dispatch action.
951pub fn upgrade_repair_choice(q: &mut ask::Question, state: &RunState) -> bool {
952    if q.node != APPROVAL_NODE
953        || !state
954            .land_approval
955            .as_ref()
956            .is_some_and(|a| a.question == q.id)
957    {
958        return false;
959    }
960    let before = (q.choices.clone(), q.actions.clone(), q.merge_target.clone());
961    if q.status.open() {
962        // Older cards attached Resume to hold; a hold must remain answerable
963        // without dispatching a question action.
964        q.actions.remove(HOLD);
965        for choice in approval_choices(state) {
966            if !q.choices.contains(&choice) {
967                q.choices.push(choice);
968            }
969        }
970        if q.merge_target.is_none() {
971            q.merge_target = state.pr.as_ref().map(|pr| crate::merge_decision::Target {
972                pr: pr.url.clone(),
973                head: state.land_approval.as_ref().unwrap().head.clone(),
974                language: state.config.graph.language.clone(),
975            });
976        }
977    }
978    for choice in q.choices.clone() {
979        if (q.status.open()
980            && crate::merge_decision::stops(&choice)
981            && choice != HOLD
982            && choice != crate::merge_decision::DISMISS)
983            || (choice == REPAIR && (q.status.open() || q.resolution().as_deref() == Some(REPAIR)))
984        {
985            q.actions.insert(
986                choice,
987                ask::ChoiceAction::Resume {
988                    run: state.id.clone(),
989                },
990            );
991        }
992    }
993    before != (q.choices.clone(), q.actions.clone(), q.merge_target.clone())
994}
995
996/// Graph node recorded on the approval question.
997///
998/// The phone keys its high-stakes card off this rather than off the choice
999/// strings, so renaming a button cannot silently downgrade the card that
1000/// guards the one irreversible action magi takes.
1001pub const APPROVAL_NODE: &str = "land-approval";
1002
1003/// Unified diff lines carried in the panel before it is truncated.
1004///
1005/// Four hundred: the panel is read on a 390px phone, where a diff line often
1006/// wraps to two rows, so this is already a few thousand rows of scrolling -
1007/// past that nobody is reading, and the bytes still count against the panel's
1008/// 8 MiB cap. A larger diff is not hidden: the note says how many lines were
1009/// cut and which worktree holds the whole patch.
1010pub const DIFF_MAX_LINES: usize = 400;
1011
1012/// What the owner's answer to the approval question means.
1013#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1014pub enum Approval {
1015    /// The owner said [`APPROVE`]. Merge.
1016    Merge,
1017    /// Repair the existing PR, then ask again; never approval to merge.
1018    Repair,
1019    /// Anything else, including silence. Leave the pull request open.
1020    Hold,
1021}
1022
1023/// Read the owner's answer, where `None` is an unanswered question.
1024///
1025/// Silence is a hold. A timed-out question means the owner never saw it or
1026/// never decided, and defaulting an irreversible merge to "yes" would make this
1027/// gate worse than no gate at all: it would merge unattended while claiming to
1028/// have asked. Only the exact [`APPROVE`] choice merges, so an answer this
1029/// function does not recognise holds too.
1030pub fn approval(answer: Option<&str>) -> Approval {
1031    match answer {
1032        Some(a) if a.trim().eq_ignore_ascii_case(APPROVE) => Approval::Merge,
1033        Some(a) if a.trim() == REPAIR => Approval::Repair,
1034        _ => Approval::Hold,
1035    }
1036}
1037
1038/// What [`approval_gate`] found on one check of the owner's merge decision.
1039#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1040enum ApprovalGate {
1041    /// The owner said [`APPROVE`]. Merge.
1042    Approved,
1043    /// The owner explicitly requested repair, without authorizing a merge.
1044    Repair,
1045    /// The owner said anything else, the question timed out, or it was
1046    /// closed with no decision recorded.
1047    Held,
1048    /// Filed and still waiting - the caller parks rather than blocking on it.
1049    Pending,
1050}
1051
1052/// Escape text for HTML, including both quote characters.
1053///
1054/// Every string in the panel is agent-influenced: a branch name, a file path, a
1055/// commit subject, a review comment. The sandboxed frame stops such text from
1056/// *running*, but it does not stop a `<` from ending the document early or a
1057/// `"` from ending an attribute and inventing a new one - the panel would then
1058/// render a lie, or not render at all. Both quotes are escaped because the same
1059/// function is used inside attributes, where remembering which quote style the
1060/// caller used is one mistake away from an injected attribute.
1061fn esc(s: &str) -> String {
1062    let mut out = String::with_capacity(s.len());
1063    for c in s.chars() {
1064        match c {
1065            '&' => out.push_str("&amp;"),
1066            '<' => out.push_str("&lt;"),
1067            '>' => out.push_str("&gt;"),
1068            '"' => out.push_str("&quot;"),
1069            '\'' => out.push_str("&#39;"),
1070            _ => out.push(c),
1071        }
1072    }
1073    out
1074}
1075
1076/// One row of the diffstat table.
1077#[derive(Debug, Clone, PartialEq, Eq)]
1078struct StatRow {
1079    path: String,
1080    /// `None` for a binary file, which `git` reports as `-`.
1081    added: Option<u64>,
1082    removed: Option<u64>,
1083}
1084
1085impl StatRow {
1086    /// Lines touched, for sorting. A binary file counts as zero rather than as
1087    /// unknown, which puts it at the bottom where it needs no attention.
1088    fn churn(&self) -> u64 {
1089        self.added.unwrap_or(0) + self.removed.unwrap_or(0)
1090    }
1091}
1092
1093/// Parse `git diff --numstat` into rows, biggest churn first.
1094///
1095/// `--numstat` and not `--stat`: the `+++---` bar in `--stat` is *scaled* to the
1096/// terminal width, so counting its characters would print fabricated numbers in
1097/// the one table an operator approves an irreversible action from.
1098fn parse_numstat(numstat: &str) -> Vec<StatRow> {
1099    let mut rows: Vec<StatRow> = numstat
1100        .lines()
1101        .filter_map(|line| {
1102            let mut parts = line.splitn(3, '\t');
1103            let added = parts.next()?.trim();
1104            let removed = parts.next()?.trim();
1105            let path = parts.next()?.trim();
1106            if path.is_empty() {
1107                return None;
1108            }
1109            Some(StatRow {
1110                path: path.to_owned(),
1111                added: added.parse().ok(),
1112                removed: removed.parse().ok(),
1113            })
1114        })
1115        .collect();
1116    // Path breaks the tie so the same change always renders the same table; an
1117    // operator comparing two panels should not see rows shuffle.
1118    rows.sort_by(|a, b| b.churn().cmp(&a.churn()).then_with(|| a.path.cmp(&b.path)));
1119    rows
1120}
1121
1122/// How one diff line is shown: a gutter character, a style, and the body to
1123/// print - which is the line minus its marker, so the marker appears exactly
1124/// once, in the gutter.
1125///
1126/// The gutter is why this exists at all. The operator may be colour blind, or
1127/// reading in sunlight with the screen dimmed, so an added line is never
1128/// distinguished by its background alone: `+` and `-` sit in a fixed column,
1129/// the same mark they already read in a terminal.
1130fn diff_row(line: &str) -> (&'static str, &'static str, &str) {
1131    if line.starts_with("+++") || line.starts_with("---") {
1132        (" ", "color:#57606a;font-weight:600", line)
1133    } else if let Some(body) = line.strip_prefix('+') {
1134        ("+", "background:#e6ffec;color:#0a3622", body)
1135    } else if let Some(body) = line.strip_prefix('-') {
1136        ("-", "background:#ffebe9;color:#5c1a17", body)
1137    } else if line.starts_with("@@") {
1138        ("~", "background:#eef2ff;color:#3730a3", line)
1139    } else if let Some(body) = line.strip_prefix(' ') {
1140        (" ", "", body)
1141    } else {
1142        (" ", "color:#57606a;font-weight:600", line)
1143    }
1144}
1145
1146/// The handful of words the approval panel says in its own voice.
1147///
1148/// magi's own text, not an agent's, so `[graph] language` has to reach it too:
1149/// the operator asked why the merge question spoke English on a repository
1150/// configured for Japanese, and "because that string is a literal in Rust" is
1151/// not an answer. Only the languages magi can actually check are translated;
1152/// anything else falls back to English rather than shipping a guess, and that
1153/// fallback is deliberate.
1154struct Words {
1155    html_lang: &'static str,
1156    task: &'static str,
1157    what_changed: &'static str,
1158    review_verdict: &'static str,
1159    reviewer: &'static str,
1160    reviewer_no_answer: &'static str,
1161    checks: &'static str,
1162    nothing_failing: &'static str,
1163    files_changed: &'static str,
1164    commits: &'static str,
1165    no_commits: &'static str,
1166    comments: &'static str,
1167    no_comments: &'static str,
1168    diff: &'static str,
1169    truncated: &'static str,
1170    lands_as: &'static str,
1171}
1172
1173const EN: Words = Words {
1174    html_lang: "en",
1175    task: "Task",
1176    what_changed: "What changed",
1177    review_verdict: "Review verdict",
1178    reviewer: "Reviewer",
1179    reviewer_no_answer: "produced no answer",
1180    checks: "Checks",
1181    nothing_failing: "Nothing failing.",
1182    files_changed: "file(s) changed",
1183    commits: "Commits being squashed",
1184    no_commits: "No commit subjects could be read from the branch.",
1185    comments: "External PR review comments",
1186    no_comments: "No unaddressed external PR comments at this observation. This does not mean internal findings are resolved.",
1187    diff: "Diff",
1188    truncated: "Truncated",
1189    lands_as: "They land as one commit titled",
1190};
1191
1192const JA: Words = Words {
1193    html_lang: "ja",
1194    task: "タスク",
1195    what_changed: "変更内容",
1196    review_verdict: "レビューの結論",
1197    reviewer: "レビュアー",
1198    reviewer_no_answer: "回答なし",
1199    checks: "チェック",
1200    nothing_failing: "失敗しているものはありません。",
1201    files_changed: "ファイル変更",
1202    commits: "squash されるコミット",
1203    no_commits: "ブランチからコミット件名を読めませんでした。",
1204    comments: "外部 PR レビューコメント",
1205    no_comments: "この時点で未対応の外部 PR コメントはありません。内部指摘の解決を意味するものではありません。",
1206    diff: "差分",
1207    truncated: "省略",
1208    lands_as: "これらは次の件名の1コミットとして入ります:",
1209};
1210
1211impl Words {
1212    /// The clause after the merge subject. Split out because word order moves:
1213    /// Japanese puts the subject before the verb, so a shared template with a
1214    /// hole in the middle would read as machine translation.
1215    fn lands_as_tail(&self) -> &'static str {
1216        if self.html_lang == "ja" {
1217            "。この件名も承認の対象です。"
1218        } else {
1219            ", which you are approving too."
1220        }
1221    }
1222
1223    /// The question's own one-line summary, which is what a phone shows first.
1224    fn approval_summary(&self, number: u64, subject: &str) -> String {
1225        if self.html_lang == "ja" {
1226            format!("プルリクエスト #{number} をマージ: {subject}")
1227        } else {
1228            format!("merge pull request #{number}: {subject}")
1229        }
1230    }
1231
1232    /// The body under the summary, above the panel.
1233    fn approval_detail(
1234        &self,
1235        url: &str,
1236        base: &str,
1237        subject: &str,
1238        contested: Option<&ContestedHandoff>,
1239    ) -> String {
1240        let body = if self.html_lang == "ja" {
1241            format!(
1242                "{url} はチェックが緑で、`{base}` へ `{subject}` として squash \
1243                 できる状態です。差分の要約・パッチ・squash されるコミットは\
1244                 下のパネルにあります。"
1245            )
1246        } else {
1247            format!(
1248                "{url} is green and ready to squash into `{base}` as `{subject}`. \
1249                 The panel holds the diffstat, the patch and the commits being squashed."
1250            )
1251        };
1252        match contested {
1253            Some(c) => format!("{}\n\n{body}", self.contested_reason(url, c)),
1254            None => body,
1255        }
1256    }
1257
1258    /// Why this question exists although merge approvals are off: the open
1259    /// blocking findings and who rejected. Short enough for a phone.
1260    fn contested_reason(&self, url: &str, c: &ContestedHandoff) -> String {
1261        const SHOWN: usize = 5;
1262        const TITLE_CHARS: usize = 100;
1263        let ja = self.html_lang == "ja";
1264        let mut out = if ja {
1265            format!(
1266                "{url} は、マージ承認がオフでも保留しています。レビューが予算切れで終わった\
1267                 時点で、却下票を伴う重大な未解決の指摘が残っているためです。\n"
1268            )
1269        } else {
1270            format!(
1271                "{url} is held for approval although merge approvals are off: the \
1272                 review ended with blocking findings still open and a reviewer \
1273                 voting reject.\n"
1274            )
1275        };
1276        for f in c.findings.iter().take(SHOWN) {
1277            let at = match (&f.file, f.line) {
1278                (Some(file), Some(line)) => format!("{file}:{line}"),
1279                (Some(file), None) => file.clone(),
1280                _ => (if ja { "場所未指定" } else { "no location" }).to_owned(),
1281            };
1282            let title: String = f.title.chars().take(TITLE_CHARS).collect();
1283            let _ = writeln!(out, "- {} {} {at}: {title}", f.id, f.severity);
1284        }
1285        if c.findings.len() > SHOWN {
1286            let more = c.findings.len() - SHOWN;
1287            let _ = writeln!(
1288                out,
1289                "{}",
1290                if ja {
1291                    format!("- ほか {more} 件")
1292                } else {
1293                    format!("- and {more} more")
1294                }
1295            );
1296        }
1297        let seats: Vec<String> = c
1298            .rejecters
1299            .iter()
1300            .map(|(seat, agent)| format!("#{seat} ({agent})"))
1301            .collect();
1302        let _ = write!(
1303            out,
1304            "{} {}",
1305            if ja {
1306                "却下したレビュアー:"
1307            } else {
1308                "Rejected by reviewer:"
1309            },
1310            seats.join(", ")
1311        );
1312        out
1313    }
1314
1315    /// The truncation note, written whole in each language for the same reason.
1316    fn truncated_note(
1317        &self,
1318        omitted: usize,
1319        total: usize,
1320        shown: usize,
1321        where_: &str,
1322        base: &str,
1323        head: &str,
1324    ) -> String {
1325        if self.html_lang == "ja" {
1326            format!(
1327                "先頭 {shown} 行のあと、差分 {total} 行のうち {omitted} 行を省略しました。\
1328                 全体は <code>{where_}</code>(<code>git diff {base}...{head}</code>)と\
1329                 プルリクエストにあります。"
1330            )
1331        } else {
1332            format!(
1333                "{omitted} of {total} diff lines omitted after the first {shown}. \
1334                 The whole patch is in <code>{where_}</code> \
1335                 (<code>git diff {base}...{head}</code>) and on the pull request."
1336            )
1337        }
1338    }
1339}
1340
1341/// Pick the panel's language. Codes and names both, because `[graph] language`
1342/// has always accepted either.
1343fn words(language: &str) -> &'static Words {
1344    if crate::lang::is_japanese(language) {
1345        &JA
1346    } else {
1347        &EN
1348    }
1349}
1350
1351/// The approval panel's html: what is about to land, and the evidence for it.
1352///
1353/// Pure, so the whole document is asserted in tests without `gh`, without a
1354/// network and without a repository. The caller gathers `diffstat`
1355/// (`git diff --numstat`), `diff` (the unified patch), `commits` (the subjects
1356/// being squashed) and `subject` (what the squash will be called) from the
1357/// winner's worktree.
1358///
1359/// It emits no `<script>`, no `<form>` and no remote url, because the frame's
1360/// content security policy blocks all three: anything of the sort here would be
1361/// dead markup that misleads the next reader into thinking it works.
1362pub fn approval_panel(
1363    state: &RunState,
1364    pr: &PrState,
1365    diffstat: &str,
1366    diff: &str,
1367    commits: &[String],
1368    subject: &str,
1369) -> String {
1370    let rows = parse_numstat(diffstat);
1371    let w = words(&state.config.graph.language);
1372    let mut h = String::with_capacity(4_096 + diff.len().min(200_000));
1373
1374    let _ = writeln!(
1375        h,
1376        "<!doctype html>\n<html lang=\"{}\">\n<head>\n<meta charset=\"utf-8\">\n\
1377         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
1378        w.html_lang
1379    );
1380    let _ = writeln!(
1381        h,
1382        "<title>merge #{} — {}</title>\n</head>",
1383        pr.number,
1384        esc(subject)
1385    );
1386    h.push_str(
1387        "<body style=\"margin:0;padding:12px;font:15px/1.5 -apple-system,\
1388         'Segoe UI',system-ui,sans-serif;color:#1f2328;background:#fff;\
1389         word-break:break-word\">\n",
1390    );
1391
1392    // The decision, in the words the operator is approving.
1393    let _ = writeln!(
1394        h,
1395        "<h1 style=\"margin:0 0 4px;font-size:19px\">Merge #{} into \
1396         <code style=\"background:#f6f8fa;padding:1px 4px;border-radius:4px\">{}</code></h1>\n\
1397         <p style=\"margin:0 0 4px;font-size:17px;font-weight:600\">{}</p>\n\
1398         <p style=\"margin:0 0 12px;font-size:13px;color:#57606a\">squash merge · run {} · \
1399         <a href=\"{}\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:#0969da\">{}</a></p>",
1400        pr.number,
1401        esc(&state.base_branch),
1402        esc(subject),
1403        esc(&state.id),
1404        esc(&pr.url),
1405        esc(&pr.url),
1406    );
1407
1408    let _ = writeln!(
1409        h,
1410        "<section style=\"padding:12px;background:#fff8c5;border:1px solid #9a6700;border-radius:6px;white-space:pre-wrap\">{}</section>",
1411        esc(&approval_evidence(state))
1412    );
1413
1414    // The task, verbatim: the operator's own words for what was asked, so the
1415    // panel does not make them reconstruct the request from a diffstat.
1416    let _ = writeln!(
1417        h,
1418        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>\n\
1419         <p style=\"margin:0;font-size:13px;white-space:pre-wrap\">{}</p>",
1420        w.task,
1421        esc(&state.instruction)
1422    );
1423
1424    // The winner's own account of what it did and why, when there is one.
1425    if let Some(summary) = state
1426        .winner()
1427        .map(|c| c.summary.as_str())
1428        .filter(|s| !s.is_empty())
1429    {
1430        let _ = writeln!(
1431            h,
1432            "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>\n\
1433             <p style=\"margin:0;font-size:13px;white-space:pre-wrap\">{}</p>",
1434            w.what_changed,
1435            esc(summary)
1436        );
1437    }
1438
1439    // Only the last round's reviewer prose is current. Its votes and
1440    // remaining findings are shown explicitly in the evidence above.
1441    if let Some(round) = state.reviews.last() {
1442        let _ = writeln!(
1443            h,
1444            "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1445            w.review_verdict
1446        );
1447        for r in &round.reviews {
1448            // A seat the review loop counted as answered has real prose in
1449            // `summary`; one it counted against `incomplete` (see
1450            // `graph::Runner::review_loop`) never produced any and left it
1451            // empty - which must not be read back as a blank verdict, since
1452            // an empty box here looks like "nothing to say" rather than
1453            // "never answered".
1454            let body = match &r.failed {
1455                Some(reason) => format!("{}: {}", w.reviewer_no_answer, esc(reason)),
1456                None => esc(&r.summary),
1457            };
1458            let _ = writeln!(
1459                h,
1460                "<div style=\"margin:0 0 8px;padding:8px;background:#f6f8fa;\
1461                 border-radius:6px\">\
1462                 <div style=\"font-size:12px;color:#57606a\">{} {} · {}</div>\
1463                 <div style=\"white-space:pre-wrap;font-size:13px\">{}</div></div>",
1464                w.reviewer,
1465                r.reviewer,
1466                esc(&r.agent),
1467                body,
1468            );
1469        }
1470    }
1471
1472    let _ = writeln!(
1473        h,
1474        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}: {}</h2>",
1475        w.checks,
1476        esc(pr.checks.as_str())
1477    );
1478    if pr.failing.is_empty() {
1479        let _ = writeln!(
1480            h,
1481            "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>",
1482            w.nothing_failing
1483        );
1484    } else {
1485        h.push_str("<ul style=\"margin:0;padding-left:20px;font-size:13px\">\n");
1486        for f in &pr.failing {
1487            let _ = writeln!(h, "<li>{}</li>", esc(f));
1488        }
1489        h.push_str("</ul>\n");
1490    }
1491
1492    // Diffstat as a real table, so a phone reads what moved without scrolling
1493    // sideways through a terminal bar chart.
1494    let _ = writeln!(
1495        h,
1496        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{} {}</h2>",
1497        rows.len(),
1498        w.files_changed
1499    );
1500    h.push_str(
1501        "<table style=\"width:100%;border-collapse:collapse;font-size:13px\">\n\
1502         <thead><tr>\
1503         <th style=\"text-align:left;border-bottom:1px solid #d0d7de;padding:4px 2px\">file</th>\
1504         <th style=\"text-align:right;border-bottom:1px solid #d0d7de;padding:4px 2px\">added</th>\
1505         <th style=\"text-align:right;border-bottom:1px solid #d0d7de;padding:4px 2px\">removed\
1506         </th></tr></thead>\n<tbody>\n",
1507    );
1508    let mut total_added = 0u64;
1509    let mut total_removed = 0u64;
1510    for r in &rows {
1511        total_added += r.added.unwrap_or(0);
1512        total_removed += r.removed.unwrap_or(0);
1513        let cell = |n: Option<u64>| match n {
1514            Some(n) => n.to_string(),
1515            None => "bin".to_owned(),
1516        };
1517        let _ = writeln!(
1518            h,
1519            "<tr>\
1520             <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;\
1521             font-family:ui-monospace,monospace\">{}</td>\
1522             <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;text-align:right;\
1523             color:#0a3622\">{}</td>\
1524             <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;text-align:right;\
1525             color:#5c1a17\">{}</td></tr>",
1526            esc(&r.path),
1527            cell(r.added),
1528            cell(r.removed),
1529        );
1530    }
1531    let _ = writeln!(
1532        h,
1533        "</tbody>\n<tfoot><tr style=\"font-weight:600\">\
1534         <td style=\"padding:4px 2px\">total</td>\
1535         <td style=\"padding:4px 2px;text-align:right\">{total_added}</td>\
1536         <td style=\"padding:4px 2px;text-align:right\">{total_removed}</td>\
1537         </tr></tfoot>\n</table>"
1538    );
1539
1540    // The commits being squashed, and the subject that replaces them.
1541    let _ = writeln!(
1542        h,
1543        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1544        w.commits
1545    );
1546    if commits.is_empty() {
1547        h.push_str(&format!(
1548            "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>\n",
1549            w.no_commits
1550        ));
1551    } else {
1552        h.push_str("<ol style=\"margin:0;padding-left:20px;font-size:13px\">\n");
1553        for c in commits {
1554            let _ = writeln!(h, "<li>{}</li>", esc(c));
1555        }
1556        h.push_str("</ol>\n");
1557    }
1558    let _ = writeln!(
1559        h,
1560        "<p style=\"margin:8px 0 0;font-size:13px\">{} <strong>{}</strong>{}</p>",
1561        w.lands_as,
1562        esc(subject),
1563        w.lands_as_tail()
1564    );
1565
1566    // The review comments that shaped this branch, and who asked for them.
1567    let _ = writeln!(
1568        h,
1569        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1570        w.comments
1571    );
1572    if pr.review_comments.is_empty() {
1573        h.push_str(&format!(
1574            "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>\n",
1575            w.no_comments
1576        ));
1577    } else {
1578        for c in &pr.review_comments {
1579            let anchor = match (&c.path, c.line) {
1580                (Some(p), Some(l)) => format!("{p}:{l}"),
1581                (Some(p), None) => p.clone(),
1582                _ => "pull request thread".to_owned(),
1583            };
1584            let _ = writeln!(
1585                h,
1586                "<div style=\"margin:0 0 8px;padding:8px;background:#f6f8fa;border-radius:6px\">\
1587                 <div style=\"font-size:12px;color:#57606a\">{} · {}</div>\
1588                 <div style=\"white-space:pre-wrap;font-size:13px\">{}</div></div>",
1589                esc(&c.author),
1590                esc(&anchor),
1591                esc(&tail(&c.body, 800)),
1592            );
1593        }
1594    }
1595
1596    // The patch itself.
1597    let total = diff.lines().count();
1598    let shown = total.min(DIFF_MAX_LINES);
1599    let _ = writeln!(
1600        h,
1601        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1602        w.diff
1603    );
1604    h.push_str(
1605        "<div style=\"font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;\
1606         border:1px solid #d0d7de;border-radius:6px;overflow-x:auto\">\n",
1607    );
1608    for line in diff.lines().take(shown) {
1609        let (gutter, style, body) = diff_row(line);
1610        let _ = writeln!(
1611            h,
1612            "<div style=\"display:flex;{style}\">\
1613             <span style=\"flex:0 0 1.4em;text-align:center;user-select:none;\
1614             border-right:1px solid #d0d7de\">{gutter}</span>\
1615             <span style=\"white-space:pre;padding-left:6px\">{}</span></div>",
1616            esc(body),
1617        );
1618    }
1619    h.push_str("</div>\n");
1620    if total > shown {
1621        let omitted = total - shown;
1622        let head = state.winner().map_or("HEAD", |w| w.branch.as_str());
1623        let where_ = state.winner().map_or_else(
1624            || state.repo.display().to_string(),
1625            |w| w.worktree.display().to_string(),
1626        );
1627        let _ = writeln!(
1628            h,
1629            "<p style=\"margin:8px 0 0;padding:8px;background:#fff8c5;border-radius:6px;\
1630             font-size:13px\">{}: {}</p>",
1631            w.truncated,
1632            w.truncated_note(
1633                omitted,
1634                total,
1635                shown,
1636                &esc(&where_),
1637                &esc(&state.base_branch),
1638                &esc(head),
1639            ),
1640        );
1641    }
1642
1643    h.push_str("</body>\n</html>\n");
1644    h
1645}
1646
1647/// Historical contested hand-off evidence for the question detail. Approval
1648/// itself is decided by `approval_reasons`, including reject-only cases.
1649fn contested_to_ask(state: &RunState) -> Option<ContestedHandoff> {
1650    if state.owner_hold(crate::config::OwnerHold::HoldContestedMerge) {
1651        state.contested_handoff.clone()
1652    } else {
1653        None
1654    }
1655}
1656
1657/// What a merge-approval question's deputy is told: the pull request, the run,
1658/// what each answer does, and the evidence saved when the question was filed.
1659///
1660/// Rebuilt for every deputy turn, it is still a snapshot of that moment, so it
1661/// says so and points at `magi show` / `gh pr view` for anything current.
1662/// `state` is `None` for a run that cannot be read; what is missing is named as
1663/// missing, and no past approval basis is rebuilt from today's state.
1664pub fn deputy_brief(q: &ask::Question, state: Option<&RunState>) -> String {
1665    let mut s = format!(
1666        "This is the merge approval for run {run} (`magi show {run}`). The question's \
1667         own text above names the pull request. Answering `{APPROVE}` squash-merges \
1668         it into the base branch; `{HOLD}` leaves the pull request open. Silence is a \
1669         hold: the owner not answering never merges. When the owner tells you to \
1670         merge, in whatever words, settle `{APPROVE}`; when they ask for what another \
1671         offered choice does, settle that one. If you cannot tell what they want, ask \
1672         with `magi ask --thread`.\n\n\
1673         This brief is a snapshot from when your turn started: check `magi show {run}` \
1674         and `gh pr view` (read-only) before telling the owner anything current. The \
1675         driver carries out the merge, repair, withdrawal or replacement: do not \
1676         change files, branches or the pull request yourself.",
1677        run = q.run
1678    );
1679    if let Some(target) = &q.merge_target {
1680        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));
1681    }
1682    if q.choices.iter().any(|c| c == REPAIR) {
1683        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.");
1684    }
1685    if q.detail.contains("Approval required because:") || q.detail.contains("承認が必要な理由:")
1686    {
1687        s.push_str("\n\nSaved approval evidence (at question creation):\n");
1688        s.push_str(&q.detail);
1689    } else {
1690        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.");
1691    }
1692    let Some(state) = state else {
1693        s.push_str(
1694            "\n\nThe run's record could not be read, so the pull request, the panel \
1695             summary and any contested findings are not known to you beyond the \
1696             question's own text. Say so to the owner rather than guessing.",
1697        );
1698        return s;
1699    };
1700    if let Some(pr) = &state.pr {
1701        s.push_str(&format!(
1702            "\n\nPull request #{} {} (recorded state: {}, last seen).",
1703            pr.number, pr.url, pr.state
1704        ));
1705    }
1706    s.push_str(&format!("\nBase branch: `{}`.", state.base_branch));
1707    if let Some(w) = state.winner() {
1708        s.push_str(&format!("\nWinning branch: `{}`.", w.branch));
1709    }
1710
1711    s
1712}
1713
1714// Releasing a task permits work to resume; it does not renew merge consent.
1715// Check the persisted operator decision both when reusing a card and at the
1716// final merge boundary, since a hold/release can arrive between those reads.
1717fn merge_consent_superseded(state: &RunState, question: &ask::Question) -> Result<bool> {
1718    if !question.status.open() && approval(question.resolution().as_deref()) != Approval::Merge {
1719        return Ok(false);
1720    }
1721    let Some(task_id) = state
1722        .origin
1723        .as_ref()
1724        .and_then(|origin| origin.task.as_ref())
1725    else {
1726        return Ok(false);
1727    };
1728    let task = crate::queue::Queue::open()
1729        .get(task_id)
1730        .context("cannot verify operator decisions for the merge approval")?;
1731    Ok(task
1732        .operator_decided_at
1733        .is_some_and(|at| at > question.answered_at.unwrap_or(question.asked_at)))
1734}
1735
1736/// Ask the owner before merging, with the whole case attached as a panel.
1737///
1738/// The evidence is gathered from the winner's own worktree with the `git` CLI,
1739/// never from the network, so a phone on a slow link gets the diff magi is
1740/// looking at rather than a link it has to go and open.
1741///
1742/// Never blocks. `land` used to sit inside [`ask::ask_and_wait`]'s poll loop
1743/// for up to a day right here, which held the whole run's task claim - and
1744/// the daemon's one slot with it - for exactly as long as the owner took to
1745/// notice their phone. [`ApprovalGate::Pending`] is the answer that lets the
1746/// caller park the run and hand the slot back instead: the question is on
1747/// disk either way, so nothing about the wait itself changes, only who is
1748/// blocked on it.
1749///
1750/// Idempotent across resumes: called again for a run already waiting on its
1751/// own question, this finds that question by [`crate::ask::Questions::list`]
1752/// rather than filing a second one - asking twice would double the
1753/// notification for one decision, and leave the first question's panel an
1754/// orphan nobody's answer ever reaches.
1755async fn approval_gate(
1756    state: &mut RunState,
1757    pr: &PrState,
1758    subject: &str,
1759    contested: Option<&ContestedHandoff>,
1760    head: &str,
1761) -> Result<ApprovalGate> {
1762    let _chat_merge = crate::chat_merge::target_lock_wait(&crate::run::home(), &pr.url).await?;
1763    let store = ask::Questions::open();
1764    // An answer belongs to the commit its panel showed. A question recorded
1765    // for another head - or none recorded at all, as for a question filed
1766    // before heads were tracked - is never reused: a fix or rebase push made
1767    // a commit the owner has not seen, and their word does not carry over.
1768    let reusable = state.land_approval.as_ref().and_then(|a| {
1769        store
1770            .list_for_effects()
1771            .into_iter()
1772            .find(|q| q.id == a.question)
1773            .filter(|q| {
1774                q.status != ask::QuestionStatus::Abandoned
1775                    && state
1776                        .repair_grants
1777                        .last()
1778                        .is_none_or(|g| q.asked_at > g.receipt.at)
1779                    && state
1780                        .land_sync_recovery
1781                        .authorizations
1782                        .iter()
1783                        .rev()
1784                        .find(|auth| auth.consumed && auth.invalidated.is_none())
1785                        .is_none_or(|auth| q.asked_at > auth.consumed_at.unwrap_or(auth.at))
1786                    && (a.head.eq_ignore_ascii_case(head)
1787                        || q.resolution()
1788                            .as_deref()
1789                            .is_some_and(crate::merge_decision::stops))
1790            })
1791    });
1792    let reusable = match reusable {
1793        Some(q) if merge_consent_superseded(state, &q)? => None,
1794        other => other,
1795    };
1796    if reusable.is_none() {
1797        for stale in store.list_for_effects().into_iter().filter(|q| {
1798            q.run == state.id
1799                && q.node == APPROVAL_NODE
1800                && q.status.open()
1801                && !store.held_reply(&q.id)
1802        }) {
1803            let why =
1804                "the pull request head or operator decision changed; asked again for approval";
1805            if let Err(e) = store.update(&stale.id, |q| {
1806                q.abandon(why);
1807                Ok(())
1808            }) {
1809                tracing::warn!("could not retire the superseded approval question: {e:#}");
1810            }
1811        }
1812    }
1813
1814    let q = match reusable {
1815        Some(mut q) => {
1816            if upgrade_repair_choice(&mut q, state) {
1817                q = store
1818                    .update(&q.id, |current| {
1819                        upgrade_repair_choice(current, state);
1820                        Ok(())
1821                    })?
1822                    .0;
1823            }
1824            q
1825        }
1826        None => {
1827            let worktree = match state.winner() {
1828                Some(w) => w.worktree.clone(),
1829                None => state.repo.clone(),
1830            };
1831            // The diff is built from the commit being approved, not from the
1832            // branch name, which may already point somewhere else.
1833            let head = if head.is_empty() {
1834                state
1835                    .winner()
1836                    .map_or_else(|| "HEAD".to_owned(), |w| w.branch.clone())
1837            } else {
1838                head.to_owned()
1839            };
1840            // The diff is against what the remote's base holds, never the
1841            // local branch of that name; unreadable means less evidence.
1842            let remote = &state.config.merge.remote;
1843            let tracking = format!("{remote}/{}", state.base_branch);
1844            let base = if git::rev_exists(&worktree, &tracking).await {
1845                tracking
1846            } else {
1847                String::new()
1848            };
1849            let range = format!("{base}...{head}");
1850            // A failed `git` must not decide the merge: the panel degrades to
1851            // less evidence and the owner still chooses. Merging because the
1852            // diff could not be read would be the worst of both.
1853            let numstat = if base.is_empty() {
1854                String::new()
1855            } else {
1856                git::git_raw(&worktree, &["diff", "--numstat", "-M", &range])
1857                    .await
1858                    .map(|o| o.stdout)
1859                    .unwrap_or_default()
1860            };
1861            let diff = if base.is_empty() {
1862                String::new()
1863            } else {
1864                git::diff(&worktree, &base, &head).await.unwrap_or_default()
1865            };
1866            let commits: Vec<String> = if base.is_empty() {
1867                Vec::new()
1868            } else {
1869                git::git_raw(
1870                    &worktree,
1871                    &[
1872                        "log",
1873                        "--reverse",
1874                        "--format=%s",
1875                        &format!("{base}..{head}"),
1876                    ],
1877                )
1878                .await
1879                .map(|o| o.stdout)
1880                .unwrap_or_default()
1881                .lines()
1882                .filter(|l| !l.trim().is_empty())
1883                .map(str::to_owned)
1884                .collect()
1885            };
1886
1887            let w = words(&state.config.graph.language);
1888            let html = approval_panel(state, pr, &numstat, &diff, &commits, subject);
1889            let mut fresh = ask::Question::new(
1890                state.id.clone(),
1891                APPROVAL_NODE.to_owned(),
1892                "land".to_owned(),
1893                w.approval_summary(pr.number, subject),
1894                format!(
1895                    "{}\n\n{}",
1896                    approval_evidence(state),
1897                    w.approval_detail(&pr.url, &state.base_branch, subject, contested)
1898                ),
1899                approval_choices(state),
1900            );
1901            fresh.merge_target = Some(crate::merge_decision::Target {
1902                pr: pr.url.clone(),
1903                head: head.clone(),
1904                language: state.config.graph.language.clone(),
1905            });
1906            if fresh.choices.iter().any(|c| c == REPAIR) {
1907                fresh.actions.insert(
1908                    REPAIR.to_owned(),
1909                    ask::ChoiceAction::Resume {
1910                        run: state.id.clone(),
1911                    },
1912                );
1913                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.");
1914            }
1915            for choice in fresh.choices.clone() {
1916                if crate::merge_decision::stops(&choice)
1917                    && choice != HOLD
1918                    && choice != crate::merge_decision::DISMISS
1919                {
1920                    fresh.actions.insert(
1921                        choice,
1922                        ask::ChoiceAction::Resume {
1923                            run: state.id.clone(),
1924                        },
1925                    );
1926                }
1927            }
1928            store
1929                .put_panel(&mut fresh, &html, &[])
1930                .context("write the merge approval panel")?;
1931            store
1932                .put_executable(&mut fresh)
1933                .context("file the merge approval question")?;
1934            state.land_approval = Some(LandApproval {
1935                question: fresh.id.clone(),
1936                head: head.clone(),
1937            });
1938            state.event(
1939                "land",
1940                format!("asking for merge approval ({})", fresh.short()),
1941            );
1942            state.save()?;
1943            if let Err(e) = ask::notify(&state.config.notify, &fresh).await {
1944                // A broken webhook is not a reason to lose the merge: the
1945                // question is already on disk and the web UI already shows
1946                // it, so the operator still has a way in.
1947                tracing::warn!(
1948                    "could not notify about merge approval question {}: {e:#} - \
1949                     the web UI is the only surface for it now",
1950                    fresh.short()
1951                );
1952            }
1953            fresh
1954        }
1955    };
1956
1957    Ok(match q.status {
1958        ask::QuestionStatus::Open => ApprovalGate::Pending,
1959        // Nobody answered before `state.config.graph.answer_timeout` passed,
1960        // or the question was closed with no decision recorded underneath
1961        // this run - either way there is nothing left to wait on.
1962        ask::QuestionStatus::Abandoned => ApprovalGate::Held,
1963        // The merge gate does not speak `--thread`: an owner who talked back
1964        // instead of choosing never reaches `Answered`, so this arm only
1965        // ever sees an actual decision.
1966        ask::QuestionStatus::Answered => match approval(q.resolution().as_deref()) {
1967            Approval::Merge => ApprovalGate::Approved,
1968            Approval::Repair if !state.reviews.is_empty() => {
1969                if !state.merge_repairs.iter().any(|r| r.question == q.id) {
1970                    state.merge_repairs.push(crate::run::MergeRepair {
1971                        question: q.id.clone(),
1972                        head: head.to_owned(),
1973                        pr: pr.url.clone(),
1974                        reviews: state.reviews.clone(),
1975                        gate: state.gate.clone(),
1976                        gate_head: state.gate_head.clone(),
1977                        gate_fixes: state.gate_fixes.clone(),
1978                        pre_gate: state.pre_gate.clone(),
1979                        phase: crate::run::MergeRepairPhase::Requested,
1980                        failure: None,
1981                    });
1982                    state.land_approval = None;
1983                    state.event(
1984                        "repair",
1985                        "owner requested fix findings and re-review; merge is not approved",
1986                    );
1987                    state.save()?;
1988                }
1989                ApprovalGate::Repair
1990            }
1991            Approval::Repair | Approval::Hold => ApprovalGate::Held,
1992        },
1993    })
1994}
1995
1996/// Fold a rollup's entries into one verdict plus the failing checks' labels.
1997/// No I/O. An empty rollup is `Unknown`, never green.
1998fn rollup_verdict(rollup: &[GhCheck]) -> (Checks, Vec<String>) {
1999    let mut failing = Vec::new();
2000    let mut pending = false;
2001    let mut unknown = false;
2002    for check in rollup {
2003        match check.verdict() {
2004            Verdict::Pass => {}
2005            Verdict::Pending => pending = true,
2006            Verdict::Fail => failing.push(check.label()),
2007            Verdict::Unknown => unknown = true,
2008        }
2009    }
2010    let checks = if rollup.is_empty() {
2011        Checks::Unknown
2012    } else if pending {
2013        Checks::Pending
2014    } else if !failing.is_empty() {
2015        Checks::Red
2016    } else if unknown {
2017        Checks::Unknown
2018    } else {
2019        Checks::Green
2020    };
2021    (checks, failing)
2022}
2023
2024/// Parse `gh pr view --json url,number,state,statusCheckRollup,reviews,comments`
2025/// output into a [`PrState`]. No I/O.
2026pub fn parse_pr(json: &str) -> Result<PrState> {
2027    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2028    let state = match raw.state.to_ascii_uppercase().as_str() {
2029        "OPEN" => PrLifecycle::Open,
2030        "MERGED" => PrLifecycle::Merged,
2031        "CLOSED" => PrLifecycle::Closed,
2032        other => bail!("unknown pull request state `{other}`"),
2033    };
2034
2035    let (checks, failing) = rollup_verdict(&raw.status_check_rollup);
2036
2037    let mut review_comments = Vec::new();
2038    for r in raw.reviews {
2039        push_if_outstanding(
2040            &mut review_comments,
2041            ReviewComment {
2042                author: r.author.login,
2043                path: None,
2044                line: None,
2045                body: r.body,
2046            },
2047        );
2048    }
2049    for c in raw.comments {
2050        push_if_outstanding(
2051            &mut review_comments,
2052            ReviewComment {
2053                author: c.author.login,
2054                path: None,
2055                line: None,
2056                body: c.body,
2057            },
2058        );
2059    }
2060
2061    Ok(PrState {
2062        url: raw.url,
2063        number: raw.number,
2064        state,
2065        checks,
2066        failing,
2067        review_comments,
2068        blocking: Blocking::of(&raw.merge_state_status),
2069    })
2070}
2071
2072/// One rollup entry as the release watcher reads it.
2073#[derive(Debug, Clone, PartialEq, Eq)]
2074pub(crate) struct CheckView {
2075    pub name: String,
2076    pub verdict: Verdict,
2077    /// Workflow run behind the check, when its url names one.
2078    pub run: Option<String>,
2079    pub url: Option<String>,
2080}
2081
2082/// A pull request's lifecycle, head commit and per-check verdicts, without
2083/// [`rollup_verdict`]'s aggregation (a pending check anywhere hides a failure
2084/// from it, which is exactly what the release watcher must not inherit).
2085#[derive(Debug, Clone, PartialEq, Eq)]
2086pub(crate) struct RollupView {
2087    pub url: String,
2088    pub number: u64,
2089    pub state: PrLifecycle,
2090    pub head: String,
2091    pub checks: Vec<CheckView>,
2092}
2093
2094/// Parse `gh pr view --json url,number,state,headRefOid,statusCheckRollup`
2095/// output. No I/O.
2096pub(crate) fn parse_rollup(json: &str) -> Result<RollupView> {
2097    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2098    let state = match raw.state.to_ascii_uppercase().as_str() {
2099        "OPEN" => PrLifecycle::Open,
2100        "MERGED" => PrLifecycle::Merged,
2101        "CLOSED" => PrLifecycle::Closed,
2102        other => bail!("unknown pull request state `{other}`"),
2103    };
2104    let checks = raw
2105        .status_check_rollup
2106        .iter()
2107        .map(|c| CheckView {
2108            name: c.label(),
2109            verdict: c.verdict(),
2110            run: c.url().and_then(run_of),
2111            url: c.url().map(str::to_owned),
2112        })
2113        .collect();
2114    Ok(RollupView {
2115        url: raw.url,
2116        number: raw.number,
2117        state,
2118        head: raw.head_ref_oid,
2119        checks,
2120    })
2121}
2122
2123/// Read just a pull request's lifecycle state - open, merged, or closed -
2124/// with none of the checks/reviews/comments [`land`] itself needs to decide
2125/// what to do next.
2126///
2127/// For a caller that only ever wants one fact and must not risk anything
2128/// else: `magi fold --merged` uses this to confirm a URL the operator hands
2129/// it is actually a merged pull request *before* touching a run's state, so a
2130/// typo or a still-open PR fails loudly instead of quietly recording a merge
2131/// that never happened.
2132pub async fn lifecycle(repo: &Path, pr_url: &str) -> Result<PrLifecycle> {
2133    let view = gh(
2134        repo,
2135        &[
2136            "pr".to_owned(),
2137            "view".to_owned(),
2138            pr_url.to_owned(),
2139            "--json".to_owned(),
2140            "state".to_owned(),
2141        ],
2142    )
2143    .await?;
2144    if !view.ok {
2145        bail!("gh pr view {pr_url}: {}", view.combined());
2146    }
2147    // `parse_pr` reads every other field of `GhPr` as its serde default
2148    // (empty string, empty vec, zero) when this narrower `--json` selection
2149    // does not carry them - harmless, since only `.state` is read back.
2150    Ok(parse_pr(&view.stdout)?.state)
2151}
2152
2153/// A pull request the operator merged outside of `land::land`'s own loop,
2154/// found by asking GitHub about the run's own winning branch rather than
2155/// requiring the operator to go and find the URL themselves.
2156#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2157pub struct ExternalMerge {
2158    /// The pull request's URL, ready to hand to [`correct_manual_merge`].
2159    pub url: String,
2160    /// The pull request's number.
2161    pub number: u64,
2162}
2163
2164#[derive(Debug, Deserialize)]
2165#[serde(rename_all = "camelCase")]
2166struct GhMergedPr {
2167    url: String,
2168    number: u64,
2169    merged_at: String,
2170    base_ref_name: String,
2171}
2172
2173/// Pure half of [`find_external_merge`]: given the raw `gh pr list --head
2174/// <branch> --state merged --json url,number,mergedAt,baseRefName` output,
2175/// decide whether exactly one of the pull requests it lists could actually
2176/// be *this* run's.
2177///
2178/// A branch name alone does not prove it: [`RunState::branch_for`] derives it
2179/// from the run's own short id, so a collision with some other, unrelated
2180/// task's merged pull request from a same-named branch is rare but not
2181/// impossible once branches are deleted and ids run out. Filtering on
2182/// `base_ref_name` (the branch this run actually targets) and `merged_at`
2183/// (which cannot predate the run itself) rules that case out. More than one
2184/// survivor is exactly as uninformative as zero — something this run cannot
2185/// tell apart from another — so only a unique survivor is returned.
2186fn pick_merged_pr(
2187    json: &str,
2188    base_branch: &str,
2189    created_at: Timestamp,
2190) -> Result<Option<ExternalMerge>> {
2191    pick_merged_pr_with(json, base_branch, created_at, false)
2192}
2193
2194fn pick_merged_pr_with(
2195    json: &str,
2196    base_branch: &str,
2197    created_at: Timestamp,
2198    reject_ambiguous: bool,
2199) -> Result<Option<ExternalMerge>> {
2200    let raw: Vec<GhMergedPr> =
2201        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2202    let mut matches: Vec<ExternalMerge> = Vec::new();
2203    for pr in raw {
2204        if pr.base_ref_name != base_branch {
2205            continue;
2206        }
2207        let Ok(merged_at) = pr.merged_at.parse::<Timestamp>() else {
2208            continue;
2209        };
2210        if merged_at < created_at {
2211            continue;
2212        }
2213        matches.push(ExternalMerge {
2214            url: pr.url,
2215            number: pr.number,
2216        });
2217    }
2218    anyhow::ensure!(
2219        !reject_ambiguous || matches.len() <= 1,
2220        "multiple merged pull requests match this run; merge evidence is ambiguous"
2221    );
2222    if matches.len() == 1 {
2223        Ok(matches.pop())
2224    } else {
2225        Ok(None)
2226    }
2227}
2228
2229/// What `gh pr list --head <branch> --base <base> --state open` found.
2230#[derive(Debug, Clone, PartialEq, Eq)]
2231pub enum OpenPr {
2232    /// Nothing open: the caller creates one.
2233    None,
2234    /// Exactly one: the caller adopts it instead of creating a second.
2235    One {
2236        /// The pull request's URL.
2237        url: String,
2238        /// Its current title.
2239        title: String,
2240    },
2241    /// More than one: magi does not pick between them.
2242    Many(Vec<String>),
2243}
2244
2245#[derive(Debug, Deserialize)]
2246#[serde(rename_all = "camelCase")]
2247struct GhOpenPr {
2248    // `url` and `baseRefName` are required: a record missing either must be a
2249    // parse error, not a pull request that silently fails the base filter and
2250    // reads as "none open" (which would go on to create a duplicate).
2251    url: String,
2252    #[serde(default)]
2253    title: String,
2254    base_ref_name: String,
2255    // A fork's branch of the same name is not the task head; `gh pr list --head`
2256    // matches by branch name alone, so the filter has to be ours.
2257    #[serde(default)]
2258    is_cross_repository: bool,
2259}
2260
2261/// Pure half of [`find_open_pr`]: classify the raw `--json
2262/// number,url,title,baseRefName` output. Entries whose base is not `base` are
2263/// dropped even though the query already filtered on it, so a stub or an old
2264/// `gh` that ignores `--base` cannot get a pull request into the wrong branch
2265/// adopted.
2266pub fn pick_open_pr(json: &str, base: &str) -> Result<OpenPr> {
2267    let raw: Vec<GhOpenPr> =
2268        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2269    let mut hits: Vec<GhOpenPr> = raw
2270        .into_iter()
2271        .filter(|p| p.base_ref_name == base && !p.is_cross_repository)
2272        .collect();
2273    Ok(match hits.len() {
2274        0 => OpenPr::None,
2275        1 => {
2276            let p = hits.remove(0);
2277            OpenPr::One {
2278                url: p.url,
2279                title: p.title,
2280            }
2281        }
2282        _ => OpenPr::Many(hits.into_iter().map(|p| p.url).collect()),
2283    })
2284}
2285
2286/// Open pull requests whose head is `branch` and whose base is `base`. A
2287/// failing `gh` is an error carrying its own output, never "none": guessing
2288/// there is how a duplicate gets created.
2289pub async fn find_open_pr(repo: &Path, branch: &str, base: &str) -> Result<OpenPr> {
2290    find_open_pr_with(Path::new("gh"), repo, branch, base).await
2291}
2292
2293pub(crate) async fn find_open_pr_with(
2294    program: &Path,
2295    repo: &Path,
2296    branch: &str,
2297    base: &str,
2298) -> Result<OpenPr> {
2299    let out = gh_with(
2300        program,
2301        repo,
2302        &[
2303            "pr".to_owned(),
2304            "list".to_owned(),
2305            "--head".to_owned(),
2306            branch.to_owned(),
2307            "--base".to_owned(),
2308            base.to_owned(),
2309            "--state".to_owned(),
2310            "open".to_owned(),
2311            "--json".to_owned(),
2312            "number,url,title,baseRefName,isCrossRepository".to_owned(),
2313        ],
2314    )
2315    .await?;
2316    if !out.ok {
2317        bail!("gh pr list failed: {}", out.combined());
2318    }
2319    pick_open_pr(&out.stdout, base)
2320}
2321
2322#[derive(Debug, Deserialize)]
2323#[serde(rename_all = "camelCase")]
2324struct GhPrHead {
2325    head_ref_name: String,
2326    base_ref_name: String,
2327    state: String,
2328    // Required, like `GhOpenPr`'s fields: a record that cannot say whether the
2329    // head lives in a fork must be a parse error, never "same repository".
2330    is_cross_repository: bool,
2331    // Required too: it is what ties the pull request to the commits that were
2332    // actually proven to be on the base.
2333    head_ref_oid: String,
2334}
2335
2336/// Why [`closable`] said no, and whether asking again later could say yes.
2337#[derive(Debug, Clone, PartialEq, Eq)]
2338pub struct Refusal {
2339    /// A later attempt may succeed (the head moved, the view was unreadable);
2340    /// `false` means this pull request is simply not the run's to close.
2341    pub retry: bool,
2342    /// What was wrong.
2343    pub why: String,
2344}
2345
2346impl Refusal {
2347    fn final_(why: String) -> Self {
2348        Self { retry: false, why }
2349    }
2350}
2351
2352/// Pure half of [`close_superseded_pr`]: read `gh pr view --json
2353/// headRefName,baseRefName,state,isCrossRepository` and say whether closing
2354/// is safe, `Err` carrying the reason when it is not.
2355///
2356/// Closing is outward-facing, so every property is checked on what the forge
2357/// says now, not on what magi recorded: the head must be exactly `branch` in
2358/// this repository (a fork's branch of the same name is somebody else's), the
2359/// base must be `base`, and the pull request must still be open.
2360pub fn closable(
2361    json: &str,
2362    branch: &str,
2363    base: &str,
2364    verified: &[String],
2365) -> std::result::Result<(), Refusal> {
2366    let pr: GhPrHead = serde_json::from_str(json).map_err(|e| Refusal {
2367        retry: true,
2368        why: format!("could not read the pull request ({e})"),
2369    })?;
2370    if pr.head_ref_name != branch {
2371        return Err(Refusal::final_(format!(
2372            "its head is `{}`, not this run's `{branch}`",
2373            pr.head_ref_name
2374        )));
2375    }
2376    if pr.is_cross_repository {
2377        return Err(Refusal::final_("its head lives in a fork".to_owned()));
2378    }
2379    if pr.base_ref_name != base {
2380        return Err(Refusal::final_(format!(
2381            "it targets `{}`, not `{base}`",
2382            pr.base_ref_name
2383        )));
2384    }
2385    if !pr.state.eq_ignore_ascii_case("open") {
2386        return Err(Refusal::final_(format!(
2387            "it is already {}",
2388            pr.state.to_ascii_lowercase()
2389        )));
2390    }
2391    // Last, so a pull request that is not this run's at all is reported as
2392    // such. A head that is this branch but not a commit checked against the
2393    // base (somebody pushed since) may well get checked next time: retry.
2394    if !verified.contains(&pr.head_ref_oid) {
2395        return Err(Refusal {
2396            retry: true,
2397            why: format!(
2398                "its head {} is not a commit this run checked against the base",
2399                crate::already::short_sha(&pr.head_ref_oid)
2400            ),
2401        });
2402    }
2403    Ok(())
2404}
2405
2406/// Does `remote` point at something a forge could host - a URL or an scp-style
2407/// `user@host:path` - rather than a filesystem path or nothing at all? Judged
2408/// from the URL alone, so it answers the same on every machine, whatever `gh`
2409/// happens to be installed or logged in to.
2410async fn remote_is_forge(repo: &Path, remote: &str) -> bool {
2411    let Ok(url) = git::git(repo, &["remote", "get-url", remote]).await else {
2412        return false;
2413    };
2414    is_forge_url(url.trim())
2415}
2416
2417fn is_forge_url(url: &str) -> bool {
2418    url.contains("://") && !url.starts_with("file://")
2419        || url
2420            .split_once(':')
2421            .is_some_and(|(host, _)| host.contains('@') && !host.contains(['/', '\\']))
2422}
2423
2424/// Does this `gh` failure mean there is no GitHub to ask, as opposed to a
2425/// request that failed?
2426fn forge_unavailable(message: &str) -> bool {
2427    message.contains("known GitHub host") || message.contains("spawn gh")
2428}
2429
2430/// The comment left on a pull request closed because its change is already on
2431/// the base.
2432pub fn superseded_comment(base: &str, evidence: &crate::already::Evidence) -> String {
2433    let how = match evidence.proof {
2434        crate::already::Proof::PatchId => format!(
2435            "carried by commit {} on `{base}` with the same patch",
2436            evidence.names()
2437        ),
2438        crate::already::Proof::Ancestry => {
2439            format!("already in the history of `{base}` as {}", evidence.names())
2440        }
2441        crate::already::Proof::Tree => format!(
2442            "already part of `{base}` (merging this branch changes nothing at {})",
2443            crate::already::short_sha(&evidence.tip)
2444        ),
2445    };
2446    format!(
2447        "Closing: everything this branch adds is {how}, so there is nothing left to \
2448         land. This pull request was closed automatically after that was verified; \
2449         reopen it if you disagree."
2450    )
2451}
2452
2453/// Close the open pull request for `branch`, if there is one and it is
2454/// provably this run's, with a comment naming what supersedes it. `Ok(Ok(url))` is
2455/// the URL closed; `Ok(Err(why))` is a final "nothing to close" (no pull request,
2456/// not this run's, no forge); `Err` is anything a later attempt could resolve (a
2457/// failed `gh` call, a head that moved since it was checked), which the caller
2458/// must not treat as settled.
2459///
2460/// The recorded `state.pr` is preferred, else the forge is asked for an open
2461/// pull request on `branch`; either way the candidate is re-read and passed
2462/// through [`closable`] before anything is written; `verified` lists the
2463/// commits proven to be on the base, and the pull request's head must be one.
2464pub async fn close_superseded_pr(
2465    state: &mut RunState,
2466    branch: &str,
2467    evidence: &crate::already::Evidence,
2468    verified: &[String],
2469) -> Result<std::result::Result<String, String>> {
2470    let repo = state.repo.clone();
2471    let base = state.base_branch.clone();
2472    let url = match state.pr.as_ref().filter(|p| p.state == "open") {
2473        Some(p) => p.url.clone(),
2474        // No recorded pull request. A forge that cannot be asked at all (no
2475        // GitHub remote, no `gh`) says nothing about this run, so that is
2476        // "none found"; any other lookup failure is an error, because "could
2477        // not look" is not "nothing there" and the caller must retry.
2478        None if !remote_is_forge(&repo, &state.config.merge.remote).await => {
2479            return Ok(Err(
2480                "the remote is not a forge, so there is no pull request".to_owned(),
2481            ));
2482        }
2483        None => match find_open_pr(&repo, branch, &base).await {
2484            Err(e) if forge_unavailable(&format!("{e:#}")) => {
2485                return Ok(Err(format!("no forge to ask: {e:#}")));
2486            }
2487            Err(e) => return Err(e),
2488            Ok(OpenPr::One { url, .. }) => url,
2489            Ok(OpenPr::None) => return Ok(Err("no open pull request".to_owned())),
2490            Ok(OpenPr::Many(urls)) => {
2491                return Ok(Err(format!(
2492                    "{} open pull requests name it; not choosing between them",
2493                    urls.len()
2494                )));
2495            }
2496        },
2497    };
2498    let view = gh(
2499        &repo,
2500        &[
2501            "pr".to_owned(),
2502            "view".to_owned(),
2503            url.clone(),
2504            "--json".to_owned(),
2505            "headRefName,headRefOid,baseRefName,state,isCrossRepository".to_owned(),
2506        ],
2507    )
2508    .await?;
2509    if !view.ok {
2510        bail!("gh pr view {url} failed: {}", view.combined());
2511    }
2512    if let Err(refusal) = closable(&view.stdout, branch, &base, verified) {
2513        // A pull request whose head cannot be tied to what was proven is not
2514        // one to walk away from: the caller keeps the run resumable.
2515        if refusal.retry {
2516            bail!("left {url} open: {}", refusal.why);
2517        }
2518        return Ok(Err(format!("left {url} open: {}", refusal.why)));
2519    }
2520    let out = gh(
2521        &repo,
2522        &[
2523            "pr".to_owned(),
2524            "close".to_owned(),
2525            url.clone(),
2526            "--comment".to_owned(),
2527            superseded_comment(&base, evidence),
2528        ],
2529    )
2530    .await?;
2531    if !out.ok {
2532        bail!("gh pr close {url} failed: {}", out.combined());
2533    }
2534    if let Some(p) = state.pr.as_mut().filter(|p| p.url == url) {
2535        p.state = "closed".to_owned();
2536    }
2537    Ok(Ok(url))
2538}
2539
2540/// `gh pr edit <url> --title <title>`, for an adopted pull request whose title
2541/// differs from the one this run computed. Only the title: the body may have
2542/// been edited by the owner and cannot be compared.
2543pub async fn set_pr_title(state: &mut RunState, repo: &Path, url: &str, title: &str) -> Result<()> {
2544    let (title, _) = crate::github_text::prepare(state, title, "");
2545    edit_pr_title(repo, url, &title).await
2546}
2547
2548/// [`set_pr_title`] for a title the owner explicitly chose to post unmodified
2549/// (`github_text::POST_ORIGINAL` or `github_text::USE_REWRITE`): the posting
2550/// gate is skipped on purpose.
2551pub async fn set_pr_title_verbatim(repo: &Path, url: &str, title: &str) -> Result<()> {
2552    edit_pr_title(repo, url, title).await
2553}
2554
2555/// Post both fields of the owner's chosen rewrite to an adopted pull request,
2556/// unmodified and without the posting gate.
2557pub async fn set_pr_text_verbatim(repo: &Path, url: &str, title: &str, body: &str) -> Result<()> {
2558    let out = gh(
2559        repo,
2560        &[
2561            "pr".to_owned(),
2562            "edit".to_owned(),
2563            url.to_owned(),
2564            "--title".to_owned(),
2565            title.to_owned(),
2566            "--body".to_owned(),
2567            body.to_owned(),
2568        ],
2569    )
2570    .await
2571    .map_err(|_| anyhow::anyhow!("could not run gh pr edit for the chosen rewrite"))?;
2572    if !out.ok {
2573        // Command output may echo the chosen text; keep it out of run events.
2574        bail!("gh pr edit failed while posting the chosen rewrite");
2575    }
2576    Ok(())
2577}
2578
2579async fn edit_pr_title(repo: &Path, url: &str, title: &str) -> Result<()> {
2580    let out = gh(
2581        repo,
2582        &[
2583            "pr".to_owned(),
2584            "edit".to_owned(),
2585            url.to_owned(),
2586            "--title".to_owned(),
2587            title.to_owned(),
2588        ],
2589    )
2590    .await?;
2591    if !out.ok {
2592        bail!("gh pr edit failed: {}", out.combined());
2593    }
2594    Ok(())
2595}
2596
2597/// Ask GitHub whether this run's winning candidate branch was actually merged
2598/// somewhere `land::land`'s own loop never saw — the gap `magi fold
2599/// --merged` exists to close, minus the operator having to find the URL by
2600/// hand.
2601///
2602/// `Ok(None)` covers every case where nothing can be said with confidence: no
2603/// winner decided yet (nothing to check a branch for), no merged pull request
2604/// found, or [`pick_merged_pr`] found more than one candidate and would not
2605/// guess between them. Never wired to a weaker, URL-less signal like
2606/// [`branch_is_ancestor`] — a caller wanting that has to ask for it
2607/// separately, precisely because it cannot drive an automatic correction on
2608/// its own (see that function's own doc).
2609pub async fn find_external_merge(state: &RunState) -> Result<Option<ExternalMerge>> {
2610    let Some(winner) = state.winner() else {
2611        return Ok(None);
2612    };
2613    find_external_merge_with(
2614        state,
2615        state.pr_head.as_deref().unwrap_or(&winner.branch),
2616        false,
2617    )
2618    .await
2619}
2620
2621/// Reopening needs proof of absence, not merely failure to identify one PR.
2622pub(crate) async fn find_external_merge_for_reopen(
2623    state: &RunState,
2624) -> Result<Option<ExternalMerge>> {
2625    let Some(branch) = state.pr_branch() else {
2626        anyhow::ensure!(
2627            state.pr.is_none() && state.pr_pushed_head.is_none(),
2628            "run has public PR evidence but no known branch to check"
2629        );
2630        return Ok(None);
2631    };
2632    find_external_merge_with(state, branch, true).await
2633}
2634
2635async fn find_external_merge_with(
2636    state: &RunState,
2637    branch: &str,
2638    reject_ambiguous: bool,
2639) -> Result<Option<ExternalMerge>> {
2640    let out = gh(
2641        &state.repo,
2642        &[
2643            "pr".to_owned(),
2644            "list".to_owned(),
2645            "--head".to_owned(),
2646            branch.to_owned(),
2647            "--state".to_owned(),
2648            "merged".to_owned(),
2649            "--json".to_owned(),
2650            "url,number,mergedAt,baseRefName".to_owned(),
2651        ],
2652    )
2653    .await?;
2654    if !out.ok {
2655        bail!("gh pr list --head {branch}: {}", out.combined());
2656    }
2657    if reject_ambiguous {
2658        pick_merged_pr_with(&out.stdout, &state.base_branch, state.created_at, true)
2659    } else {
2660        pick_merged_pr(&out.stdout, &state.base_branch, state.created_at)
2661    }
2662}
2663
2664/// Whether `branch` is, right now, an ancestor of `base_branch` in the local
2665/// git graph — the weaker, URL-less signal that a branch landed somewhere.
2666///
2667/// Deliberately never consulted by [`find_external_merge`]: a base branch
2668/// that has moved since the run started can make an old, abandoned branch
2669/// look like an ancestor of the *current* base for reasons that have nothing
2670/// to do with a merge (a later commit that happens to supersede it, an
2671/// unrelated squash), and there is no pull request URL here to confirm
2672/// against or to land through anyway. Its only honest use is a weaker
2673/// notice — "this looks merged, go check" — never an automatic rewrite of
2674/// `status`/`merge`.
2675pub async fn branch_is_ancestor(repo: &Path, branch: &str, base_branch: &str) -> Result<bool> {
2676    let out = tokio::process::Command::new("git")
2677        .args(["merge-base", "--is-ancestor", branch, base_branch])
2678        .current_dir(repo)
2679        .quiet()
2680        .stdin(std::process::Stdio::null())
2681        .output()
2682        .await
2683        .context("spawn git merge-base --is-ancestor")?;
2684    Ok(out.status.success())
2685}
2686
2687/// Parse `host/owner/repo` out of a forge URL, with no network access.
2688///
2689/// The host is part of the slug, not discarded: `owner/repo` alone would
2690/// treat `github.example.com/o/r` and `github.com/o/r` as the same
2691/// repository, which is exactly the mix-up the same-repo guard exists to
2692/// catch. Returns `None` for anything that doesn't have a `<host>/<path>`
2693/// shape at all.
2694fn forge_slug(url: &str) -> Option<(String, &str)> {
2695    let rest = url.rsplit("://").next()?;
2696    let (host, path) = rest.split_once('/')?;
2697    if host.is_empty() {
2698        return None;
2699    }
2700    Some((host.to_ascii_lowercase(), path))
2701}
2702
2703/// Parse `host/owner/repo` out of a GitHub pull request URL, with no network
2704/// access - the first half of the same-repo guard [`correct_manual_merge`]
2705/// applies before it writes anything.
2706///
2707/// Returns `None` for anything that does not look like
2708/// `https://<host>/<owner>/<repo>/pull/<n>`, which the caller treats as
2709/// fail-closed: a URL this cannot make sense of refuses rather than guesses.
2710pub(crate) fn slug_of_pr_url(url: &str) -> Option<String> {
2711    let (host, path) = forge_slug(url)?;
2712    let mut segments = path.split('/');
2713    let owner = segments.next()?;
2714    let repo = segments.next()?;
2715    let kind = segments.next()?;
2716    if owner.is_empty() || repo.is_empty() || kind != "pull" {
2717        return None;
2718    }
2719    Some(format!("{host}/{owner}/{repo}"))
2720}
2721
2722/// Parse `host/owner/repo` out of a plain repository URL (no `/pull/<n>`
2723/// suffix), the shape `gh repo view --json url` returns - the other half of
2724/// the same-repo guard, matched against [`slug_of_pr_url`]'s output.
2725fn slug_of_repo_url(url: &str) -> Option<String> {
2726    let (host, path) = forge_slug(url)?;
2727    let mut segments = path.split('/');
2728    let owner = segments.next()?;
2729    let repo = segments.next()?;
2730    if owner.is_empty() || repo.is_empty() {
2731        return None;
2732    }
2733    Some(format!("{host}/{owner}/{repo}"))
2734}
2735
2736/// Refuse to correct a run against a pull request from a different
2737/// repository than the one it is recorded against.
2738///
2739/// This is the guard the shun/8c75 incident argued for: an operator ran
2740/// `magi fold --merged <shun PR url>` meaning to correct an old `Blocked` run
2741/// in a different repository, omitted the run id, and the id defaulted to
2742/// this machine's most recently created run - an unrelated, still-in-progress
2743/// run in a completely different repository - which then had its `status`
2744/// rewritten to `merged` from a pull request it had nothing to do with.
2745/// `correct_manual_merge` now requires an explicit id (see `magi fold`'s own
2746/// CLI help), but a mistyped or stale id could still name a run in a
2747/// different repository than the one the URL belongs to, so this checks that
2748/// independently rather than trusting the id alone.
2749///
2750/// Comparison is case-insensitive - GitHub owner/repo names are - and a
2751/// mismatch names both slugs rather than just refusing, so an operator whose
2752/// local checkout's `origin` is a fork of the repository the pull request was
2753/// opened against (a legitimate setup this cannot tell apart from a genuine
2754/// mix-up) can judge for themselves rather than being blocked with no way to
2755/// see why.
2756pub(crate) fn ensure_same_repo(run_repo_slug: &str, pr_repo_slug: &str) -> Result<()> {
2757    if run_repo_slug.eq_ignore_ascii_case(pr_repo_slug) {
2758        return Ok(());
2759    }
2760    bail!(
2761        "refusing to correct this run: it is recorded against {run_repo_slug}, but the pull \
2762         request URL belongs to {pr_repo_slug} - pass the run id whose repository the URL \
2763         actually belongs to (or, if `origin` is a fork opened against a different upstream, \
2764         verify by hand before treating this as a false positive)"
2765    );
2766}
2767
2768/// Ask the forge which `host/owner/repo` a local checkout's `origin` remote
2769/// actually resolves to, for the same-repo guard in [`correct_manual_merge`].
2770///
2771/// Asking `gh` rather than parsing `git remote -v` locally is deliberate: it
2772/// normalizes case, SSH vs. HTTPS remotes, and a renamed or transferred
2773/// repository the same way GitHub itself would recognize it, so the
2774/// comparison in [`ensure_same_repo`] is against the same canonical slug on
2775/// both sides. Reads `url` rather than `nameWithOwner` so the host is part of
2776/// the answer too - `nameWithOwner` alone cannot tell a `github.com` repo from
2777/// a same-named one on a GitHub Enterprise host.
2778async fn repo_slug(repo: &Path) -> Result<String> {
2779    let out = gh(
2780        repo,
2781        &[
2782            "repo".to_owned(),
2783            "view".to_owned(),
2784            "--json".to_owned(),
2785            "url".to_owned(),
2786        ],
2787    )
2788    .await?;
2789    if !out.ok {
2790        bail!("gh repo view --json url: {}", out.combined());
2791    }
2792    #[derive(Debug, Deserialize)]
2793    struct GhRepo {
2794        url: String,
2795    }
2796    let parsed: GhRepo = serde_json::from_str(&out.stdout)
2797        .with_context(|| format!("parse `gh repo view` output: {}", out.stdout.trim()))?;
2798    slug_of_repo_url(&parsed.url)
2799        .with_context(|| format!("could not parse a host/owner/repo out of {}", parsed.url))
2800}
2801
2802/// Confirm `url` is actually a merged pull request, then rewrite `state`'s
2803/// `status` and `merge` exactly as the automatic land loop (`land::land`)
2804/// would have written them had magi opened and merged this pull request
2805/// itself.
2806///
2807/// This is `magi fold --merged`'s whole implementation, and also what the
2808/// web `fold-merged` route calls once it has a URL in hand — an operator
2809/// recovery path for a merge magi could not finish on its own: a PR title too
2810/// long for the GraphQL mutation, `gh pr create` unreachable, a stale token -
2811/// closed by hand with a pull request magi never opened and so never
2812/// recorded. Reusing `land::land` rather than writing `status`/`merge`
2813/// directly keeps this one authoritative: a merged pull request decides
2814/// `Step::Done { merged: true }` on the very first read, before any of
2815/// `land`'s own checks/fix/rebase machinery can run, which is what makes it
2816/// safe to call here even though this pull request was never magi's own.
2817///
2818/// [`ensure_same_repo`] is checked before anything else: a pull request from
2819/// a different repository than the one `state` is recorded against is
2820/// refused outright, regardless of its lifecycle. This is the guard for a
2821/// URL an *operator* hands in - the CLI or the web route - where a stale or
2822/// mistyped run id could otherwise get corrected from an unrelated
2823/// repository's pull request (see the shun/8c75 incident in `magi fold`'s own
2824/// CLI help). The automatic janitor sweep (`clean::reconcile_external_merges`)
2825/// goes through [`correct_confirmed_external_merge`] instead, which skips
2826/// this check: its `url` was never operator-supplied, it comes from
2827/// [`find_external_merge`] querying `gh` from inside `state.repo` itself, so
2828/// it is already guaranteed to name a pull request in that same repository -
2829/// re-deriving and re-checking the repository here would only be a second
2830/// `gh repo view` call that can fail for reasons that have nothing to do with
2831/// correctness (a rate limit, a network blip), turning a self-heal that would
2832/// otherwise have succeeded into a run left `Blocked` for another pass.
2833///
2834/// [`lifecycle`] is checked next and separately so a mistyped or still-open
2835/// URL fails loudly without writing anything, rather than handing an open
2836/// pull request to the full autonomous loop by accident.
2837///
2838/// Correcting `status` this way does not run `bump::after_merge`
2839/// (`src/bump.rs`): that call is made only from `graph::Runner::run_land`,
2840/// which this path never goes through. A release version bump the change
2841/// might have earned is therefore not filed automatically and has to be
2842/// requested by hand - recorded as an event on the run so the gap is visible
2843/// to whoever reads it later, not just wherever this was called from. Follow-up
2844/// tasks for findings the merge left open (`crate::followup`) *are* filed here.
2845///
2846/// Returns the status before and after, so every caller (CLI, janitor, web
2847/// route) can build its own log line or response from the same pair rather
2848/// than each re-deriving it.
2849pub async fn correct_manual_merge(
2850    state: &mut RunState,
2851    url: &str,
2852) -> Result<(RunStatus, RunStatus)> {
2853    let Some(pr_slug) = slug_of_pr_url(url) else {
2854        bail!(
2855            "could not parse an owner/repo out of {url}; refusing to guess which repository \
2856             this pull request belongs to"
2857        );
2858    };
2859    let run_slug = repo_slug(&state.repo).await?;
2860    ensure_same_repo(&run_slug, &pr_slug)?;
2861    correct_merge(state, url).await
2862}
2863
2864/// The janitor's own entry point into the same correction
2865/// [`correct_manual_merge`] performs for an operator-supplied URL, minus the
2866/// same-repo guard - see that function's own doc for why skipping it here is
2867/// safe rather than a hole: [`clean::reconcile_external_merges`] only ever
2868/// calls this with a `url` [`find_external_merge`] already found by querying
2869/// `state.repo`'s own remote, so the guard could never do anything here but
2870/// fail on its own transient errors.
2871///
2872/// [`crate::clean`] is the only caller; `pub(crate)` rather than private only
2873/// because it lives in a different module.
2874pub(crate) async fn correct_confirmed_external_merge(
2875    state: &mut RunState,
2876    url: &str,
2877) -> Result<(RunStatus, RunStatus)> {
2878    correct_merge(state, url).await
2879}
2880
2881/// Same pull request, same repository: the url, or the number within one repo.
2882fn names_same_pr(a: &RunState, url: &str, number: u64, repo: &Path) -> bool {
2883    let Some(pr) = a.pr.as_ref() else {
2884        return false;
2885    };
2886    if !url.is_empty()
2887        && pr
2888            .url
2889            .trim_end_matches('/')
2890            .eq_ignore_ascii_case(url.trim_end_matches('/'))
2891    {
2892        return true;
2893    }
2894    number > 0
2895        && pr.number == number
2896        && match (a.repo.canonicalize(), repo.canonicalize()) {
2897            (Ok(x), Ok(y)) => x == y,
2898            _ => a.repo == repo,
2899        }
2900}
2901
2902/// Rewrite `pr.state` to a final state on every run record under `home` that
2903/// `decide` picks, and report how many were rewritten.
2904///
2905/// Lifecycle writes through to other runs are deliberately narrow (task-head
2906/// ownership is recorded separately): only a **terminal** run (never one a
2907/// driver may still be writing), only a proven-stopped driver with no daemon
2908/// claim (the shared liveness judge), only a record
2909/// whose `pr.state` is still `open`, and only `merged` / `closed` ever goes in.
2910/// The record is read as folding reads it (no schema check: every bump so far
2911/// only added fields, and the whole struct round-trips) and written through
2912/// [`RunState::save_under`], the path every record uses, so nothing but
2913/// `pr.state` and an event line changes (and `updated_at`, as for any save).
2914/// A run that cannot be read or written is skipped with a warning.
2915fn rewrite_open_prs(
2916    home: &Path,
2917    decide: &mut dyn FnMut(&RunState) -> Option<PrLifecycle>,
2918) -> usize {
2919    let now = Timestamp::now();
2920    let mut changed = 0;
2921    for id in crate::run::list_ids_in(&home.join("runs")) {
2922        let path = home.join("runs").join(&id).join("run.json");
2923        let read = || {
2924            let body = std::fs::read_to_string(&path).ok()?;
2925            serde_json::from_str::<RunState>(&body).ok()
2926        };
2927        // Do not contend with recovery of unrelated runs. This first read is
2928        // only a filter; every write still uses the record read under its lock.
2929        let Some(snapshot) = read() else {
2930            continue;
2931        };
2932        if !snapshot.status.done()
2933            || snapshot.pr.as_ref().is_none_or(|p| p.state != "open")
2934            || !matches!(
2935                decide(&snapshot),
2936                Some(PrLifecycle::Merged | PrLifecycle::Closed)
2937            )
2938        {
2939            continue;
2940        }
2941        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2942            continue;
2943        };
2944        let Some(mut state) = read() else {
2945            continue;
2946        };
2947        if !state.status.done()
2948            || state.pr.as_ref().is_none_or(|p| p.state != "open")
2949            || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2950                != crate::run::Liveness::Dead
2951        {
2952            continue;
2953        }
2954        let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2955            continue;
2956        };
2957        if let Some(pr) = state.pr.as_mut() {
2958            pr.state = to.as_str().to_owned();
2959        }
2960        let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2961        state.event(
2962            "land",
2963            format!("recorded {url} as {}: another run settled it", to.as_str()),
2964        );
2965        match state.save_under(home) {
2966            Ok(()) => changed += 1,
2967            Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2968        }
2969    }
2970    changed
2971}
2972
2973/// A run reached a final state for its pull request: tell every other terminal
2974/// run in the same repository that names the same pull request (handed-over
2975/// predecessors, blocked attempts, anything), so their records stop saying
2976/// `open`. Best effort; `run`'s own record is the caller's.
2977pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2978    if to == PrLifecycle::Open {
2979        return;
2980    }
2981    let Some(home) = crate::run::try_home() else {
2982        return;
2983    };
2984    write_pr_state_through_in(&home, run, to);
2985}
2986
2987pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2988    let Some(pr) = run.pr.as_ref() else {
2989        return 0;
2990    };
2991    let (url, number) = (pr.url.clone(), pr.number);
2992    rewrite_open_prs(home, &mut |other| {
2993        (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2994    })
2995}
2996
2997/// Terminal runs whose record still says their pull request is open, as
2998/// `(run id, repo, url)`, for [`repair_stale_pr_states`].
2999pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
3000    let now = Timestamp::now();
3001    let mut out = Vec::new();
3002    for id in crate::run::list_ids_in(&home.join("runs")) {
3003        let path = home.join("runs").join(&id).join("run.json");
3004        let Ok(body) = std::fs::read_to_string(&path) else {
3005            continue;
3006        };
3007        let Ok(state) = serde_json::from_str::<RunState>(&body) else {
3008            continue;
3009        };
3010        if let Some(pr) = state.pr.as_ref()
3011            && state.status.done()
3012            && pr.state == "open"
3013            && !pr.url.is_empty()
3014            && !crate::daemon::is_working_on(home, &id, now)
3015        {
3016            out.push((id, state.repo.clone(), pr.url.clone()));
3017        }
3018    }
3019    out
3020}
3021
3022/// Apply forge answers (`pr url -> state`) to every stale terminal record.
3023/// A url with no answer (the forge was unreadable) changes nothing.
3024pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
3025    rewrite_open_prs(home, &mut |s| {
3026        s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
3027    })
3028}
3029
3030/// Observe terminal records' open pull requests, with a bounded rotating scan.
3031/// Rewrite settled PRs and record conclusive stale-base observations separately
3032/// from the synchronization budget. Unknown answers leave evidence unchanged.
3033pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
3034    let mut known = BTreeMap::new();
3035    let mut failed = 0;
3036    let mut observed = 0;
3037    let mut groups = BTreeMap::<String, (PathBuf, Vec<String>)>::new();
3038    for (id, repo, url) in stale_open_prs(home) {
3039        groups
3040            .entry(url)
3041            .or_insert_with(|| (repo, Vec::new()))
3042            .1
3043            .push(id);
3044    }
3045    let mut groups = groups.into_iter().collect::<Vec<_>>();
3046    static CURSOR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3047    if !groups.is_empty() {
3048        let offset =
3049            CURSOR.fetch_add(max_lookups, std::sync::atomic::Ordering::Relaxed) % groups.len();
3050        groups.rotate_left(offset);
3051    }
3052    for (url, (repo, ids)) in groups.into_iter().take(max_lookups) {
3053        let view = gh(
3054            &repo,
3055            &[
3056                "pr".into(),
3057                "view".into(),
3058                url.clone(),
3059                "--json".into(),
3060                "state,mergeStateStatus,headRefOid,baseRefName".into(),
3061            ],
3062        )
3063        .await
3064        .and_then(|out| {
3065            anyhow::ensure!(out.ok, "gh pr view: {}", out.combined());
3066            let raw: GhPr = serde_json::from_str(&out.stdout)?;
3067            let state = match raw.state.to_ascii_uppercase().as_str() {
3068                "OPEN" => PrLifecycle::Open,
3069                "MERGED" => PrLifecycle::Merged,
3070                "CLOSED" => PrLifecycle::Closed,
3071                other => bail!("unknown pull request state `{other}`"),
3072            };
3073            Ok((state, raw))
3074        });
3075        match view {
3076            Ok((state, raw)) => {
3077                for id in ids {
3078                    if state != PrLifecycle::Open {
3079                        continue;
3080                    }
3081                    let Ok(snapshot) = RunState::load_under(&id, home) else {
3082                        continue;
3083                    };
3084                    if snapshot.status != RunStatus::Ready || snapshot.pr_taken_over_by.is_some() {
3085                        continue;
3086                    }
3087                    let tip = if matches!(
3088                        Blocking::of(&raw.merge_state_status),
3089                        Blocking::Conflict | Blocking::Behind
3090                    ) {
3091                        tokio::time::timeout(
3092                            std::time::Duration::from_secs(15),
3093                            git::remote_head(
3094                                &snapshot.repo,
3095                                &snapshot.config.merge.remote,
3096                                &snapshot.base_branch,
3097                            ),
3098                        )
3099                        .await
3100                        .ok()
3101                        .and_then(Result::ok)
3102                        .flatten()
3103                    } else {
3104                        None
3105                    };
3106                    if let Ok(_lock) = crate::pr_head::owner_lock(home, &id)
3107                        && let Ok(mut run) = RunState::load_under(&id, home)
3108                        && run.repo == snapshot.repo
3109                        && run.config.merge.remote == snapshot.config.merge.remote
3110                        && run.base_branch == snapshot.base_branch
3111                        && run.updated_at == snapshot.updated_at
3112                        && run.status == RunStatus::Ready
3113                        && run.pr_taken_over_by.is_none()
3114                        && run.retired_to.is_none()
3115                        && !run.released()
3116                        && run
3117                            .pr
3118                            .as_ref()
3119                            .is_some_and(|p| p.url == url && p.state == "open")
3120                        && run.liveness_under(
3121                            home,
3122                            crate::daemon::is_working_on(home, &id, Timestamp::now()),
3123                        ) == crate::run::Liveness::Dead
3124                        && raw.base_ref_name == run.base_branch
3125                        && !raw.head_ref_oid.is_empty()
3126                    {
3127                        let recorded = run
3128                            .base_sync
3129                            .as_ref()
3130                            .map_or(run.base_commit.as_str(), |bs| bs.tip.as_str());
3131                        let next = stale_public_pr(
3132                            &raw,
3133                            recorded,
3134                            tip.as_deref(),
3135                            run.stale_public_pr.as_ref(),
3136                        );
3137                        if run.stale_public_pr != next {
3138                            run.stale_public_pr = next;
3139                            match run.save_under(home) {
3140                                Ok(()) => {
3141                                    observed += 1;
3142                                    if let Some(detail) = run.stale_pr_cause() {
3143                                        crate::notices::raise_in(
3144                                            home,
3145                                            crate::notices::Notice::warn(
3146                                                &format!("stale-pr:{id}"),
3147                                                detail,
3148                                            )
3149                                            .link(crate::notices::Link::Run { id: id.clone() })
3150                                            .about([id.clone()]),
3151                                        );
3152                                    }
3153                                }
3154                                Err(e) => tracing::warn!(
3155                                    "record PR synchronization state for {id}: {e:#}"
3156                                ),
3157                            }
3158                        }
3159                    }
3160                }
3161                known.insert(url, state);
3162            }
3163            Err(e) => {
3164                tracing::warn!("repair pr state of {url}: {e:#}");
3165                failed += 1;
3166            }
3167        }
3168    }
3169    (apply_pr_states(home, &known) + observed, failed)
3170}
3171
3172pub(crate) fn stale_pr_recovery_command(task: &str, url: &str, head: &str) -> String {
3173    format!("magi task recover-pr {task} --pr {url} --head {head} --disposition land")
3174}
3175
3176fn pr_went_stale(
3177    recorded_base: &str,
3178    base_tip: &str,
3179    state: PrLifecycle,
3180    blocking: Blocking,
3181) -> bool {
3182    state == PrLifecycle::Open
3183        && !recorded_base.is_empty()
3184        && !base_tip.is_empty()
3185        && recorded_base != base_tip
3186        && matches!(blocking, Blocking::Conflict | Blocking::Behind)
3187}
3188
3189fn stale_public_pr(
3190    raw: &GhPr,
3191    recorded_base: &str,
3192    base_tip: Option<&str>,
3193    previous: Option<&crate::run::StalePublicPr>,
3194) -> Option<crate::run::StalePublicPr> {
3195    use crate::run::{PublicBaseState, StalePublicPr};
3196    let state = match raw.merge_state_status.as_str() {
3197        "DIRTY" => PublicBaseState::Conflicting,
3198        "BEHIND" => PublicBaseState::Behind,
3199        "CLEAN" | "UNSTABLE" => return None,
3200        _ => return previous.cloned(),
3201    };
3202    if raw.head_ref_oid.len() != 40 || !raw.head_ref_oid.bytes().all(|b| b.is_ascii_hexdigit()) {
3203        return previous.cloned();
3204    }
3205    let Some(base_tip) = base_tip.filter(|tip| !tip.is_empty() && !recorded_base.is_empty()) else {
3206        return previous.cloned();
3207    };
3208    if !pr_went_stale(
3209        recorded_base,
3210        base_tip,
3211        PrLifecycle::Open,
3212        Blocking::of(&raw.merge_state_status),
3213    ) {
3214        return None;
3215    }
3216    Some(StalePublicPr {
3217        head: raw.head_ref_oid.clone(),
3218        state,
3219        recorded_base: recorded_base.into(),
3220        base_tip: base_tip.into(),
3221    })
3222}
3223
3224#[test]
3225fn stale_pr_needs_moved_base_and_forge_evidence() {
3226    use PrLifecycle::{Closed, Merged, Open};
3227    assert!(pr_went_stale("a", "b", Open, Blocking::Conflict));
3228    assert!(pr_went_stale("a", "b", Open, Blocking::Behind));
3229    assert!(!pr_went_stale("a", "a", Open, Blocking::Conflict));
3230    assert!(!pr_went_stale("a", "b", Open, Blocking::No));
3231    assert!(!pr_went_stale("a", "b", Open, Blocking::Unsaid));
3232    assert!(!pr_went_stale("a", "b", Merged, Blocking::Conflict));
3233    assert!(!pr_went_stale("a", "b", Closed, Blocking::Conflict));
3234    assert!(!pr_went_stale("a", "", Open, Blocking::Conflict));
3235    assert!(!pr_went_stale("", "b", Open, Blocking::Conflict));
3236}
3237
3238#[test]
3239fn stale_public_pr_retains_conflict_until_conclusive_observation() {
3240    use crate::run::PublicBaseState;
3241    let raw = |status: &str| -> GhPr {
3242        serde_json::from_value(serde_json::json!({
3243            "mergeStateStatus": status,
3244            "headRefOid": "a".repeat(40)
3245        }))
3246        .unwrap()
3247    };
3248    let conflict = stale_public_pr(&raw("DIRTY"), "a", Some("b"), None).unwrap();
3249    assert_eq!(conflict.state, PublicBaseState::Conflicting);
3250    assert_eq!(
3251        stale_public_pr(&raw("UNKNOWN"), "a", Some("b"), Some(&conflict)),
3252        Some(conflict.clone())
3253    );
3254    assert_eq!(
3255        stale_public_pr(&raw("DIRTY"), "a", None, Some(&conflict)),
3256        Some(conflict.clone())
3257    );
3258    assert_eq!(stale_public_pr(&raw("DIRTY"), "a", Some("a"), None), None);
3259    assert_eq!(
3260        stale_public_pr(&raw("CLEAN"), "a", None, Some(&conflict)),
3261        None
3262    );
3263    assert_eq!(
3264        stale_public_pr(&raw("BEHIND"), "a", Some("b"), None)
3265            .unwrap()
3266            .state,
3267        PublicBaseState::Behind
3268    );
3269}
3270
3271async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
3272    match lifecycle(&state.repo, url).await? {
3273        PrLifecycle::Merged => {}
3274        other => bail!(
3275            "{url} is {}, not merged; refusing to record {} as merged on a guess",
3276            other.as_str(),
3277            state.id
3278        ),
3279    }
3280    let before = state.status;
3281    if let Err(e) = land(state, url).await {
3282        // `land` sets `status` to `Landing` and saves before its first read
3283        // of the pull request — see its own doc — so a failure here (a
3284        // transient `gh` hiccup between the two forge reads this function
3285        // makes) can leave the run stuck on that in-between value with
3286        // nothing left driving it. Land it on the same terminal shape an
3287        // automated `land` failure lands on instead of leaving it stuck.
3288        state.status = RunStatus::Blocked;
3289        state.event("fold", format!("manual-merge correction failed: {e:#}"));
3290        state.save()?;
3291        return Err(e).context(format!("confirming the merge of {url}"));
3292    }
3293    state.event(
3294        "fold",
3295        "operator recorded this pull request as a manual merge; this run never \
3296         re-entered `land`, so `bump::after_merge` did not run for it - a release \
3297         bump this change might warrant has to be filed by hand",
3298    );
3299    // Unlike the bump, the findings the merge left open are filed on this
3300    // path too: nothing else would ever carry them forward.
3301    if state.status == RunStatus::Merged {
3302        crate::followup::after_merge(state, url).await;
3303    }
3304    state.save()?;
3305    Ok((before, state.status))
3306}
3307
3308/// Parse `gh api repos/{owner}/{repo}/pulls/<n>/comments` into inline review
3309/// comments. No I/O.
3310///
3311/// `gh pr view` does not surface inline comments, and inline is exactly where
3312/// both review bots put their findings - a landing loop that read only the
3313/// top-level thread would never see the thing it is supposed to fix.
3314pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3315    let raw: Vec<GhInline> =
3316        serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3317    let mut out = Vec::new();
3318    for c in raw {
3319        push_if_outstanding(
3320            &mut out,
3321            ReviewComment {
3322                author: c.user.login,
3323                path: c.path,
3324                line: c.line,
3325                body: c.body,
3326            },
3327        );
3328    }
3329    Ok(out)
3330}
3331
3332/// Keep a comment only when it asks for something.
3333///
3334/// An inline comment always does: it names a file and a line. A top-level
3335/// comment is dropped when it is empty, when it is magi's own, or when it is
3336/// [noise](is_noise).
3337fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3338    if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3339        return;
3340    }
3341    if comment.path.is_none() && is_noise(&comment.body) {
3342        return;
3343    }
3344    out.push(comment);
3345}
3346
3347/// Is this comment body machinery rather than a finding?
3348///
3349/// Two tests, both structural, because guessing from prose is how a "looks
3350/// good to me" turns into a fix round:
3351///
3352/// 1. The bot said so - the body carries one of the [`NOT_A_REVIEW`] markers
3353///    with which CodeRabbit labels its trigger notice, its walkthrough, and its
3354///    footer.
3355/// 2. It asks for nothing - once HTML comments, `<details>` blocks, headings,
3356///    horizontal rules, and the bot's own status banner are removed, every
3357///    remaining line is a task-list item. That is exactly the shape of the
3358///    comment the Claude review job posts while it is still working.
3359///
3360/// Anything else is input, including bot prose. A bot that writes a paragraph
3361/// has said something, and the fix prompt tells the fixer it may decline a
3362/// comment with an argument - a wasted sentence in a prompt is cheaper than a
3363/// missed finding.
3364pub fn is_noise(body: &str) -> bool {
3365    if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3366        return true;
3367    }
3368    let mut content = false;
3369    for line in strip_blocks(body).lines() {
3370        let line = unquote(line);
3371        if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3372            continue;
3373        }
3374        content = true;
3375        break;
3376    }
3377    !content
3378}
3379
3380/// Remove HTML comments and collapsed `<details>` blocks.
3381fn strip_blocks(body: &str) -> String {
3382    let mut out = String::with_capacity(body.len());
3383    let mut rest = body;
3384    loop {
3385        let open = ["<!--", "<details>"]
3386            .iter()
3387            .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3388            .min_by_key(|(i, _)| *i);
3389        let Some((at, tag)) = open else {
3390            out.push_str(rest);
3391            return out;
3392        };
3393        out.push_str(&rest[..at]);
3394        let after = &rest[at + tag.len()..];
3395        let close = if tag == "<!--" { "-->" } else { "</details>" };
3396        match after.find(close) {
3397            Some(end) => rest = &after[end + close.len()..],
3398            // Unterminated: the rest of the body is inside the block.
3399            None => return out,
3400        }
3401    }
3402}
3403
3404/// Strip blockquote markers, which both bots wrap their callouts in.
3405fn unquote(line: &str) -> &str {
3406    let mut s = line.trim();
3407    while let Some(rest) = s.strip_prefix('>') {
3408        s = rest.trim_start();
3409    }
3410    s.trim()
3411}
3412
3413/// `- [ ]` / `- [x]`, in any of the bullet styles GitHub renders.
3414fn is_checklist(line: &str) -> bool {
3415    let rest = line
3416        .strip_prefix("- ")
3417        .or_else(|| line.strip_prefix("* "))
3418        .unwrap_or("");
3419    let rest = rest.trim_start();
3420    matches!(
3421        rest.get(..3),
3422        Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3423    )
3424}
3425
3426/// A heading, a horizontal rule, or a callout tag - shape, never content.
3427fn is_decoration(line: &str) -> bool {
3428    line.starts_with('#')
3429        || line.starts_with("[!")
3430        || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3431}
3432
3433/// A line that is nothing but emphasis and links.
3434///
3435/// Both review jobs open with a status banner
3436/// (`**Claude finished ... in 4m 14s** —— [View job](url)`). It reads as prose
3437/// to a line-based test and asks for nothing, so it is measured the same way a
3438/// heading is: strip the markup, and if no word survives, it was decoration.
3439fn is_banner(line: &str) -> bool {
3440    let plain = drop_spans(line, "**", "**");
3441    let plain = if plain.contains("](") {
3442        drop_spans(&plain, "[", ")")
3443    } else {
3444        plain
3445    };
3446    !plain.chars().any(char::is_alphanumeric)
3447}
3448
3449/// Remove every `open` .. `close` span, including the delimiters. An
3450/// unterminated span swallows the rest of the input, which is what a reader
3451/// sees too.
3452fn drop_spans(s: &str, open: &str, close: &str) -> String {
3453    let mut out = String::with_capacity(s.len());
3454    let mut rest = s;
3455    while let Some(at) = rest.find(open) {
3456        out.push_str(&rest[..at]);
3457        let after = &rest[at + open.len()..];
3458        match after.find(close) {
3459            Some(end) => rest = &after[end + close.len()..],
3460            None => return out,
3461        }
3462    }
3463    out.push_str(rest);
3464    out
3465}
3466
3467/// The lock that keeps at most one run per repository actually moving the
3468/// base branch at a time: a rebase push, or `gh pr merge`.
3469///
3470/// Deliberately narrow. Everything else in [`land`]'s loop - watching CI,
3471/// running a fix round in the winner's own worktree, waiting on the owner's
3472/// approval - touches nothing a *different* run in the same repository could
3473/// collide with, and holding a lock across any of that would serialise one
3474/// run's CI wait (up to [`WAIT_CEILING`]) against another run's land-approval
3475/// resume, which is precisely the "must not wait on another task" property
3476/// the daemon's slot-freeing exists to give a resume. Only the two moments
3477/// that actually write to the shared base branch need mutual exclusion, and
3478/// both are brief.
3479///
3480/// One entry per repository, each its own `tokio::sync::Mutex`, so two
3481/// different repositories' runs never wait on each other. The outer
3482/// `std::sync::Mutex` guards only the map itself, held long enough to find or
3483/// insert an entry and clone its `Arc`, never across an `.await`.
3484fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3485    static LOCKS: std::sync::LazyLock<
3486        std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3487    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3488    LOCKS
3489        .lock()
3490        .unwrap_or_else(std::sync::PoisonError::into_inner)
3491        .entry(repo.to_path_buf())
3492        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3493        .clone()
3494}
3495
3496/// `owner/repo` out of a pull request url, falling back to the checkout's
3497/// directory name when the url is not the usual `host/owner/repo/pull/N`.
3498fn repo_label(repo: &Path, pr_url: &str) -> String {
3499    let parts: Vec<&str> = pr_url.split('/').collect();
3500    if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3501        && at >= 2
3502        && !parts[at - 1].is_empty()
3503        && !parts[at - 2].is_empty()
3504    {
3505        return format!("{}/{}", parts[at - 2], parts[at - 1]);
3506    }
3507    repo.file_name()
3508        .map(|n| n.to_string_lossy().into_owned())
3509        .unwrap_or_default()
3510}
3511
3512/// The operator-facing sentence for a merge that went ahead with red checks,
3513/// or `None` when the checks were not red. Judged on `checks`, not on
3514/// `failing`, which can be non-empty on a green observation.
3515fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3516    (pr.checks == Checks::Red).then(|| {
3517        let details = crate::notices::format_list(&pr.failing)
3518            .map(|names| format!(": {names}"))
3519            .unwrap_or_default();
3520        format!(
3521            "Merged {repo_name} PR #{} with red checks{details} ({})",
3522            pr.number, pr.url
3523        )
3524    })
3525}
3526
3527/// After a merge that succeeded: record which checks were red and tell the
3528/// operator. The decision to merge is already made; this only makes it audible.
3529/// Best-effort - a broken notifier never fails the run.
3530async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3531    let repo_name = repo_label(&state.repo, &pr.url);
3532    let Some(summary) = red_merge_summary(&repo_name, pr) else {
3533        return;
3534    };
3535    if let Some(rec) = state.pr.as_mut() {
3536        rec.red_at_merge = pr.failing.clone();
3537    }
3538    state.event("land", summary.clone());
3539    // The notice pages through `[notify]` itself, once, unless a question
3540    // already carries the cause.
3541    crate::notices::raise_with(
3542        crate::notices::merged_red(&state.id, &summary),
3543        &state.config.notify,
3544    );
3545}
3546
3547/// Run the loop against a real pull request until it merges or the budget runs
3548/// out.
3549///
3550/// The caller decides whether landing happens at all: this is only reached when
3551/// `graph.land` is on. Returns the last observation, so the caller can report
3552/// what magi was looking at when it stopped.
3553pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3554    land_with(state, pr_url, &GhForge).await
3555}
3556
3557/// The forge calls whose timing the loop's decisions depend on, behind a seam
3558/// so a test can script what the pull request looks like from one observation
3559/// to the next. Comments, logs and rebases stay on `gh` and `git` directly.
3560trait Forge {
3561    async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3562        let out = gh(
3563            repo,
3564            &[
3565                "pr".into(),
3566                "close".into(),
3567                pr_url.into(),
3568                "--comment".into(),
3569                comment.into(),
3570            ],
3571        )
3572        .await?;
3573        if !out.ok {
3574            bail!("PR closure failed: {}", out.combined());
3575        }
3576        Ok(())
3577    }
3578    async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3579        None
3580    }
3581    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3582    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3583    async fn poll(&self);
3584    /// Rerun the failed jobs of one workflow run.
3585    async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3586    /// Unix seconds, behind the seam so a test owns the clock.
3587    fn now(&self) -> i64;
3588    /// The check contexts the base branch requires, for a stop reason only.
3589    /// `None` when they could not be read, which is not the same as none.
3590    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3591    #[allow(clippy::too_many_arguments)]
3592    async fn fix(
3593        &self,
3594        state: &mut RunState,
3595        pr: &PrState,
3596        round: usize,
3597        budget: usize,
3598        reason: &str,
3599        logs: &str,
3600    ) -> Result<Fixed>;
3601}
3602
3603struct GhForge;
3604
3605impl Forge for GhForge {
3606    async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3607        collect_ci_evidence(state, seen).await
3608    }
3609    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3610        observe(repo, pr_url).await
3611    }
3612    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3613        let out = gh(repo, argv).await?;
3614        Ok((out.ok, out.combined()))
3615    }
3616    async fn poll(&self) {
3617        tokio::time::sleep(POLL).await;
3618    }
3619    async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3620        let args = [
3621            "run".to_owned(),
3622            "rerun".to_owned(),
3623            run.to_owned(),
3624            "--failed".to_owned(),
3625        ];
3626        let out = gh(repo, &args).await?;
3627        if !out.ok {
3628            bail!("gh run rerun {run}: {}", out.combined());
3629        }
3630        Ok(())
3631    }
3632    fn now(&self) -> i64 {
3633        jiff::Timestamp::now().as_second()
3634    }
3635    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3636        required_contexts_of(repo, base).await
3637    }
3638    async fn fix(
3639        &self,
3640        state: &mut RunState,
3641        pr: &PrState,
3642        round: usize,
3643        budget: usize,
3644        reason: &str,
3645        logs: &str,
3646    ) -> Result<Fixed> {
3647        fix_round(state, pr, round, budget, reason, logs).await
3648    }
3649}
3650
3651/// Percent-encode a branch name for a URL path segment (`/` included).
3652fn encode_path_segment(s: &str) -> String {
3653    let mut out = String::new();
3654    for b in s.bytes() {
3655        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3656            out.push(b as char);
3657        } else {
3658            let _ = write!(out, "%{b:02X}");
3659        }
3660    }
3661    out
3662}
3663
3664/// Read the required contexts of `base` from classic branch protection and
3665/// from rulesets, once, for a stop reason. Organisation-level rulesets that
3666/// these two endpoints do not list are missed. Any unreadable source makes the
3667/// whole answer `None`: a partial set would read as a complete one.
3668async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3669    let enc = encode_path_segment(base);
3670    let mut all = BTreeSet::new();
3671    // Classic protection answers 404 for an unprotected branch, which is
3672    // "nothing required here", not a failure to read.
3673    let classic = gh(
3674        repo,
3675        &[
3676            "api".to_owned(),
3677            format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3678        ],
3679    )
3680    .await
3681    .ok()?;
3682    if classic.ok {
3683        all.extend(parse_classic_required(&classic.stdout)?);
3684    } else if !classic.combined().contains("404") {
3685        return None;
3686    }
3687    let rules = gh(
3688        repo,
3689        &[
3690            "api".to_owned(),
3691            format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3692        ],
3693    )
3694    .await
3695    .ok()?;
3696    if !rules.ok {
3697        return None;
3698    }
3699    all.extend(parse_ruleset_required(&rules.stdout)?);
3700    Some(all)
3701}
3702
3703/// `required_status_checks` of classic protection: `contexts` plus the
3704/// `checks[].context` form.
3705fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3706    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3707    let mut out = BTreeSet::new();
3708    for c in v.get("contexts")?.as_array()? {
3709        out.insert(c.as_str()?.to_owned());
3710    }
3711    for c in v
3712        .get("checks")
3713        .and_then(|c| c.as_array())
3714        .into_iter()
3715        .flatten()
3716    {
3717        if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3718            out.insert(name.to_owned());
3719        }
3720    }
3721    Some(out)
3722}
3723
3724/// `rules/branches/<base>`: every `required_status_checks` rule's contexts.
3725fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3726    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3727    let mut out = BTreeSet::new();
3728    for rule in v.as_array()? {
3729        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3730            continue;
3731        }
3732        let checks = rule
3733            .pointer("/parameters/required_status_checks")?
3734            .as_array()?;
3735        for c in checks {
3736            out.insert(c.get("context")?.as_str()?.to_owned());
3737        }
3738    }
3739    Some(out)
3740}
3741
3742/// Is the observation older than the commit a fix round pushed?
3743///
3744/// The forge takes a few seconds to move the pull request to a new head and
3745/// attach that head's check runs, and until it has, the rollup is the previous
3746/// head's - all green, which is exactly what a merge decision must not read.
3747/// An absent or different head counts as not yet: guessing "close enough"
3748/// would reopen the hole.
3749fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3750    awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3751}
3752
3753/// The commit an observation may be decided on, or `None` while it cannot be
3754/// trusted to describe one.
3755///
3756/// `None` when a pushed commit is awaited and the pull request is not on it,
3757/// when the head is unreadable, or when the rollup (`statusCheckRollup` is the
3758/// last commit's) is not the head's: that is the previous commit's checks. The
3759/// caller re-polls on `None`. A rollup that cannot be read (including one
3760/// longer than a page) leaves `rollup_head` empty, so the wait runs to
3761/// [`WAIT_CEILING`] and stops - a safe failure, never a merge.
3762fn bound_head<'a>(
3763    seen_head: &'a str,
3764    rollup_head: &str,
3765    awaiting: Option<&str>,
3766) -> Option<&'a str> {
3767    if seen_head.is_empty()
3768        || awaiting_new_head(awaiting, seen_head)
3769        || !rollup_head.eq_ignore_ascii_case(seen_head)
3770    {
3771        return None;
3772    }
3773    Some(seen_head)
3774}
3775
3776/// What a refused `gh pr merge` means.
3777#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3778enum Refused {
3779    /// An open PR on the observed head has a proven stale base.
3780    Behind,
3781    /// The branch policy is not satisfied *yet*: go back to waiting.
3782    Pending,
3783    /// Checks have settled and the merge state still says no, seen for the
3784    /// first time. The forge updates `mergeStateStatus` a moment after the last
3785    /// check finishes, so one more look is allowed before believing it.
3786    Recheck,
3787    /// Nothing is in flight and the policy still refuses: a person has to
3788    /// supply what it asks for (a review, say).
3789    Final,
3790}
3791
3792/// Judged from the pull request's state after the refusal, never from the
3793/// refusal's wording, which belongs to the forge and changes.
3794fn classify_refusal(
3795    after: Option<&Seen>,
3796    rechecked: bool,
3797    observed_head: &str,
3798    ci: CiExpectation,
3799) -> Refused {
3800    let Some(after) = after else {
3801        // Unreadable is not evidence of anything; the next loop reads again.
3802        return Refused::Pending;
3803    };
3804    if after.pr.state != PrLifecycle::Open {
3805        return Refused::Final;
3806    }
3807    // The branch moved after it was observed (the forge refuses a merge pinned
3808    // to the old commit): not a verdict on anything, look again.
3809    if !after.head.eq_ignore_ascii_case(observed_head) {
3810        return Refused::Pending;
3811    }
3812    if Blocking::of(&after.merge_state) == Blocking::Behind {
3813        return Refused::Behind;
3814    }
3815    // The same binding the loop applies: checks of another commit say nothing.
3816    if bound_head(&after.head, &after.rollup_head, None).is_none() {
3817        return Refused::Pending;
3818    }
3819    let state = after.merge_state.to_ascii_uppercase();
3820    if (ci == CiExpectation::Expected
3821        && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3822        || state.is_empty()
3823        || state == "UNKNOWN"
3824    {
3825        return Refused::Pending;
3826    }
3827    if rechecked {
3828        Refused::Final
3829    } else {
3830        Refused::Recheck
3831    }
3832}
3833
3834/// Take auto-merge back from the forge and forget that it was armed.
3835///
3836/// `Err` carries the forge's message: the caller must not push or move on, as
3837/// an armed merge left behind could still fire for a commit nobody approved.
3838async fn disarm<F: Forge>(
3839    forge: &F,
3840    state: &mut RunState,
3841    repo: &Path,
3842    number: u64,
3843) -> std::result::Result<(), String> {
3844    let argv = disable_automerge_argv(number);
3845    let out = {
3846        let merge_lock = repo_merge_lock(repo);
3847        let _merge_slot = merge_lock.lock().await;
3848        forge.merge(repo, &argv).await
3849    };
3850    match out {
3851        Ok((true, _)) => {
3852            state.land_armed_head = None;
3853            state.event("land", "auto-merge disabled");
3854            state.save().map_err(|e| format!("{e:#}"))?;
3855            Ok(())
3856        }
3857        Ok((false, msg)) => Err(msg),
3858        Err(e) => Err(format!("{e:#}")),
3859    }
3860}
3861
3862/// [`stop`], first taking back an armed auto-merge so a pull request magi
3863/// gave up on does not merge on its own later. A failure to disarm is added
3864/// to the reason rather than hiding it.
3865async fn stop_disarmed<F: Forge>(
3866    forge: &F,
3867    state: &mut RunState,
3868    repo: &Path,
3869    pr: &PrState,
3870    why: &str,
3871) -> Result<()> {
3872    if state.land_armed_head.is_none() {
3873        return stop(state, repo, pr, why).await;
3874    }
3875    match disarm(forge, state, repo, pr.number).await {
3876        Ok(()) => stop(state, repo, pr, why).await,
3877        Err(e) => {
3878            let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3879            stop(state, repo, pr, &why).await
3880        }
3881    }
3882}
3883
3884/// Check the persisted card again around awaits that can outlive an owner tap.
3885fn owner_requested_stop(state: &RunState) -> Result<bool> {
3886    let Some(binding) = &state.land_approval else {
3887        return Ok(false);
3888    };
3889    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3890    Ok(q.run == state.id
3891        && q.node == APPROVAL_NODE
3892        && q.resolution()
3893            .as_deref()
3894            .is_some_and(crate::merge_decision::stops))
3895}
3896
3897/// Read stop choices before checks, repair or rebase. These are about stopping
3898/// ownership, so a changed head never cancels them as it cancels merge consent.
3899async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3900    use crate::merge_decision as md;
3901    let Some(binding) = &state.land_approval else {
3902        return Ok(false);
3903    };
3904    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3905    let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3906        return Ok(false);
3907    };
3908    if q.run != state.id || q.node != APPROVAL_NODE {
3909        bail!("stop decision names another run");
3910    }
3911    let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3912        pr: pr.url.clone(),
3913        head: binding.head.clone(),
3914        language: state.config.graph.language.clone(),
3915    });
3916    if target.pr != pr.url {
3917        bail!("stop decision names another PR");
3918    }
3919    if state.merge_decision.is_none() {
3920        state.merge_decision = Some(md::Decision {
3921            question: q.id.clone(),
3922            target,
3923            choice: choice.clone(),
3924            closed: false,
3925            replacement_run: None,
3926            replacement_pr: None,
3927        });
3928        state.save()?;
3929    }
3930    let repo = state.repo.clone();
3931    // Always disable, including arms left by an older driver.
3932    if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3933        stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3934        return Ok(true);
3935    }
3936    if choice.eq_ignore_ascii_case(HOLD) {
3937        stop(
3938            state,
3939            &repo,
3940            pr,
3941            "owner held the decision: PR left open; no further repair or merge work",
3942        )
3943        .await?;
3944        return Ok(true);
3945    }
3946    if md::selected_agent(&choice).is_some()
3947        || state
3948            .origin
3949            .as_ref()
3950            .and_then(|o| o.task.as_ref())
3951            .is_some()
3952    {
3953        let owners: Vec<_> = crate::queue::Queue::open()
3954            .list()
3955            .into_iter()
3956            .filter(|task| task.execution_runs().last() == Some(&state.id))
3957            .collect();
3958        let owner = (owners.len() == 1).then(|| &owners[0]);
3959        if !owner.is_some_and(|task| {
3960            task.execution_runs().last() == Some(&state.id)
3961                && (!task
3962                    .operator_decided_at
3963                    .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3964                    || task.resumption.as_ref().is_some_and(|release| {
3965                        release.question_id.as_deref() == Some(q.id.as_str())
3966                            && task.operator_decided_at == Some(release.at)
3967                    }))
3968        }) {
3969            stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3970            return Ok(true);
3971        }
3972    }
3973    if pr.state == PrLifecycle::Merged {
3974        stop(
3975            state,
3976            &repo,
3977            pr,
3978            "PR already merged; withdrawal/replacement cannot be applied",
3979        )
3980        .await?;
3981        return Ok(true);
3982    }
3983    let comment = format!(
3984        "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3985        q.id, choice, state.id
3986    );
3987    if pr.state == PrLifecycle::Open {
3988        if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3989            stop(
3990                state,
3991                &repo,
3992                pr,
3993                &format!(
3994                    "owner requested closure but it failed: {e}; task held, no replacement started"
3995                ),
3996            )
3997            .await?;
3998            return Ok(true);
3999        }
4000    }
4001    let confirmed = forge.view(&repo, &pr.url).await?;
4002    if confirmed.pr.state != PrLifecycle::Closed {
4003        stop(
4004            state,
4005            &repo,
4006            pr,
4007            "PR closure was not confirmed; task held, no replacement started",
4008        )
4009        .await?;
4010        return Ok(true);
4011    }
4012    *pr = confirmed.pr;
4013    state.merge_decision.as_mut().unwrap().closed = true;
4014    if let Some(record) = &mut state.pr {
4015        record.state = "closed".into();
4016    }
4017    state.status = RunStatus::Superseded;
4018    state.merge = Some(MergeOutcome {
4019        mode: MergeMode::Pr,
4020        ok: false,
4021        detail: format!("owner decision: {choice}; PR closure confirmed"),
4022        empty: false,
4023    });
4024    state.event(
4025        "land",
4026        format!(
4027            "{} applied: PR closure confirmed; old execution retired",
4028            choice
4029        ),
4030    );
4031    state.save()?;
4032    Ok(true)
4033}
4034
4035/// Keep an unstarted verification resumable without charging a task attempt.
4036fn check_landing_resources(
4037    state: &mut RunState,
4038    node: &str,
4039    outcomes: &[crate::run::CommandOutcome],
4040) -> Result<()> {
4041    if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
4042        let detail = format!("{}: {}", blocked.command, blocked.output_tail);
4043        state
4044            .resource_block
4045            .get_or_insert_with(|| crate::run::ResourceBlock {
4046                cause: crate::run::ResourceBlockCause::Other,
4047                node: node.into(),
4048                kind: "shared build cache".into(),
4049                detail: detail.clone(),
4050                at: jiff::Timestamp::now(),
4051            });
4052        state.event("resource", &detail);
4053        state.save()?;
4054        bail!("landing verification could not start: {detail}");
4055    }
4056    Ok(())
4057}
4058
4059/// Gate the local winner and publish that exact SHA, retaining the saved lease.
4060/// A push completed before a crash is recoverable only when its SHA was gated.
4061async fn publish_landing_head<F: Forge>(
4062    state: &mut RunState,
4063    observed: &str,
4064    pr_url: &str,
4065    forge: &F,
4066) -> Result<String> {
4067    crate::pr_head::ensure_owner(state)?;
4068    let winner = state.winner().cloned().context("landing has no winner")?;
4069    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
4070    let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
4071    anyhow::ensure!(
4072        observed == expected
4073            || (observed == head
4074                && state.gate_head.as_deref() == Some(&head)
4075                && state.gate_allows_progress()),
4076        "public head moved outside this run; refusing to overwrite it"
4077    );
4078    anyhow::ensure!(
4079        git::is_clean(&winner.worktree).await?,
4080        "landing worktree is dirty"
4081    );
4082    // Even without a rebase, verification can change HEAD through gate repair.
4083    // Persist the start before either verification or repair can run.
4084    if state.land_sync_unstarted_grant() {
4085        state.land_sync_attempts += 1;
4086        state.land_sync_pending = true;
4087        state.event(
4088            "land-sync-recovery",
4089            "started recovery attempt without rebase",
4090        );
4091        state.save()?;
4092    }
4093    if state.gate_head.as_deref() != Some(&head)
4094        || !state.gate_ran
4095        || !state.gate_commands_allow_progress()
4096    {
4097        state.reconcile_verification_head(&head);
4098        state.gate.clear();
4099        state.gate_head = None;
4100        state.gate_ran = false;
4101        state.pre_gate.clear();
4102        state.pre_gate_commit = None;
4103        state.save()?;
4104        let inherited = crate::repo_lock::WaitPolicy::current();
4105        let wait = crate::repo_lock::WaitPolicy::new(
4106            Duration::from_secs(state.config.graph.timeout_resource_wait),
4107            move || inherited.cancelled(),
4108        );
4109        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
4110        loop {
4111            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
4112                state.gate = outcomes.clone();
4113                check_landing_resources(state, "gate", &outcomes)?;
4114            }
4115            if outcomes.iter().all(|o| o.ok()) {
4116                break;
4117            }
4118            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
4119                crate::graph::GateFix::Retry => {
4120                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
4121                }
4122                crate::graph::GateFix::Stop => break,
4123                crate::graph::GateFix::Defer => {
4124                    // The repair checks e2e immediately, before the next gate.
4125                    // Preserve a cache wait here as well as below; otherwise
4126                    // the daemon charges an attempt for unstarted verification.
4127                    if let Some(e2e) = &state.gate_repair_e2e {
4128                        let outcomes = e2e.outcomes.clone();
4129                        check_landing_resources(state, "e2e", &outcomes)?;
4130                    }
4131                    bail!("landing gate repair deferred");
4132                }
4133            }
4134        }
4135        state.gate = outcomes;
4136        state.gate_ran = true;
4137        state.save()?;
4138    }
4139    let inherited = crate::repo_lock::WaitPolicy::current();
4140    let wait = crate::repo_lock::WaitPolicy::new(
4141        Duration::from_secs(state.config.graph.timeout_resource_wait),
4142        move || inherited.cancelled(),
4143    );
4144    let checked = state
4145        .gate_head
4146        .clone()
4147        .context("landing gate has no checked SHA")?;
4148    anyhow::ensure!(
4149        git::rev_parse(&winner.worktree, "HEAD").await? == checked
4150            && git::is_clean(&winner.worktree).await?,
4151        "landing tree changed after gate"
4152    );
4153    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
4154    if matches!(e2e, crate::graph::GateFix::Defer) {
4155        let outcomes = state
4156            .gate_repair_e2e
4157            .as_ref()
4158            .context("deferred landing e2e has no outcomes")?
4159            .outcomes
4160            .clone();
4161        check_landing_resources(state, "e2e", &outcomes)?;
4162    }
4163    anyhow::ensure!(
4164        matches!(e2e, crate::graph::GateFix::Retry),
4165        "post-repair e2e has not passed on the landing head; nothing published"
4166    );
4167    anyhow::ensure!(
4168        git::rev_parse(&winner.worktree, "HEAD").await? == checked
4169            && git::is_clean(&winner.worktree).await?,
4170        "landing tree changed during post-repair e2e"
4171    );
4172    anyhow::ensure!(
4173        crate::graph::verify_current_head(state, &winner, &wait).await?,
4174        "current head e2e has not passed; nothing published"
4175    );
4176    anyhow::ensure!(
4177        state.gate_allows_progress(),
4178        "landing gate failed; nothing published"
4179    );
4180    crate::pr_head::ensure_owner(state)?;
4181    if owner_requested_stop(state)? {
4182        bail!("owner requested stop before publication");
4183    }
4184    let current = forge.view(&state.repo, pr_url).await?;
4185    anyhow::ensure!(
4186        current.pr.state == PrLifecycle::Open,
4187        "PR closed or merged while gating; nothing published"
4188    );
4189    anyhow::ensure!(
4190        current.head == observed,
4191        "PR head changed while gating; nothing published"
4192    );
4193    anyhow::ensure!(
4194        crate::foreign_checkout::write_back(state, &checked).await?,
4195        "foreign checkout delivery is blocked; see the run events"
4196    );
4197    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
4198    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
4199    let refspec = format!("{checked}:refs/heads/{public}");
4200    let lock = repo_merge_lock(&state.repo);
4201    let _slot = lock.lock().await;
4202    let pushed = git::git_raw(
4203        &winner.worktree,
4204        &["push", &lease, &state.config.merge.remote, &refspec],
4205    )
4206    .await?;
4207    anyhow::ensure!(
4208        pushed.ok(),
4209        "publishing gated landing head failed: {}",
4210        pushed.stderr
4211    );
4212    state.pr_pushed_head = Some(checked.clone());
4213    state.land_sync_checkpoint = None;
4214    state.land_sync_pending = false;
4215    state.save()?;
4216    Ok(checked)
4217}
4218
4219/// A scratch rebase moves the winner ref before its index and files. Recover
4220/// only a tree proven unchanged since the saved start; never discard edits.
4221async fn restore_landing_worktree(
4222    state: &mut RunState,
4223    checkpoint: Option<crate::land_sync_recovery::Checkpoint>,
4224) -> Result<()> {
4225    let winner = state.winner().cloned().context("landing has no winner")?;
4226    let inherited = crate::repo_lock::WaitPolicy::current();
4227    let wait = crate::repo_lock::WaitPolicy::new(
4228        Duration::from_secs(state.config.graph.timeout_resource_wait),
4229        move || inherited.cancelled(),
4230    );
4231    let _coordination = crate::repo_lock::SeatLease::operation_with(
4232        &winner.worktree,
4233        state.config.coordination.as_ref(),
4234        &wait,
4235    )
4236    .await?;
4237    if !git::is_clean(&winner.worktree).await? {
4238        let from = state
4239            .land_rebase_from
4240            .as_deref()
4241            .context("landing worktree is dirty")?;
4242        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
4243        anyhow::ensure!(head != from, "landing worktree is dirty");
4244        for args in [
4245            vec!["diff", "--cached", "--quiet", from],
4246            vec!["diff", "--quiet"],
4247        ] {
4248            anyhow::ensure!(
4249                git::git_raw(&winner.worktree, &args).await?.ok(),
4250                "landing worktree has edits beyond the interrupted rebase"
4251            );
4252        }
4253        // Preserve build artifacts and local files, including ignored ones.
4254        // read-tree can overwrite ignored paths, so reject collisions with
4255        // the new tree (including file/directory conflicts) before updating.
4256        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
4257        let tracked = git::git(
4258            &winner.worktree,
4259            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
4260        )
4261        .await?;
4262        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
4263            anyhow::ensure!(
4264                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
4265                    path == local
4266                        || path
4267                            .strip_prefix(local)
4268                            .is_some_and(|rest| rest.starts_with('/'))
4269                        || local
4270                            .strip_prefix(path)
4271                            .is_some_and(|rest| rest.starts_with('/'))
4272                }),
4273                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
4274            );
4275        }
4276        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
4277    }
4278    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
4279        anyhow::ensure!(
4280            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
4281            "landing synchronization started outside the foreign checkout history"
4282        );
4283        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
4284            // The rebase's tree already includes the base and the fixer's
4285            // resolutions. Retain that exact tree, but join the pre-sync
4286            // history so delivery remains fast-forward. Keep the checkpoint
4287            // until this succeeds: a crash after rebase (or after this merge)
4288            // must recover through this same idempotent path before gating.
4289            git::git(
4290                &winner.worktree,
4291                &[
4292                    "-c",
4293                    "core.hooksPath=/dev/null",
4294                    "merge",
4295                    "--strategy=ours",
4296                    "--no-ff",
4297                    "--no-autostash",
4298                    "--no-edit",
4299                    "-m",
4300                    "Merge pre-sync history into the repaired landing tree",
4301                    from,
4302                ],
4303            )
4304            .await?;
4305        }
4306    }
4307    crate::worktree_setup::prepare_with(
4308        &state.config,
4309        &state.repo,
4310        &winner.worktree,
4311        crate::build_target::Coordination::Held(_coordination.as_ref()),
4312    )
4313    .await?;
4314    if let Some(checkpoint) = checkpoint {
4315        anyhow::ensure!(
4316            git::rev_parse(&winner.worktree, "HEAD").await? == checkpoint.head
4317                && git::is_clean(&winner.worktree).await?,
4318            "landing rebase result changed during restoration"
4319        );
4320        state.land_sync_checkpoint = Some(checkpoint);
4321    }
4322    state.land_rebase_from = None;
4323    state.save()?;
4324    Ok(())
4325}
4326
4327async fn rebase_landing_worktree(
4328    state: &mut RunState,
4329    onto: &str,
4330) -> Result<crate::rebase::Rebased> {
4331    restore_landing_worktree(state, None).await?;
4332    let winner = state.winner().cloned().context("landing has no winner")?;
4333    let scratch = state.dir().join("rebase");
4334    let target = match state.land_sync_target.clone() {
4335        Some(target) => {
4336            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4337            target
4338        }
4339        // Older records lack the target checkpoint, but Git retains the
4340        // exact target of an interrupted operation. It is a continuation too.
4341        None if crate::rebase::checked_progress(state, &scratch, "").await? => {
4342            crate::rebase::rebase_target(&scratch).await?
4343        }
4344        None => {
4345            if state.land_sync_attempts >= state.land_sync_budget() {
4346                let head = git::rev_parse(&winner.worktree, "HEAD")
4347                    .await
4348                    .unwrap_or_default();
4349                let tip = git::rev_parse(&state.repo, onto).await.unwrap_or_default();
4350                let pr_head = state.pr_pushed_head.clone().unwrap_or_else(|| head.clone());
4351                state.land_sync_pending = true;
4352                state.record_land_sync_exhausted_stop(&head, &pr_head, &tip);
4353                let _ = state.save();
4354                bail!("{}", crate::land_sync_recovery::EXHAUSTED_DETAIL);
4355            }
4356            let target = git::rev_parse(&state.repo, onto).await?;
4357            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4358            state.land_sync_attempts += 1;
4359            state.land_sync_target = Some(target.clone());
4360            target
4361        }
4362    };
4363    let from = git::rev_parse(&winner.worktree, "HEAD").await?;
4364    save_landing_rebase_start(state, &target, &from)?;
4365    let published = state.pr_pushed_head.clone().filter(|published| {
4366        published == &from
4367            || state.land_sync_checkpoint.as_ref().is_some_and(|c| {
4368                c.published == *published && c.head == from && c.attempt < state.land_sync_attempts
4369            })
4370    });
4371    // A continuation owns the attempt already charged above, including a
4372    // crash before the scratch rebase started. Finish its pinned base first;
4373    // a newer base must use another attempt on the next observation.
4374    // A previously running scratch sequencer has its own source identity.
4375    // Without a validated completion checkpoint, do not infer provenance from
4376    // the winner ref observed while resuming that sequencer.
4377    let fresh_scratch = !crate::rebase::checked_progress(state, &scratch, "").await?;
4378    let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4379    state.land_sync_target = None;
4380    if result == crate::rebase::Rebased::Applied {
4381        let checkpoint = if let Some(published) = published
4382            && state.foreign_checkout.is_none()
4383            && fresh_scratch
4384        {
4385            let previous = state.land_sync_checkpoint.take();
4386            Some(crate::land_sync_recovery::Checkpoint {
4387                previous: if published == from {
4388                    None
4389                } else {
4390                    previous.map(Box::new)
4391                },
4392                published,
4393                from,
4394                base: target,
4395                head: git::rev_parse(&winner.worktree, "HEAD").await?,
4396                attempt: state.land_sync_attempts,
4397                at: jiff::Timestamp::now(),
4398            })
4399        } else {
4400            state.land_sync_checkpoint = None;
4401            None
4402        };
4403        Box::pin(restore_landing_worktree(state, checkpoint)).await?;
4404    } else {
4405        state.save()?;
4406    }
4407    Ok(result)
4408}
4409
4410/// Reconcile a repair interrupted after publication but before saving the
4411/// successful push. The caller has already checked the clean, gated local head.
4412pub(crate) async fn repair_publication_observed(
4413    state: &RunState,
4414    publication: &crate::run::PrPublication,
4415) -> Result<bool> {
4416    if state.pr_publication.as_ref() != Some(publication) {
4417        return Ok(false);
4418    }
4419    let winner = state.winner().context("repair has no winner")?;
4420    let remote = git::remote_head(
4421        &winner.worktree,
4422        &state.config.merge.remote,
4423        &publication.branch,
4424    )
4425    .await?;
4426    Ok(remote.as_deref() == Some(publication.head.as_str()))
4427}
4428
4429/// Whether `observed` is the forge's stale view of this run's own completed
4430/// repair push. Proven only by the pre-push checkpoint: the observation is the
4431/// leased previous head, and the saved lease, retained HEAD and public ref all
4432/// name the checkpoint's commit. A third commit, a divergent or remote-only
4433/// update, or a missing checkpoint is not self-publication.
4434async fn lagging_self_publication(state: &RunState, observed: &str) -> Result<bool> {
4435    let Some(published) = &state.pr_publication else {
4436        return Ok(false);
4437    };
4438    let Some(winner) = state.winner() else {
4439        return Ok(false);
4440    };
4441    if !observed.eq_ignore_ascii_case(&published.previous)
4442        || observed.eq_ignore_ascii_case(&published.head)
4443        || state.pr_branch().unwrap_or(&winner.branch) != published.branch
4444        || !state
4445            .pr_pushed_head
4446            .as_deref()
4447            .is_some_and(|saved| saved.eq_ignore_ascii_case(&published.head))
4448        || state.gate_head.as_deref() != Some(published.head.as_str())
4449        || !state.gate_allows_progress()
4450    {
4451        return Ok(false);
4452    }
4453    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4454    if !local.eq_ignore_ascii_case(&published.head) || !git::is_clean(&winner.worktree).await? {
4455        return Ok(false);
4456    }
4457    let public =
4458        git::remote_head(&state.repo, &state.config.merge.remote, &published.branch).await?;
4459    Ok(public.is_some_and(|head| head.eq_ignore_ascii_case(&published.head)))
4460}
4461
4462// Keep the last completed result durable until the next rebase has completed.
4463// The attempt and source binding prevent that older result from authorizing
4464// recovery of a different retained head while this operation is pending.
4465fn save_landing_rebase_start(state: &mut RunState, target: &str, from: &str) -> Result<()> {
4466    state.land_sync_target = Some(target.to_owned());
4467    state.land_sync_pending = true;
4468    state.land_rebase_from = Some(from.to_owned());
4469    state.save()
4470}
4471
4472/// Reconcile a stopped landing before changing its branch. This also handles
4473/// old records whose graph status or merge detail no longer identifies land.
4474async fn resume_landing_head<F: Forge>(
4475    state: &mut RunState,
4476    observed: &str,
4477    pr_url: &str,
4478    forge: &F,
4479    reason: Option<Blocking>,
4480) -> Result<String> {
4481    crate::pr_head::ensure_owner(state)?;
4482    let winner = state.winner().cloned().context("landing has no winner")?;
4483    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4484    let expected = state
4485        .pr_pushed_head
4486        .as_deref()
4487        .or(state.gate_head.as_deref())
4488        .context("missing public head lease")?;
4489    anyhow::ensure!(
4490        observed == expected
4491            || (observed == local
4492                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4493                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4494        "public head moved outside this run; refusing to sync"
4495    );
4496    // An operator may have extended and published the winner while approval
4497    // was pending. Matching local/public history can be adopted as the lease,
4498    // but publish_landing_head must gate its new SHA before proceeding. A
4499    // remote-only or divergent update still cannot be overwritten.
4500    // Save reconciliation before rebasing again; a prior push may have reached
4501    // the remote immediately before the previous driver's last save.
4502    if state.pr_pushed_head.as_deref() != Some(observed) {
4503        state.land_sync_checkpoint = None;
4504    }
4505    state.pr_pushed_head = Some(observed.to_owned());
4506    state.save()?;
4507    restore_landing_worktree(state, None).await?;
4508    // Recover a rebase that finished before its completion checkpoint was
4509    // saved. Restoration above has already reconciled its files and ancestry.
4510    let scratch = state.dir().join("rebase");
4511    if let Some(target) = state.land_sync_target.clone()
4512        && !crate::rebase::checked_progress(state, &scratch, "").await?
4513        && git::ancestry(&winner.worktree, &target, &local).await?
4514    {
4515        state.land_sync_target = None;
4516        state.save()?;
4517    }
4518    let remote = state.config.merge.remote.clone();
4519    let base = state.base_branch.clone();
4520    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4521    anyhow::ensure!(
4522        fetched.ok(),
4523        "cannot fetch landing base: {}",
4524        fetched.stderr
4525    );
4526    anyhow::ensure!(
4527        !owner_requested_stop(state)?,
4528        "owner requested stop before base synchronization"
4529    );
4530    let onto = format!("{remote}/{base}");
4531    let tip = git::rev_parse(&state.repo, &onto).await?;
4532    if state.land_sync_unstarted_grant() {
4533        let auth = state
4534            .land_sync_recovery
4535            .authorizations
4536            .last()
4537            .context("missing recovery grant")?;
4538        anyhow::ensure!(
4539            auth.invalidated.is_none()
4540                && git::ancestry(&state.repo, &auth.scope.tip, &tip).await?
4541                && git::ancestry(&state.repo, &auth.stop.tip, &tip).await?,
4542            "fetched landing base is outside the authorized recovery lineage"
4543        );
4544    }
4545    let contains_base = git::ancestry(&state.repo, &tip, &local)
4546        .await
4547        .context("could not determine whether the landing head contains the fetched base")?;
4548    anyhow::ensure!(
4549        reason != Some(Blocking::Behind) || !contains_base,
4550        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4551    );
4552    if !contains_base || reason == Some(Blocking::Conflict) {
4553        match rebase_landing_worktree(state, &tip).await? {
4554            crate::rebase::Rebased::Applied => {}
4555            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4556        }
4557    }
4558    if reason == Some(Blocking::Behind) {
4559        anyhow::ensure!(
4560            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4561            "BEHIND synchronization left the head unchanged"
4562        );
4563    }
4564    publish_landing_head(state, observed, pr_url, forge).await
4565}
4566
4567/// Share the synchronization path with structured evidence retained after a refusal.
4568async fn synchronize_landing<F: Forge>(
4569    state: &mut RunState,
4570    pr: &mut PrState,
4571    observed: &str,
4572    pr_url: &str,
4573    forge: &F,
4574) -> Result<Option<String>> {
4575    if owner_stop(state, pr, forge).await? {
4576        return Ok(None);
4577    }
4578    state.event(
4579        "land",
4580        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4581    );
4582    state.save()?;
4583    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4584    if owner_stop(state, pr, forge).await? {
4585        return Ok(None);
4586    }
4587    match synced {
4588        Ok(head) => {
4589            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4590                crate::graph::refresh_reviewed_commits(state, &branch).await;
4591            }
4592            Ok(Some(head))
4593        }
4594        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4595        Err(e) => {
4596            let repo = state.repo.clone();
4597            stop(
4598                state,
4599                &repo,
4600                pr,
4601                &format!("could not synchronize landing base: {e:#}"),
4602            )
4603            .await?;
4604            Ok(None)
4605        }
4606    }
4607}
4608
4609enum LandSyncPrep {
4610    Continue(Option<Seen>),
4611    Stop(PrState),
4612}
4613
4614/// Revalidate and durably consume a pending landing base-sync recovery
4615/// authorization under the live execution lease before mutating landing status
4616/// or adopting any observed PR head.
4617async fn prepare_land_sync_recovery<F: Forge>(
4618    state: &mut RunState,
4619    pr_url: &str,
4620    forge: &F,
4621) -> Result<LandSyncPrep> {
4622    let has_unconsumed = state.has_unconsumed_land_sync_authorization();
4623    let unstarted = state.land_sync_unstarted_grant();
4624    let exhausted = state.land_sync_exhausted();
4625    if !has_unconsumed && !exhausted && !unstarted {
4626        return Ok(LandSyncPrep::Continue(None));
4627    }
4628    let repo = state.repo.clone();
4629    let seen = forge.view(&repo, pr_url).await?;
4630    if seen.pr.state != PrLifecycle::Open {
4631        anyhow::ensure!(
4632            state
4633                .pr
4634                .as_ref()
4635                .is_some_and(|pr| pr.url == seen.pr.url && pr.number == seen.pr.number),
4636            "terminal pull request does not match the retained run"
4637        );
4638        return Ok(LandSyncPrep::Continue(Some(seen)));
4639    }
4640    if !has_unconsumed && !unstarted {
4641        bail!(
4642            "{}; explicit recover-land-sync authorization required",
4643            crate::land_sync_recovery::EXHAUSTED_DETAIL
4644        );
4645    }
4646    let observed = crate::land_sync_recovery::ObservedPr {
4647        url: seen.pr.url.clone(),
4648        number: seen.pr.number,
4649        open: seen.pr.state == PrLifecycle::Open,
4650        head: seen.head.clone(),
4651        base_branch: (!seen.base.is_empty()).then(|| seen.base.clone()),
4652    };
4653    let home = crate::run::home();
4654    let validation = if owner_requested_stop(state)? {
4655        Err("owner requested stop before landing base-sync recovery".into())
4656    } else {
4657        crate::land_sync_recovery::validate_pending_authorization(
4658            &home,
4659            state,
4660            None,
4661            Some(&observed),
4662            &crate::land_sync_recovery::GhPrObserver,
4663        )
4664        .await
4665    };
4666    match validation {
4667        Ok((local_head, pr_head)) => {
4668            if unstarted {
4669                return Ok(LandSyncPrep::Continue(Some(seen)));
4670            }
4671            if let Err(reason) = state.consume_land_sync_recovery(&local_head, &pr_head) {
4672                state.status = RunStatus::Blocked;
4673                state.event("land-sync-recovery", format!("refused: {reason}"));
4674                state.save()?;
4675                return Ok(LandSyncPrep::Stop(seen.pr));
4676            }
4677            state.event(
4678                "land-sync-recovery",
4679                format!(
4680                    "consumed recovery grant {}/{}: authorized {} landing sync attempt ({}/{}); prior verification archived, fresh E2E and gate required",
4681                    state.land_sync_recovery.extra_attempts,
4682                    crate::land_sync_recovery::MAX_GRANTS,
4683                    crate::land_sync_recovery::GRANT_ATTEMPTS,
4684                    state.land_sync_attempts,
4685                    state.land_sync_budget()
4686                ),
4687            );
4688            state.save()?;
4689            Ok(LandSyncPrep::Continue(Some(seen)))
4690        }
4691        Err(failure) => {
4692            let reason = failure.reason;
4693            if !failure.observation_failed
4694                && let Some(auth) = state
4695                    .land_sync_recovery
4696                    .authorizations
4697                    .iter_mut()
4698                    .rev()
4699                    .find(|a| {
4700                        a.invalidated.is_none()
4701                            && (!a.consumed || unstarted && a.archived_verification.is_some())
4702                    })
4703            {
4704                auth.refuse(&reason);
4705            }
4706            state.status = RunStatus::Blocked;
4707            state.event("land-sync-recovery", format!("refused: {reason}"));
4708            state.save()?;
4709            Ok(LandSyncPrep::Stop(seen.pr))
4710        }
4711    }
4712}
4713
4714async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4715    crate::pr_head::ensure_owner(state)?;
4716    anyhow::ensure!(
4717        state.unfinished_instruction_revision().is_none(),
4718        "instruction revision repair did not complete; explicitly recover and review the revised instruction before landing"
4719    );
4720    let mut initial_seen = match prepare_land_sync_recovery(state, pr_url, forge).await? {
4721        LandSyncPrep::Continue(seen) => seen,
4722        LandSyncPrep::Stop(pr) => return Ok(pr),
4723    };
4724    state.land_unrelated = None;
4725    let reopening_hold = crate::merge_decision::resumable_hold(state);
4726    let repo = state.repo.clone();
4727    let budget = state.config.graph.land_rounds;
4728    let mut round = 0usize;
4729    let ci = state.config.merge.ci.expectation();
4730    if ci == CiExpectation::Absent {
4731        state.event(
4732            "land",
4733            "CI not expected ([merge] ci = \"none\"); check status ignored",
4734        );
4735    }
4736    let mut waited = Duration::ZERO;
4737    // Comment bodies the fixer has already been shown. A comment is
4738    // outstanding until it has been handed over once; after that it is a
4739    // recorded decision, not an open question, and re-feeding it would loop the
4740    // budget away on a comment the fixer already declined with an argument.
4741    let mut shown: BTreeSet<String> = BTreeSet::new();
4742    // Await the last successfully published head, including across resumes.
4743    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4744    // Whether a settled-checks refusal has already been given its one re-look.
4745    let mut rechecked = false;
4746
4747    // Marks the run resumable through exactly this function, not through a
4748    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4749    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4750    // status specifically to know a resumed run belongs back in `land`
4751    // rather than at a second `gh pr create`. Set on every entry - fresh or
4752    // resumed - because a resume that parked here again must keep reading
4753    // `Landing`, not whatever a first pass through `merge` left behind.
4754    state.status = RunStatus::Landing;
4755    state.event("land", format!("watching {pr_url}"));
4756    state.save()?;
4757
4758    // An armed merge recorded by an earlier pass may or may not have reached
4759    // the forge (the record is written before the call). It is taken back on
4760    // the first observation, where a pull request is known to stop with.
4761    let mut resumed_armed = state.land_armed_head.is_some();
4762
4763    'landing: loop {
4764        let seen = match initial_seen.take() {
4765            Some(seen) => seen,
4766            None => forge.view(&repo, pr_url).await?,
4767        };
4768        let mut pr = seen.pr.clone();
4769        pr.review_comments.retain(|c| !shown.contains(&c.body));
4770        state.pr = Some(crate::run::PrRecord {
4771            url: pr.url.clone(),
4772            number: pr.number,
4773            state: pr.state.as_str().to_owned(),
4774            checks: pr.checks.as_str().to_owned(),
4775            round,
4776            rounds: budget,
4777            red_at_merge: Vec::new(),
4778        });
4779        state.save()?;
4780
4781        if pr.state == PrLifecycle::Open {
4782            state.observe_branch_owner_holds(&seen.head).await;
4783            state.save()?;
4784        }
4785        crate::pr_head::ensure_owner(state)?;
4786        if reopening_hold {
4787            anyhow::ensure!(
4788                pr.state == PrLifecycle::Open,
4789                "held PR is no longer open; cannot request a fresh decision"
4790            );
4791            // An explicit resume authorizes a fresh question only. Preserve the
4792            // answered card, and never enter repair/rebase/merge on this pass.
4793            disarm(forge, state, &repo, pr.number)
4794                .await
4795                .map_err(anyhow::Error::msg)?;
4796            let previous = state.merge_decision.take();
4797            let binding = state.land_approval.take();
4798            state.config.graph.land_approval = true;
4799            let subject = merge_subject(
4800                crate::graph::landing_title(state, &seen.title),
4801                &crate::graph::landing_subject_source(state),
4802            );
4803            let contested = contested_to_ask(state);
4804            if let Err(error) =
4805                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4806            {
4807                state.merge_decision = previous;
4808                state.land_approval = binding;
4809                return Err(error);
4810            }
4811            state.end_pass_parked(crate::run::ParkCause::Question);
4812            state.parked = true;
4813            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()));
4814            state.save()?;
4815            return Ok(pr);
4816        }
4817        if owner_stop(state, &mut pr, forge).await? {
4818            return Ok(pr);
4819        }
4820
4821        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4822            // An approval already given for the same head is reused, so
4823            // nothing is asked twice. A failed disable
4824            // stops the run with the record kept: pushing on could change the
4825            // head under an arm that is still live.
4826            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4827                let why = format!(
4828                    "a previous pass may have armed auto-merge and it could not be disabled \
4829                     on resume: {e}"
4830                );
4831                stop(state, &repo, &pr, &why).await?;
4832                return Ok(pr);
4833            }
4834        }
4835
4836        // The head moved away from the one auto-merge was armed on, by
4837        // someone other than this loop. The arm is pinned and would refuse to
4838        // merge the new commit, but the approval was for the old one: take it
4839        // back and go through the normal path again.
4840        if pr.state == PrLifecycle::Open
4841            && !seen.head.is_empty()
4842            && state
4843                .land_armed_head
4844                .as_deref()
4845                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4846        {
4847            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4848                let why = format!(
4849                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4850                );
4851                stop(state, &repo, &pr, &why).await?;
4852                return Ok(pr);
4853            }
4854        }
4855
4856        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4857            // Disarming can outlive an owner answer. Consume it before our
4858            // own rebase invalidates the head shown on the decision card.
4859            if owner_stop(state, &mut pr, forge).await? {
4860                return Ok(pr);
4861            }
4862            if Box::pin(lagging_self_publication(state, &seen.head)).await? {
4863                if waited < WAIT_CEILING {
4864                    waited += POLL;
4865                    forge.poll().await;
4866                    continue;
4867                }
4868                let why = format!(
4869                    "forge did not observe the published repair head {} (still showing {})",
4870                    state.pr_pushed_head.as_deref().unwrap_or_default(),
4871                    seen.head
4872                );
4873                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4874                return Ok(pr);
4875            }
4876            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4877                binding.head.eq_ignore_ascii_case(&seen.head)
4878                    && ask::Questions::open()
4879                        .get_for_effects(&binding.question)
4880                        .is_ok_and(|q| {
4881                            q.run == state.id
4882                                && q.node == APPROVAL_NODE
4883                                && q.status == ask::QuestionStatus::Answered
4884                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4885                        })
4886            });
4887            if repair_answer {
4888                let subject = merge_subject(
4889                    crate::graph::landing_title(state, &seen.title),
4890                    &crate::graph::landing_subject_source(state),
4891                );
4892                let contested = contested_to_ask(state);
4893                if matches!(
4894                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4895                    ApprovalGate::Repair
4896                ) {
4897                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4898                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4899                        state.save()?;
4900                    }
4901                    return Ok(pr);
4902                }
4903            }
4904            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4905            // A stop detected before publication must apply its durable
4906            // decision, even when verification returned an error meanwhile.
4907            if owner_stop(state, &mut pr, forge).await? {
4908                return Ok(pr);
4909            }
4910            let head = synced?;
4911            awaiting_head = Some(head);
4912            waited = Duration::ZERO;
4913            rechecked = false;
4914            // Read CI and approvals afresh, never from the pre-push observation.
4915            continue;
4916        }
4917
4918        // A stale base is independent of the CI rollup. Keep the public-head
4919        // lease, but synchronize before waiting for checks on the old tree.
4920        if pr.state == PrLifecycle::Open
4921            && pr.blocking == Blocking::Behind
4922            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4923        {
4924            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4925            let Some(head) = synced else {
4926                return Ok(pr);
4927            };
4928            awaiting_head = Some(head);
4929            rechecked = false;
4930            waited = Duration::ZERO;
4931            continue;
4932        }
4933
4934        if pr.state == PrLifecycle::Open {
4935            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4936                if waited >= WAIT_CEILING {
4937                    let want = awaiting_head.as_deref().unwrap_or_default();
4938                    let why = format!(
4939                        "the pull request's checks were still not about one readable head after \
4940                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4941                         someone may have pushed over it",
4942                        WAIT_CEILING.as_secs() / 60,
4943                        if want.is_empty() { "any" } else { want },
4944                        if seen.head.is_empty() {
4945                            "nothing readable"
4946                        } else {
4947                            &seen.head
4948                        },
4949                        if seen.rollup_head.is_empty() {
4950                            "nothing readable"
4951                        } else {
4952                            &seen.rollup_head
4953                        },
4954                    );
4955                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4956                    return Ok(pr);
4957                }
4958                waited += POLL;
4959                forge.poll().await;
4960                continue;
4961            }
4962            // Reset once, when the awaited head first shows up; resetting on
4963            // every re-observation would let a standing refusal wait forever.
4964            if awaiting_head.take().is_some() {
4965                // The checks now being read belong to the new head; give them
4966                // the same grace a fresh pull request gets.
4967                waited = Duration::ZERO;
4968            }
4969        }
4970
4971        // The merge-state grace is head-bound and durable. Reruns reset the
4972        // checks clock, but must not extend this deadline across resumes.
4973        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4974            let first = state
4975                .land_unsaid
4976                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4977            if !first.0.eq_ignore_ascii_case(&seen.head) {
4978                *first = (seen.head.clone(), forge.now());
4979            }
4980            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4981            state.save()?;
4982            elapsed
4983        } else {
4984            waited
4985        };
4986        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4987        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4988            if waited >= WAIT_CEILING {
4989                stop_disarmed(
4990                    forge,
4991                    state,
4992                    &repo,
4993                    &pr,
4994                    "merge state remained unreadable; refusing to merge on a guess",
4995                )
4996                .await?;
4997                return Ok(pr);
4998            }
4999            waited += POLL;
5000            forge.poll().await;
5001            continue;
5002        }
5003
5004        // A failed workflow run is rerun once, judged by its own run rather
5005        // than by the rollup's aggregate: another run still pending, or a fix
5006        // budget already spent, must not keep a flaky failure from its one
5007        // rerun. It spends no round and no attempt.
5008        if ci == CiExpectation::Expected
5009            && pr.state == PrLifecycle::Open
5010            && state.config.graph.rerun_flaky_checks
5011        {
5012            let include_optional = pr.checks == Checks::Red
5013                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
5014            let failing = rerunnable_with(&seen.contexts, include_optional);
5015            let now = forge.now();
5016            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
5017                RerunStep::Rerun(runs) => {
5018                    let rec = state.land_reruns.get_or_insert_with(Default::default);
5019                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
5020                        *rec = LandReruns {
5021                            head: seen.head.clone(),
5022                            runs: BTreeMap::new(),
5023                        };
5024                    }
5025                    for run in &runs {
5026                        rec.runs.insert(run.clone(), now);
5027                    }
5028                    // Durable before the call: a restart must not
5029                    // rerun the same run twice. A save that fails
5030                    // means no rerun.
5031                    state.save()?;
5032                    let mut any = false;
5033                    for run in &runs {
5034                        let names = failing
5035                            .iter()
5036                            .filter(|(_, r)| r.as_deref() == Some(run))
5037                            .map(|(l, _)| l.as_str())
5038                            .collect::<Vec<_>>()
5039                            .join(", ");
5040                        match forge.rerun(&repo, run).await {
5041                            Ok(()) => {
5042                                any = true;
5043                                state.event(
5044                                    "land",
5045                                    format!("reran failed check(s) {names} (run {run})"),
5046                                );
5047                            }
5048                            // Stays recorded: never a retry loop.
5049                            Err(e) => state.event(
5050                                "land",
5051                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
5052                            ),
5053                        }
5054                    }
5055                    state.save()?;
5056                    if any {
5057                        waited = Duration::ZERO;
5058                        forge.poll().await;
5059                        continue;
5060                    }
5061                }
5062                RerunStep::Grace => {
5063                    if waited >= WAIT_CEILING {
5064                        let why = format!(
5065                            "checks were still failing after a rerun and {} minutes",
5066                            WAIT_CEILING.as_secs() / 60
5067                        );
5068                        stop(state, &repo, &pr, &why).await?;
5069                        return Ok(pr);
5070                    }
5071                    waited += POLL;
5072                    forge.poll().await;
5073                    continue;
5074                }
5075                RerunStep::Fix => {}
5076            }
5077        }
5078
5079        let step = proposed;
5080        // Armed on exactly this head: the forge is doing the waiting. A
5081        // decision to merge (or keep waiting) is only watched, never re-armed
5082        // and never re-approved; anything else - a red check, a comment, a
5083        // conflict - falls through to its own arm, which disarms first.
5084        let armed_here = state
5085            .land_armed_head
5086            .as_deref()
5087            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
5088        if armed_here && matches!(step, Step::Merge | Step::Wait) {
5089            if waited >= WAIT_CEILING {
5090                let required = if seen.base.is_empty() {
5091                    None
5092                } else {
5093                    forge.required_contexts(&repo, &seen.base).await
5094                };
5095                let why = format!(
5096                    "auto-merge was armed on {} but the pull request did not merge within {} \
5097                     minutes ({})",
5098                    seen.head,
5099                    WAIT_CEILING.as_secs() / 60,
5100                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
5101                );
5102                stop_disarmed(forge, state, &repo, &pr, &why).await?;
5103                return Ok(pr);
5104            }
5105            waited += POLL;
5106            forge.poll().await;
5107            continue;
5108        }
5109        if armed_here && !matches!(step, Step::Done { .. }) {
5110            // Not merging or waiting any more: whatever is next may change the
5111            // head or give up, and neither may leave the arm standing.
5112            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
5113                let why = format!("auto-merge could not be disabled: {e}");
5114                stop(state, &repo, &pr, &why).await?;
5115                return Ok(pr);
5116            }
5117        }
5118        if pr.checks == Checks::Red
5119            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
5120            && pr.review_comments.is_empty()
5121            && let Some(evidence) = forge.attribution(state, &seen).await
5122            && evidence.unrelated(&seen.head, &pr.failing)
5123        {
5124            if owner_stop(state, &mut pr, forge).await? {
5125                return Ok(pr);
5126            }
5127            // Attribution does not authorize action against an unseen push.
5128            let fresh = forge.view(&repo, pr_url).await?;
5129            if fresh.head != seen.head
5130                || fresh.rollup_head != seen.rollup_head
5131                || fresh.pr.state != PrLifecycle::Open
5132                || fresh.pr.checks != Checks::Red
5133                || fresh.pr.failing != pr.failing
5134                || fresh
5135                    .pr
5136                    .review_comments
5137                    .iter()
5138                    .any(|c| !shown.contains(&c.body))
5139            {
5140                continue;
5141            }
5142            hold_unrelated(state, &pr, evidence).await?;
5143            return Ok(pr);
5144        }
5145        match step {
5146            Step::Wait => {
5147                if waited >= WAIT_CEILING {
5148                    let why = format!(
5149                        "checks were still running after {} minutes",
5150                        WAIT_CEILING.as_secs() / 60
5151                    );
5152                    stop(state, &repo, &pr, &why).await?;
5153                    return Ok(pr);
5154                }
5155                waited += POLL;
5156                forge.poll().await;
5157            }
5158            Step::Done { merged } => {
5159                if merged {
5160                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
5161                }
5162                // Auto-merge is pinned to the approved head, but the forge's
5163                // own handling of a later push is not something magi can
5164                // see: if the pull request merged on another commit, say so
5165                // loudly rather than record a clean landing.
5166                if let Some(armed) = state.land_armed_head.take() {
5167                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
5168                        let msg = format!(
5169                            "{} merged on {} but the owner approved {armed}; review what landed",
5170                            pr.url, seen.head
5171                        );
5172                        tracing::warn!("{msg}");
5173                        state.event("land", msg);
5174                        // Only an arm left by an older build can get here.
5175                        // The wording is fixed so a repeat does not relight
5176                        // the notice.
5177                        crate::notices::raise_with(
5178                            crate::notices::Notice::warn(
5179                                &format!("merged-unapproved-head:{}", state.id),
5180                                "A pull request merged on a commit the owner did not approve; \
5181                                 review what landed",
5182                            )
5183                            .link(crate::notices::Link::Run {
5184                                id: state.id.clone(),
5185                            }),
5186                            &state.config.notify,
5187                        );
5188                    }
5189                }
5190                state.status = if merged {
5191                    RunStatus::Merged
5192                } else {
5193                    RunStatus::Ready
5194                };
5195                let detail = if merged {
5196                    format!("{} was merged", pr.url)
5197                } else {
5198                    format!("{} was closed without merging", pr.url)
5199                };
5200                state.merge = Some(MergeOutcome {
5201                    mode: MergeMode::Pr,
5202                    ok: merged,
5203                    detail: detail.clone(),
5204                    empty: false,
5205                });
5206                state.event("land", detail);
5207                state.save()?;
5208                write_pr_state_through(state, pr.state);
5209                return Ok(pr);
5210            }
5211            Step::Merge => {
5212                state.check_delivery_evidence(&seen.head)?;
5213                let subject = merge_subject(
5214                    crate::graph::landing_title(state, &seen.title),
5215                    &crate::graph::landing_subject_source(state),
5216                );
5217                // The owner sees the panel before the one irreversible step,
5218                // and an unanswered question is a hold: silence never merges.
5219                //
5220                // The dedicated policy includes existing consent and post-repair
5221                // decisions; repair choice availability never grants merge authority.
5222                let contested = contested_to_ask(state);
5223                if !approval_reasons(state).is_empty() {
5224                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
5225                        .await?
5226                    {
5227                        ApprovalGate::Approved => {}
5228                        ApprovalGate::Repair => {
5229                            // The driver consumes the saved request under the existing
5230                            // run/task claim. No merge, no second run or task.
5231                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
5232                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
5233                                state.save()?;
5234                            }
5235                            return Ok(pr);
5236                        }
5237                        ApprovalGate::Held => {
5238                            // Another entry point may have saved a stop after
5239                            // the first read above. Apply its durable action.
5240                            if owner_stop(state, &mut pr, forge).await? {
5241                                return Ok(pr);
5242                            }
5243                            stop(
5244                                state,
5245                                &repo,
5246                                &pr,
5247                                "the owner did not approve the merge (held or unanswered)",
5248                            )
5249                            .await?;
5250                            return Ok(pr);
5251                        }
5252                        // Filed (or still standing from an earlier visit) and
5253                        // not yet answered. Park here rather than wait: the
5254                        // question survives on disk, the daemon hands this
5255                        // run's slot to something else, and a later resume
5256                        // re-enters `land`, finds the same question, and
5257                        // either merges or stops depending on what it says
5258                        // by then.
5259                        ApprovalGate::Pending => {
5260                            state.end_pass_parked(crate::run::ParkCause::Question);
5261                            state.parked = true;
5262                            state.event(
5263                                "land",
5264                                "parked awaiting merge approval - resumes once answered",
5265                            );
5266                            state.save()?;
5267                            return Ok(pr);
5268                        }
5269                    }
5270                }
5271                // Open and past the gate above, so `seen.head` is the commit
5272                // the checks were bound to and the owner approved.
5273                //
5274                // Merge directly, bound to that commit. Auto-merge is not
5275                // armed any more: the forge checks `--match-head-commit` only
5276                // when the request is made, so an arm outlives the head it
5277                // was made for, and a push of another commit whose
5278                // requirements are met first would merge without approval.
5279                // A direct merge is checked by the forge at the moment it
5280                // happens, so only the approved head can land.
5281                let observed_head = seen.head.clone();
5282                // Read the pull request again just before: the state seen
5283                // above can be a moment old.
5284                {
5285                    let fresh = forge.view(&repo, pr_url).await.ok();
5286                    if fresh.as_ref().is_some_and(|current| {
5287                        current.pr.state == PrLifecycle::Open
5288                            && current.head.eq_ignore_ascii_case(&observed_head)
5289                            && Blocking::of(&current.merge_state) == Blocking::Behind
5290                    }) {
5291                        pr.blocking = Blocking::Behind;
5292                        let synced =
5293                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5294                                .await?;
5295                        let Some(head) = synced else {
5296                            return Ok(pr);
5297                        };
5298                        awaiting_head = Some(head);
5299                        rechecked = false;
5300                        waited = Duration::ZERO;
5301                        continue 'landing;
5302                    }
5303                    if !direct_merge_is_safe(
5304                        fresh.as_ref(),
5305                        &observed_head,
5306                        &shown,
5307                        round,
5308                        budget,
5309                        waited,
5310                        ci,
5311                    ) {
5312                        if waited >= WAIT_CEILING {
5313                            let why = "the pull request did not settle on the approved head \
5314                                       before it could be merged";
5315                            stop(state, &repo, &pr, why).await?;
5316                            return Ok(pr);
5317                        }
5318                        state.event(
5319                            "land",
5320                            "the pull request changed before merging; looking again",
5321                        );
5322                        waited += POLL;
5323                        forge.poll().await;
5324                        continue;
5325                    }
5326                }
5327                let argv = merge_argv_at(pr.number, &subject, &observed_head);
5328                let out = {
5329                    let merge_lock = repo_merge_lock(&repo);
5330                    let _merge_slot = merge_lock.lock().await;
5331                    crate::pr_head::ensure_owner(state)?;
5332                    if let Some(task_id) = state
5333                        .origin
5334                        .as_ref()
5335                        .and_then(|origin| origin.task.as_ref())
5336                    {
5337                        let task = crate::queue::Queue::open()
5338                            .get(task_id)
5339                            .context("cannot verify the task owner immediately before merge")?;
5340                        if task.execution_runs().last() != Some(&state.id)
5341                            || task.operator_held()
5342                            || task.status == crate::queue::TaskStatus::Done
5343                        {
5344                            bail!(
5345                                "task ownership or an operator hold superseded this merge approval"
5346                            );
5347                        }
5348                    }
5349                    if let Some(binding) = &state.land_approval {
5350                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
5351                        if merge_consent_superseded(state, &current)?
5352                            || current.run != state.id
5353                            || !binding.head.eq_ignore_ascii_case(&observed_head)
5354                            || approval(current.resolution().as_deref()) != Approval::Merge
5355                            || current.merge_target.as_ref().is_some_and(|t| {
5356                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
5357                            })
5358                        {
5359                            bail!(
5360                                "merge decision is stale or no longer authorizes the reviewed head"
5361                            );
5362                        }
5363                    }
5364                    forge.merge(&repo, &argv).await?
5365                };
5366                if out.0 {
5367                    // Exit 0 is not proof of a merge: with a merge queue `gh`
5368                    // enqueues (or reports the pull request already queued)
5369                    // and succeeds while it is still open. Ask the forge; an
5370                    // unreadable answer is not a confirmation either, so it
5371                    // is looked at again rather than recorded as merged.
5372                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
5373                        if c.pr.state == PrLifecycle::Merged {
5374                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
5375                            true
5376                        } else {
5377                            false
5378                        }
5379                    });
5380                    if !confirmed {
5381                        if waited >= WAIT_CEILING {
5382                            let why = "the merge request succeeded but the pull request \
5383                                       could not be confirmed merged after waiting";
5384                            stop(state, &repo, &pr, why).await?;
5385                            return Ok(pr);
5386                        }
5387                        state.event(
5388                            "land",
5389                            "merge accepted but the pull request is not confirmed merged yet; waiting",
5390                        );
5391                        state.save()?;
5392                        waited += POLL;
5393                        forge.poll().await;
5394                        continue;
5395                    }
5396                    pr.state = PrLifecycle::Merged;
5397                    state.status = RunStatus::Merged;
5398                    state.merge = Some(MergeOutcome {
5399                        mode: MergeMode::Pr,
5400                        ok: true,
5401                        detail: format!("gh {}", argv.join(" ")),
5402                        empty: false,
5403                    });
5404                    // The last `state.pr` snapshot is whatever the poll before
5405                    // this merge observed - still `open` - and nothing below
5406                    // refreshes it from GitHub again, so the UI's round rail
5407                    // would otherwise keep animating a merged run forever.
5408                    if let Some(pr_record) = state.pr.as_mut() {
5409                        pr_record.state = pr.state.as_str().to_owned();
5410                    }
5411                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5412                    announce_red_merge(state, &pr).await;
5413                    state.save()?;
5414                    write_pr_state_through(state, pr.state);
5415                    return Ok(pr);
5416                }
5417                let after_seen = forge.view(&repo, pr_url).await.ok();
5418                let after = after_seen.as_ref().map(|s| s.pr.state);
5419                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
5420                    state.pr_merged_head = after_seen
5421                        .as_ref()
5422                        .map(|s| s.head.clone())
5423                        .filter(|h| !h.is_empty());
5424                    pr.state = PrLifecycle::Merged;
5425                    state.status = RunStatus::Merged;
5426                    state.merge = Some(outcome);
5427                    if let Some(pr_record) = state.pr.as_mut() {
5428                        pr_record.state = pr.state.as_str().to_owned();
5429                    }
5430                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5431                    announce_red_merge(state, &pr).await;
5432                    state.save()?;
5433                    write_pr_state_through(state, pr.state);
5434                    return Ok(pr);
5435                }
5436                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
5437                match verdict {
5438                    Refused::Behind => {
5439                        pr.blocking = Blocking::Behind;
5440                        let synced =
5441                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5442                                .await?;
5443                        let Some(head) = synced else {
5444                            return Ok(pr);
5445                        };
5446                        awaiting_head = Some(head);
5447                        rechecked = false;
5448                        waited = Duration::ZERO;
5449                        continue 'landing;
5450                    }
5451                    Refused::Final => {
5452                        let merge_state = after_seen
5453                            .as_ref()
5454                            .map(|s| s.merge_state.as_str())
5455                            .filter(|m| !m.is_empty())
5456                            .unwrap_or("unknown");
5457                        // Which refusal this was decides what a person has to
5458                        // do about it, so the two are worded apart; both carry
5459                        // the forge's own message.
5460                        let why = format!(
5461                            "the merge was refused: {} (merge state: {merge_state})",
5462                            out.1
5463                        );
5464                        stop(state, &repo, &pr, &why).await?;
5465                        return Ok(pr);
5466                    }
5467                    verdict => {
5468                        // Back to the top, which re-decides and passes the
5469                        // approval gate again, a poll later. `waited` is not
5470                        // reset here: only a pushed fix restarts it, or a
5471                        // standing refusal would wait forever.
5472                        if waited >= WAIT_CEILING {
5473                            let why = format!(
5474                                "the merge was still refused after {} minutes: {}",
5475                                WAIT_CEILING.as_secs() / 60,
5476                                out.1
5477                            );
5478                            stop(state, &repo, &pr, &why).await?;
5479                            return Ok(pr);
5480                        }
5481                        if verdict == Refused::Recheck {
5482                            rechecked = true;
5483                        }
5484                        state.event(
5485                            "land",
5486                            "merge refused while the branch policy is not satisfied yet; waiting",
5487                        );
5488                        state.save()?;
5489                        waited += POLL;
5490                        forge.poll().await;
5491                    }
5492                }
5493            }
5494            Step::Rebase => {
5495                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
5496                let Some(head) = synced else {
5497                    return Ok(pr);
5498                };
5499                awaiting_head = Some(head);
5500                rechecked = false;
5501                waited = Duration::ZERO;
5502                continue 'landing;
5503            }
5504            Step::GiveUp { reason } => {
5505                stop(state, &repo, &pr, &reason).await?;
5506                return Ok(pr);
5507            }
5508            Step::Fix { reason } => {
5509                round += 1;
5510                waited = Duration::ZERO;
5511                for c in &pr.review_comments {
5512                    shown.insert(c.body.clone());
5513                }
5514                state.event("land", format!("round {round}: {reason}"));
5515                state.save()?;
5516
5517                let logs = failing_logs(&repo, &seen.failing_urls).await;
5518                let was_red = pr.checks == Checks::Red;
5519                if owner_stop(state, &mut pr, forge).await? {
5520                    return Ok(pr);
5521                }
5522                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
5523                if owner_stop(state, &mut pr, forge).await? {
5524                    return Ok(pr);
5525                }
5526                match fixed {
5527                    Fixed::Committed { head } => {
5528                        // Whatever the next look shows may still be the
5529                        // previous head; see `awaiting_new_head`.
5530                        state.pr_pushed_head = Some(head.clone());
5531                        state.land_sync_checkpoint = None;
5532                        awaiting_head = Some(head);
5533                        rechecked = false;
5534                        waited = Duration::ZERO;
5535                        forge.poll().await;
5536                    }
5537                    Fixed::Declined if was_red => {
5538                        // Review comments may have required this round even
5539                        // when CI was unrelated. Once the fixer has read them,
5540                        // use the same structural attribution before charging
5541                        // a no-commit stop to the task.
5542                        if let Some(evidence) = forge.attribution(state, &seen).await
5543                            && evidence.unrelated(&seen.head, &pr.failing)
5544                        {
5545                            let fresh = forge.view(&repo, pr_url).await?;
5546                            if fresh.head != seen.head
5547                                || fresh.rollup_head != seen.rollup_head
5548                                || fresh.pr.state != PrLifecycle::Open
5549                                || fresh.pr.checks != Checks::Red
5550                                || fresh.pr.failing != pr.failing
5551                                || fresh
5552                                    .pr
5553                                    .review_comments
5554                                    .iter()
5555                                    .any(|c| !shown.contains(&c.body))
5556                            {
5557                                continue;
5558                            }
5559                            if owner_stop(state, &mut pr, forge).await? {
5560                                return Ok(pr);
5561                            }
5562                            hold_unrelated(state, &pr, evidence).await?;
5563                            return Ok(pr);
5564                        }
5565                        let why = format!(
5566                            "the fixer produced no commit while {} check(s) were failing \
5567                             ({}); stopping instead of looping on an unchanged tree",
5568                            pr.failing.len(),
5569                            pr.failing.join(", ")
5570                        );
5571                        stop(state, &repo, &pr, &why).await?;
5572                        return Ok(pr);
5573                    }
5574                    // Comment-driven round with no commit: the fixer read the
5575                    // comments and changed nothing, which is a decision it is
5576                    // allowed to make. The comments are recorded as shown, so
5577                    // the next observation sees a clean pull request.
5578                    Fixed::Declined => state.event(
5579                        "land",
5580                        format!("round {round}: fixer declined the comments, nothing committed"),
5581                    ),
5582                    Fixed::Deferred => {
5583                        // No fixer was available to judge these comments or
5584                        // checks. Keep the previous completed-round count and
5585                        // return without handing the PR off as a task failure.
5586                        state.status = RunStatus::Blocked;
5587                        state.save()?;
5588                        return Ok(pr);
5589                    }
5590                    Fixed::Failed(why) => {
5591                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5592                        return Ok(pr);
5593                    }
5594                }
5595                state.save()?;
5596            }
5597        }
5598    }
5599}
5600
5601/// Owner decision for a CI failure independently reproduced on the base.
5602pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5603
5604/// Durable machine-hold evidence, bound to one observed PR head.
5605#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5606pub struct CiHold {
5607    /// Head that exhibited the independently reproduced failures.
5608    pub head: String,
5609    /// Typed owner question controlling resumption.
5610    pub question: String,
5611    /// Complete structured facts used to attribute the failures.
5612    pub evidence: CiEvidence,
5613}
5614
5615/// Only structured forge annotations are compared, never log prose.
5616#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5617struct CiFailure {
5618    path: String,
5619    start_line: u64,
5620    end_line: u64,
5621    title: String,
5622    message: String,
5623}
5624
5625#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5626struct CiCheckEvidence {
5627    label: String,
5628    head_check: u64,
5629    base_check: u64,
5630    app: u64,
5631    run: String,
5632    base_run: String,
5633    head_failures: Vec<CiFailure>,
5634    base_failures: Vec<CiFailure>,
5635    rerun_exhausted: bool,
5636}
5637
5638/// Pinned Git diff and forge failure annotations used for CI attribution.
5639#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5640pub struct CiEvidence {
5641    head: String,
5642    base: String,
5643    changed: Vec<String>,
5644    checks: Vec<CiCheckEvidence>,
5645}
5646
5647impl CiEvidence {
5648    /// Every red check must have the same located failure on the base, outside
5649    /// the diff. Changes to CI/build configuration invalidate this inference.
5650    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5651        if self.head != head
5652            || self.base.is_empty()
5653            || failing.is_empty()
5654            || self.changed.iter().any(|p| {
5655                p.starts_with(".github/")
5656                    || p.starts_with(".config/")
5657                    || p.starts_with(".cargo/")
5658                    || matches!(
5659                        p.rsplit('/').next().unwrap_or(p),
5660                        "Cargo.toml"
5661                            | "Cargo.lock"
5662                            | "Makefile.toml"
5663                            | "build.rs"
5664                            | "rust-toolchain.toml"
5665                    )
5666            })
5667        {
5668            return false;
5669        }
5670        failing.iter().all(|label| {
5671            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5672            matches.len() == 1
5673                && matches[0].rerun_exhausted
5674                && !matches[0].head_failures.is_empty()
5675                && matches[0].head_failures.iter().all(|f| {
5676                    // Workflow-level exit-code annotations do not identify a
5677                    // failing test or source file, and prove nothing here.
5678                    !f.path.is_empty()
5679                        && !f.path.starts_with('.')
5680                        && !f.path.contains("..")
5681                        && !f.path.starts_with('/')
5682                        && !self.changed.contains(&f.path)
5683                        && matches[0].base_failures.contains(f)
5684                })
5685        })
5686    }
5687}
5688
5689async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5690    let out = gh(repo, &["api".into(), endpoint]).await.ok()?;
5691    if !out.ok {
5692        return None;
5693    }
5694    serde_json::from_str(&out.stdout).ok()
5695}
5696
5697async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5698    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5699    if count == 0 || count >= 100 {
5700        return None;
5701    }
5702    let id = check.get("id")?.as_u64()?;
5703    let value = ci_json(
5704        repo,
5705        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5706    )
5707    .await?;
5708    let annotations = value.as_array()?;
5709    if annotations.len() != count as usize {
5710        return None;
5711    }
5712    annotations
5713        .iter()
5714        .filter(|a| a["annotation_level"] == "failure")
5715        .map(|a| {
5716            Some(CiFailure {
5717                path: a["path"].as_str()?.into(),
5718                start_line: a["start_line"].as_u64()?,
5719                end_line: a["end_line"].as_u64()?,
5720                title: a["title"].as_str()?.into(),
5721                message: a["message"].as_str()?.into(),
5722            })
5723        })
5724        .collect()
5725}
5726
5727async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5728    let value = ci_json(
5729        repo,
5730        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5731    )
5732    .await?;
5733    let runs = value["check_runs"].as_array()?;
5734    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5735        return None;
5736    }
5737    Some(runs.clone())
5738}
5739
5740async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5741    let repo = &state.repo;
5742    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5743    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5744        .await
5745        .ok()?;
5746    if !base.ok() {
5747        return None;
5748    }
5749    let range = format!("{}...{}", base.stdout, seen.head);
5750    // No rename detection: both old and new paths must count as changed.
5751    let diff = git::git_raw(
5752        repo,
5753        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5754    )
5755    .await
5756    .ok()?;
5757    if !diff.ok() {
5758        return None;
5759    }
5760    let head_runs = ci_runs(repo, &seen.head).await?;
5761    let base_runs = ci_runs(repo, &base.stdout).await?;
5762    let mut checks = Vec::new();
5763    for label in &seen.pr.failing {
5764        let matching = |runs: &[serde_json::Value]| {
5765            runs.iter()
5766                .filter(|r| r["name"].as_str() == Some(label))
5767                .cloned()
5768                .collect::<Vec<_>>()
5769        };
5770        let heads = matching(&head_runs);
5771        let bases = matching(&base_runs);
5772        if heads.len() != 1 || bases.len() != 1 {
5773            return None;
5774        }
5775        let h = &heads[0];
5776        let b = &bases[0];
5777        if h["conclusion"] != "failure"
5778            || b["conclusion"] != "failure"
5779            || h["status"] != "completed"
5780            || b["status"] != "completed"
5781            || h["head_sha"].as_str()? != seen.head
5782            || b["head_sha"].as_str()? != base.stdout
5783            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5784        {
5785            return None;
5786        }
5787        let run = run_of(h["details_url"].as_str()?)?;
5788        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5789        if contexts.len() != 1
5790            || contexts[0].run.as_ref() != Some(&run)
5791            || contexts[0].verdict != Verdict::Fail
5792        {
5793            return None;
5794        }
5795        // A persisted request alone is not a completed rerun: require the
5796        // workflow's structured attempt number as well.
5797        let workflow =
5798            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5799        let base_run = run_of(b["details_url"].as_str()?)?;
5800        let base_workflow = ci_json(
5801            repo,
5802            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5803        )
5804        .await?;
5805        if base_workflow["head_sha"].as_str()? != base.stdout
5806            || base_workflow["head_branch"].as_str()? != seen.base
5807            || base_workflow["status"] != "completed"
5808            || base_workflow["conclusion"] != "failure"
5809            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5810        {
5811            return None;
5812        }
5813        let exhausted = state
5814            .land_reruns
5815            .as_ref()
5816            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5817            && workflow["head_sha"].as_str()? == seen.head
5818            && workflow["run_attempt"].as_u64()? > 1
5819            && workflow["status"] == "completed";
5820        checks.push(CiCheckEvidence {
5821            label: label.clone(),
5822            head_check: h["id"].as_u64()?,
5823            base_check: b["id"].as_u64()?,
5824            app: h.pointer("/app/id")?.as_u64()?,
5825            run,
5826            base_run,
5827            head_failures: ci_annotations(repo, h).await?,
5828            base_failures: ci_annotations(repo, b).await?,
5829            rerun_exhausted: exhausted,
5830        });
5831    }
5832    Some(CiEvidence {
5833        head: seen.head.clone(),
5834        base: base.stdout,
5835        changed: diff
5836            .stdout
5837            .split('\0')
5838            .filter(|p| !p.is_empty())
5839            .map(str::to_owned)
5840            .collect(),
5841        checks,
5842    })
5843}
5844
5845async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5846    let detail = serde_json::to_string(&evidence)?;
5847    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5848    let hold = "operator: 保留して後で判断する".to_owned();
5849    let mut q = ask::Question::new(
5850        state.id.clone(),
5851        CI_HOLD_NODE.into(),
5852        "land".into(),
5853        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5854        format!(
5855            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5856        ),
5857        vec![resume.clone(), hold.clone()],
5858    );
5859    q.actions.insert(
5860        resume,
5861        ask::ChoiceAction::Resume {
5862            run: state.id.clone(),
5863        },
5864    );
5865    q.actions.insert(hold, ask::ChoiceAction::Hold);
5866    ask::Questions::open().put_executable(&mut q)?;
5867    state.land_unrelated = Some(CiHold {
5868        head: evidence.head.clone(),
5869        question: q.id.clone(),
5870        evidence,
5871    });
5872    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5873    state.end_pass_parked(crate::run::ParkCause::Question);
5874    state.parked = true;
5875    state.save()?;
5876    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5877        tracing::warn!("could not notify about CI hold: {e:#}");
5878    }
5879    // A durable question and evidence are sufficient even if commenting fails.
5880    let body = stop_comment(
5881        &state.id,
5882        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5883    );
5884    let (_, body) = crate::github_text::prepare(state, "", &body);
5885    gh(
5886        &state.repo,
5887        &[
5888            "pr".into(),
5889            "comment".into(),
5890            pr.number.to_string(),
5891            "--body".into(),
5892            body,
5893        ],
5894    )
5895    .await
5896    .ok();
5897    Ok(())
5898}
5899
5900/// One observation, plus the two things [`PrState`] deliberately does not carry:
5901/// the title (needed for the squash subject) and where the failing checks'
5902/// logs live.
5903#[derive(Clone)]
5904struct Seen {
5905    pr: PrState,
5906    title: String,
5907    failing_urls: Vec<(String, String)>,
5908    /// `headRefOid`: the commit this observation, checks included, is about.
5909    head: String,
5910    /// The commit the checks belong to, read from the same GraphQL node as
5911    /// the checks themselves. Empty when unreadable.
5912    rollup_head: String,
5913    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5914    /// and DRAFT together, and a stop reason has to say which.
5915    merge_state: String,
5916    /// Every check of the rollup, for naming what an armed merge waits on.
5917    contexts: Vec<CheckInfo>,
5918    /// `baseRefName`, to look up which contexts the base requires.
5919    base: String,
5920}
5921
5922/// One check of the rollup as far as a stop reason needs it.
5923#[derive(Clone)]
5924struct CheckInfo {
5925    label: String,
5926    verdict: Verdict,
5927    required: Option<bool>,
5928    /// The workflow run the check belongs to; `None` for an external status.
5929    run: Option<String>,
5930}
5931
5932/// What to do with a red head before a fix round is spent on it.
5933#[derive(Debug, Clone, PartialEq, Eq)]
5934enum RerunStep {
5935    /// Rerun these workflow runs (each not yet rerun for this head).
5936    Rerun(Vec<String>),
5937    /// Reran already and the forge may still report the old failure: wait.
5938    Grace,
5939    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5940    Fix,
5941}
5942
5943/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5944/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5945/// pending checks in another run do not delay this run's rerun.
5946#[cfg(test)]
5947fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5948    rerunnable_with(contexts, false)
5949}
5950
5951fn rerunnable_with(
5952    contexts: &[CheckInfo],
5953    include_optional: bool,
5954) -> Vec<(String, Option<String>)> {
5955    contexts
5956        .iter()
5957        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5958        // `gh run rerun --failed` refuses a run with a job still going.
5959        .filter(|c| {
5960            c.run.as_ref().is_none_or(|r| {
5961                !contexts.iter().any(|o| {
5962                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5963                        && o.run.as_ref() == Some(r)
5964                })
5965            })
5966        })
5967        .map(|c| (c.label.clone(), c.run.clone()))
5968        .collect()
5969}
5970
5971/// Pure: rerun once per run id, wait out the grace, then hand over.
5972fn rerun_step(
5973    failing: &[(String, Option<String>)],
5974    record: Option<&LandReruns>,
5975    head: &str,
5976    now: i64,
5977) -> RerunStep {
5978    // A failure with no workflow run (an external status) cannot be rerun, and
5979    // the fixer's push re-runs everything anyway.
5980    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5981        return RerunStep::Fix;
5982    }
5983    // Reruns belong to the head they were made on.
5984    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5985    let mut fresh: Vec<String> = Vec::new();
5986    let mut recent = false;
5987    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5988        match record.and_then(|r| r.runs.get(run)) {
5989            None => {
5990                if !fresh.iter().any(|f| f == run) {
5991                    fresh.push(run.to_owned());
5992                }
5993            }
5994            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5995            Some(_) => {}
5996        }
5997    }
5998    if !fresh.is_empty() {
5999        RerunStep::Rerun(fresh)
6000    } else if recent {
6001        RerunStep::Grace
6002    } else {
6003        RerunStep::Fix
6004    }
6005}
6006
6007/// Read minimal live PR metadata (`url`, `number`, `state`, `headRefOid`,
6008/// `baseRefName`) for landing base-sync recovery admission and dispatch checks.
6009pub(crate) async fn observe_pr_summary(
6010    repo: &Path,
6011    pr_url: &str,
6012) -> Result<crate::land_sync_recovery::ObservedPr> {
6013    #[derive(serde::Deserialize)]
6014    struct Summary {
6015        #[serde(default)]
6016        url: String,
6017        #[serde(default)]
6018        number: u64,
6019        #[serde(default)]
6020        state: String,
6021        #[serde(default, rename = "headRefOid")]
6022        head_ref_oid: String,
6023        #[serde(default, rename = "baseRefName")]
6024        base_ref_name: String,
6025    }
6026    let view = gh(
6027        repo,
6028        &[
6029            "pr".to_owned(),
6030            "view".to_owned(),
6031            pr_url.to_owned(),
6032            "--json".to_owned(),
6033            "url,number,state,headRefOid,baseRefName".to_owned(),
6034        ],
6035    )
6036    .await?;
6037    if !view.ok {
6038        bail!("gh pr view {pr_url}: {}", view.combined());
6039    }
6040    let parsed: Summary = serde_json::from_str(&view.stdout).context("parse pull request json")?;
6041    Ok(crate::land_sync_recovery::ObservedPr {
6042        url: parsed.url,
6043        number: parsed.number,
6044        open: parsed.state.eq_ignore_ascii_case("OPEN"),
6045        head: parsed.head_ref_oid,
6046        base_branch: (!parsed.base_ref_name.is_empty()).then_some(parsed.base_ref_name),
6047    })
6048}
6049
6050/// Read the pull request: `gh pr view` for the top-level thread and merge
6051/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
6052/// inline review comments `gh pr view` does not report.
6053async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
6054    let view = gh(
6055        repo,
6056        &[
6057            "pr".to_owned(),
6058            "view".to_owned(),
6059            pr_url.to_owned(),
6060            "--json".to_owned(),
6061            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
6062                .to_owned(),
6063        ],
6064    )
6065    .await?;
6066    if !view.ok {
6067        bail!("gh pr view {pr_url}: {}", view.combined());
6068    }
6069    let number = parse_pr(&view.stdout)?.number;
6070    let node = last_commit_node(repo, number).await;
6071    let mut seen = seen_from(&view.stdout, node.as_deref())?;
6072
6073    let inline = gh(
6074        repo,
6075        &[
6076            "api".to_owned(),
6077            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
6078        ],
6079    )
6080    .await?;
6081    if inline.ok {
6082        match parse_inline_comments(&inline.stdout) {
6083            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
6084            // An unreadable inline thread must not end a landing: the rollup
6085            // and the top-level thread are still real signal.
6086            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
6087        }
6088    } else {
6089        tracing::warn!(
6090            "gh api pulls/{}/comments: {}",
6091            seen.pr.number,
6092            inline.combined()
6093        );
6094    }
6095    Ok(seen)
6096}
6097
6098/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
6099/// response. No I/O.
6100///
6101/// The commit oid and the checks are read from the *same* node, so the rollup
6102/// is bound to the commit it belongs to by construction; two reads that agree
6103/// before and after another response prove nothing about what that response
6104/// held. The view's own rollup is never used. A node that is missing,
6105/// unreadable, carries GraphQL errors, or whose checks run past the page
6106/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
6107/// as "look again" and never as a reason to merge.
6108fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
6109    let mut pr = parse_pr(view_json)?;
6110    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
6111
6112    let mut rollup_head = String::new();
6113    let mut failing_urls = Vec::new();
6114    let mut contexts = Vec::new();
6115    let mut checks = Checks::Unknown;
6116    let mut failing = Vec::new();
6117    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
6118        (checks, failing) = rollup_verdict(&rollup);
6119        failing_urls = rollup
6120            .iter()
6121            .filter(|c| c.verdict() == Verdict::Fail)
6122            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
6123            .collect();
6124        contexts = rollup
6125            .iter()
6126            .map(|c| CheckInfo {
6127                label: c.label(),
6128                verdict: c.verdict(),
6129                required: c.is_required,
6130                run: c.url().and_then(run_of),
6131            })
6132            .collect();
6133        rollup_head = oid;
6134    }
6135    pr.checks = checks;
6136    pr.failing = failing;
6137
6138    Ok(Seen {
6139        pr,
6140        title: raw.title,
6141        failing_urls,
6142        head: raw.head_ref_oid,
6143        rollup_head,
6144        merge_state: raw.merge_state_status,
6145        contexts,
6146        base: raw.base_ref_name,
6147    })
6148}
6149
6150/// The last commit's oid and its checks from one GraphQL response, `None`
6151/// when anything about it cannot be trusted.
6152fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
6153    let v: serde_json::Value = serde_json::from_str(json).ok()?;
6154    if v.get("errors").is_some_and(|e| !e.is_null()) {
6155        return None;
6156    }
6157    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
6158    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
6159    let contexts = commit.pointer("/statusCheckRollup/contexts");
6160    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
6161        // No rollup at all: the commit has no checks.
6162        return Some((oid.to_owned(), Vec::new()));
6163    };
6164    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
6165        return None;
6166    }
6167    let nodes = contexts.get("nodes")?.as_array()?;
6168    let rollup = nodes
6169        .iter()
6170        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
6171        .collect::<Result<Vec<_>, _>>()
6172        .ok()?;
6173    Some((oid.to_owned(), rollup))
6174}
6175
6176/// The pull request's last commit and its checks, in one response. `None`
6177/// when the forge could not be asked.
6178async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
6179    let out = gh(
6180        repo,
6181        &[
6182            "api".to_owned(),
6183            "graphql".to_owned(),
6184            "-F".to_owned(),
6185            "owner={owner}".to_owned(),
6186            "-F".to_owned(),
6187            "repo={repo}".to_owned(),
6188            "-F".to_owned(),
6189            format!("number={number}"),
6190            "-f".to_owned(),
6191            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
6192             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
6193             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
6194             ... on CheckRun{name status conclusion detailsUrl \
6195             isRequired(pullRequestNumber:$number)} \
6196             ... on StatusContext{context state targetUrl \
6197             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
6198                .to_owned(),
6199        ],
6200    )
6201    .await
6202    .ok()?;
6203    out.ok.then_some(out.stdout)
6204}
6205
6206/// What a fix round did.
6207#[doc(hidden)]
6208#[derive(Debug, PartialEq)]
6209pub enum Fixed {
6210    /// The fixer committed something, and this is the head that was pushed.
6211    Committed {
6212        /// The commit now at the tip of the pushed branch.
6213        head: String,
6214    },
6215    /// The fixer ran and chose to change nothing.
6216    Declined,
6217    /// Machine availability prevented a result; retry this round on resume.
6218    Deferred,
6219    /// The fixer could not run, or said nothing usable.
6220    Failed(String),
6221}
6222
6223/// Hand the failures and the comments to the fixer, then commit and push.
6224///
6225/// The fixer works in the winner's own worktree so its commits land on the
6226/// branch the pull request is built from, and it runs with `allow_write` for
6227/// the same reason.
6228#[doc(hidden)]
6229pub async fn fix_round(
6230    state: &mut RunState,
6231    pr: &PrState,
6232    round: usize,
6233    budget: usize,
6234    reason: &str,
6235    logs: &str,
6236) -> Result<Fixed> {
6237    let winner = state
6238        .winner()
6239        .cloned()
6240        .context("landing needs a winning candidate; none is recorded on this run")?;
6241    let roles = state
6242        .config
6243        .resolve_roles()
6244        .context("resolve the roster for the fix round")?;
6245    // Same chain as the review loop (see `crate::fixer`): the configured
6246    // fixers in order, otherwise the winner's own author continuing its own
6247    // conversation - the competition is over, so its context is pure benefit.
6248    let attempts = crate::fixer::attempts(state, &roles, &winner);
6249    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
6250
6251    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
6252    let mut artifacts = agent::artifacts_dir(&state.dir());
6253    if let Some(request) = state
6254        .merge_repairs
6255        .last()
6256        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
6257    {
6258        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
6259    }
6260    let prompt =
6261        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
6262            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
6263        } else {
6264            prompt
6265        };
6266    // Read before the fixer runs: it normally commits for itself, so HEAD has
6267    // already moved by the time it returns and a later read would see no
6268    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
6269    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
6270    // Each id at most once, forward only: the next one is asked only when the
6271    // call advances, and only the last attempt's result is judged below, so an
6272    // exhausted chain ends as a single failed fixer does.
6273    let mut last = None;
6274    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
6275        if owner_requested_stop(state)? {
6276            return Ok(Fixed::Declined);
6277        }
6278        let mut seat = seat_of(state, &seat_key, &spec.id);
6279        let stem = if i == 0 {
6280            format!("land-{round}")
6281        } else {
6282            format!("land-{round}-{}", spec.id)
6283        };
6284        let out = agent::invoke(
6285            &spec,
6286            &mut seat,
6287            &Invocation {
6288                coordination: state.config.coordination.as_ref(),
6289                fetched_base: state.fetched_base.as_ref(),
6290                cwd: &winner.worktree,
6291                prompt: &prompt,
6292                timeout: Duration::from_secs(state.config.graph.timeout_fix),
6293                allow_write: true,
6294                sessions: state.config.graph.sessions,
6295                artifacts: &artifacts,
6296                stem: &stem,
6297                run: &state.id,
6298                node: "land",
6299                cache_dir: state.config.cache_dir().as_deref(),
6300                attachments: &[],
6301                writable: &[],
6302            },
6303        )
6304        .await;
6305        state.seats.insert(seat.key.clone(), seat);
6306        if let Some(next) = ids.get(i + 1)
6307            && agent::chain_advances(&out)
6308        {
6309            let (class, why) = crate::fixer::failure_of(&out);
6310            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
6311            continue;
6312        }
6313        last = Some((seat_key, out));
6314        break;
6315    }
6316    let (seat_key, out) = last.expect("the fixer chain always has an entry");
6317
6318    match out {
6319        Ok(o) if o.quota_exhausted() => {
6320            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
6321            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
6322            state.quota.push(loss);
6323            state.status = RunStatus::Blocked;
6324            state.save()?;
6325            // Keep partial edits reachable on the winner branch and leave a
6326            // clean tree for resume_landing_head. The resumed landing gates
6327            // this new commit before it can publish it; no push happens here.
6328            let inherited = crate::repo_lock::WaitPolicy::current();
6329            let wait = crate::repo_lock::WaitPolicy::new(
6330                Duration::from_secs(state.config.graph.timeout_resource_wait),
6331                move || inherited.cancelled(),
6332            );
6333            let _coordination = crate::repo_lock::SeatLease::operation_with(
6334                &winner.worktree,
6335                state.config.coordination.as_ref(),
6336                &wait,
6337            )
6338            .await?;
6339            let rescue = git::rescue_commit(
6340                &winner.worktree,
6341                &format!("magi: deferred land round {round} (uncommitted work)"),
6342            )
6343            .await?;
6344            state.note_withheld("land", &rescue.withheld);
6345            state.save()?;
6346            return Ok(Fixed::Deferred);
6347        }
6348        Ok(o) if !o.usable() => {
6349            return Ok(Fixed::Failed(format!(
6350                "the fixer produced nothing usable ({})",
6351                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
6352            )));
6353        }
6354        Ok(_) => {}
6355        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
6356        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
6357    }
6358
6359    if owner_requested_stop(state)? {
6360        return Ok(Fixed::Declined);
6361    }
6362
6363    // An agent that edited files but never committed would otherwise push
6364    // nothing and look like a refusal.
6365    let wait = crate::repo_lock::WaitPolicy::new(
6366        Duration::from_secs(state.config.graph.timeout_resource_wait),
6367        || false,
6368    );
6369    let coordination = crate::repo_lock::SeatLease::operation_with(
6370        &winner.worktree,
6371        state.config.coordination.as_ref(),
6372        &wait,
6373    )
6374    .await?;
6375    match git::rescue_commit(
6376        &winner.worktree,
6377        &format!("magi: land round {round} fixes (uncommitted work)"),
6378    )
6379    .await
6380    {
6381        Ok(r) => state.note_withheld("land", &r.withheld),
6382        Err(e)
6383            if state
6384                .merge_repairs
6385                .last()
6386                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
6387        {
6388            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
6389        }
6390        Err(_) => {}
6391    }
6392    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
6393    drop(coordination);
6394    if after == before {
6395        return Ok(Fixed::Declined);
6396    }
6397
6398    if owner_requested_stop(state)? {
6399        return Ok(Fixed::Declined);
6400    }
6401    crate::pr_head::ensure_owner(state)?;
6402    let remote = state.config.merge.remote.clone();
6403    anyhow::ensure!(
6404        crate::foreign_checkout::write_back(state, &after).await?,
6405        "foreign checkout delivery is blocked; see the run events"
6406    );
6407    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
6408    let push = if state.pr_head.is_some() {
6409        let expected = state
6410            .pr_pushed_head
6411            .as_deref()
6412            .context("missing public head lease")?;
6413        git::push_as(
6414            &winner.worktree,
6415            &remote,
6416            &winner.branch,
6417            &public_head,
6418            expected,
6419        )
6420        .await?
6421    } else {
6422        git::push(&winner.worktree, &remote, &winner.branch).await?
6423    };
6424    if !push.ok() {
6425        return Ok(Fixed::Failed(format!(
6426            "pushing {} to {remote} failed: {}",
6427            public_head, push.stderr
6428        )));
6429    }
6430    state.event(
6431        "land",
6432        format!("round {round}: pushed a fix to {public_head}"),
6433    );
6434    state.pr_pushed_head = Some(after.clone());
6435    state.land_sync_checkpoint = None;
6436    state.save()?;
6437    Ok(Fixed::Committed { head: after })
6438}
6439
6440/// Fetch or create a seat, keeping its conversation across nodes.
6441pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
6442    crate::fixer::seat_for(state, key, agent)
6443}
6444
6445/// Recheck the live PR and local worktree before spending the requested fix.
6446/// A moved/closed PR is held, never repaired using obsolete evidence.
6447pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
6448    let seen = observe(&state.repo, url).await?;
6449    let winner = state.winner().context("no winning branch to repair")?;
6450    if seen.pr.state != PrLifecycle::Open || seen.head != head {
6451        anyhow::bail!(
6452            "PR is closed or its head changed; review the current head before requesting repair again"
6453        );
6454    }
6455    if git::rev_parse(&winner.worktree, "HEAD").await? != head
6456        || !git::is_clean(&winner.worktree).await?
6457    {
6458        anyhow::bail!(
6459            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
6460        );
6461    }
6462    // Always disable any forge-side reservation, including one not recorded
6463    // by this run. A repair request is never merge authorization.
6464    let view = gh(
6465        &state.repo,
6466        &[
6467            "pr".into(),
6468            "view".into(),
6469            url.into(),
6470            "--json".into(),
6471            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
6472        ],
6473    )
6474    .await?;
6475    if !view.ok {
6476        bail!("cannot check auto-merge: {}", view.combined());
6477    }
6478    let live: serde_json::Value = serde_json::from_str(&view.stdout)?;
6479    let public = state.pr_branch().unwrap_or(&winner.branch);
6480    if live["state"] != "OPEN"
6481        || live["headRefOid"] != head
6482        || live["headRefName"] != public
6483        || live["baseRefName"] != state.base_branch
6484        || live["isCrossRepository"] != false
6485    {
6486        bail!("PR changed during repair preflight; review its current head explicitly");
6487    }
6488    let auto_merge = live
6489        .get("autoMergeRequest")
6490        .context("cannot read the PR auto-merge reservation; repair held")?;
6491    if !auto_merge.is_null() {
6492        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
6493        if !out.ok {
6494            bail!("cannot disable auto-merge; repair held: {}", out.combined());
6495        }
6496    }
6497    Ok(seen.pr)
6498}
6499
6500pub(crate) fn merge_repair_reason(
6501    state: &RunState,
6502    request: &crate::run::MergeRepair,
6503) -> Result<String> {
6504    let evidence = serde_json::to_string_pretty(request)?;
6505    Ok(
6506        if state
6507            .instruction_revisions
6508            .iter()
6509            .any(|r| r.repair == request.question)
6510        {
6511            format!(
6512                "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}"
6513            )
6514        } else {
6515            format!(
6516                "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}"
6517            )
6518        },
6519    )
6520}
6521
6522/// What the fixer is told.
6523fn fix_prompt(
6524    state: &RunState,
6525    pr: &PrState,
6526    round: usize,
6527    budget: usize,
6528    reason: &str,
6529    logs: &str,
6530) -> String {
6531    let mut s = format!(
6532        "Your patch is open as a pull request and it is not landing. Land round \
6533         {round} of {budget}.\n\n\
6534         Pull request: {}\n\n\
6535         What is holding it: {reason}\n\n\
6536         # The task\n\n{}\n",
6537        pr.url, state.instruction
6538    );
6539
6540    if pr.failing.is_empty() {
6541        s.push_str("\n# Failing checks\n\n(none)\n");
6542    } else {
6543        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
6544        if logs.trim().is_empty() {
6545            s.push_str(
6546                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
6547            );
6548        } else {
6549            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
6550        }
6551    }
6552
6553    if pr.review_comments.is_empty() {
6554        s.push_str("\n# Review comments\n\n(none)\n");
6555    } else {
6556        s.push_str("\n# Review comments\n");
6557        for c in &pr.review_comments {
6558            let where_ = match (&c.path, c.line) {
6559                (Some(p), Some(l)) => format!(" ({p}:{l})"),
6560                (Some(p), None) => format!(" ({p})"),
6561                _ => String::new(),
6562            };
6563            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
6564        }
6565    }
6566
6567    let revision_repair = state.merge_repairs.last().is_some_and(|repair| {
6568        repair.phase == crate::run::MergeRepairPhase::Fixing
6569            && state
6570                .instruction_revisions
6571                .iter()
6572                .any(|r| r.repair == repair.question)
6573    });
6574    s.push_str(
6575        "\n# Rules\n\n\
6576         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
6577            failing test; do not silence a lint with an allow attribute; do not \
6578            stretch a timeout to hide a race. If the check is right, the code is \
6579            wrong.\n",
6580    );
6581    if revision_repair {
6582        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");
6583    } else {
6584        s.push_str(
6585            "2. Change nothing the checks and the comments did not raise. A \
6586            drive-by refactor turns a one-line fix into a pull request that \
6587            needs reviewing again.\n",
6588        );
6589    }
6590    s.push_str(
6591        "\
6592         3. If a comment is wrong, say so with a checkable argument and change \
6593            nothing for it. A declined comment with a reason is a correct \
6594            outcome; a change made to appease a reviewer is not.\n\
6595         4. Commit in this worktree. magi pushes to the pull request's branch \
6596            for you; do not push, merge, or close anything yourself.\n\
6597         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
6598         # Output\n\n\
6599         Say what you changed and why, and what you declined and why.",
6600    );
6601
6602    let language = &state.config.graph.language;
6603    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
6604        let _ = write!(s, "\n\nWrite all prose in {language}.");
6605    }
6606    // After the language line, so the exception is the last word on it.
6607    s.push_str(&crate::prompt::github_rule(
6608        language,
6609        &state.config.graph.github_language,
6610    ));
6611    if let Some(overlay) = state.config.prompts.overlay("fix") {
6612        let _ = write!(s, "\n\n{overlay}");
6613    }
6614    s.push('\n');
6615    s.push_str(crate::prompt::child_run_ownership());
6616    s
6617}
6618
6619/// Failing log tails, the way the operator collects them by hand:
6620/// `gh run view --log-failed`.
6621async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6622    let mut out = String::new();
6623    for (name, url) in failing.iter().take(MAX_LOGS) {
6624        let args = match (job_of(url), run_of(url)) {
6625            (Some(job), _) => vec![
6626                "run".to_owned(),
6627                "view".to_owned(),
6628                "--log-failed".to_owned(),
6629                "--job".to_owned(),
6630                job,
6631            ],
6632            (None, Some(run)) => vec![
6633                "run".to_owned(),
6634                "view".to_owned(),
6635                run,
6636                "--log-failed".to_owned(),
6637            ],
6638            // Not a GitHub Actions check - an external status has no log here.
6639            (None, None) => continue,
6640        };
6641        let (ok, body) = match gh(repo, &args).await {
6642            Ok(v) => (v.ok, v.combined()),
6643            Err(e) => (false, format!("{e:#}")),
6644        };
6645        if !ok && body.trim().is_empty() {
6646            continue;
6647        }
6648        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6649    }
6650    out
6651}
6652
6653/// Job id out of a check's `detailsUrl`
6654/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
6655fn job_of(details_url: &str) -> Option<String> {
6656    let after = details_url.split("/job/").nth(1)?;
6657    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6658    (!id.is_empty()).then_some(id)
6659}
6660
6661/// Workflow run id out of a check's `detailsUrl`.
6662pub(crate) fn run_of(details_url: &str) -> Option<String> {
6663    let after = details_url.split("/actions/runs/").nth(1)?;
6664    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6665    (!id.is_empty()).then_some(id)
6666}
6667
6668/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6669/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6670/// it to that.
6671fn stop_comment(run_id: &str, why: &str) -> String {
6672    format!(
6673        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6674         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6675    )
6676}
6677
6678/// Leave the pull request open, say why on it, and mark the run blocked.
6679///
6680/// The comment is what makes an unattended stop actionable: the operator wakes
6681/// up to a pull request that explains itself rather than to a silent queue.
6682async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6683    let body = stop_comment(&state.id, why);
6684    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6685    if !body.contains(MARKER) {
6686        body = format!("{MARKER}\n{body}");
6687    }
6688    let posted = gh(
6689        repo,
6690        &[
6691            "pr".to_owned(),
6692            "comment".to_owned(),
6693            pr.number.to_string(),
6694            "--body".to_owned(),
6695            body,
6696        ],
6697    )
6698    .await;
6699    match posted {
6700        Ok(out) if out.ok => {}
6701        Ok(out) => tracing::warn!("could not comment on {}: {}", pr.url, out.combined()),
6702        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6703    }
6704    state.status = RunStatus::Blocked;
6705    state.merge = Some(MergeOutcome {
6706        mode: MergeMode::Pr,
6707        ok: false,
6708        detail: why.to_owned(),
6709        empty: false,
6710    });
6711    state.event("land", format!("stopped: {why}"));
6712    state.save()?;
6713    Ok(())
6714}
6715
6716/// Output of a `gh` subprocess, keeping machine-readable `stdout` separate from
6717/// diagnostic `stderr`.
6718///
6719/// Newer `gh` releases (for example `gh` 2.105.0) can emit advisory hints on
6720/// `stderr` even when a read-only `--json` or API command succeeds with exit
6721/// status 0. Appending `stderr` onto `stdout` before deserialization breaks
6722/// strict JSON parsing (for example `trailing characters at line 2 column 1`).
6723///
6724/// Output contract:
6725/// - **Successful structured reads** (`--json`, REST `gh api`, GraphQL, etc.):
6726///   check [`Self::ok`], then pass [`Self::stdout`] straight to a strict parser.
6727///   Never fall back to [`Self::stderr`] when `stdout` is empty, and never strip
6728///   specific hint text or heuristically extract JSON substrings.
6729/// - **Failed invocations (`!ok`)**: use [`Self::combined`] so both `stdout`
6730///   and `stderr` diagnostics stay actionable (for example `404` detection and
6731///   refused-merge details).
6732/// - **Human-facing or mutating commands** (`pr merge`, `pr close`, `pr edit`,
6733///   `pr comment`, `run rerun`, `run view --log-failed`): use
6734///   [`Self::combined`] for failure diagnostics or human-readable output.
6735#[derive(Debug, Clone, PartialEq, Eq)]
6736pub(crate) struct GhOutput {
6737    /// Whether `gh` exited with status 0.
6738    pub(crate) ok: bool,
6739    /// Process `stdout`, decoded lossily as UTF-8.
6740    pub(crate) stdout: String,
6741    /// Process `stderr`, decoded lossily as UTF-8.
6742    pub(crate) stderr: String,
6743}
6744
6745impl GhOutput {
6746    /// Build from a completed subprocess output and log non-empty `stderr`
6747    /// emitted on exit status 0 at debug level without logging command
6748    /// arguments.
6749    pub(crate) fn from_output(output: std::process::Output) -> Self {
6750        let parsed = Self {
6751            ok: output.status.success(),
6752            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
6753            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
6754        };
6755        if parsed.ok && !parsed.stderr.trim().is_empty() {
6756            tracing::debug!(
6757                stderr = parsed.stderr.trim(),
6758                "gh exited successfully with stderr diagnostics"
6759            );
6760        }
6761        parsed
6762    }
6763
6764    /// Combined trimmed `stdout` and `stderr` for failure diagnostics and
6765    /// human-facing commands.
6766    pub(crate) fn combined(&self) -> String {
6767        let out = self.stdout.trim();
6768        let err = self.stderr.trim();
6769        match (out.is_empty(), err.is_empty()) {
6770            (true, true) => String::new(),
6771            (false, true) => out.to_owned(),
6772            (true, false) => err.to_owned(),
6773            (false, false) => format!("{out}\n{err}"),
6774        }
6775    }
6776}
6777
6778/// Run `gh` in `cwd`, returning exit status with separated `stdout` and
6779/// `stderr` in [`GhOutput`].
6780///
6781/// Structured callers must check [`GhOutput::ok`] and parse [`GhOutput::stdout`]
6782/// strictly without substituting [`GhOutput::stderr`]. Failed invocations and
6783/// human-facing or mutating commands should use [`GhOutput::combined`] so both
6784/// streams remain available as diagnostics.
6785///
6786/// `GH_REPO` is stripped from the child's environment: every call site here
6787/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6788/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6789/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6790/// `GH_REPO` the operator happens to have exported for an unrelated script
6791/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6792/// below) to a different repository than the one actually on disk - which
6793/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6794/// could be made to agree with whatever repository a forged `--merged` URL
6795/// claims, defeating it entirely.
6796pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<GhOutput> {
6797    gh_with(Path::new("gh"), cwd, args).await
6798}
6799
6800pub(crate) async fn gh_with(program: &Path, cwd: &Path, args: &[String]) -> Result<GhOutput> {
6801    let out = tokio::process::Command::new(program)
6802        .args(args)
6803        .current_dir(cwd)
6804        .env_remove("GH_REPO")
6805        .quiet()
6806        .stdin(std::process::Stdio::null())
6807        .output()
6808        .await
6809        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6810    Ok(GhOutput::from_output(out))
6811}
6812
6813/// Verdict of one entry in the status rollup.
6814#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6815pub(crate) enum Verdict {
6816    Pass,
6817    Fail,
6818    Pending,
6819    Unknown,
6820}
6821
6822impl Verdict {
6823    /// Short operator-facing check result.
6824    pub(crate) fn label(self) -> &'static str {
6825        match self {
6826            Self::Pass => "passed",
6827            Self::Fail => "failed",
6828            Self::Pending => "pending",
6829            Self::Unknown => "unknown",
6830        }
6831    }
6832}
6833
6834#[derive(Debug, Deserialize)]
6835#[serde(rename_all = "camelCase")]
6836struct GhPr {
6837    #[serde(default)]
6838    url: String,
6839    #[serde(default)]
6840    number: u64,
6841    #[serde(default)]
6842    state: String,
6843    #[serde(default)]
6844    title: String,
6845    #[serde(default)]
6846    status_check_rollup: Vec<GhCheck>,
6847    /// GitHub's own verdict on whether the pull request can be merged.
6848    ///
6849    /// Worth asking for because it is the only place the *required* check set
6850    /// is applied: the rollup lists every check equally, so a repository that
6851    /// deliberately does not require `coverage` still looks red here. See
6852    /// [`Blocking`].
6853    #[serde(default)]
6854    merge_state_status: String,
6855    /// The commit the pull request currently points at. Compared with the
6856    /// commit a fix round pushed, it is how the loop knows the forge has moved
6857    /// on and the rollup belongs to the new head.
6858    #[serde(default)]
6859    head_ref_oid: String,
6860    #[serde(default)]
6861    base_ref_name: String,
6862    #[serde(default)]
6863    reviews: Vec<GhReview>,
6864    #[serde(default)]
6865    comments: Vec<GhComment>,
6866}
6867
6868/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6869/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6870/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6871/// conclusion at all.
6872#[derive(Debug, Deserialize)]
6873#[serde(rename_all = "camelCase")]
6874struct GhCheck {
6875    #[serde(default)]
6876    name: Option<String>,
6877    #[serde(default)]
6878    context: Option<String>,
6879    #[serde(default)]
6880    status: Option<String>,
6881    #[serde(default)]
6882    conclusion: Option<String>,
6883    #[serde(default)]
6884    state: Option<String>,
6885    #[serde(default)]
6886    details_url: Option<String>,
6887    #[serde(default)]
6888    target_url: Option<String>,
6889    /// Whether the base branch requires this check. Only the GraphQL node
6890    /// carries it; `None` is "not read", never "not required".
6891    #[serde(default)]
6892    is_required: Option<bool>,
6893}
6894
6895impl GhCheck {
6896    /// Name to show a human and hand to the fixer.
6897    fn label(&self) -> String {
6898        self.name
6899            .clone()
6900            .or_else(|| self.context.clone())
6901            .unwrap_or_else(|| "(unnamed check)".to_owned())
6902    }
6903
6904    /// Where this check's logs live, when it has any.
6905    fn url(&self) -> Option<&str> {
6906        self.details_url
6907            .as_deref()
6908            .or(self.target_url.as_deref())
6909            .filter(|u| !u.is_empty())
6910    }
6911
6912    /// Did it pass?
6913    ///
6914    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6915    /// skips release and bot pull requests by design, and a skip that blocked
6916    /// landing would block exactly the pull requests that need no review.
6917    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6918    /// merging over one is merging over a check that never ran.
6919    fn verdict(&self) -> Verdict {
6920        if let Some(status) = self.status.as_deref() {
6921            if !status.eq_ignore_ascii_case("COMPLETED") {
6922                return Verdict::Pending;
6923            }
6924        }
6925        let outcome = self
6926            .conclusion
6927            .as_deref()
6928            .or(self.state.as_deref())
6929            .unwrap_or("");
6930        match outcome.to_ascii_uppercase().as_str() {
6931            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6932            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6933            | "ACTION_REQUIRED" => Verdict::Fail,
6934            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6935                Verdict::Pending
6936            }
6937            _ => Verdict::Unknown,
6938        }
6939    }
6940}
6941
6942#[derive(Debug, Deserialize)]
6943struct GhAuthor {
6944    #[serde(default)]
6945    login: String,
6946}
6947
6948#[derive(Debug, Deserialize)]
6949struct GhReview {
6950    #[serde(default)]
6951    author: GhAuthor,
6952    #[serde(default)]
6953    body: String,
6954}
6955
6956#[derive(Debug, Deserialize)]
6957struct GhComment {
6958    #[serde(default)]
6959    author: GhAuthor,
6960    #[serde(default)]
6961    body: String,
6962}
6963
6964#[derive(Debug, Deserialize)]
6965struct GhUser {
6966    #[serde(default)]
6967    login: String,
6968}
6969
6970#[derive(Debug, Deserialize)]
6971struct GhInline {
6972    #[serde(default)]
6973    user: GhUser,
6974    #[serde(default)]
6975    path: Option<String>,
6976    #[serde(default)]
6977    line: Option<u64>,
6978    #[serde(default)]
6979    body: String,
6980}
6981
6982impl Default for GhAuthor {
6983    fn default() -> Self {
6984        Self {
6985            login: "(unknown)".to_owned(),
6986        }
6987    }
6988}
6989
6990impl Default for GhUser {
6991    fn default() -> Self {
6992        Self {
6993            login: "(unknown)".to_owned(),
6994        }
6995    }
6996}
6997
6998#[cfg(test)]
6999pub(crate) mod tests {
7000    use super::*;
7001    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
7002
7003    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
7004        format!(
7005            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
7006        )
7007    }
7008
7009    #[test]
7010    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
7011        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
7012        assert_eq!(
7013            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
7014            Ok(())
7015        );
7016        for (json, why) in [
7017            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
7018            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
7019            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
7020            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
7021            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
7022            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
7023        ] {
7024            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
7025                .unwrap_err()
7026                .why;
7027            assert!(err.contains(why), "{json}: {err}");
7028        }
7029        // A head that moved on past what was verified is left alone.
7030        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
7031        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
7032        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
7033        assert!(
7034            !closable(
7035                &head_json("x", "main", "OPEN", false),
7036                "magi/27b2/A",
7037                "main",
7038                &[]
7039            )
7040            .unwrap_err()
7041            .retry
7042        );
7043        assert!(is_forge_url("https://github.com/o/r.git"));
7044        assert!(is_forge_url("git@github.com:o/r.git"));
7045        assert!(!is_forge_url("/tmp/origin.git"));
7046        assert!(!is_forge_url("C:\\work\\origin.git"));
7047        assert!(!is_forge_url("file:///tmp/origin.git"));
7048        assert!(forge_unavailable(
7049            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
7050        ));
7051        assert!(!forge_unavailable(
7052            "gh pr list failed: error connecting to api.github.com"
7053        ));
7054        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
7055        // A record that does not say whether it is a fork is not trusted.
7056        assert!(
7057            closable(
7058                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
7059                "b",
7060                "main",
7061                &["aaa".to_owned()]
7062            )
7063            .is_err()
7064        );
7065    }
7066
7067    #[test]
7068    fn the_close_comment_names_the_commit_on_the_base() {
7069        let e = crate::already::Evidence {
7070            proof: crate::already::Proof::PatchId,
7071            tip: "1234567890".to_owned(),
7072            commits: vec!["0e368de0000".to_owned()],
7073        };
7074        let c = superseded_comment("main", &e);
7075        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
7076    }
7077
7078    /// 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.
7079    const GREEN_OPEN: &str = r####"{
7080  "url": "https://github.com/yukimemi/magi/pull/10",
7081  "number": 10,
7082  "state": "OPEN",
7083  "mergeStateStatus": "CLEAN",
7084  "statusCheckRollup": [
7085    {
7086      "__typename": "CheckRun",
7087      "conclusion": "SKIPPED",
7088      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
7089      "name": "review",
7090      "status": "COMPLETED",
7091      "workflowName": "claude-review"
7092    },
7093    {
7094      "__typename": "CheckRun",
7095      "conclusion": "SUCCESS",
7096      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
7097      "name": "check (ubuntu-latest)",
7098      "status": "COMPLETED",
7099      "workflowName": "CI"
7100    },
7101    {
7102      "__typename": "CheckRun",
7103      "conclusion": "SUCCESS",
7104      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
7105      "name": "rustfmt",
7106      "status": "COMPLETED",
7107      "workflowName": "CI"
7108    },
7109    {
7110      "__typename": "StatusContext",
7111      "context": "CodeRabbit",
7112      "state": "SUCCESS",
7113      "targetUrl": ""
7114    }
7115  ],
7116  "reviews": [],
7117  "comments": [
7118    {
7119      "author": {
7120        "login": "coderabbitai"
7121      },
7122      "authorAssociation": "NONE",
7123      "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"
7124    }
7125  ]
7126}"####;
7127
7128    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
7129    const RED_OPEN: &str = r####"{
7130  "url": "https://github.com/yukimemi/magi/pull/9",
7131  "number": 9,
7132  "state": "OPEN",
7133  "mergeStateStatus": "UNSTABLE",
7134  "statusCheckRollup": [
7135    {
7136      "__typename": "CheckRun",
7137      "conclusion": "SUCCESS",
7138      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
7139      "name": "check (ubuntu-latest)",
7140      "status": "COMPLETED",
7141      "workflowName": "CI"
7142    },
7143    {
7144      "__typename": "CheckRun",
7145      "conclusion": "SUCCESS",
7146      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
7147      "name": "rustfmt",
7148      "status": "COMPLETED",
7149      "workflowName": "CI"
7150    },
7151    {
7152      "__typename": "CheckRun",
7153      "conclusion": "FAILURE",
7154      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
7155      "name": "editorconfig",
7156      "status": "COMPLETED",
7157      "workflowName": "CI"
7158    },
7159    {
7160      "__typename": "StatusContext",
7161      "context": "CodeRabbit",
7162      "state": "SUCCESS",
7163      "targetUrl": ""
7164    }
7165  ],
7166  "reviews": [],
7167  "comments": [
7168    {
7169      "author": {
7170        "login": "coderabbitai"
7171      },
7172      "authorAssociation": "NONE",
7173      "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"
7174    }
7175  ]
7176}"####;
7177
7178    /// 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.
7179    const PENDING_OPEN: &str = r####"{
7180  "url": "https://github.com/yukimemi/magi/pull/9",
7181  "number": 9,
7182  "state": "OPEN",
7183  "statusCheckRollup": [
7184    {
7185      "__typename": "CheckRun",
7186      "conclusion": "SUCCESS",
7187      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
7188      "name": "check (ubuntu-latest)",
7189      "status": "COMPLETED",
7190      "workflowName": "CI"
7191    },
7192    {
7193      "__typename": "CheckRun",
7194      "conclusion": "SUCCESS",
7195      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
7196      "name": "rustfmt",
7197      "status": "COMPLETED",
7198      "workflowName": "CI"
7199    },
7200    {
7201      "__typename": "CheckRun",
7202      "conclusion": null,
7203      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
7204      "name": "editorconfig",
7205      "status": "IN_PROGRESS",
7206      "workflowName": "CI"
7207    },
7208    {
7209      "__typename": "StatusContext",
7210      "context": "CodeRabbit",
7211      "state": "SUCCESS",
7212      "targetUrl": ""
7213    }
7214  ],
7215  "reviews": [],
7216  "comments": []
7217}"####;
7218
7219    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
7220    const MERGED: &str = r####"{
7221  "url": "https://github.com/yukimemi/magi/pull/16",
7222  "number": 16,
7223  "state": "MERGED",
7224  "statusCheckRollup": [
7225    {
7226      "__typename": "CheckRun",
7227      "conclusion": "SUCCESS",
7228      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
7229      "name": "check (ubuntu-latest)",
7230      "status": "COMPLETED",
7231      "workflowName": "CI"
7232    },
7233    {
7234      "__typename": "CheckRun",
7235      "conclusion": "SUCCESS",
7236      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
7237      "name": "review",
7238      "status": "COMPLETED",
7239      "workflowName": "claude-review"
7240    }
7241  ],
7242  "reviews": [],
7243  "comments": []
7244}"####;
7245
7246    /// 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.
7247    const REVIEWED_OPEN: &str = r####"{
7248  "url": "https://github.com/yukimemi/magi/pull/12",
7249  "number": 12,
7250  "state": "OPEN",
7251  "statusCheckRollup": [
7252    {
7253      "__typename": "CheckRun",
7254      "conclusion": "SUCCESS",
7255      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
7256      "name": "check (ubuntu-latest)",
7257      "status": "COMPLETED",
7258      "workflowName": "CI"
7259    },
7260    {
7261      "__typename": "CheckRun",
7262      "conclusion": "SUCCESS",
7263      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
7264      "name": "review",
7265      "status": "COMPLETED",
7266      "workflowName": "claude-review"
7267    }
7268  ],
7269  "reviews": [
7270    {
7271      "author": {
7272        "login": "claude"
7273      },
7274      "state": "COMMENTED",
7275      "body": ""
7276    }
7277  ],
7278  "comments": [
7279    {
7280      "author": {
7281        "login": "coderabbitai"
7282      },
7283      "authorAssociation": "NONE",
7284      "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"
7285    },
7286    {
7287      "author": {
7288        "login": "claude"
7289      },
7290      "authorAssociation": "NONE",
7291      "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"
7292    }
7293  ]
7294}"####;
7295
7296    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
7297    const INLINE: &str = r####"[
7298  {
7299    "user": {
7300      "login": "claude[bot]"
7301    },
7302    "path": "src/graph.rs",
7303    "line": 231,
7304    "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"
7305  }
7306]"####;
7307
7308    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
7309    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
7310<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
7311
7312> [!IMPORTANT]
7313> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
7314> 
7315> This repository does not receive automatic reviews because it has fewer than 10 stars.
7316> 
7317> <details>
7318> <summary>⚙️ Run configuration</summary>
7319> 
7320> **Configuration used**: defaults
7321> 
7322> **Review profile**: CHILL
7323> 
7324> **Plan**: Team
7325> 
7326> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
7327> 
7328> </details>
7329
7330<!-- end of auto-generated comment: skip review by coderabbit.ai -->
7331
7332<!-- tips_start -->
7333
7334---
7335
7336Thanks 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.
7337
7338<details>
7339<summary>❤️ Share</summary>
7340
7341- [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"####;
7342
7343    /// 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.
7344    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
7345
7346---
7347### Reviewing PR #16
7348
7349- [x] Read AGENTS.md conventions
7350- [x] Review `src/daemon.rs` changes
7351- [x] Review `src/main.rs` changes (new `doctor` reporting)
7352- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
7353- [x] Check test coverage for new behavior
7354- [x] Run verification commands (blocked — see note)
7355- [x] Post findings"####;
7356
7357    /// The same job's real comment on pull request #12 once it had something to say.
7358    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
7359
7360---
7361### Review: `magi review <branch>` — cheap-half-only graph
7362
7363Read 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.
7364
7365**Correctness**
7366
7367- 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"####;
7368
7369    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
7370        PrState {
7371            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
7372            number: 16,
7373            state: PrLifecycle::Open,
7374            checks,
7375            // These tests are about red-means-fix, so a red here is one the
7376            // forge gates on. Without saying so they would assert the new
7377            // "merge past a check nobody requires" path by accident.
7378            blocking: if matches!(checks, Checks::Red) {
7379                Blocking::Yes
7380            } else {
7381                Blocking::No
7382            },
7383            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
7384            review_comments: (0..comments)
7385                .map(|i| ReviewComment {
7386                    author: "coderabbitai".to_owned(),
7387                    path: Some("src/graph.rs".to_owned()),
7388                    line: Some(231),
7389                    body: format!("finding {i}"),
7390                })
7391                .collect(),
7392        }
7393    }
7394
7395    #[test]
7396    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
7397        use CiExpectation::{Absent, Expected};
7398        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
7399            let p = pr(checks, &["x"], 0);
7400            for waited in [Duration::ZERO, CHECKS_GRACE] {
7401                assert_eq!(
7402                    decide_with(&p, 0, 4, waited, Expected),
7403                    decide(&p, 0, 4, waited)
7404                );
7405            }
7406        }
7407        // Nothing will ever report: no wait, no give-up, no fix round.
7408        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
7409            let p = pr(checks, &["x"], 0);
7410            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
7411            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
7412        }
7413        // Third-party statuses never change the review decision, even at budget.
7414        for comments in [0, 1] {
7415            for round in [0, 4] {
7416                let absent = decide_with(
7417                    &pr(Checks::Unknown, &[], comments),
7418                    round,
7419                    4,
7420                    CHECKS_GRACE,
7421                    Absent,
7422                );
7423                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
7424                    assert_eq!(
7425                        decide_with(
7426                            &pr(checks, &["third-party"], comments),
7427                            round,
7428                            4,
7429                            Duration::ZERO,
7430                            Absent
7431                        ),
7432                        absent
7433                    );
7434                }
7435                if comments != 0 {
7436                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
7437                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
7438                }
7439            }
7440        }
7441        let empty = pr(Checks::Unknown, &[], 0);
7442        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
7443            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
7444        }
7445        assert_eq!(
7446            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
7447            Step::Wait
7448        );
7449        assert_eq!(
7450            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
7451            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
7452        );
7453        // A conflict is not a check: it still wants the rebase.
7454        let mut p = pr(Checks::Unknown, &[], 0);
7455        p.blocking = Blocking::Conflict;
7456        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
7457        // And a pull request that left our hands is still done.
7458        p.state = PrLifecycle::Merged;
7459        assert_eq!(
7460            decide_with(&p, 0, 4, Duration::ZERO, Absent),
7461            Step::Done { merged: true }
7462        );
7463    }
7464
7465    #[test]
7466    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
7467        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
7468        assert_eq!(state.number, 10);
7469        assert_eq!(state.state, PrLifecycle::Open);
7470        assert_eq!(state.checks, Checks::Green);
7471        assert!(state.failing.is_empty());
7472        assert!(
7473            state.review_comments.is_empty(),
7474            "the only comment is CodeRabbit's trigger notice: {:?}",
7475            state.review_comments
7476        );
7477        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
7478    }
7479
7480    #[test]
7481    fn a_failing_check_parses_as_red_and_is_named() {
7482        let state = parse_pr(RED_OPEN).expect("red fixture parses");
7483        assert_eq!(state.checks, Checks::Red);
7484        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
7485        // The captured payload says `UNSTABLE` - mergeable, with a check
7486        // nobody requires red - which is exactly the shape that had to be
7487        // merged by hand. Asserted separately, in
7488        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
7489        // test is about is that a red check is *named*, so the reason a fixer
7490        // is handed says which one; so it asks the blocking question here.
7491        let mut blocking = state.clone();
7492        blocking.blocking = Blocking::Yes;
7493        match decide(&blocking, 0, 4, Duration::ZERO) {
7494            Step::Fix { reason } => {
7495                assert!(reason.contains("editorconfig"), "reason: {reason}");
7496                assert!(reason.contains("failing"), "reason: {reason}");
7497            }
7498            other => panic!("expected a fix round, got {other:?}"),
7499        }
7500    }
7501
7502    #[test]
7503    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
7504        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
7505        assert_eq!(state.checks, Checks::Pending);
7506        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
7507    }
7508
7509    #[test]
7510    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
7511        let state = parse_pr(MERGED).expect("merged fixture parses");
7512        assert_eq!(state.state, PrLifecycle::Merged);
7513        assert_eq!(
7514            decide(&state, 0, 4, Duration::ZERO),
7515            Step::Done { merged: true }
7516        );
7517    }
7518
7519    #[test]
7520    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
7521        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
7522        assert_eq!(state.checks, Checks::Green);
7523        let authors: Vec<&str> = state
7524            .review_comments
7525            .iter()
7526            .map(|c| c.author.as_str())
7527            .collect();
7528        assert_eq!(
7529            authors,
7530            vec!["claude"],
7531            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
7532        );
7533        match decide(&state, 0, 4, Duration::ZERO) {
7534            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
7535            other => panic!("expected a fix round, got {other:?}"),
7536        }
7537    }
7538
7539    #[test]
7540    fn inline_review_comments_keep_their_file_and_line() {
7541        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
7542        assert_eq!(comments.len(), 1);
7543        assert_eq!(comments[0].author, "claude[bot]");
7544        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
7545        assert_eq!(comments[0].line, Some(231));
7546        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
7547    }
7548
7549    #[test]
7550    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
7551        assert!(
7552            is_noise(CODERABBIT_TRIGGER),
7553            "CodeRabbit's trigger notice declares itself not a review"
7554        );
7555        assert!(
7556            is_noise(CLAUDE_CHECKLIST),
7557            "a progress checklist asks for nothing"
7558        );
7559        assert!(
7560            !is_noise(CLAUDE_FINDING),
7561            "a review that names a bug is input, not noise"
7562        );
7563
7564        let mut clean = pr(Checks::Green, &[], 0);
7565        clean.review_comments.push(ReviewComment {
7566            author: "coderabbitai".to_owned(),
7567            path: None,
7568            line: None,
7569            body: CODERABBIT_TRIGGER.to_owned(),
7570        });
7571        clean.review_comments.retain(|c| !is_noise(&c.body));
7572        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
7573
7574        let mut found = pr(Checks::Green, &[], 0);
7575        found.review_comments.push(ReviewComment {
7576            author: "claude".to_owned(),
7577            path: None,
7578            line: None,
7579            body: CLAUDE_FINDING.to_owned(),
7580        });
7581        found.review_comments.retain(|c| !is_noise(&c.body));
7582        assert!(matches!(
7583            decide(&found, 0, 4, Duration::ZERO),
7584            Step::Fix { .. }
7585        ));
7586    }
7587
7588    #[test]
7589    fn the_policy_table_holds_for_every_combination_that_matters() {
7590        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
7591            (
7592                "pending checks are waited for, even on the last round",
7593                pr(Checks::Pending, &[], 0),
7594                4,
7595                4,
7596                Duration::ZERO,
7597                Step::Wait,
7598            ),
7599            (
7600                "red checks are fixed",
7601                pr(Checks::Red, &["editorconfig"], 0),
7602                0,
7603                4,
7604                Duration::ZERO,
7605                Step::Fix {
7606                    reason: "1 check(s) failing: editorconfig".to_owned(),
7607                },
7608            ),
7609            (
7610                "green with comments is fixed, not merged",
7611                pr(Checks::Green, &[], 2),
7612                1,
7613                4,
7614                Duration::ZERO,
7615                Step::Fix {
7616                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
7617                        .to_owned(),
7618                },
7619            ),
7620            (
7621                "green and clean merges",
7622                pr(Checks::Green, &[], 0),
7623                3,
7624                4,
7625                Duration::ZERO,
7626                Step::Merge,
7627            ),
7628            (
7629                "an unreadable rollup is waited on while the grace lasts",
7630                pr(Checks::Unknown, &[], 0),
7631                0,
7632                4,
7633                Duration::ZERO,
7634                Step::Wait,
7635            ),
7636            (
7637                "an unreadable rollup is never merged once the grace is spent",
7638                pr(Checks::Unknown, &[], 0),
7639                0,
7640                4,
7641                CHECKS_GRACE,
7642                Step::GiveUp {
7643                    reason: "no check status is readable on the pull request after 3 minute(s); \
7644                             refusing to merge on a guess"
7645                        .to_owned(),
7646                },
7647            ),
7648        ];
7649        for (what, state, round, budget, waited, want) in cases {
7650            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
7651        }
7652    }
7653
7654    #[test]
7655    fn the_forge_verdict_survives_the_round_trip_from_gh() {
7656        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
7657        // requested but never parsed is the kind of thing that looks wired up
7658        // and answers `Unsaid` forever.
7659        let green = parse_pr(GREEN_OPEN).expect("parse");
7660        assert_eq!(green.blocking, Blocking::No);
7661        let red = parse_pr(RED_OPEN).expect("parse");
7662        assert_eq!(
7663            red.blocking,
7664            Blocking::No,
7665            "`UNSTABLE` is mergeable: the red check is one nobody requires"
7666        );
7667        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
7668        // A payload from an older `gh` has no such field at all.
7669        let quiet =
7670            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
7671        assert_eq!(quiet.blocking, Blocking::Unsaid);
7672    }
7673
7674    #[test]
7675    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
7676        // Pull request 37's only red check was `editorconfig`, failing
7677        // because the action could not fetch its own binary after
7678        // editorconfig-checker v4 renamed its release assets. The repository
7679        // does not require it. magi answered by asking a fixer to repair a
7680        // change that was fine, and the pull request had to be merged by hand.
7681        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7682        nonblocking.blocking = Blocking::No;
7683        assert_eq!(
7684            decide(&nonblocking, 0, 4, Duration::ZERO),
7685            Step::Merge,
7686            "the forge says nothing is in the way, so nothing is"
7687        );
7688
7689        // The same red, gated on: that is a fix round, as before.
7690        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7691        blocking.blocking = Blocking::Yes;
7692        assert!(matches!(
7693            decide(&blocking, 0, 4, Duration::ZERO),
7694            Step::Fix { .. }
7695        ));
7696
7697        // A review comment still outranks green-enough: a non-required red
7698        // must not become a way to merge past an unanswered reviewer.
7699        let mut commented = pr(Checks::Red, &["coverage"], 1);
7700        commented.blocking = Blocking::No;
7701        assert!(matches!(
7702            decide(&commented, 0, 4, Duration::ZERO),
7703            Step::Fix { .. }
7704        ));
7705
7706        // And silence from the forge is not consent.
7707        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7708        unsaid.blocking = Blocking::Unsaid;
7709        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7710        assert!(matches!(
7711            decide(&unsaid, 0, 4, CHECKS_GRACE),
7712            Step::Fix { .. }
7713        ));
7714    }
7715
7716    #[test]
7717    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7718        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7719        red.blocking = Blocking::No;
7720        assert_eq!(
7721            decide(&red, 0, 4, Duration::ZERO),
7722            Step::Merge,
7723            "announcing must not change the decision"
7724        );
7725        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7726        assert!(said.contains("yukimemi/magi"), "{said}");
7727        assert!(said.contains("#16"), "{said}");
7728        assert!(
7729            said.contains("https://github.com/yukimemi/magi/pull/16"),
7730            "{said}"
7731        );
7732        assert!(
7733            said.contains("test (windows-latest)") && said.contains("coverage"),
7734            "{said}"
7735        );
7736
7737        // `failing` can be left over on a green observation; only `checks` counts.
7738        let green = pr(Checks::Green, &["stale"], 0);
7739        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7740    }
7741
7742    #[test]
7743    fn red_merge_notices_omit_empty_check_details() {
7744        for checks in [vec![], vec!["", "  "]] {
7745            let red = pr(Checks::Red, &checks, 0);
7746            let summary = red_merge_summary("owner/repo", &red).unwrap();
7747            let notice = crate::notices::merged_red("run-1", &summary);
7748            assert_eq!(
7749                notice.message,
7750                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7751            );
7752            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7753        }
7754        let red = pr(Checks::Red, &["", " test ", " "], 0);
7755        let summary = red_merge_summary("owner/repo", &red).unwrap();
7756        assert!(summary.contains("with red checks: test ("), "{summary}");
7757    }
7758
7759    #[test]
7760    fn the_repo_label_comes_from_the_pull_request_url() {
7761        let p = Path::new("/tmp/checkout");
7762        assert_eq!(
7763            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7764            "yukimemi/magi"
7765        );
7766        assert_eq!(repo_label(p, "not a url"), "checkout");
7767    }
7768
7769    #[test]
7770    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7771        // Pull requests 35 and 37 were both rebased by hand: a competition
7772        // that runs for two hours against a repository merging pull requests
7773        // all day conflicts on the way in, and that is arithmetic rather
7774        // than a defect in the change.
7775        let mut conflicted = pr(Checks::Green, &[], 0);
7776        conflicted.blocking = Blocking::Conflict;
7777        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7778
7779        // Decided before the checks, and even with the rounds spent: every
7780        // check on a branch that cannot land is an answer about a state that
7781        // cannot land, and a conflict is not the change's fault.
7782        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7783        red.blocking = Blocking::Conflict;
7784        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7785
7786        // The lifecycle still wins over everything, conflict included.
7787        let mut merged = pr(Checks::Red, &[], 0);
7788        merged.blocking = Blocking::Conflict;
7789        merged.state = PrLifecycle::Merged;
7790        assert_eq!(
7791            decide(&merged, 0, 4, Duration::ZERO),
7792            Step::Done { merged: true }
7793        );
7794    }
7795
7796    #[test]
7797    fn the_forge_verdict_is_read_off_merge_state_status() {
7798        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7799        // matters: mergeable, with a non-required check red or still running.
7800        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7801            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7802            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7803        }
7804        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7805        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7806        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7807        // An older `gh`, or a token without the scope, says nothing - and
7808        // refusing to guess is the rule everywhere else in this module.
7809        for quiet in ["", "UNKNOWN"] {
7810            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7811            assert!(Blocking::of(quiet).stops_a_merge());
7812        }
7813    }
7814
7815    #[test]
7816    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7817        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7818        // The exact stderr from run ec12, in a jj-colocated repository.
7819        let jj = "could not determine current branch: failed to run git: not on any branch";
7820
7821        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7822            .expect("the forge says merged, so it merged");
7823        assert!(landed.ok);
7824        assert!(
7825            landed.detail.contains("but the pull request is merged"),
7826            "the record must not read as a clean success: {}",
7827            landed.detail
7828        );
7829        assert!(
7830            landed.detail.contains("not on any branch"),
7831            "and it must keep what the command actually said: {}",
7832            landed.detail
7833        );
7834
7835        // A pull request still open means the merge really failed.
7836        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7837        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7838        // And an unreadable answer is not evidence of success.
7839        assert!(merged_after_all(&argv, jj, None).is_none());
7840    }
7841
7842    #[test]
7843    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7844        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7845        state.state = PrLifecycle::Closed;
7846        assert_eq!(
7847            decide(&state, 0, 4, Duration::ZERO),
7848            Step::Done { merged: false },
7849            "a human closing the pull request ends the loop, whatever CI says"
7850        );
7851    }
7852
7853    #[test]
7854    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7855        let red = decide(
7856            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7857            4,
7858            4,
7859            Duration::ZERO,
7860        );
7861        match red {
7862            Step::GiveUp { reason } => {
7863                assert!(reason.contains("editorconfig"), "reason: {reason}");
7864                assert!(reason.contains("test (macos)"), "reason: {reason}");
7865                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7866            }
7867            other => panic!("expected a give-up, got {other:?}"),
7868        }
7869
7870        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7871        match commented {
7872            Step::GiveUp { reason } => {
7873                assert!(reason.contains("unresolved"), "reason: {reason}");
7874                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7875            }
7876            other => panic!("expected a give-up, got {other:?}"),
7877        }
7878    }
7879
7880    #[test]
7881    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7882        let candidate_commit = "magi: candidate A (uncommitted work)";
7883        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7884        let argv = merge_argv(16, &subject);
7885
7886        assert!(argv.contains(&"--squash".to_owned()));
7887        assert!(argv.contains(&"--delete-branch".to_owned()));
7888        assert!(argv.contains(&"--subject".to_owned()));
7889        assert_eq!(
7890            argv.last().map(String::as_str),
7891            Some("add retries to the uploader"),
7892            "the subject must not be the candidate commit message"
7893        );
7894        assert_ne!(subject, candidate_commit);
7895    }
7896
7897    #[test]
7898    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7899        assert_eq!(
7900            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7901            "feat: a queue, an unattended loop, and a phone UI"
7902        );
7903        assert_eq!(
7904            merge_subject("", "# port the retry logic\n\ndetails"),
7905            "port the retry logic",
7906            "an empty title falls back to the task's first line, heading marks stripped"
7907        );
7908    }
7909
7910    #[test]
7911    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7912        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7913        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7914        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7915        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7916        assert_eq!(run_of(""), None);
7917    }
7918
7919    #[test]
7920    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7921        let mut out = Vec::new();
7922        push_if_outstanding(
7923            &mut out,
7924            ReviewComment {
7925                author: "yukimemi".to_owned(),
7926                path: None,
7927                line: None,
7928                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7929            },
7930        );
7931        assert!(out.is_empty());
7932    }
7933
7934    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7935    /// falls back to the repository - which keeps these tests free of a
7936    /// worktree, a `git` invocation and a network.
7937    fn run_state() -> RunState {
7938        let mut state = RunState::new(
7939            std::path::PathBuf::from("/repo/magi"),
7940            "main".to_owned(),
7941            "abcdef1234".to_owned(),
7942            "add retries to the uploader".to_owned(),
7943            crate::config::Config::default(),
7944        );
7945        // These fixtures test execution flow, independent of host disk capacity.
7946        state.config.disk.min_free_bytes = 0;
7947        // Tests run in parallel against one persistent home and the ids
7948        // `RunState::new` draws from the clock can repeat, so two tests would
7949        // share a run's questions. The home also outlives the process, so the
7950        // counter alone would reuse an earlier run's ids.
7951        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7952        let nanos = std::time::SystemTime::now()
7953            .duration_since(std::time::UNIX_EPOCH)
7954            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7955        state.id = format!(
7956            "20261004-{nanos:06}-{:04x}",
7957            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7958        );
7959        state
7960    }
7961
7962    fn green_pr() -> PrState {
7963        PrState {
7964            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7965            number: 42,
7966            state: PrLifecycle::Open,
7967            checks: Checks::Green,
7968            // The forge sees nothing in the way unless a test says otherwise.
7969            blocking: Blocking::No,
7970            failing: Vec::new(),
7971            review_comments: vec![ReviewComment {
7972                author: "coderabbitai".to_owned(),
7973                path: Some("src/land.rs".to_owned()),
7974                line: Some(212),
7975                body: "this branch never checks the exit code".to_owned(),
7976            }],
7977        }
7978    }
7979
7980    #[test]
7981    fn land_fixer_defers_review_and_verification_without_a_cache() {
7982        let state = run_state();
7983        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7984        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7985        assert!(p.contains("Commit in this worktree"), "{p}");
7986    }
7987
7988    #[test]
7989    fn github_facing_land_text_is_english_whatever_the_language() {
7990        let mut state = run_state();
7991        state.config.graph.language = "ja".to_owned();
7992        let comment = stop_comment(&state.id, "checks are still red");
7993        assert!(crate::github_text::check("", &comment).is_empty());
7994        assert!(comment.is_ascii(), "{comment}");
7995        assert!(comment.starts_with(MARKER));
7996
7997        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7998        let ja_at = p.find("Write all prose in ja").unwrap();
7999        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
8000        assert!(ja_at < rule_at, "{p}");
8001        assert!(p.contains("stays in Japanese"), "{p}");
8002
8003        state.config.graph.language = "en".to_owned();
8004        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
8005        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
8006        assert!(!p.contains("does not apply"), "{p}");
8007    }
8008
8009    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
8010
8011    fn panel() -> String {
8012        approval_panel(
8013            &run_state(),
8014            &green_pr(),
8015            NUMSTAT,
8016            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
8017            &[
8018                "land: ask before merging".to_owned(),
8019                "land: colour the diff".to_owned(),
8020            ],
8021            "feat: merge approval from the phone",
8022        )
8023    }
8024
8025    #[test]
8026    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
8027        let html = panel();
8028        for needle in [
8029            "42",
8030            "main",
8031            "src/land.rs",
8032            "src/web.rs",
8033            "assets/logo.png",
8034            "feat: merge approval from the phone",
8035            "land: ask before merging",
8036            "land: colour the diff",
8037            "coderabbitai",
8038            "this branch never checks the exit code",
8039            "green",
8040        ] {
8041            assert!(html.contains(needle), "the panel must state `{needle}`");
8042        }
8043    }
8044
8045    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
8046        crate::run::pin_test_home();
8047        let tmp = tempfile::tempdir().unwrap();
8048        let repo = tmp.path().join("repo");
8049        let remote = tmp.path().join("remote.git");
8050        std::fs::create_dir(&repo).unwrap();
8051        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
8052            .await
8053            .unwrap();
8054        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
8055        git::git(&repo, &["config", "user.name", "Test"])
8056            .await
8057            .unwrap();
8058        git::git(&repo, &["config", "user.email", "test@example.test"])
8059            .await
8060            .unwrap();
8061        std::fs::write(repo.join("base"), "base").unwrap();
8062        git::git(&repo, &["add", "."]).await.unwrap();
8063        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
8064        git::git(
8065            &repo,
8066            &["remote", "add", "origin", remote.to_str().unwrap()],
8067        )
8068        .await
8069        .unwrap();
8070        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
8071        git::git(&repo, &["checkout", "-b", "winner"])
8072            .await
8073            .unwrap();
8074        std::fs::write(repo.join("change"), "change").unwrap();
8075        git::git(&repo, &["add", "."]).await.unwrap();
8076        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
8077        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
8078        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
8079            .await
8080            .unwrap();
8081        let mut state = run_state();
8082        state.repo = repo.clone();
8083        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
8084        state.config.graph.land = true;
8085        state.config.graph.land_approval = true;
8086        state.pr_head = Some("task-head".into());
8087        state.pr_pushed_head = Some(head.clone());
8088        state.candidates = vec![winning_candidate("change")];
8089        state.candidates[0].worktree = repo;
8090        state.candidates[0].branch = "winner".into();
8091        state.tally = Some(uncontested_tally());
8092        state.gate_ran = true;
8093        state.gate_head = Some(head.clone());
8094        state.land_sync_pending = true;
8095        state.save().unwrap();
8096        (tmp, state, head)
8097    }
8098
8099    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
8100        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
8101        resume_landing_head(state, head, &green_pr().url, &forge, None).await
8102    }
8103
8104    async fn advance_landing_base(state: &RunState) {
8105        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8106        std::fs::write(state.repo.join("advance"), "advance").unwrap();
8107        git::git(&state.repo, &["add", "."]).await.unwrap();
8108        git::git(&state.repo, &["commit", "-m", "advance base"])
8109            .await
8110            .unwrap();
8111        git::git(&state.repo, &["push", "origin", "main"])
8112            .await
8113            .unwrap();
8114        git::git(&state.repo, &["checkout", "winner"])
8115            .await
8116            .unwrap();
8117    }
8118
8119    #[tokio::test]
8120    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
8121        let (_tmp, mut state, head) = landing_git_fixture().await;
8122        advance_landing_base(&state).await;
8123        let scratch = state.dir().join("rebase");
8124        std::fs::create_dir_all(&scratch).unwrap();
8125        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
8126        let attempts = state.land_sync_attempts;
8127        let error = rebase_landing_worktree(&mut state, "origin/main")
8128            .await
8129            .unwrap_err();
8130        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8131        assert_eq!(state.land_sync_attempts, attempts);
8132        assert!(state.land_sync_target.is_none());
8133        assert!(state.rebase_fixes.is_empty());
8134        assert!(
8135            state
8136                .base_sync
8137                .as_ref()
8138                .is_none_or(|sync| sync.conflict.is_none())
8139        );
8140        let block = state.resource_block.as_ref().unwrap();
8141        assert_eq!(block.kind, crate::rebase::SEQUENCER_INFRASTRUCTURE);
8142        assert!(
8143            block.detail.contains("inspect scratch Git backlink"),
8144            "{}",
8145            block.detail
8146        );
8147        assert_eq!(
8148            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
8149            "keep"
8150        );
8151        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
8152        std::fs::remove_dir_all(&scratch).unwrap();
8153        state.resource_block = None;
8154        assert_eq!(
8155            rebase_landing_worktree(&mut state, "origin/main")
8156                .await
8157                .unwrap(),
8158            crate::rebase::Rebased::Applied
8159        );
8160        assert_eq!(state.land_sync_attempts, attempts + 1);
8161        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
8162        assert!(git::is_clean(&state.repo).await.unwrap());
8163        assert!(state.rebase_fixes.is_empty());
8164    }
8165
8166    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
8167    {
8168        let (tmp, mut state, old) = landing_git_fixture().await;
8169        let path = tmp.path().join("foreign");
8170        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
8171            .await
8172            .unwrap();
8173        state.foreign_checkout = Some(
8174            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
8175                .await
8176                .unwrap(),
8177        );
8178        state.config.merge.mode = crate::config::MergeMode::Pr;
8179        state.save().unwrap();
8180        (tmp, state, old, path)
8181    }
8182
8183    #[tokio::test]
8184    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
8185        for phase in 0..4 {
8186            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
8187            advance_landing_base(&state).await;
8188            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
8189            if phase == 0 {
8190                // The live Step::Rebase path uses this same synchronization
8191                // and publication pair, without going through resume.
8192                assert_eq!(
8193                    rebase_landing_worktree(&mut state, "origin/main")
8194                        .await
8195                        .unwrap(),
8196                    crate::rebase::Rebased::Applied
8197                );
8198            } else {
8199                interrupt_landing_rebase(&mut state).await;
8200                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
8201                if phase == 2 {
8202                    git::sync_to_head(&state.repo).await.unwrap();
8203                } else if phase == 3 {
8204                    // Crash after joining history, before clearing its saved
8205                    // start. Repeating restoration must not add another merge.
8206                    restore_landing_worktree(&mut state, None).await.unwrap();
8207                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8208                    state.land_rebase_from = Some(old.clone());
8209                    state.save().unwrap();
8210                    restore_landing_worktree(&mut state, None).await.unwrap();
8211                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
8212                }
8213                state.save().unwrap();
8214                state = RunState::load(&state.id).unwrap();
8215                restore_landing_worktree(&mut state, None).await.unwrap();
8216                assert_eq!(
8217                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
8218                    repaired_tree
8219                );
8220            }
8221            let head = if phase == 0 {
8222                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
8223                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
8224                    .await
8225                    .unwrap()
8226            } else {
8227                resume_observed_head(&mut state, &old).await.unwrap()
8228            };
8229            assert!(git::is_ancestor(&state.repo, &old, &head).await);
8230            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
8231            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
8232            assert_eq!(
8233                git::remote_head(&state.repo, "origin", "task-head")
8234                    .await
8235                    .unwrap(),
8236                Some(head.clone())
8237            );
8238            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8239            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
8240            assert!(state.gate_allows_progress());
8241            assert!(state.land_rebase_from.is_none());
8242            assert!(!state.land_sync_pending);
8243            assert!(git::is_clean(&path).await.unwrap());
8244        }
8245    }
8246
8247    #[tokio::test]
8248    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
8249        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
8250        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8251        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8252        git::commit_all(&state.repo, "conflicting base")
8253            .await
8254            .unwrap();
8255        git::git(&state.repo, &["push", "origin", "main"])
8256            .await
8257            .unwrap();
8258        git::git(&state.repo, &["checkout", "winner"])
8259            .await
8260            .unwrap();
8261        landing_gate_fixer(
8262            &mut state,
8263            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
8264        );
8265        state.config.graph.gate_fix_rounds = 0;
8266        state.config.verify.gate = vec!["exit 1".into()];
8267        assert!(resume_observed_head(&mut state, &old).await.is_err());
8268        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
8269        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8270        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
8271        assert_eq!(
8272            std::fs::read_to_string(state.repo.join("change")).unwrap(),
8273            "resolved"
8274        );
8275        // A red gate must neither deliver nor publish the repaired tree.
8276        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
8277        assert_eq!(
8278            git::remote_head(&state.repo, "origin", "task-head")
8279                .await
8280                .unwrap(),
8281            Some(old.clone())
8282        );
8283        state = RunState::load(&state.id).unwrap();
8284        state.config.verify.gate = vec!["grep -q resolved change".into()];
8285        let head = resume_observed_head(&mut state, &old).await.unwrap();
8286        assert_eq!(head, repaired);
8287        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
8288        assert_eq!(
8289            std::fs::read_to_string(path.join("change")).unwrap(),
8290            "resolved"
8291        );
8292        assert_eq!(
8293            git::remote_head(&state.repo, "origin", "task-head")
8294                .await
8295                .unwrap(),
8296            Some(head.clone())
8297        );
8298        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8299        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
8300        assert!(git::is_clean(&path).await.unwrap());
8301    }
8302
8303    #[tokio::test]
8304    async fn landing_resume_completes_the_last_charged_sync_attempt() {
8305        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
8306            let (_tmp, mut state, old) = landing_git_fixture().await;
8307            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8308            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8309            git::commit_all(&state.repo, "conflicting base")
8310                .await
8311                .unwrap();
8312            git::git(&state.repo, &["push", "origin", "main"])
8313                .await
8314                .unwrap();
8315            git::git(&state.repo, &["checkout", "winner"])
8316                .await
8317                .unwrap();
8318            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
8319            state.config.graph.land_rounds = 1;
8320            state.land_sync_attempts = 1;
8321            state.land_sync_target = saved_target.then(|| target.clone());
8322            state.land_rebase_from = Some(old.clone());
8323            landing_gate_fixer(
8324                &mut state,
8325                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
8326            );
8327            state.config.verify.gate = vec!["grep -q resolved change".into()];
8328            state.save().unwrap();
8329            // Simulate interruption before the scratch start and at a conflict.
8330            if scratch_started {
8331                assert!(matches!(
8332                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
8333                        .await
8334                        .unwrap(),
8335                    git::RebaseStart::Conflicted(_)
8336                ));
8337            }
8338            state = RunState::load(&state.id).unwrap();
8339            let head = resume_observed_head(&mut state, &old).await.unwrap();
8340            assert_ne!(head, old);
8341            assert_eq!(state.land_sync_attempts, 1);
8342            assert!(state.land_sync_target.is_none());
8343            assert!(state.land_rebase_from.is_none());
8344            assert!(!state.land_sync_pending);
8345            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8346            assert!(state.gate_allows_progress());
8347            assert_eq!(
8348                git::remote_head(&state.repo, "origin", "task-head")
8349                    .await
8350                    .unwrap(),
8351                Some(head)
8352            );
8353            assert!(
8354                rebase_landing_worktree(&mut state, "origin/main")
8355                    .await
8356                    .unwrap_err()
8357                    .to_string()
8358                    .contains("budget exhausted")
8359            );
8360        }
8361    }
8362
8363    #[tokio::test]
8364    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
8365        let (_tmp, mut state, old) = landing_git_fixture().await;
8366        advance_landing_base(&state).await;
8367        state.config.verify.gate = vec!["test -f advance".into()];
8368        let head = resume_observed_head(&mut state, &old).await.unwrap();
8369        assert_ne!(head, old);
8370        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8371        assert!(state.gate_allows_progress());
8372        assert_eq!(
8373            git::remote_head(&state.repo, "origin", "task-head")
8374                .await
8375                .unwrap(),
8376            Some(head.clone())
8377        );
8378        assert_eq!(state.pr_pushed_head, Some(head));
8379        assert!(!state.land_sync_pending);
8380        assert!(state.config.graph.land_approval);
8381    }
8382
8383    fn landing_gate_fixer(state: &mut RunState, script: &str) {
8384        state.config.disk.min_free_bytes = 0;
8385        state.config.graph.gate_fix_rounds = 1;
8386        state.config.agents = vec![crate::config::AgentSpec {
8387            id: "mock".into(),
8388            kind: crate::config::AgentKind::Command,
8389            model: None,
8390            command: vec!["sh".into(), "-c".into(), script.into()],
8391            extra_args: Vec::new(),
8392            env: Default::default(),
8393            prompt_delivery: None,
8394            max_turn_secs: None,
8395        }];
8396        state.candidates[0].agent = "mock".into();
8397    }
8398
8399    #[tokio::test]
8400    async fn rebase_fixer_invocation_cap_survives_fallback_and_reload() {
8401        let (tmp, mut state, original) = landing_git_fixture().await;
8402        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8403        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8404        git::commit_all(&state.repo, "conflicting base")
8405            .await
8406            .unwrap();
8407        let target = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8408        git::git(&state.repo, &["checkout", "winner"])
8409            .await
8410            .unwrap();
8411        let scratch = state.dir().join("rebase");
8412        let counter = tmp.path().join("calls");
8413        landing_gate_fixer(
8414            &mut state,
8415            "echo \"$REBASE_AGENT\" >> \"$REBASE_COUNTER\"; exit 1",
8416        );
8417        let template = state.config.agents[0].clone();
8418        let ids = ["mock", "fallback1", "fallback2", "fallback3"].map(str::to_owned);
8419        state.config.agents = ids
8420            .iter()
8421            .map(|id| {
8422                let mut spec = template.clone();
8423                spec.id.clone_from(id);
8424                spec.env.insert("REBASE_AGENT".into(), id.clone());
8425                spec.env
8426                    .insert("REBASE_COUNTER".into(), git::path_arg(&counter));
8427                spec
8428            })
8429            .collect();
8430        state.config.roles.fixer = Some(crate::config::AgentChoice::Chain(ids.to_vec()));
8431        state.config.graph.review_rounds = 3;
8432        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8433        state.config.graph.timeout_resource_wait = 0;
8434        let started = git::rebase_start(&state.repo, &scratch, "winner", &target)
8435            .await
8436            .unwrap();
8437        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
8438        let home = crate::run::home();
8439        let cache = crate::build_target::resolve(&home, &scratch).unwrap();
8440        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", &scratch, &original);
8441        let crate::cache::AcquireOutcome::Acquired(lease) =
8442            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
8443        else {
8444            panic!("test target was already leased");
8445        };
8446        let error = crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8447            .await
8448            .unwrap_err();
8449        assert!(error.is::<crate::agent::IsolatedSeatWait>(), "{error:#}");
8450        assert!(!counter.exists());
8451        assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), ["change"]);
8452        drop(lease);
8453        state = RunState::load(&state.id).unwrap();
8454        for _ in 0..2 {
8455            let crate::rebase::Rebased::Stopped(why) =
8456                crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8457                    .await
8458                    .unwrap()
8459            else {
8460                panic!("the unresolved conflict must stop");
8461            };
8462            assert!(why.contains("after 3 of 3 fixer round(s)"), "{why}");
8463            assert_eq!(
8464                std::fs::read_to_string(&counter)
8465                    .unwrap()
8466                    .lines()
8467                    .collect::<Vec<_>>(),
8468                ["mock", "fallback1", "fallback2"]
8469            );
8470            assert_eq!(
8471                git::rev_parse(&state.repo, "winner").await.unwrap(),
8472                original
8473            );
8474            state = RunState::load(&state.id).unwrap();
8475        }
8476    }
8477
8478    #[tokio::test]
8479    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
8480        let (_tmp, mut state, old) = landing_git_fixture().await;
8481        std::fs::write(state.repo.join("change"), "operator update").unwrap();
8482        git::commit_all(&state.repo, "extend winner").await.unwrap();
8483        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8484        git::git(
8485            &state.repo,
8486            &["push", "origin", "HEAD:refs/heads/task-head"],
8487        )
8488        .await
8489        .unwrap();
8490        state.config.verify.gate = vec!["exit 1".into()];
8491        state.config.graph.gate_fix_rounds = 0;
8492        assert!(resume_observed_head(&mut state, &updated).await.is_err());
8493        assert_ne!(old, updated);
8494        assert_eq!(state.gate_head.as_ref(), Some(&updated));
8495        assert!(!state.gate_allows_progress());
8496        assert!(state.land_sync_pending);
8497        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
8498        let head = resume_observed_head(&mut state, &updated).await.unwrap();
8499        assert_eq!(head, updated);
8500        assert!(state.gate_allows_progress());
8501        assert!(!state.land_sync_pending);
8502        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8503        land_with(&mut state, &green_pr().url, &forge)
8504            .await
8505            .unwrap();
8506        assert!(state.parked);
8507        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8508        assert!(forge.argvs().is_empty());
8509    }
8510
8511    #[tokio::test]
8512    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
8513        for divergent in [false, true] {
8514            let (_tmp, mut state, old) = landing_git_fixture().await;
8515            if divergent {
8516                git::git(&state.repo, &["reset", "--hard", "origin/main"])
8517                    .await
8518                    .unwrap();
8519            }
8520            std::fs::write(state.repo.join("external"), "external").unwrap();
8521            git::commit_all(&state.repo, "external update")
8522                .await
8523                .unwrap();
8524            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8525            git::git(
8526                &state.repo,
8527                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
8528            )
8529            .await
8530            .unwrap();
8531            if !divergent {
8532                git::git(&state.repo, &["reset", "--hard", &old])
8533                    .await
8534                    .unwrap();
8535            }
8536            let error = resume_observed_head(&mut state, &external)
8537                .await
8538                .unwrap_err();
8539            assert!(
8540                error
8541                    .to_string()
8542                    .contains("public head moved outside this run")
8543            );
8544            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
8545            assert_eq!(
8546                git::remote_head(&state.repo, "origin", "task-head")
8547                    .await
8548                    .unwrap(),
8549                Some(external)
8550            );
8551        }
8552    }
8553
8554    #[test]
8555    fn fixer_prompt_carries_the_adopted_instruction_not_the_obsolete_one() {
8556        let mut state = repair_state(true, true);
8557        state.reviews[0].reviews[0].findings[0].detail = "require teravars 0.7.0".into();
8558        state.instruction = "use teravars 0.7.0".into();
8559        crate::instruction_revision_control::adopt_into_run(
8560            &mut state,
8561            "cli/r",
8562            "instruction-cli-r",
8563            "use teravars 0.8.0",
8564            1,
8565            "h",
8566            &green_pr().url,
8567        );
8568        state.merge_repairs[0].phase = crate::run::MergeRepairPhase::Fixing;
8569        let reason = merge_repair_reason(&state, &state.merge_repairs[0]).unwrap();
8570        let prompt = fix_prompt(&state, &green_pr(), 1, 4, &reason, "");
8571        assert!(prompt.contains("# The task\n\nuse teravars 0.8.0"));
8572        assert!(prompt.contains("require teravars 0.7.0"));
8573        assert!(prompt.contains("evidence is historical, not a list of requirements"));
8574        assert!(prompt.contains("Implement the revised task"));
8575        assert!(!prompt.contains("Address the unresolved Major findings"));
8576        assert!(!prompt.contains("Change nothing the checks and the comments did not raise"));
8577    }
8578
8579    /// A repair publication leaves a checkpoint; a forge still showing the
8580    /// leased head is then this run's own lagging view, and nothing else is.
8581    #[tokio::test]
8582    async fn only_a_checkpointed_self_push_counts_as_a_lagging_observation() {
8583        let (_tmp, mut state, old) = landing_git_fixture().await;
8584        let repo = state.repo.clone();
8585        std::fs::write(repo.join("repair"), "repair").unwrap();
8586        git::git(&repo, &["add", "."]).await.unwrap();
8587        git::git(&repo, &["commit", "-m", "repair"]).await.unwrap();
8588        let new = git::rev_parse(&repo, "HEAD").await.unwrap();
8589        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
8590            .await
8591            .unwrap();
8592        state.pr_pushed_head = Some(new.clone());
8593        // Without the pre-push checkpoint the refusal path is untouched.
8594        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8595        state.pr_publication = Some(crate::run::PrPublication {
8596            previous: old.clone(),
8597            head: new.clone(),
8598            branch: "task-head".into(),
8599        });
8600        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8601        state.gate_head = Some(new.clone());
8602        assert!(lagging_self_publication(&state, &old).await.unwrap());
8603        state.gate_ran = false;
8604        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8605        state.gate_ran = true;
8606        std::fs::write(repo.join("dirty"), "unverified").unwrap();
8607        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8608        std::fs::remove_file(repo.join("dirty")).unwrap();
8609        // The new head itself is not stale, and a third commit never is.
8610        assert!(!lagging_self_publication(&state, &new).await.unwrap());
8611        assert!(
8612            !lagging_self_publication(&state, &"d".repeat(40))
8613                .await
8614                .unwrap()
8615        );
8616        // The saved lease must name the checkpointed commit.
8617        let mut unsaved = state.clone();
8618        unsaved.pr_pushed_head = Some(old.clone());
8619        assert!(!lagging_self_publication(&unsaved, &old).await.unwrap());
8620        let checkpoint = unsaved.pr_publication.clone().unwrap();
8621        assert!(
8622            repair_publication_observed(&unsaved, &checkpoint)
8623                .await
8624                .unwrap()
8625        );
8626        let mut other = checkpoint.clone();
8627        other.previous = "other lease".into();
8628        assert!(!repair_publication_observed(&unsaved, &other).await.unwrap());
8629        unsaved.pr_publication = None;
8630        assert!(
8631            !repair_publication_observed(&unsaved, &checkpoint)
8632                .await
8633                .unwrap()
8634        );
8635        unsaved.pr_publication = Some(checkpoint.clone());
8636        // A remote-only update after the push is not self-publication.
8637        git::git(&repo, &["commit", "--allow-empty", "-m", "external"])
8638            .await
8639            .unwrap();
8640        git::git(
8641            &repo,
8642            &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
8643        )
8644        .await
8645        .unwrap();
8646        git::git(&repo, &["reset", "--hard", &new]).await.unwrap();
8647        assert!(!lagging_self_publication(&state, &old).await.unwrap());
8648        assert!(
8649            !repair_publication_observed(&unsaved, &checkpoint)
8650                .await
8651                .unwrap()
8652        );
8653        // The existing refusal for a foreign head is retained.
8654        assert!(
8655            resume_observed_head(&mut state, &"d".repeat(40))
8656                .await
8657                .is_err()
8658        );
8659    }
8660
8661    #[tokio::test]
8662    async fn repair_publication_lag_binds_fresh_approval() {
8663        let (_tmp, mut state, old) = landing_git_fixture().await;
8664        advance_landing_base(&state).await;
8665        let new = resume_observed_head(&mut state, &old).await.unwrap();
8666        state.pr_publication = Some(crate::run::PrPublication {
8667            previous: old.clone(),
8668            head: new.clone(),
8669            branch: "task-head".into(),
8670        });
8671        state.land_sync_pending = true;
8672        state.save().unwrap();
8673        let mut state = RunState::load(&state.id).unwrap();
8674        let forge = Scripted::new(
8675            vec![
8676                seen(&old, Checks::Green, "CLEAN", false),
8677                seen(&new, Checks::Green, "CLEAN", false),
8678            ],
8679            vec![],
8680        );
8681        land_with(&mut state, &green_pr().url, &forge)
8682            .await
8683            .unwrap();
8684        assert!(forge.calls().contains(&"poll"));
8685        assert_eq!(state.land_approval.as_ref().unwrap().head, new);
8686        assert!(forge.argvs().is_empty());
8687    }
8688
8689    #[tokio::test]
8690    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
8691        let (_tmp, mut state, old) = landing_git_fixture().await;
8692        advance_landing_base(&state).await;
8693        landing_gate_fixer(
8694            &mut state,
8695            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8696        );
8697        state.config.verify.gate =
8698            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8699        state.config.verify.e2e = vec!["test -f advance".into()];
8700        // First save a red gate without spending a fixer round. Resume must
8701        // still offer the remaining budget for this exact same failed head.
8702        state.config.graph.gate_fix_rounds = 0;
8703        assert!(resume_observed_head(&mut state, &old).await.is_err());
8704        assert_eq!(
8705            git::remote_head(&state.repo, "origin", "task-head")
8706                .await
8707                .unwrap(),
8708            Some(old.clone())
8709        );
8710        state.config.graph.gate_fix_rounds = 1;
8711        let head = resume_observed_head(&mut state, &old).await.unwrap();
8712        assert_eq!(state.gate_fixes.len(), 1);
8713        assert!(state.gate_fixes[0].committed);
8714        assert!(state.gate_allows_progress());
8715        assert_eq!(state.gate_head.as_ref(), Some(&head));
8716        assert_eq!(
8717            git::remote_head(&state.repo, "origin", "task-head")
8718                .await
8719                .unwrap(),
8720            Some(head.clone())
8721        );
8722        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8723        land_with(&mut state, &green_pr().url, &forge)
8724            .await
8725            .unwrap();
8726        assert!(state.parked);
8727        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8728        assert!(forge.argvs().is_empty());
8729    }
8730
8731    #[tokio::test]
8732    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
8733        let (_tmp, mut state, old) = landing_git_fixture().await;
8734        advance_landing_base(&state).await;
8735        landing_gate_fixer(
8736            &mut state,
8737            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8738        );
8739        state.config.verify.gate = vec!["echo still red; exit 1".into()];
8740        for _ in 0..2 {
8741            assert!(resume_observed_head(&mut state, &old).await.is_err());
8742            assert_eq!(state.gate_fixes.len(), 1);
8743            assert_eq!(
8744                git::remote_head(&state.repo, "origin", "task-head")
8745                    .await
8746                    .unwrap(),
8747                Some(old.clone())
8748            );
8749        }
8750    }
8751
8752    #[tokio::test]
8753    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
8754        let (_tmp, mut state, old) = landing_git_fixture().await;
8755        advance_landing_base(&state).await;
8756        landing_gate_fixer(
8757            &mut state,
8758            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8759        );
8760        state.config.verify.gate =
8761            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8762        // The repair makes the gate green while breaking an e2e invariant.
8763        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
8764        let mut saved_comparison = None;
8765        for resume in 0..3 {
8766            assert!(resume_observed_head(&mut state, &old).await.is_err());
8767            state = RunState::load(&state.id).unwrap();
8768            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8769            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8770            assert_eq!(evidence.head, head);
8771            assert!(!evidence.passed);
8772            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
8773            let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
8774            if let Some(saved) = &saved_comparison {
8775                assert_eq!(comparison, saved);
8776            } else {
8777                saved_comparison = Some(comparison.clone());
8778            }
8779            assert_eq!(state.gate_fixes.len(), 1);
8780            assert_eq!(
8781                git::remote_head(&state.repo, "origin", "task-head")
8782                    .await
8783                    .unwrap(),
8784                Some(old.clone())
8785            );
8786            if resume > 0 {
8787                assert!(
8788                    state.gate_allows_progress(),
8789                    "a green gate must not bypass red e2e"
8790                );
8791            }
8792        }
8793        // A changed command is not new evidence about the already checked SHA.
8794        state.config.verify.e2e = vec!["grep -q fixed change".into()];
8795        assert!(resume_observed_head(&mut state, &old).await.is_err());
8796        assert_eq!(
8797            state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
8798            saved_comparison
8799        );
8800    }
8801
8802    #[tokio::test]
8803    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
8804        for phase in 0..3 {
8805            let (_tmp, mut state, old) = landing_git_fixture().await;
8806            advance_landing_base(&state).await;
8807            let head = resume_observed_head(&mut state, &old).await.unwrap();
8808            // Persist the shapes left by interruption, resource deferral,
8809            // and a successful check for a different (older) SHA.
8810            state.land_sync_pending = true;
8811            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
8812            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8813                if phase == 2 {
8814                    old.clone()
8815                } else {
8816                    head.clone()
8817                },
8818                phase == 2,
8819                if phase == 1 {
8820                    vec![crate::run::CommandOutcome {
8821                        command: state.config.verify.e2e[0].clone(),
8822                        code: None,
8823                        output_tail: "verification resource unavailable".into(),
8824                        duration_ms: 0,
8825                        resource_blocked: true,
8826                        ..Default::default()
8827                    }]
8828                } else {
8829                    Vec::new()
8830                },
8831            ));
8832            state.save().unwrap();
8833            for _ in 0..2 {
8834                state = RunState::load(&state.id).unwrap();
8835                assert!(resume_observed_head(&mut state, &head).await.is_err());
8836                let evidence = state.gate_repair_e2e.as_ref().unwrap();
8837                assert_eq!(evidence.head, head);
8838                assert!(!evidence.passed);
8839                assert!(!evidence.outcomes.is_empty());
8840                assert_eq!(
8841                    git::remote_head(&state.repo, "origin", "task-head")
8842                        .await
8843                        .unwrap(),
8844                    Some(head.clone())
8845                );
8846                assert!(state.land_sync_pending);
8847            }
8848        }
8849    }
8850
8851    #[tokio::test]
8852    async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
8853        for code in [None, Some(126), Some(127)] {
8854            let (_tmp, mut state, old) = landing_git_fixture().await;
8855            advance_landing_base(&state).await;
8856            let head = resume_observed_head(&mut state, &old).await.unwrap();
8857            state.land_sync_pending = true;
8858            state.config.verify.e2e = vec!["true".into()];
8859            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8860                head.clone(),
8861                false,
8862                vec![crate::run::CommandOutcome {
8863                    command: state.config.verify.e2e[0].clone(),
8864                    code,
8865                    output_tail: "verification command did not complete".into(),
8866                    ..Default::default()
8867                }],
8868            ));
8869            state.save().unwrap();
8870            state = RunState::load(&state.id).unwrap();
8871            assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
8872            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8873            assert_eq!(evidence.head, head);
8874            assert!(evidence.passed);
8875            assert_eq!(evidence.outcomes[0].code, Some(0));
8876        }
8877    }
8878
8879    async fn interrupt_landing_rebase(state: &mut RunState) {
8880        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
8881        state.save().unwrap();
8882        let scratch = state.dir().join("rebase");
8883        assert_eq!(
8884            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
8885                .await
8886                .unwrap(),
8887            crate::rebase::Rebased::Applied
8888        );
8889        assert!(!git::is_clean(&state.repo).await.unwrap());
8890    }
8891
8892    async fn landing_setup(state: &mut RunState) {
8893        git::git(
8894            &state.repo,
8895            &["config", "extensions.worktreeConfig", "true"],
8896        )
8897        .await
8898        .unwrap();
8899        state.config.worktree.setup =
8900            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8901        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8902            .await
8903            .unwrap();
8904        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8905    }
8906
8907    #[tokio::test]
8908    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8909        let (tmp, mut state, head) = landing_git_fixture().await;
8910        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8911        git::acquire_worktree_config(&state.repo).await.unwrap();
8912        let winner = tmp.path().join("landing");
8913        git::worktree_add_existing(&state.repo, &winner, "winner", false)
8914            .await
8915            .unwrap();
8916        state.candidates[0].worktree = winner.clone();
8917        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8918        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8919        state.config.disk.min_free_bytes = 0;
8920        state.config.worktree.setup = vec![crate::config::SetupStep {
8921            run: Some("touch setup-completed".into()),
8922            ..Default::default()
8923        }];
8924        #[cfg(unix)]
8925        {
8926            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8927            state.config.coordination = Some(crate::config::Coordination {
8928                contract_file: "fixture-contract".into(),
8929                contract_token: "fixture-v1".into(),
8930                lock_file: "fixture-lock".into(),
8931            });
8932        }
8933        state.land_rebase_from = Some(head);
8934        let restore = restore_landing_worktree(&mut state, None);
8935        // Only the registered Unix fixture can deadlock by reacquiring its
8936        // own operation lease. Don't time the whole Git/setup path elsewhere.
8937        #[cfg(unix)]
8938        let restore = async {
8939            tokio::time::timeout(Duration::from_secs(15), restore)
8940                .await
8941                .expect("landing setup must not wait for its own repository operation")
8942        };
8943        restore.await.unwrap();
8944        assert!(winner.join("setup-completed").is_file());
8945        assert!(git::is_clean(&winner).await.unwrap());
8946        assert!(state.land_rebase_from.is_none());
8947    }
8948
8949    #[tokio::test]
8950    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8951        for phase in 0..3 {
8952            let (_tmp, mut state, old) = landing_git_fixture().await;
8953            advance_landing_base(&state).await;
8954            landing_setup(&mut state).await;
8955            if phase > 0 {
8956                interrupt_landing_rebase(&mut state).await;
8957                if phase == 2 {
8958                    // Crash after clean removed setup products, before setup.
8959                    git::sync_to_head(&state.repo).await.unwrap();
8960                    assert!(!state.repo.join(".env").exists());
8961                }
8962                state = RunState::load(&state.id).unwrap();
8963            }
8964            let head = resume_observed_head(&mut state, &old).await.unwrap();
8965            assert_ne!(head, old);
8966            assert!(state.gate_allows_progress());
8967            assert!(state.land_rebase_from.is_none());
8968            assert_eq!(
8969                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8970                "secret"
8971            );
8972            assert!(git::is_clean(&state.repo).await.unwrap());
8973            assert!(
8974                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8975                    .await
8976                    .unwrap()
8977                    .contains(".env")
8978            );
8979        }
8980    }
8981
8982    #[tokio::test]
8983    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8984        let (_tmp, mut state, _) = landing_git_fixture().await;
8985        advance_landing_base(&state).await;
8986        landing_setup(&mut state).await;
8987        interrupt_landing_rebase(&mut state).await;
8988        // Exercise unusual names without asking Windows to create an invalid
8989        // control-character filename. Unix also covers embedded newlines.
8990        let locals = [
8991            "local notes",
8992            #[cfg(unix)]
8993            "local\nnotes",
8994        ];
8995        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8996            .await
8997            .unwrap();
8998        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8999        for local in locals {
9000            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
9001            assert!(
9002                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
9003                    .await
9004                    .unwrap()
9005                    .ok()
9006            );
9007        }
9008        restore_landing_worktree(&mut state, None).await.unwrap();
9009        for local in locals {
9010            assert_eq!(
9011                std::fs::read_to_string(state.repo.join(local)).unwrap(),
9012                "keep these notes"
9013            );
9014        }
9015        assert_eq!(
9016            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
9017            "secret"
9018        );
9019        assert!(git::is_clean(&state.repo).await.unwrap());
9020        assert!(state.land_rebase_from.is_none());
9021    }
9022
9023    #[tokio::test]
9024    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
9025        for local in ["advance", "advance/notes", "new-directory"] {
9026            let (_tmp, mut state, _) = landing_git_fixture().await;
9027            advance_landing_base(&state).await;
9028            // Also cover a local file blocking a new tracked directory.
9029            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
9030            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
9031            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
9032            git::git(&state.repo, &["add", "."]).await.unwrap();
9033            git::git(&state.repo, &["commit", "-m", "add directory"])
9034                .await
9035                .unwrap();
9036            git::git(&state.repo, &["push", "origin", "main"])
9037                .await
9038                .unwrap();
9039            git::git(&state.repo, &["checkout", "winner"])
9040                .await
9041                .unwrap();
9042            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
9043                .await
9044                .unwrap();
9045            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
9046            let path = state.repo.join(local);
9047            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
9048            std::fs::write(&path, "local notes").unwrap();
9049            interrupt_landing_rebase(&mut state).await;
9050            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
9051            let checkpoint = state.land_rebase_from.clone();
9052            let error = restore_landing_worktree(&mut state, None)
9053                .await
9054                .unwrap_err();
9055            assert!(
9056                error.to_string().contains("conflicting with HEAD"),
9057                "{error:#}"
9058            );
9059            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
9060            assert_eq!(
9061                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
9062                before
9063            );
9064            assert_eq!(state.land_rebase_from, checkpoint);
9065        }
9066    }
9067
9068    #[tokio::test]
9069    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
9070        for interrupted in [false, true] {
9071            let (_tmp, mut state, old) = landing_git_fixture().await;
9072            assert!(state.config.worktree.setup.is_empty());
9073            // A gate product exists before the base moves, without setup metadata.
9074            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
9075                .await
9076                .unwrap();
9077            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
9078            state.config.verify.gate =
9079                vec!["mkdir -p target && printf artifact > target/probe".into()];
9080            state.gate_ran = false;
9081            resume_observed_head(&mut state, &old).await.unwrap();
9082            assert_eq!(
9083                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
9084                "artifact"
9085            );
9086            advance_landing_base(&state).await;
9087            if interrupted {
9088                interrupt_landing_rebase(&mut state).await;
9089                state = RunState::load(&state.id).unwrap();
9090            }
9091            state.config.verify.gate =
9092                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
9093            let head = resume_observed_head(&mut state, &old).await.unwrap();
9094            assert_ne!(head, old);
9095            assert!(state.gate_allows_progress());
9096            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
9097            assert_eq!(
9098                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
9099                "artifact"
9100            );
9101            assert!(state.land_rebase_from.is_none());
9102            assert_eq!(
9103                git::remote_head(&state.repo, "origin", "task-head")
9104                    .await
9105                    .unwrap(),
9106                Some(head.clone())
9107            );
9108            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
9109            land_with(&mut state, &green_pr().url, &forge)
9110                .await
9111                .unwrap();
9112            assert!(state.parked);
9113            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
9114            assert!(forge.argvs().is_empty());
9115        }
9116    }
9117
9118    #[tokio::test]
9119    #[cfg(unix)]
9120    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
9121        use std::os::fd::AsRawFd as _;
9122
9123        for interrupted in [false, true] {
9124            let (_tmp, mut state, _) = landing_git_fixture().await;
9125            advance_landing_base(&state).await;
9126            landing_setup(&mut state).await;
9127            if interrupted {
9128                interrupt_landing_rebase(&mut state).await;
9129            }
9130            state.config.worktree.setup =
9131                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
9132            let common = crate::repo_lock::common_dir(&state.repo)
9133                .await
9134                .unwrap()
9135                .unwrap();
9136            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
9137            state.config.coordination = crate::config::test_coordination();
9138            state.config.graph.timeout_resource_wait = 0;
9139            let external = std::fs::OpenOptions::new()
9140                .read(true)
9141                .write(true)
9142                .create(true)
9143                .truncate(false)
9144                .open(common.join("updater.lock"))
9145                .unwrap();
9146            // SAFETY: the descriptor belongs to `external` and remains open.
9147            let locked =
9148                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
9149            assert_eq!(locked, 0);
9150            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
9151            let checkpoint = state.land_rebase_from.clone();
9152            let error = restore_landing_worktree(&mut state, None)
9153                .await
9154                .unwrap_err();
9155            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
9156            assert_eq!(
9157                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
9158                before
9159            );
9160            assert_eq!(state.land_rebase_from, checkpoint);
9161            assert_eq!(
9162                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
9163                "secret"
9164            );
9165
9166            drop(external);
9167            state.config.graph.timeout_resource_wait = 2;
9168            restore_landing_worktree(&mut state, None).await.unwrap();
9169            assert!(git::is_clean(&state.repo).await.unwrap());
9170            assert!(state.land_rebase_from.is_none());
9171            assert_eq!(
9172                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
9173                "restored"
9174            );
9175        }
9176    }
9177
9178    #[tokio::test]
9179    #[cfg(unix)]
9180    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
9181        use std::sync::atomic::{AtomicBool, Ordering};
9182
9183        let (_tmp, mut state, _) = landing_git_fixture().await;
9184        advance_landing_base(&state).await;
9185        landing_setup(&mut state).await;
9186        interrupt_landing_rebase(&mut state).await;
9187        let common = crate::repo_lock::common_dir(&state.repo)
9188            .await
9189            .unwrap()
9190            .unwrap();
9191        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
9192        state.config.coordination = crate::config::test_coordination();
9193        let holder = crate::repo_lock::SeatLease::for_checkout(
9194            &state.repo,
9195            true,
9196            state.config.coordination.as_ref(),
9197        )
9198        .await
9199        .unwrap();
9200        assert!(holder.is_some());
9201        let cancelled = Arc::new(AtomicBool::new(false));
9202        let signal = cancelled.clone();
9203        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
9204            signal.load(Ordering::SeqCst)
9205        });
9206        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
9207        let checkpoint = state.land_rebase_from.clone();
9208        let (result, ()) = tokio::join!(
9209            tokio::time::timeout(
9210                Duration::from_secs(2),
9211                wait.scope(restore_landing_worktree(&mut state, None)),
9212            ),
9213            async {
9214                tokio::time::sleep(Duration::from_millis(100)).await;
9215                cancelled.store(true, Ordering::SeqCst);
9216            }
9217        );
9218        let error = result
9219            .expect("cancellation must release the waiting driver")
9220            .unwrap_err();
9221        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
9222        assert_eq!(
9223            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
9224            before
9225        );
9226        assert_eq!(state.land_rebase_from, checkpoint);
9227        assert_eq!(
9228            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
9229            "secret"
9230        );
9231        drop(holder);
9232        restore_landing_worktree(&mut state, None).await.unwrap();
9233        assert!(state.land_rebase_from.is_none());
9234        assert!(git::is_clean(&state.repo).await.unwrap());
9235    }
9236
9237    #[tokio::test]
9238    #[cfg(unix)]
9239    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
9240        use std::sync::atomic::{AtomicBool, Ordering};
9241
9242        for e2e in [false, true] {
9243            let (_tmp, mut state, head) = landing_git_fixture().await;
9244            let common = crate::repo_lock::common_dir(&state.repo)
9245                .await
9246                .unwrap()
9247                .unwrap();
9248            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
9249            state.config.coordination = crate::config::test_coordination();
9250            if e2e {
9251                state.config.verify.e2e = vec!["true".into()];
9252                state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9253                    head.clone(),
9254                    false,
9255                    Vec::new(),
9256                ));
9257            } else {
9258                state.config.verify.gate = vec!["true".into()];
9259                state.gate_ran = false;
9260            }
9261            let holder = crate::repo_lock::SeatLease::for_checkout(
9262                &state.repo,
9263                true,
9264                state.config.coordination.as_ref(),
9265            )
9266            .await
9267            .unwrap();
9268            assert!(holder.is_some());
9269            let cancelled = Arc::new(AtomicBool::new(false));
9270            let signal = cancelled.clone();
9271            let waiting = Arc::new(tokio::sync::Notify::new());
9272            let observed = waiting.clone();
9273            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
9274                observed.notify_one();
9275                signal.load(Ordering::SeqCst)
9276            });
9277            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
9278            let url = green_pr().url;
9279            let result = {
9280                let mut publishing =
9281                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
9282                // Git and fixture I/O precede local coordination. Start the
9283                // cancellation deadline only once the inherited wait policy
9284                // is polled, rather than timing those unrelated subprocesses.
9285                tokio::time::timeout(Duration::from_secs(30), async {
9286                    tokio::select! {
9287                        result = &mut publishing => panic!(
9288                            "verification must wait behind the held seat: {result:?}"
9289                        ),
9290                        () = waiting.notified() => {}
9291                    }
9292                })
9293                .await
9294                .expect("verification must reach the inherited coordination wait");
9295                cancelled.store(true, Ordering::SeqCst);
9296                tokio::time::timeout(Duration::from_secs(2), publishing).await
9297            };
9298            let error = result
9299                .expect("cancellation must release the verification waiter")
9300                .unwrap_err();
9301            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
9302            assert!(error.to_string().contains("cancelled"), "{error:#}");
9303            assert!(forge.argvs().is_empty());
9304            assert_eq!(
9305                git::remote_head(&state.repo, "origin", "task-head")
9306                    .await
9307                    .unwrap(),
9308                Some(head.clone())
9309            );
9310            drop(holder);
9311            // Cancellation must release its reservation so another attempt can verify.
9312            assert_eq!(
9313                publish_landing_head(&mut state, &head, &url, &forge)
9314                    .await
9315                    .unwrap(),
9316                head
9317            );
9318        }
9319    }
9320
9321    #[tokio::test]
9322    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
9323        for staged in [false, true] {
9324            let (_tmp, mut state, old) = landing_git_fixture().await;
9325            advance_landing_base(&state).await;
9326            interrupt_landing_rebase(&mut state).await;
9327            std::fs::write(state.repo.join("change"), "user edit").unwrap();
9328            if staged {
9329                git::git(&state.repo, &["add", "change"]).await.unwrap();
9330            }
9331            assert!(resume_observed_head(&mut state, &old).await.is_err());
9332            assert_eq!(
9333                std::fs::read_to_string(state.repo.join("change")).unwrap(),
9334                "user edit"
9335            );
9336            assert_eq!(
9337                git::remote_head(&state.repo, "origin", "task-head")
9338                    .await
9339                    .unwrap(),
9340                Some(old)
9341            );
9342        }
9343    }
9344
9345    #[tokio::test]
9346    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
9347        let (_tmp, mut state, head) = landing_git_fixture().await;
9348        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
9349        let id = state.id.clone();
9350        let pr = land_with(&mut state, &green_pr().url, &forge)
9351            .await
9352            .unwrap();
9353        assert_eq!(pr.state, PrLifecycle::Open);
9354        assert_eq!(state.id, id);
9355        assert!(state.parked);
9356        assert_eq!(state.status, RunStatus::Landing);
9357        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
9358        assert!(forge.argvs().is_empty());
9359
9360        state.land_sync_pending = true;
9361        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
9362        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
9363        closed.pr.state = PrLifecycle::Closed;
9364        let forge = Scripted::new(vec![closed], vec![]);
9365        assert_eq!(
9366            land_with(&mut state, &green_pr().url, &forge)
9367                .await
9368                .unwrap()
9369                .state,
9370            PrLifecycle::Closed
9371        );
9372        assert_eq!(
9373            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
9374            "do not touch"
9375        );
9376        assert!(forge.argvs().is_empty());
9377    }
9378
9379    #[tokio::test]
9380    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
9381        let (_tmp, mut state, old) = landing_git_fixture().await;
9382        advance_landing_base(&state).await;
9383        state.config.verify.gate = vec!["exit 1".into()];
9384        assert!(resume_observed_head(&mut state, &old).await.is_err());
9385        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
9386        assert!(!state.gate_allows_progress());
9387        assert_eq!(
9388            git::remote_head(&state.repo, "origin", "task-head")
9389                .await
9390                .unwrap(),
9391            Some(old)
9392        );
9393        assert!(state.land_sync_pending);
9394    }
9395
9396    #[tokio::test]
9397    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
9398        let (_tmp, mut state, old) = landing_git_fixture().await;
9399        advance_landing_base(&state).await;
9400        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
9401        // Model a crash after the push but before saving its published SHA.
9402        state.pr_pushed_head = Some(old.clone());
9403        state.land_sync_pending = true;
9404        assert_eq!(
9405            resume_observed_head(&mut state, &pushed).await.unwrap(),
9406            pushed
9407        );
9408        // A writer races the observed PR snapshot: the explicit remote lease
9409        // must reject the push even though preflight saw our expected head.
9410        git::git(
9411            &state.repo,
9412            &["push", "--force", "origin", "main:refs/heads/task-head"],
9413        )
9414        .await
9415        .unwrap();
9416        assert!(
9417            publish_landing_head(
9418                &mut state,
9419                &pushed,
9420                &green_pr().url,
9421                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
9422            )
9423            .await
9424            .unwrap_err()
9425            .to_string()
9426            .contains("publishing gated")
9427        );
9428        assert!(
9429            resume_observed_head(&mut state, "foreign-head")
9430                .await
9431                .is_err()
9432        );
9433    }
9434    #[tokio::test]
9435    async fn landing_publication_refuses_a_pr_closed_during_gate() {
9436        let (_tmp, mut state, head) = landing_git_fixture().await;
9437        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
9438        closed.pr.state = PrLifecycle::Closed;
9439        let forge = Scripted::new(vec![closed], vec![]);
9440        assert!(
9441            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
9442                .await
9443                .unwrap_err()
9444                .to_string()
9445                .contains("PR closed or merged")
9446        );
9447    }
9448
9449    /// A candidate selected by the uncontested tally.
9450    fn winning_candidate(summary: &str) -> Candidate {
9451        Candidate {
9452            index: 0,
9453            label: 'A',
9454            agent: "opus".to_owned(),
9455            branch: "magi/x/A".to_owned(),
9456            worktree: PathBuf::from("/wt/A"),
9457            summary: summary.to_owned(),
9458            stat: String::new(),
9459            files: 1,
9460            commits: 1,
9461            empty: false,
9462            failed: None,
9463            verified_noop: None,
9464            duration_ms: 0,
9465            folded: false,
9466        }
9467    }
9468
9469    fn uncontested_tally() -> Tally {
9470        Tally {
9471            first_choice: BTreeMap::from([('A', 1)]),
9472            borda: BTreeMap::new(),
9473            winner: 'A',
9474            rankings: 1,
9475            unanimous_initial: true,
9476            deliberated: false,
9477            changed_votes: 0,
9478            unanimous_final: true,
9479            tie_break: None,
9480            judges: 1,
9481            present: 1,
9482            quorum: 1,
9483            met_quorum: true,
9484            uncontested: None,
9485        }
9486    }
9487
9488    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
9489        ReviewRecord {
9490            attempts: 0,
9491            reviewer,
9492            agent: agent.to_owned(),
9493            summary: summary.to_owned(),
9494            findings: Vec::new(),
9495            vote: None,
9496            failed: None,
9497            duration_ms: 0,
9498        }
9499    }
9500
9501    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
9502        let answered = reviews.len();
9503        ReviewRound {
9504            round,
9505            head: "abc1234".to_owned(),
9506            verified_head: None,
9507            verified_at: None,
9508            reviews,
9509            e2e: Vec::new(),
9510            verify_retried: false,
9511            e2e_deferred: false,
9512            e2e_defer_reason: None,
9513            fix: None,
9514            blocking: 0,
9515            answered,
9516            expected: answered,
9517            clean: true,
9518            progressed: false,
9519            vote_split: false,
9520            reconsideration: Vec::new(),
9521            verdict: None,
9522        }
9523    }
9524
9525    #[test]
9526    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
9527        let en = panel();
9528        assert!(en.contains("Task"), "{en}");
9529        assert!(en.contains("add retries to the uploader"), "{en}");
9530
9531        let mut state = run_state();
9532        state.config.graph.language = "ja".to_owned();
9533        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9534        assert!(ja.contains("タスク"), "{ja}");
9535        assert!(
9536            ja.contains("add retries to the uploader"),
9537            "the task itself is not translated: {ja}"
9538        );
9539    }
9540
9541    #[test]
9542    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
9543        // `run_state()` has no candidates, no tally and no reviews - exactly
9544        // the shape a run has before anything has judged or reviewed it, and
9545        // the panel must not print an empty box for either.
9546        let html = panel();
9547        assert!(!html.contains("What changed"), "{html}");
9548        assert!(!html.contains("Review verdict"), "{html}");
9549    }
9550
9551    #[test]
9552    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
9553        let mut state = run_state();
9554        state.candidates = vec![winning_candidate("")];
9555        state.tally = Some(uncontested_tally());
9556        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9557        assert!(
9558            !html.contains("What changed"),
9559            "an empty summary must not render an empty box: {html}"
9560        );
9561    }
9562
9563    #[test]
9564    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
9565        let mut state = run_state();
9566        state.candidates = vec![winning_candidate(
9567            "Added a retry loop around the uploader PUT call.",
9568        )];
9569        state.tally = Some(uncontested_tally());
9570        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9571        assert!(en.contains("What changed"), "{en}");
9572        assert!(
9573            en.contains("Added a retry loop around the uploader PUT call."),
9574            "{en}"
9575        );
9576
9577        state.config.graph.language = "ja".to_owned();
9578        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9579        assert!(ja.contains("変更内容"), "{ja}");
9580        assert!(
9581            ja.contains("Added a retry loop around the uploader PUT call."),
9582            "{ja}"
9583        );
9584    }
9585
9586    #[test]
9587    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
9588        let mut state = run_state();
9589        state.reviews = vec![
9590            review_round(
9591                1,
9592                vec![review_record(1, "alpha", "found a race, sent back")],
9593            ),
9594            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
9595        ];
9596        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9597        assert!(en.contains("Review verdict"), "{en}");
9598        assert!(en.contains("race is fixed, clean"), "{en}");
9599        assert!(
9600            !en.contains("found a race, sent back"),
9601            "only the round that actually cleared the merge should show: {en}"
9602        );
9603
9604        state.config.graph.language = "ja".to_owned();
9605        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9606        assert!(ja.contains("レビューの結論"), "{ja}");
9607        assert!(ja.contains("レビュアー"), "{ja}");
9608        assert!(ja.contains("race is fixed, clean"), "{ja}");
9609    }
9610
9611    /// The `incomplete_review = "warn"` policy (see
9612    /// `graph::Runner::review_loop`) can push a `clean` round to
9613    /// `state.reviews` while one seat's own record still has `failed: Some`
9614    /// and an empty `summary` - a seat that never answered, not one that
9615    /// answered with nothing to say.
9616    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
9617        ReviewRecord {
9618            attempts: 0,
9619            reviewer,
9620            agent: agent.to_owned(),
9621            summary: String::new(),
9622            findings: Vec::new(),
9623            vote: None,
9624            failed: Some(reason.to_owned()),
9625            duration_ms: 0,
9626        }
9627    }
9628
9629    #[test]
9630    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
9631        let mut state = run_state();
9632        state.reviews = vec![review_round(
9633            1,
9634            vec![
9635                review_record(1, "alpha", "clean, nothing to add"),
9636                unanswered_review_record(2, "beta", "timed out"),
9637            ],
9638        )];
9639        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9640        assert!(en.contains("clean, nothing to add"), "{en}");
9641        assert!(
9642            en.contains("produced no answer: timed out"),
9643            "a seat that never answered must say so, not render a blank box: {en}"
9644        );
9645        assert!(
9646            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
9647            "no reviewer box may be left empty: {en}"
9648        );
9649
9650        state.config.graph.language = "ja".to_owned();
9651        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9652        assert!(ja.contains("回答なし: timed out"), "{ja}");
9653    }
9654
9655    #[test]
9656    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
9657        let html = panel();
9658        assert!(!html.contains("<script"), "no script survives the csp");
9659        assert!(!html.contains("<form"), "form-action is 'none'");
9660        let pr = green_pr();
9661        assert_eq!(
9662            html.matches("http").count(),
9663            html.matches(pr.url.as_str()).count(),
9664            "the only http url in the panel is the pull request's own link"
9665        );
9666        assert!(
9667            html.contains("target=\"_blank\""),
9668            "the PR link must open in a new tab so it escapes the iframe"
9669        );
9670        assert!(
9671            html.contains("rel=\"noopener noreferrer\""),
9672            "external links opening in new tabs must carry noopener noreferrer"
9673        );
9674    }
9675
9676    #[test]
9677    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
9678        let html = panel();
9679        assert!(
9680            html.contains(">+</span>"),
9681            "an added line carries a `+` in the gutter, not only a background"
9682        );
9683        assert!(
9684            html.contains(">-</span>"),
9685            "a removed line carries a `-` in the gutter, not only a background"
9686        );
9687        assert!(
9688            html.contains(">new line</span>"),
9689            "the marker is moved to the gutter, so the body is printed once without it"
9690        );
9691    }
9692
9693    #[test]
9694    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
9695        let total = DIFF_MAX_LINES + 100;
9696        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
9697        let html = approval_panel(
9698            &run_state(),
9699            &green_pr(),
9700            NUMSTAT,
9701            &diff,
9702            &[],
9703            "feat: something long",
9704        );
9705        assert!(
9706            html.contains(&format!("100 of {total} diff lines omitted")),
9707            "the note must say exactly how much was cut"
9708        );
9709        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
9710        assert!(
9711            !html.contains(&format!("line {DIFF_MAX_LINES}")),
9712            "nothing past the threshold is rendered"
9713        );
9714        assert!(
9715            html.contains("/repo/magi"),
9716            "the note says where the rest is"
9717        );
9718    }
9719
9720    #[test]
9721    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
9722        let html = approval_panel(
9723            &run_state(),
9724            &green_pr(),
9725            "1\t2\tsrc/<b>&\"x\"'.rs",
9726            "",
9727            &[],
9728            "subject",
9729        );
9730        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
9731        assert!(
9732            !html.contains("<b>"),
9733            "an agent-influenced path must never become markup"
9734        );
9735    }
9736
9737    #[tokio::test]
9738    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
9739        let a = std::path::PathBuf::from("/repo/a");
9740        let b = std::path::PathBuf::from("/repo/b");
9741
9742        let held = repo_merge_lock(&a).lock_owned().await;
9743
9744        // A second, concurrent land run against the *same* repository must
9745        // wait - `try_lock` fails while `held` is alive.
9746        assert!(
9747            repo_merge_lock(&a).try_lock().is_err(),
9748            "a second merge into the same repository must not proceed concurrently"
9749        );
9750
9751        // A run against a *different* repository must not be blocked by it -
9752        // this is what keeps a slow rebase or `gh pr merge` in one
9753        // repository from also stalling a land-approval resume in another.
9754        assert!(
9755            repo_merge_lock(&b).try_lock().is_ok(),
9756            "a different repository's merge lock must be independent"
9757        );
9758
9759        drop(held);
9760        assert!(
9761            repo_merge_lock(&a).try_lock().is_ok(),
9762            "the lock is released once the holder is done"
9763        );
9764    }
9765
9766    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
9767        let mut state = landing_state();
9768        let mut rec = review_record(1, "alpha", "precise rejection reason");
9769        rec.vote = Some(if reject {
9770            crate::verdict::ReviewVote::Reject
9771        } else {
9772            crate::verdict::ReviewVote::Approve
9773        });
9774        if major {
9775            rec.findings = contested().findings;
9776        }
9777        let mut round = review_round(1, vec![rec]);
9778        round.clean = false;
9779        round.blocking = usize::from(major);
9780        state.reviews.push(round);
9781        state.config.graph.review_rounds = 1;
9782        state
9783    }
9784
9785    #[test]
9786    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
9787        for every in [false, true] {
9788            for contested in [false, true] {
9789                for major in [false, true] {
9790                    for reject in [false, true] {
9791                        let mut state = repair_state(major, reject);
9792                        state.config.graph.land_approval = every;
9793                        state.config.graph.hold_contested_merge = contested;
9794                        let reasons = approval_reasons(&state);
9795                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
9796                        assert_eq!(
9797                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
9798                            contested && major
9799                        );
9800                        assert_eq!(
9801                            reasons.contains(&ApprovalReason::FinalReject),
9802                            contested && reject
9803                        );
9804                        assert_eq!(
9805                            reasons.len(),
9806                            usize::from(every)
9807                                + usize::from(contested && major)
9808                                + usize::from(contested && reject)
9809                        );
9810                    }
9811                }
9812            }
9813        }
9814    }
9815
9816    #[test]
9817    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
9818        use crate::verdict::ReviewVote::{Approve, Reject};
9819        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
9820            let mut state = repair_state(false, initial_reject);
9821            state.reviews[0]
9822                .reconsideration
9823                .push(crate::run::ReviewRevoteRecord {
9824                    reviewer: 1,
9825                    agent: "alpha".into(),
9826                    vote: Some(final_vote),
9827                    reason: "changed after reading the panel <evidence>".into(),
9828                    failed: None,
9829                });
9830            assert_eq!(
9831                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9832                final_vote == Reject
9833            );
9834            for language in ["en", "ja"] {
9835                state.config.graph.language = language.into();
9836                let evidence = approval_evidence(&state);
9837                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
9838                assert!(evidence.contains("changed after reading the panel <evidence>"));
9839                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9840                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
9841                assert!(!html.contains("<evidence>"));
9842            }
9843            state.reviews[0].reconsideration[0].vote = None;
9844            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
9845            assert_eq!(
9846                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9847                initial_reject
9848            );
9849            assert!(approval_evidence(&state).contains("timed out"));
9850        }
9851    }
9852
9853    #[tokio::test]
9854    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
9855        for every in [false, true] {
9856            for contested in [false, true] {
9857                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
9858                {
9859                    let mut state = repair_state(major, reject);
9860                    state.config.graph.land_approval = every;
9861                    state.config.graph.hold_contested_merge = contested;
9862                    let forge = Scripted::new(
9863                        vec![seen("abc", Checks::Green, "CLEAN", false)],
9864                        vec![(true, "")],
9865                    );
9866                    land_with(&mut state, URL, &forge).await.unwrap();
9867                    let expected = every || (contested && (major || reject));
9868                    assert_eq!(state.land_approval.is_some(), expected);
9869                    assert_eq!(forge.calls().contains(&"merge"), !expected);
9870                    if expected {
9871                        assert!(state.parked);
9872                    }
9873                }
9874            }
9875        }
9876    }
9877
9878    #[tokio::test]
9879    async fn reviewed_branch_hold_is_read_before_landing_decision() {
9880        for (base, control) in [
9881            (false, "land_approval"),
9882            (true, "land_approval"),
9883            (false, "hold_contested_merge"),
9884        ] {
9885            let (_tmp, mut state, _) = landing_git_fixture().await;
9886            state.config.graph.land_approval = base;
9887            state.config.graph.hold_contested_merge = false;
9888            state.reviewed_commits = Some(Vec::new());
9889            if control == "hold_contested_merge" {
9890                state.reviews = repair_state(false, true).reviews;
9891            }
9892            std::fs::write(
9893                state.repo.join("magi.toml"),
9894                format!("[graph]\n{control} = {}\n", !base),
9895            )
9896            .unwrap();
9897            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
9898            git::git(&state.repo, &["commit", "-m", "approval policy"])
9899                .await
9900                .unwrap();
9901            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9902            state.land_sync_pending = false;
9903            state.pr_pushed_head = Some(head.clone());
9904            state.gate_head = Some(head.clone());
9905            let forge = Scripted::new(
9906                vec![seen(&head, Checks::Green, "CLEAN", false)],
9907                vec![(true, "")],
9908            );
9909            land_with(&mut state, URL, &forge).await.unwrap();
9910            assert!(
9911                state.land_approval.is_some(),
9912                "base={base}, control={control}"
9913            );
9914            assert!(!forge.calls().contains(&"merge"));
9915            if !base {
9916                let question = ask::Questions::open()
9917                    .get(&state.land_approval.as_ref().unwrap().question)
9918                    .unwrap();
9919                assert!(question.detail.contains(&format!(
9920                    "{control}=true from the reviewed branch's magi.toml"
9921                )));
9922            }
9923        }
9924    }
9925
9926    #[tokio::test]
9927    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9928        for file in ["magi.toml", ".magi/config.toml"] {
9929            for control in crate::config::OwnerHold::ALL {
9930                let (_tmp, mut state, _) = landing_git_fixture().await;
9931                state.config.graph.land_approval = false;
9932                state.config.graph.hold_contested_merge = false;
9933                state.reviewed_commits = Some(Vec::new());
9934                if control == crate::config::OwnerHold::HoldContestedMerge {
9935                    state.reviews = repair_state(false, true).reviews;
9936                }
9937                let config = state.repo.join(file);
9938                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9939                std::fs::write(
9940                    &config,
9941                    format!(
9942                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9943                        control.key()
9944                    ),
9945                )
9946                .unwrap();
9947                git::git(&state.repo, &["add", file]).await.unwrap();
9948                git::git(&state.repo, &["commit", "-m", "require approval"])
9949                    .await
9950                    .unwrap();
9951                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9952                let gate = state.config.verify.gate.clone();
9953                state.observe_branch_owner_holds(&head).await;
9954                assert_eq!(state.config.verify.gate, gate);
9955                assert!(state.owner_hold(control));
9956                let holds = state.branch_owner_holds.clone();
9957                git::git(&state.repo, &["rm", file]).await.unwrap();
9958                git::git(&state.repo, &["commit", "-m", "remove config"])
9959                    .await
9960                    .unwrap();
9961                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9962                state.save().unwrap();
9963                state = RunState::load(&state.id).unwrap();
9964                state.observe_branch_owner_holds(&later).await;
9965                assert_eq!(state.branch_owner_holds, holds);
9966                assert_eq!(state.branch_owner_holds[0].head, head);
9967                state.land_sync_pending = false;
9968                state.pr_pushed_head = Some(later.clone());
9969                state.gate_head = Some(later.clone());
9970                let forge = Scripted::new(
9971                    vec![seen(&later, Checks::Green, "CLEAN", false)],
9972                    vec![(true, "")],
9973                );
9974                land_with(&mut state, URL, &forge).await.unwrap();
9975                assert!(!forge.calls().contains(&"merge"));
9976                assert!(state.parked);
9977                let question = ask::Questions::open()
9978                    .get(&state.land_approval.as_ref().unwrap().question)
9979                    .unwrap();
9980                assert!(question.detail.contains("Approval required because:"));
9981                assert!(question.detail.contains(&format!(
9982                    "{}=true from the reviewed branch's {file}",
9983                    control.key()
9984                )));
9985                assert_eq!(state.branch_owner_holds, holds);
9986                state.save().unwrap();
9987                let resumed = RunState::load(&state.id).unwrap();
9988                assert!(resumed.owner_hold(control));
9989                assert_eq!(resumed.branch_owner_holds, holds);
9990                assert_eq!(
9991                    resumed.land_approval.unwrap().question,
9992                    state.land_approval.unwrap().question
9993                );
9994            }
9995        }
9996    }
9997
9998    #[tokio::test]
9999    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
10000        let mut state = repair_state(false, true);
10001        state.reviews[0].clean = true;
10002        let mut finding = contested().findings.remove(0);
10003        finding.severity = crate::verdict::Severity::Minor;
10004        state.reviews[0].reviews[0].findings.push(finding);
10005        assert!(state.open_findings().is_empty());
10006        let mut pr = green_pr();
10007        pr.review_comments.clear();
10008        for language in ["en", "ja"] {
10009            state.config.graph.language = language.into();
10010            let html = approval_panel(&state, &pr, "", "", &[], "subject");
10011            assert!(html.contains("[R3-1-1] minor"));
10012            assert!(html.contains(if language == "ja" {
10013                "内部指摘の解決を意味するものではありません"
10014            } else {
10015                "This does not mean internal findings are resolved"
10016            }));
10017            assert!(
10018                html.find(if language == "ja" {
10019                    "承認が必要な理由:"
10020                } else {
10021                    "Approval required because:"
10022                })
10023                .unwrap()
10024                    < html.find("[R3-1-1]").unwrap()
10025            );
10026        }
10027        state.config.graph.language = "en".into();
10028        let observed = seen("abc", Checks::Green, "CLEAN", false);
10029        assert_eq!(
10030            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
10031                .await
10032                .unwrap(),
10033            ApprovalGate::Pending
10034        );
10035        let id = state.land_approval.as_ref().unwrap().question.clone();
10036        let q = ask::Questions::open().get(&id).unwrap();
10037        assert!(q.detail.starts_with("Approval required because:"));
10038        assert!(q.detail.contains("final reviewer reject"));
10039        assert!(q.detail.contains("[R3-1-1] minor"));
10040        assert!(
10041            q.detail
10042                .contains("No adoption or resolution evidence recorded")
10043        );
10044        state.config.graph.land_approval = false;
10045        state.config.graph.hold_contested_merge = false;
10046        state.reviews.clear();
10047        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
10048        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
10049        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
10050        let forge = Scripted::new(vec![observed], vec![]);
10051        land_with(&mut state, URL, &forge).await.unwrap();
10052        assert!(!forge.calls().contains(&"merge"));
10053        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
10054        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
10055    }
10056
10057    #[tokio::test]
10058    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
10059        let mut state = repair_state(false, true);
10060        state.config.graph.land_approval = false;
10061        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
10062        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
10063        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
10064        state.reviews[0].reviews[0].summary = long_reason.clone();
10065        for i in 1..=10 {
10066            let mut finding = contested().findings.remove(0);
10067            finding.id = format!("R1-1-{i}");
10068            finding.severity = if i == 9 {
10069                crate::verdict::Severity::Major
10070            } else {
10071                crate::verdict::Severity::Minor
10072            };
10073            finding.title = long_title.clone();
10074            finding.detail = long_detail.clone();
10075            state.reviews[0].reviews[0].findings.push(finding);
10076        }
10077        state.reviews[0].fix = Some(crate::run::FixRecord {
10078            agent: "fixer".into(),
10079            addressed: vec!["R1-1-9".into()],
10080            rejected: vec![crate::verdict::Rejection {
10081                id: "R1-1-10".into(),
10082                why: long_reason.clone(),
10083            }],
10084            notes: long_detail.clone(),
10085            committed: false,
10086            failed: None,
10087            duration_ms: 0,
10088            continuation: None,
10089        });
10090        assert_eq!(
10091            approval_reasons(&state),
10092            [
10093                ApprovalReason::OpenBlockingFindings,
10094                ApprovalReason::FinalReject
10095            ]
10096        );
10097        let excerpt = approval_excerpt(&long_reason, 300);
10098        assert_eq!(excerpt.chars().count(), 300);
10099        assert!(excerpt.ends_with('…'));
10100        let boundary = "拒".repeat(300);
10101        assert_eq!(approval_excerpt(&boundary, 300), boundary);
10102        for language in ["en", "ja"] {
10103            state.config.graph.language = language.into();
10104            for revote in [
10105                None,
10106                Some(crate::verdict::ReviewVote::Reject),
10107                Some(crate::verdict::ReviewVote::Approve),
10108            ] {
10109                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
10110                state.reviews[0].reconsideration.clear();
10111                if let Some(vote) = revote {
10112                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
10113                    state.reviews[0]
10114                        .reconsideration
10115                        .push(crate::run::ReviewRevoteRecord {
10116                            reviewer: 1,
10117                            agent: "alpha".into(),
10118                            vote: Some(vote),
10119                            reason: long_reason.clone(),
10120                            failed: None,
10121                        });
10122                }
10123                let evidence = approval_evidence(&state);
10124                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
10125                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
10126                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
10127                assert_eq!(
10128                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
10129                    final_vote == crate::verdict::ReviewVote::Reject
10130                );
10131                assert!(evidence.contains(&excerpt));
10132                assert!(evidence.contains("[R1-1-8] minor"));
10133                assert!(evidence.contains("[R1-1-9] major"));
10134                assert!(evidence.contains("[R1-1-10] minor"));
10135                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
10136                    assert!(!evidence.contains(tail));
10137                }
10138                assert!(evidence.contains(if language == "ja" {
10139                    "採用申告(解決未確認)"
10140                } else {
10141                    "claimed addressed (resolution unconfirmed)"
10142                }));
10143                assert!(evidence.contains(if language == "ja" {
10144                    "不採用理由"
10145                } else {
10146                    "declined"
10147                }));
10148                let major_evidence = evidence
10149                    .split("[R1-1-9] major")
10150                    .nth(1)
10151                    .unwrap()
10152                    .split("[R1-1-10]")
10153                    .next()
10154                    .unwrap();
10155                assert!(major_evidence.contains(if language == "ja" {
10156                    "採用申告(解決未確認)"
10157                } else {
10158                    "claimed addressed (resolution unconfirmed)"
10159                }));
10160                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
10161                assert!(last_evidence.contains(if language == "ja" {
10162                    "不採用理由"
10163                } else {
10164                    "declined"
10165                }));
10166                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
10167                assert!(html.contains(&esc(&evidence)));
10168                assert_eq!(
10169                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
10170                        .await
10171                        .unwrap(),
10172                    ApprovalGate::Pending
10173                );
10174                let id = &state.land_approval.take().unwrap().question;
10175                let q = ask::Questions::open().get(id).unwrap();
10176                assert!(q.detail.starts_with(&evidence));
10177            }
10178            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
10179        }
10180    }
10181
10182    #[test]
10183    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
10184        for (major, reject) in [(true, false), (false, true), (true, true)] {
10185            let state = repair_state(major, reject);
10186            assert!(repair_available(&state));
10187            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
10188        }
10189        assert!(!repair_available(&repair_state(false, false)));
10190        let mut clean = repair_state(true, false);
10191        clean.reviews[0].clean = true;
10192        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
10193        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
10194    }
10195
10196    #[tokio::test]
10197    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
10198        let mut state = repair_state(true, false);
10199        let pr = green_pr();
10200        approval_gate(&mut state, &pr, "feat: x", None, "abc")
10201            .await
10202            .unwrap();
10203        let store = ask::Questions::open();
10204        let id = state.land_approval.as_ref().unwrap().question.clone();
10205        // Simulate an unanswered two-choice question created by an older build.
10206        store
10207            .update(&id, |q| {
10208                q.choices = vec![APPROVE.into(), HOLD.into()];
10209                Ok(())
10210            })
10211            .unwrap();
10212        let upgraded = store.get(&id).unwrap();
10213        assert_eq!(upgraded.choices, approval_choices(&state));
10214        assert!(!upgraded.actions.contains_key(HOLD));
10215        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
10216        assert!(
10217            store
10218                .list()
10219                .iter()
10220                .any(|q| q.id == id && q.choices == upgraded.choices)
10221        );
10222        assert!(
10223            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
10224        );
10225        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
10226        store
10227            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
10228            .unwrap();
10229        // An earlier build may have recorded the repair answer and stopped
10230        // before any driver consumed it. Reconcile that durable decision too.
10231        store
10232            .update(&id, |q| {
10233                q.actions.clear();
10234                Ok(())
10235            })
10236            .unwrap();
10237        assert_eq!(
10238            store.get(&id).unwrap().chosen_action(),
10239            Some(&ask::ChoiceAction::Resume {
10240                run: state.id.clone()
10241            })
10242        );
10243        let binding = state.land_approval.clone();
10244        assert_eq!(
10245            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10246                .await
10247                .unwrap(),
10248            ApprovalGate::Repair
10249        );
10250        assert!(state.land_approval.is_none());
10251        assert_eq!(state.merge_repairs.len(), 1);
10252        let request = &state.merge_repairs[0];
10253        assert_eq!(request.question, id);
10254        assert_eq!(request.head, "abc");
10255        assert_eq!(request.pr, pr.url);
10256        assert_eq!(
10257            request.reviews[0].reviews[0].summary,
10258            "precise rejection reason"
10259        );
10260        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
10261        assert_eq!(
10262            request.reviews[0].reviews[0].findings[0].detail,
10263            state.reviews[0].reviews[0].findings[0].detail
10264        );
10265        // A repeated consumption of the same answer never dispatches another repair.
10266        state.land_approval = binding;
10267        assert_eq!(
10268            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10269                .await
10270                .unwrap(),
10271            ApprovalGate::Repair
10272        );
10273        assert_eq!(state.merge_repairs.len(), 1);
10274        state.land_approval = None;
10275        state.config.graph.land_approval = false;
10276        state.config.graph.hold_contested_merge = false;
10277        state.reviews.clear();
10278        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
10279        assert_eq!(
10280            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10281                .await
10282                .unwrap(),
10283            ApprovalGate::Pending
10284        );
10285        let fresh_id = &state.land_approval.as_ref().unwrap().question;
10286        assert_ne!(fresh_id, &id);
10287        let fresh = store.get(fresh_id).unwrap();
10288        assert!(
10289            fresh
10290                .detail
10291                .contains("fresh owner approval after merge repair")
10292        );
10293        assert!(fresh.detail.contains("No review recorded"));
10294        assert!(!fresh.detail.contains("precise rejection reason"));
10295    }
10296
10297    #[tokio::test]
10298    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
10299        for choice in [REPAIR, HOLD] {
10300            let mut state = repair_state(false, true);
10301            let observed = seen("abc", Checks::Green, "CLEAN", false);
10302            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
10303                .await
10304                .unwrap();
10305            let id = state.land_approval.as_ref().unwrap().question.clone();
10306            ask::Questions::open()
10307                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
10308                .unwrap();
10309            let forge = Scripted::new(vec![observed], vec![(true, "")]);
10310            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10311                .await
10312                .unwrap();
10313            assert!(
10314                forge
10315                    .argvs()
10316                    .iter()
10317                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
10318            );
10319            assert!(!forge.calls().contains(&"fix"));
10320            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
10321            assert_ne!(state.status, RunStatus::Merged);
10322        }
10323    }
10324
10325    #[test]
10326    fn only_the_merge_choice_merges_and_silence_holds() {
10327        let table = [
10328            (None, Approval::Hold),
10329            (Some("merge"), Approval::Merge),
10330            (Some(" merge\n"), Approval::Merge),
10331            (Some("hold"), Approval::Hold),
10332            (Some(""), Approval::Hold),
10333            (Some("yes"), Approval::Hold),
10334        ];
10335        for (answer, want) in table {
10336            assert_eq!(
10337                approval(answer),
10338                want,
10339                "answer {answer:?} must resolve to {want:?}"
10340            );
10341        }
10342    }
10343
10344    #[tokio::test]
10345    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
10346        let mut state = landing_state();
10347        state.config.graph.land_approval = true;
10348        let pr = green_pr();
10349
10350        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
10351            .await
10352            .unwrap();
10353        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
10354        assert!(
10355            !state.parked,
10356            "approval_gate itself never sets `parked`; only its caller does"
10357        );
10358
10359        let store = ask::Questions::open();
10360        let filed: Vec<_> = store
10361            .list()
10362            .into_iter()
10363            .filter(|q| q.run == state.id)
10364            .collect();
10365        assert_eq!(filed.len(), 1, "exactly one question is filed");
10366        assert_eq!(filed[0].node, APPROVAL_NODE);
10367        assert_eq!(filed[0].choices, approval_choices(&state));
10368        assert!(filed[0].status.open());
10369
10370        // A second visit - standing in for a resumed run whose slot the
10371        // daemon handed to something else while nobody had answered - must
10372        // find the same question rather than filing a second one.
10373        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
10374            .await
10375            .unwrap();
10376        assert_eq!(again, ApprovalGate::Pending);
10377        let still_one = store
10378            .list()
10379            .into_iter()
10380            .filter(|q| q.run == state.id)
10381            .count();
10382        assert_eq!(
10383            still_one, 1,
10384            "asking twice must not double-file the question"
10385        );
10386    }
10387
10388    #[tokio::test]
10389    async fn approving_the_existing_question_is_read_back_as_approved() {
10390        crate::run::pin_test_home();
10391        let mut state = run_state();
10392        state.config.graph.land_approval = true;
10393        let pr = green_pr();
10394        assert_eq!(
10395            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10396                .await
10397                .unwrap(),
10398            ApprovalGate::Pending
10399        );
10400
10401        let store = ask::Questions::open();
10402        let mut q = store
10403            .list()
10404            .into_iter()
10405            .find(|q| q.run == state.id)
10406            .expect("filed above");
10407        let talks = crate::talk::Talks::open();
10408        let cfg = crate::config::Config {
10409            agents: vec![crate::config::AgentSpec {
10410                id: "mock".into(),
10411                kind: crate::config::AgentKind::Command,
10412                model: None,
10413                command: vec!["true".into()],
10414                extra_args: Vec::new(),
10415                env: Default::default(),
10416                prompt_delivery: None,
10417                max_turn_secs: None,
10418            }],
10419            ..crate::config::Config::default()
10420        };
10421        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
10422        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
10423        crate::talk::drain(&mut talk, &talks).unwrap();
10424        assert_eq!(
10425            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10426                .await
10427                .unwrap(),
10428            ApprovalGate::Pending,
10429            "consultation cannot approve or hold the merge"
10430        );
10431        q = store.get(&q.id).unwrap();
10432        assert!(q.answer.is_none());
10433        // The owner's merge answer (from the chat or the card) is the approval.
10434        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10435        store.put(&mut q).unwrap();
10436
10437        assert_eq!(
10438            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10439                .await
10440                .unwrap(),
10441            ApprovalGate::Approved
10442        );
10443    }
10444
10445    #[tokio::test]
10446    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
10447        crate::run::pin_test_home();
10448        let store = ask::Questions::open();
10449        for via_list in [false, true] {
10450            let mut state = repair_state(false, true);
10451            let pr = green_pr();
10452            approval_gate(&mut state, &pr, "feat: x", None, "abc")
10453                .await
10454                .unwrap();
10455            let id = state.land_approval.as_ref().unwrap().question.clone();
10456            store
10457                .update(&id, |q| {
10458                    q.actions.insert(
10459                        HOLD.to_owned(),
10460                        ask::ChoiceAction::Resume {
10461                            run: state.id.clone(),
10462                        },
10463                    );
10464                    Ok(())
10465                })
10466                .unwrap();
10467            let q = if via_list {
10468                store.list().into_iter().find(|q| q.id == id).unwrap()
10469            } else {
10470                store.get(&id).unwrap()
10471            };
10472            assert!(!q.actions.contains_key(HOLD));
10473            store
10474                .update(&id, |q| {
10475                    // Check the persisted migration, without another read upgrade.
10476                    assert!(!q.actions.contains_key(HOLD));
10477                    assert!(!upgrade_repair_choice(q, &state));
10478                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
10479                })
10480                .unwrap();
10481            assert!(store.get(&id).unwrap().chosen_action().is_none());
10482            assert_eq!(
10483                approval_gate(&mut state, &pr, "feat: x", None, "abc")
10484                    .await
10485                    .unwrap(),
10486                ApprovalGate::Held
10487            );
10488        }
10489    }
10490
10491    #[tokio::test]
10492    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
10493        crate::run::pin_test_home();
10494        let store = ask::Questions::open();
10495
10496        let mut held_state = run_state();
10497        held_state.config.graph.land_approval = true;
10498        let pr = green_pr();
10499        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
10500            .await
10501            .unwrap();
10502        let mut q = store
10503            .list()
10504            .into_iter()
10505            .find(|q| q.run == held_state.id)
10506            .expect("filed above");
10507        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
10508        store.put(&mut q).unwrap();
10509        assert_eq!(
10510            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
10511                .await
10512                .unwrap(),
10513            ApprovalGate::Held
10514        );
10515
10516        let mut abandoned_state = run_state();
10517        abandoned_state.config.graph.land_approval = true;
10518        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
10519            .await
10520            .unwrap();
10521        let mut q = store
10522            .list()
10523            .into_iter()
10524            .find(|q| q.run == abandoned_state.id)
10525            .expect("filed above");
10526        q.abandon("no answer within the timeout");
10527        store.put(&mut q).unwrap();
10528        assert_eq!(
10529            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
10530                .await
10531                .unwrap(),
10532            ApprovalGate::Pending,
10533            "an expired approval must ask again without merging"
10534        );
10535        assert_eq!(
10536            store.get(&q.id).unwrap().status,
10537            ask::QuestionStatus::Abandoned
10538        );
10539        assert_ne!(
10540            abandoned_state.land_approval.as_ref().unwrap().question,
10541            q.id
10542        );
10543    }
10544
10545    fn contested() -> ContestedHandoff {
10546        let finding = |id: &str, n: u32| crate::verdict::Finding {
10547            id: id.to_owned(),
10548            severity: crate::verdict::Severity::Major,
10549            file: Some("src/a.rs".to_owned()),
10550            line: Some(n),
10551            title: format!("problem {id}"),
10552            detail: String::new(),
10553        };
10554        ContestedHandoff {
10555            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
10556            rejecters: vec![(1, "alpha".to_owned())],
10557        }
10558    }
10559
10560    #[test]
10561    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
10562        let mut state = run_state();
10563        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
10564        state.contested_handoff = Some(contested());
10565        assert!(contested_to_ask(&state).is_some());
10566        state.config.graph.hold_contested_merge = false;
10567        assert!(
10568            contested_to_ask(&state).is_none(),
10569            "the switch restores today"
10570        );
10571    }
10572
10573    #[test]
10574    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
10575        let q = ask::Question::new(
10576            "run-1".to_owned(),
10577            APPROVAL_NODE.to_owned(),
10578            "land".to_owned(),
10579            "Merge?".to_owned(),
10580            String::new(),
10581            vec![APPROVE.to_owned(), HOLD.to_owned()],
10582        );
10583        let none = deputy_brief(&q, None);
10584        assert!(none.contains("could not be read"), "{none}");
10585        assert!(none.contains("Silence is a hold"), "{none}");
10586
10587        let mut state = run_state();
10588        state.pr = Some(crate::run::PrRecord {
10589            url: "https://example.test/pull/7".to_owned(),
10590            number: 7,
10591            state: "open".to_owned(),
10592            checks: "green".to_owned(),
10593            round: 0,
10594            rounds: 3,
10595            red_at_merge: Vec::new(),
10596        });
10597        state.contested_handoff = Some(contested());
10598        let b = deputy_brief(&q, Some(&state));
10599        assert!(b.contains("https://example.test/pull/7"), "{b}");
10600        assert!(b.contains("not recorded in this legacy question"), "{b}");
10601        assert!(!b.contains("This question was filed although"));
10602        state.contested_handoff = None;
10603        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
10604    }
10605
10606    #[test]
10607    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
10608        for lang in ["en", "ja"] {
10609            let mut cfg = crate::config::Config::default();
10610            cfg.graph.language = lang.to_owned();
10611            let w = words(&cfg.graph.language);
10612            let text = w.approval_detail(
10613                "https://github.com/yukimemi/magi/pull/42",
10614                "main",
10615                "feat: x",
10616                Some(&contested()),
10617            );
10618            assert!(text.contains("pull/42"), "{text}");
10619            assert!(
10620                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
10621                "{text}"
10622            );
10623            assert!(text.contains("R3-1-5"), "{text}");
10624            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
10625            assert!(text.contains("2"), "the rest are counted: {text}");
10626            assert!(text.contains("#1 (alpha)"), "{text}");
10627        }
10628        let plain = words("en").approval_detail("u", "main", "s", None);
10629        assert!(!plain.contains("reject"), "{plain}");
10630    }
10631
10632    #[tokio::test]
10633    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
10634        crate::run::pin_test_home();
10635        let mut state = run_state();
10636        state.config.graph.land_approval = false;
10637        state.contested_handoff = Some(contested());
10638        let pr = green_pr();
10639        let c = contested_to_ask(&state);
10640        assert_eq!(
10641            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10642                .await
10643                .unwrap(),
10644            ApprovalGate::Pending,
10645            "silence is a hold"
10646        );
10647        let store = ask::Questions::open();
10648        let filed: Vec<_> = store
10649            .list()
10650            .into_iter()
10651            .filter(|q| q.run == state.id)
10652            .collect();
10653        assert_eq!(filed.len(), 1);
10654        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
10655
10656        assert_eq!(
10657            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10658                .await
10659                .unwrap(),
10660            ApprovalGate::Pending
10661        );
10662        let mut q = store
10663            .list()
10664            .into_iter()
10665            .find(|q| q.run == state.id)
10666            .unwrap();
10667        assert_eq!(q.id, filed[0].id, "the same question after a resume");
10668        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10669        store.put(&mut q).unwrap();
10670        assert_eq!(
10671            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10672                .await
10673                .unwrap(),
10674            ApprovalGate::Approved
10675        );
10676    }
10677
10678    #[test]
10679    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
10680        let rows = parse_numstat(NUMSTAT);
10681        assert_eq!(
10682            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
10683            ["src/web.rs", "src/land.rs", "assets/logo.png"]
10684        );
10685        assert_eq!(rows[2].added, None, "a binary file has no line counts");
10686    }
10687    #[test]
10688    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
10689        // Reported from a real run: the merge question arrived in English on a
10690        // repository with `language = "ja"`. magi's own strings have to follow
10691        // that setting too - "it is a literal in Rust" is not an answer.
10692        let mut state = run_state();
10693        state.config.graph.language = "ja".to_owned();
10694        let pr = green_pr();
10695        let commits = ["c1".to_owned()];
10696
10697        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10698        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
10699        assert!(ja.contains("squash されるコミット"), "{ja}");
10700        assert!(ja.contains("レビューコメント"), "{ja}");
10701        assert!(ja.contains("差分"), "{ja}");
10702        assert!(
10703            !ja.contains("Commits being squashed"),
10704            "no English left over"
10705        );
10706
10707        let w = words("ja");
10708        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
10709        assert!(
10710            w.approval_detail("http://x/1", "main", "feat: x", None)
10711                .contains("パネル")
10712        );
10713
10714        // The evidence itself is language-neutral and must survive either way.
10715        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
10716        assert!(ja.contains("feat: x"), "nor is the merge subject");
10717
10718        // English stays the default, and a language magi cannot check falls
10719        // back to it rather than shipping a guess.
10720        state.config.graph.language = "en".to_owned();
10721        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10722        assert!(en.contains("Commits being squashed"), "{en}");
10723        assert_eq!(words("Klingon").html_lang, "en");
10724    }
10725
10726    /// A `gh pr list` result naming exactly one pull request whose base and
10727    /// merge time both fit the run is exactly the case
10728    /// [`find_external_merge`] exists to act on.
10729    #[test]
10730    fn pick_open_pr_classifies_by_count_and_base() {
10731        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
10732        assert_eq!(
10733            pick_open_pr(one, "main").unwrap(),
10734            OpenPr::One {
10735                url: "https://x/pull/58".into(),
10736                title: "t".into()
10737            }
10738        );
10739        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
10740        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
10741        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
10742                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
10743        assert_eq!(
10744            pick_open_pr(two, "main").unwrap(),
10745            OpenPr::Many(vec!["u1".into(), "u2".into()])
10746        );
10747        // A fork's same-named branch is not a pull request for this head.
10748        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
10749        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
10750        assert!(pick_open_pr("not json", "main").is_err());
10751        // An incomplete record is an error, never "nothing open".
10752        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
10753        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
10754    }
10755
10756    #[test]
10757    fn pick_merged_pr_picks_the_unique_match() {
10758        let json = r#"[
10759            {"url": "https://github.com/o/r/pull/42", "number": 42,
10760             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
10761        ]"#;
10762        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10763        let found = pick_merged_pr(json, "main", created_at)
10764            .expect("valid json")
10765            .expect("one unambiguous match");
10766        assert_eq!(found.url, "https://github.com/o/r/pull/42");
10767        assert_eq!(found.number, 42);
10768    }
10769
10770    /// Two candidates surviving the filter is exactly as uninformative as
10771    /// zero — a branch name can be reused across runs — so neither is
10772    /// preferred over the other and nothing is recorded automatically.
10773    #[test]
10774    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
10775        let json = r#"[
10776            {"url": "https://github.com/o/r/pull/42", "number": 42,
10777             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
10778            {"url": "https://github.com/o/r/pull/43", "number": 43,
10779             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
10780        ]"#;
10781        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10782        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10783        let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
10784        assert!(error.to_string().contains("ambiguous"), "{error:#}");
10785    }
10786
10787    /// A pull request that targets a different base branch cannot be this
10788    /// run's, whatever its head branch is named — a reused branch name from
10789    /// an unrelated task must not be recorded as this run's merge.
10790    #[test]
10791    fn pick_merged_pr_ignores_a_different_base_branch() {
10792        let json = r#"[
10793            {"url": "https://github.com/o/r/pull/42", "number": 42,
10794             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
10795        ]"#;
10796        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10797        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10798    }
10799
10800    /// A pull request merged before this run was even created cannot be this
10801    /// run's winner, no matter how its head branch is spelled.
10802    #[test]
10803    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
10804        let json = r#"[
10805            {"url": "https://github.com/o/r/pull/42", "number": 42,
10806             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
10807        ]"#;
10808        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10809        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10810    }
10811
10812    #[test]
10813    fn slug_of_pr_url_reads_host_owner_and_repo() {
10814        assert_eq!(
10815            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
10816            Some("github.com/yukimemi/shun")
10817        );
10818    }
10819
10820    #[test]
10821    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
10822        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
10823        assert_eq!(slug_of_pr_url("not a url at all"), None);
10824        assert_eq!(slug_of_pr_url("https://github.com"), None);
10825    }
10826
10827    #[test]
10828    fn slug_of_repo_url_reads_host_owner_and_repo() {
10829        assert_eq!(
10830            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
10831            Some("github.com/yukimemi/magi")
10832        );
10833        assert_eq!(slug_of_repo_url("https://github.com"), None);
10834    }
10835
10836    #[test]
10837    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
10838        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
10839            .expect("same repo, different case");
10840    }
10841
10842    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
10843    /// own in-progress run and rewrote its status from a pull request in a
10844    /// completely different repository. This is the guard that must catch
10845    /// that even when an explicit (but wrong) id is given.
10846    #[test]
10847    fn ensure_same_repo_refuses_a_different_repo() {
10848        let err =
10849            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
10850        let msg = format!("{err:#}");
10851        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10852        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
10853    }
10854
10855    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
10856    /// instance mirroring a `github.com` repository's name, say) must not be
10857    /// treated as the same repository just because the trailing path
10858    /// matches.
10859    #[test]
10860    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
10861        let err = ensure_same_repo(
10862            "github.com/yukimemi/magi",
10863            "github.example.com/yukimemi/magi",
10864        )
10865        .unwrap_err();
10866        let msg = format!("{err:#}");
10867        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10868        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
10869    }
10870
10871    /// No winner decided yet means there is no branch to ask GitHub about at
10872    /// all — `find_external_merge` must return `None` without ever spawning
10873    /// `gh`, which this proves by never providing a real repository to spawn
10874    /// it in.
10875    #[tokio::test]
10876    async fn find_external_merge_returns_none_without_a_winner() {
10877        let state = RunState::new(
10878            PathBuf::from("/no/such/repo"),
10879            "main".to_owned(),
10880            "0000000000000000000000000000000000000000".to_owned(),
10881            "irrelevant".to_owned(),
10882            crate::config::Config::default(),
10883        );
10884        assert_eq!(find_external_merge(&state).await.unwrap(), None);
10885    }
10886
10887    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
10888        let mut run = RunState::new(
10889            PathBuf::from(repo),
10890            "main".to_owned(),
10891            "abcdef1234".to_owned(),
10892            "x".to_owned(),
10893            crate::config::Config::default(),
10894        );
10895        run.id = id.to_owned();
10896        run.status = status;
10897        run.driver_exited = true;
10898        run.pr = Some(crate::run::PrRecord {
10899            number: url.rsplit('/').next().unwrap().parse().unwrap(),
10900            url: url.to_owned(),
10901            state: state.to_owned(),
10902            checks: "red".to_owned(),
10903            round: 0,
10904            rounds: 2,
10905            red_at_merge: Vec::new(),
10906        });
10907        run.save_under(home).unwrap();
10908    }
10909
10910    fn recorded(home: &Path, id: &str) -> String {
10911        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10912        serde_json::from_str::<RunState>(&body)
10913            .unwrap()
10914            .pr
10915            .unwrap()
10916            .state
10917    }
10918
10919    const PR: &str = "https://github.com/o/r/pull/7";
10920
10921    #[test]
10922    fn write_through_updates_predecessors_and_siblings_only() {
10923        let tmp = tempfile::tempdir().unwrap();
10924        let h = tmp.path();
10925        pr_run(
10926            h,
10927            "20261004-100000-aaaa",
10928            "/repo/r",
10929            RunStatus::Superseded,
10930            PR,
10931            "open",
10932        );
10933        pr_run(
10934            h,
10935            "20261004-100100-bbbb",
10936            "/repo/r",
10937            RunStatus::Blocked,
10938            PR,
10939            "open",
10940        );
10941        // Not terminal: a driver may be writing it.
10942        pr_run(
10943            h,
10944            "20261004-100200-cccc",
10945            "/repo/r",
10946            RunStatus::Landing,
10947            PR,
10948            "open",
10949        );
10950        // Another repository's pull request with the same number.
10951        pr_run(
10952            h,
10953            "20261004-100300-dddd",
10954            "/repo/other",
10955            RunStatus::Blocked,
10956            "https://github.com/o/other/pull/7",
10957            "open",
10958        );
10959        // A different pull request of the same repository.
10960        pr_run(
10961            h,
10962            "20261004-100400-eeee",
10963            "/repo/r",
10964            RunStatus::Blocked,
10965            "https://github.com/o/r/pull/8",
10966            "open",
10967        );
10968        pr_run(
10969            h,
10970            "20261004-100500-ffff",
10971            "/repo/r",
10972            RunStatus::Merged,
10973            PR,
10974            "open",
10975        );
10976        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10977
10978        assert_eq!(
10979            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10980            2
10981        );
10982        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10983        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10984        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10985        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10986        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10987        // The source's own record is the caller's to write.
10988        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10989        // Idempotent.
10990        assert_eq!(
10991            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10992            0
10993        );
10994        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10995        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10996    }
10997
10998    #[test]
10999    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
11000        let home = tempfile::tempdir().unwrap();
11001        let live_id = "20261004-100000-aaaa";
11002        let unknown_id = "20261004-100100-bbbb";
11003        for id in [live_id, unknown_id] {
11004            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
11005            let mut s = RunState::load_under(id, home.path()).unwrap();
11006            s.driver_exited = false;
11007            // Model legacy driver evidence, not a newly reserved unstarted run.
11008            s.driver_claimed = None;
11009            if id == live_id {
11010                s.driver_pid = Some(std::process::id());
11011                s.driver_started_at = crate::proc::process_started_at(std::process::id());
11012            }
11013            s.save_under(home.path()).unwrap();
11014            if id == unknown_id {
11015                assert_eq!(
11016                    s.liveness_under(home.path(), false),
11017                    crate::run::Liveness::Unknown
11018                );
11019            }
11020        }
11021        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
11022        assert_eq!(apply_pr_states(home.path(), &known), 0);
11023        for id in [live_id, unknown_id] {
11024            assert_eq!(recorded(home.path(), id), "open");
11025        }
11026    }
11027
11028    #[test]
11029    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
11030        let tmp = tempfile::tempdir().unwrap();
11031        let h = tmp.path();
11032        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
11033        pr_run(
11034            h,
11035            "20261004-100000-aaaa",
11036            "/repo/r",
11037            RunStatus::Superseded,
11038            &url(1),
11039            "open",
11040        );
11041        pr_run(
11042            h,
11043            "20261004-100100-bbbb",
11044            "/repo/r",
11045            RunStatus::Blocked,
11046            &url(2),
11047            "open",
11048        );
11049        pr_run(
11050            h,
11051            "20261004-100200-cccc",
11052            "/repo/r",
11053            RunStatus::Ready,
11054            &url(3),
11055            "open",
11056        );
11057        pr_run(
11058            h,
11059            "20261004-100300-dddd",
11060            "/repo/r",
11061            RunStatus::Ready,
11062            &url(4),
11063            "open",
11064        );
11065        pr_run(
11066            h,
11067            "20261004-100400-eeee",
11068            "/repo/r",
11069            RunStatus::Implementing,
11070            &url(1),
11071            "open",
11072        );
11073        assert_eq!(stale_open_prs(h).len(), 4);
11074
11075        let mut known = BTreeMap::new();
11076        known.insert(url(1), PrLifecycle::Merged);
11077        known.insert(url(2), PrLifecycle::Closed);
11078        known.insert(url(3), PrLifecycle::Open);
11079        // #4: the forge could not be read, so it has no answer.
11080        assert_eq!(apply_pr_states(h, &known), 2);
11081        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
11082        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
11083        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
11084        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
11085        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
11086        assert_eq!(apply_pr_states(h, &known), 0);
11087    }
11088
11089    // --- the land loop against a scripted forge -------------------------
11090
11091    use std::collections::VecDeque;
11092    use std::sync::Mutex;
11093
11094    /// Answers views from a script (the last one repeats), merges from a
11095    /// queue, and records every call so a test can assert the order.
11096    struct Scripted {
11097        public_repo: Option<PathBuf>,
11098        evidence: Mutex<Option<CiEvidence>>,
11099        views: Mutex<VecDeque<Seen>>,
11100        merges: Mutex<VecDeque<(bool, String)>>,
11101        fix: Mutex<Option<Fixed>>,
11102        log: Mutex<Vec<&'static str>>,
11103        argvs: Mutex<Vec<Vec<String>>>,
11104        required: Mutex<Option<BTreeSet<String>>>,
11105        /// Set once a merge answered ok: the forge then reports `merged`,
11106        /// unless `queued` says the merge only entered a queue.
11107        merged: Mutex<bool>,
11108        queued: Mutex<bool>,
11109        /// Views fail once a merge answered ok.
11110        unreadable_after_merge: Mutex<bool>,
11111        /// Workflow runs asked to rerun, and whether that call fails.
11112        reruns: Mutex<Vec<String>>,
11113        rerun_fails: Mutex<bool>,
11114        /// Unix seconds; every poll moves it on by `POLL`.
11115        clock: Mutex<i64>,
11116    }
11117
11118    impl Scripted {
11119        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
11120            Self {
11121                public_repo: None,
11122                evidence: Mutex::new(None),
11123                views: Mutex::new(views.into()),
11124                merges: Mutex::new(
11125                    merges
11126                        .into_iter()
11127                        .map(|(ok, m)| (ok, m.to_owned()))
11128                        .collect(),
11129                ),
11130                fix: Mutex::new(None),
11131                log: Mutex::new(Vec::new()),
11132                argvs: Mutex::new(Vec::new()),
11133                required: Mutex::new(None),
11134                merged: Mutex::new(false),
11135                queued: Mutex::new(false),
11136                unreadable_after_merge: Mutex::new(false),
11137                reruns: Mutex::new(Vec::new()),
11138                rerun_fails: Mutex::new(false),
11139                clock: Mutex::new(1_000),
11140            }
11141        }
11142        fn for_pr(url: &str, mut views: Vec<Seen>) -> Self {
11143            for view in &mut views {
11144                view.pr.url = url.to_owned();
11145            }
11146            Self::new(views, vec![])
11147        }
11148        fn argvs(&self) -> Vec<Vec<String>> {
11149            self.argvs.lock().unwrap().clone()
11150        }
11151        fn calls(&self) -> Vec<&'static str> {
11152            self.log.lock().unwrap().clone()
11153        }
11154    }
11155
11156    impl Forge for Scripted {
11157        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
11158            self.evidence.lock().unwrap().clone()
11159        }
11160        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
11161            self.log.lock().unwrap().push("view");
11162            if *self.unreadable_after_merge.lock().unwrap()
11163                && !self.argvs.lock().unwrap().is_empty()
11164            {
11165                anyhow::bail!("forge unreachable");
11166            }
11167            let mut seen = {
11168                let mut v = self.views.lock().unwrap();
11169                if v.len() > 1 {
11170                    v.pop_front().unwrap()
11171                } else {
11172                    v[0].clone()
11173                }
11174            };
11175            if seen.head == "@published" {
11176                let head =
11177                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
11178                        .await?
11179                        .context("missing published head")?;
11180                seen.head.clone_from(&head);
11181                seen.rollup_head = head;
11182            }
11183            if *self.merged.lock().unwrap() {
11184                seen.pr.state = PrLifecycle::Merged;
11185            }
11186            Ok(seen)
11187        }
11188        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
11189            self.log.lock().unwrap().push("merge");
11190            self.argvs.lock().unwrap().push(argv.to_vec());
11191            let out = self
11192                .merges
11193                .lock()
11194                .unwrap()
11195                .pop_front()
11196                .expect("unscripted merge");
11197            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
11198            {
11199                *self.merged.lock().unwrap() = true;
11200            }
11201            Ok(out)
11202        }
11203        async fn poll(&self) {
11204            self.log.lock().unwrap().push("poll");
11205            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
11206        }
11207        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
11208            self.log.lock().unwrap().push("rerun");
11209            self.reruns.lock().unwrap().push(run.to_owned());
11210            if *self.rerun_fails.lock().unwrap() {
11211                anyhow::bail!("gh run rerun: no");
11212            }
11213            Ok(())
11214        }
11215        fn now(&self) -> i64 {
11216            *self.clock.lock().unwrap()
11217        }
11218        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
11219            self.required.lock().unwrap().clone()
11220        }
11221        async fn fix(
11222            &self,
11223            _state: &mut RunState,
11224            _pr: &PrState,
11225            _round: usize,
11226            _budget: usize,
11227            _reason: &str,
11228            _logs: &str,
11229        ) -> Result<Fixed> {
11230            self.log.lock().unwrap().push("fix");
11231            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
11232        }
11233    }
11234
11235    const REFUSED: &str =
11236        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
11237
11238    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
11239        let mut pr = green_pr();
11240        pr.checks = checks;
11241        pr.blocking = Blocking::of(merge_state);
11242        if !comments {
11243            pr.review_comments.clear();
11244        }
11245        Seen {
11246            pr,
11247            title: "feat: x".to_owned(),
11248            failing_urls: Vec::new(),
11249            head: head.to_owned(),
11250            rollup_head: head.to_owned(),
11251            merge_state: merge_state.to_owned(),
11252            contexts: Vec::new(),
11253            base: "main".to_owned(),
11254        }
11255    }
11256
11257    fn landing_state() -> RunState {
11258        crate::run::pin_test_home();
11259        let mut state = run_state();
11260        state.config.graph.land_approval = false;
11261        state
11262    }
11263
11264    #[test]
11265    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
11266        assert!(!awaiting_new_head(None, "aaa"));
11267        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
11268        assert!(awaiting_new_head(Some("abc123"), "def456"));
11269        assert!(awaiting_new_head(Some("abc123"), ""));
11270    }
11271
11272    #[test]
11273    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
11274        let open = |c, m: &str| seen("a", c, m, false);
11275        let table = [
11276            (None, false, Refused::Pending),
11277            (
11278                Some(open(Checks::Pending, "BLOCKED")),
11279                false,
11280                Refused::Pending,
11281            ),
11282            (
11283                Some(open(Checks::Unknown, "BLOCKED")),
11284                false,
11285                Refused::Pending,
11286            ),
11287            (
11288                Some(open(Checks::Green, "UNKNOWN")),
11289                false,
11290                Refused::Pending,
11291            ),
11292            (Some(open(Checks::Green, "")), false, Refused::Pending),
11293            (
11294                Some(open(Checks::Green, "BLOCKED")),
11295                false,
11296                Refused::Recheck,
11297            ),
11298            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
11299        ];
11300        for (after, rechecked, want) in table {
11301            assert_eq!(
11302                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
11303                want
11304            );
11305        }
11306        let mut closed = open(Checks::Green, "CLEAN");
11307        closed.pr.state = PrLifecycle::Closed;
11308        assert_eq!(
11309            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
11310            Refused::Final
11311        );
11312    }
11313
11314    #[test]
11315    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
11316        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
11317            let pr = seen("a", checks, "BEHIND", false).pr;
11318            assert_eq!(
11319                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
11320                Step::Rebase
11321            );
11322        }
11323        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
11324            let current = seen("a", Checks::Green, status, false);
11325            assert_ne!(
11326                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
11327                Step::Rebase
11328            );
11329            assert_ne!(
11330                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
11331                Refused::Behind
11332            );
11333        }
11334        let mut current = seen("a", Checks::Pending, "BEHIND", false);
11335        current.rollup_head = "old".into();
11336        assert_eq!(
11337            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
11338            Refused::Behind
11339        );
11340        assert_eq!(
11341            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
11342            Refused::Pending
11343        );
11344        current.pr.state = PrLifecycle::Closed;
11345        assert_eq!(
11346            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
11347            Refused::Final
11348        );
11349    }
11350
11351    #[tokio::test]
11352    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
11353        for boundary in ["initial", "premerge", "refusal"] {
11354            let (_tmp, mut state, old) = landing_git_fixture().await;
11355            state.land_sync_pending = false;
11356            advance_landing_base(&state).await;
11357            state.config.verify.gate = vec!["test -f advance".into()];
11358            state.config.verify.e2e = vec!["test -f advance".into()];
11359            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
11360                .await
11361                .unwrap();
11362            let old_binding = state.land_approval.clone().unwrap();
11363            let store = ask::Questions::open();
11364            let mut question = store.get(&old_binding.question).unwrap();
11365            question
11366                .answer(ask::Answer::Choice(APPROVE.to_owned()))
11367                .unwrap();
11368            store.put(&mut question).unwrap();
11369            let mut views = Vec::new();
11370            if boundary != "initial" {
11371                views.push(seen(&old, Checks::Green, "CLEAN", false));
11372            }
11373            if boundary == "refusal" {
11374                views.push(seen(&old, Checks::Green, "CLEAN", false));
11375            }
11376            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
11377            behind.rollup_head = "old-ci-head".into();
11378            views.push(behind);
11379            // Publication checks the PR lease while verification has completed.
11380            views.push(seen(&old, Checks::Green, "CLEAN", false));
11381            views.push(seen("@published", Checks::Pending, "CLEAN", false));
11382            views.push(seen("@published", Checks::Green, "CLEAN", false));
11383            let merges = if boundary == "refusal" {
11384                vec![(false, REFUSED)]
11385            } else {
11386                vec![]
11387            };
11388            let mut forge = Scripted::new(views, merges);
11389            forge.public_repo = Some(state.repo.clone());
11390            let run = state.id.clone();
11391            land_with(&mut state, URL, &forge).await.unwrap();
11392            let head = state.pr_pushed_head.clone().unwrap();
11393            assert_ne!(head, old, "{boundary}");
11394            assert_eq!(state.id, run);
11395            assert_eq!(state.pr_branch(), Some("task-head"));
11396            assert_eq!(state.winner().unwrap().branch, "winner");
11397            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
11398            assert!(state.gate_allows_progress());
11399            let e2e = state.head_e2e.as_ref().unwrap();
11400            assert_eq!(e2e.head, head);
11401            assert!(e2e.passed);
11402            assert_eq!(state.land_sync_attempts, 1);
11403            assert!(!state.land_sync_pending);
11404            assert!(state.parked);
11405            let binding = state.land_approval.as_ref().unwrap();
11406            assert_eq!(binding.head, head);
11407            assert_ne!(binding.question, old_binding.question);
11408            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
11409            // The new question authorizes only the synchronized head on resume.
11410            let mut question = store.get(&binding.question).unwrap();
11411            question
11412                .answer(ask::Answer::Choice(APPROVE.to_owned()))
11413                .unwrap();
11414            store.put(&mut question).unwrap();
11415            let forge = Scripted::new(
11416                vec![seen(&head, Checks::Green, "CLEAN", false)],
11417                vec![(true, "")],
11418            );
11419            land_with(&mut state, URL, &forge).await.unwrap();
11420            assert_eq!(state.status, RunStatus::Merged);
11421            assert_eq!(
11422                value_of(&forge.argvs()[0], "--match-head-commit"),
11423                Some(head.as_str())
11424            );
11425        }
11426    }
11427
11428    #[tokio::test]
11429    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
11430        let (_tmp, mut state, old) = landing_git_fixture().await;
11431        state.land_sync_pending = false;
11432        state.config.graph.land_approval = false;
11433        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
11434        advance_landing_base(&state).await;
11435        let mut forge = Scripted::new(
11436            vec![
11437                seen(&old, Checks::Green, "CLEAN", false),
11438                seen(&old, Checks::Green, "CLEAN", false),
11439                seen(&old, Checks::Green, "BEHIND", false),
11440                // The next observation is the publication lease check. The
11441                // refusal's evidence still applies to exactly this old head.
11442                seen(&old, Checks::Green, "CLEAN", false),
11443                seen("@published", Checks::Green, "CLEAN", false),
11444            ],
11445            vec![(false, REFUSED), (true, "")],
11446        );
11447        forge.public_repo = Some(state.repo.clone());
11448        land_with(&mut state, URL, &forge).await.unwrap();
11449        let head = state.pr_pushed_head.as_deref().unwrap();
11450        assert_ne!(head, old);
11451        assert_eq!(state.land_sync_attempts, 1);
11452        assert_eq!(state.gate_head.as_deref(), Some(head));
11453        assert_eq!(state.status, RunStatus::Merged);
11454        let requests = forge.argvs();
11455        assert_eq!(requests.len(), 2);
11456        assert_eq!(
11457            value_of(&requests[0], "--match-head-commit"),
11458            Some(old.as_str())
11459        );
11460        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
11461    }
11462
11463    #[tokio::test]
11464    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
11465        let (tmp, mut state, old) = landing_git_fixture().await;
11466        state.land_sync_pending = false;
11467        // A damaged history must not be interpreted as a missing base. Keep
11468        // the head's tree intact so worktree restoration itself can succeed.
11469        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
11470        let commit = tmp.path().join("broken-commit");
11471        std::fs::write(
11472            &commit,
11473            format!(
11474                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
11475                "f".repeat(40)
11476            ),
11477        )
11478        .unwrap();
11479        let replacement = git::git(
11480            &state.repo,
11481            &[
11482                "hash-object",
11483                "-t",
11484                "commit",
11485                "-w",
11486                commit.to_str().unwrap(),
11487            ],
11488        )
11489        .await
11490        .unwrap();
11491        git::git(&state.repo, &["replace", &old, replacement.trim()])
11492            .await
11493            .unwrap();
11494        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11495        land_with(&mut state, URL, &forge).await.unwrap();
11496        assert_eq!(state.land_sync_attempts, 0);
11497        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
11498        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
11499        assert!(forge.argvs().is_empty());
11500        assert!(
11501            state.events.iter().any(|e| e.message.contains(
11502                "could not determine whether the landing head contains the fetched base"
11503            ))
11504        );
11505    }
11506
11507    #[tokio::test]
11508    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
11509        let (_tmp, mut state, old) = landing_git_fixture().await;
11510        state.land_sync_pending = false;
11511        git::git(
11512            &state.repo,
11513            &["remote", "set-url", "origin", "missing-remote"],
11514        )
11515        .await
11516        .unwrap();
11517        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11518        land_with(&mut state, URL, &forge).await.unwrap();
11519        assert_eq!(state.land_sync_attempts, 0);
11520        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
11521        assert!(
11522            state
11523                .events
11524                .iter()
11525                .any(|e| e.message.contains("cannot fetch landing base"))
11526        );
11527        assert!(forge.argvs().is_empty());
11528    }
11529
11530    #[tokio::test]
11531    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
11532        let (_tmp, mut state, old) = landing_git_fixture().await;
11533        state.land_sync_pending = false;
11534        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11535        land_with(&mut state, URL, &forge).await.unwrap();
11536        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
11537        assert_eq!(state.land_sync_attempts, 0);
11538        assert!(
11539            state
11540                .events
11541                .iter()
11542                .any(|e| e.message.contains("already included"))
11543        );
11544        advance_landing_base(&state).await;
11545        state.land_sync_attempts = state.config.graph.land_rounds;
11546        state.land_sync_pending = true;
11547        state.save().unwrap();
11548        let mut restored = RunState::load(&state.id).unwrap();
11549        assert!(
11550            resume_observed_head(&mut restored, &old)
11551                .await
11552                .unwrap_err()
11553                .to_string()
11554                .contains("budget exhausted")
11555        );
11556        assert_eq!(
11557            git::remote_head(&state.repo, "origin", "task-head")
11558                .await
11559                .unwrap(),
11560            Some(old)
11561        );
11562    }
11563
11564    #[tokio::test]
11565    async fn a_normal_landing_merges_on_the_first_look() {
11566        let mut state = landing_state();
11567        let forge = Scripted::new(
11568            vec![seen("a", Checks::Green, "CLEAN", false)],
11569            vec![(true, "")],
11570        );
11571        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11572            .await
11573            .unwrap();
11574        // One fresh read, then the head-bound merge.
11575        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11576        assert_eq!(state.status, RunStatus::Merged);
11577    }
11578
11579    #[tokio::test]
11580    async fn landing_refuses_unfinished_instruction_revision_before_observing_pr() {
11581        let mut state = landing_state();
11582        let url = "https://github.com/o/r/pull/42";
11583        crate::instruction_revision_control::adopt_into_run(
11584            &mut state,
11585            "cli/revision",
11586            "revision-repair",
11587            "revised task",
11588            1,
11589            "a",
11590            url,
11591        );
11592        for phase in [
11593            crate::run::MergeRepairPhase::Requested,
11594            crate::run::MergeRepairPhase::Fixing,
11595            crate::run::MergeRepairPhase::Reviewing,
11596            crate::run::MergeRepairPhase::Failed,
11597        ] {
11598            state.merge_repairs[0].phase = phase;
11599            let forge = Scripted::new(
11600                vec![seen("a", Checks::Green, "CLEAN", false)],
11601                vec![(true, "")],
11602            );
11603            let error = land_with(&mut state, url, &forge).await.unwrap_err();
11604            assert!(
11605                error
11606                    .to_string()
11607                    .contains("instruction revision repair did not complete")
11608            );
11609            assert!(forge.calls().is_empty());
11610            assert!(state.land_approval.is_none());
11611        }
11612        state.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
11613        assert!(state.unfinished_instruction_revision().is_none());
11614    }
11615
11616    #[tokio::test]
11617    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
11618        let mut state = landing_state();
11619        let forge = Scripted::new(
11620            vec![seen("a", Checks::Green, "CLEAN", false)],
11621            std::iter::repeat_n((true, ""), 100).collect(),
11622        );
11623        *forge.queued.lock().unwrap() = true;
11624        let task = async {
11625            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11626                .await
11627                .unwrap();
11628        };
11629        // Still open after the command succeeded: it keeps watching and
11630        // never records a merge (it stops at the wait ceiling instead).
11631        task.await;
11632        assert_ne!(state.status, RunStatus::Merged);
11633    }
11634
11635    #[tokio::test]
11636    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
11637        let mut state = landing_state();
11638        let forge = Scripted::new(
11639            vec![seen("a", Checks::Green, "CLEAN", false)],
11640            std::iter::repeat_n((true, ""), 100).collect(),
11641        );
11642        *forge.unreadable_after_merge.lock().unwrap() = true;
11643        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11644            .await
11645            .ok();
11646        assert_ne!(state.status, RunStatus::Merged);
11647    }
11648
11649    #[tokio::test]
11650    async fn a_task_public_head_is_awaited_on_land_entry() {
11651        let mut state = landing_state();
11652        state.pr_head = Some("magi/task-abcd-1234".into());
11653        state.pr_pushed_head = Some("new".into());
11654        let forge = Scripted::new(
11655            vec![
11656                seen("old", Checks::Green, "CLEAN", false),
11657                seen("new", Checks::Green, "CLEAN", false),
11658            ],
11659            vec![(true, "")],
11660        );
11661        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11662            .await
11663            .unwrap();
11664        assert_eq!(
11665            forge.calls(),
11666            ["view", "poll", "view", "view", "merge", "view"]
11667        );
11668        assert_eq!(state.status, RunStatus::Merged);
11669    }
11670
11671    #[tokio::test]
11672    async fn a_superseded_public_head_owner_cannot_reenter_land() {
11673        let mut state = landing_state();
11674        state.pr_taken_over_by = Some("next".into());
11675        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
11676        assert!(
11677            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11678                .await
11679                .is_err()
11680        );
11681        assert!(forge.calls().is_empty());
11682    }
11683
11684    #[tokio::test]
11685    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
11686        let mut state = landing_state();
11687        let forge = Scripted::new(
11688            vec![
11689                seen("old", Checks::Green, "CLEAN", true),
11690                // The forge has not moved to the new head yet: still green.
11691                seen("old", Checks::Green, "CLEAN", true),
11692                seen("new", Checks::Pending, "BLOCKED", true),
11693                seen("new", Checks::Green, "CLEAN", true),
11694            ],
11695            vec![(true, "")],
11696        );
11697        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11698            head: "NEW".to_owned(),
11699        });
11700        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11701            .await
11702            .unwrap();
11703        assert_eq!(
11704            forge.calls(),
11705            [
11706                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
11707                "view"
11708            ]
11709        );
11710        assert_eq!(state.status, RunStatus::Merged);
11711    }
11712
11713    #[tokio::test]
11714    async fn a_head_that_never_arrives_stops_naming_both_commits() {
11715        let mut state = landing_state();
11716        let forge = Scripted::new(
11717            vec![
11718                seen("old", Checks::Green, "CLEAN", true),
11719                seen("someone-elses", Checks::Green, "CLEAN", true),
11720            ],
11721            vec![],
11722        );
11723        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11724            head: "mine".to_owned(),
11725        });
11726        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11727            .await
11728            .unwrap();
11729        assert!(!forge.calls().contains(&"merge"));
11730        let why = state.merge.as_ref().unwrap().detail.clone();
11731        assert!(
11732            why.contains("mine") && why.contains("someone-elses"),
11733            "{why}"
11734        );
11735        assert_eq!(state.status, RunStatus::Blocked);
11736    }
11737
11738    #[tokio::test]
11739    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
11740        let mut state = landing_state();
11741        let forge = Scripted::new(
11742            vec![
11743                seen("a", Checks::Green, "CLEAN", false),
11744                seen("a", Checks::Green, "CLEAN", false),
11745                seen("a", Checks::Pending, "BLOCKED", false),
11746                seen("a", Checks::Pending, "BLOCKED", false),
11747                seen("a", Checks::Green, "CLEAN", false),
11748            ],
11749            vec![(false, REFUSED), (true, "")],
11750        );
11751        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11752            .await
11753            .unwrap();
11754        assert_eq!(
11755            forge.calls(),
11756            [
11757                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
11758                "view"
11759            ]
11760        );
11761        assert_eq!(state.status, RunStatus::Merged);
11762    }
11763
11764    #[tokio::test]
11765    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
11766        let mut state = landing_state();
11767        let forge = Scripted::new(
11768            vec![
11769                seen("a", Checks::Green, "CLEAN", false),
11770                seen("a", Checks::Green, "BLOCKED", false),
11771            ],
11772            vec![(false, REFUSED), (false, REFUSED)],
11773        );
11774        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11775            .await
11776            .unwrap();
11777        // One re-look is allowed for the forge's own lag, then it is final.
11778        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
11779        let why = state.merge.as_ref().unwrap().detail.clone();
11780        assert!(
11781            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
11782            "{why}"
11783        );
11784        assert_eq!(state.status, RunStatus::Blocked);
11785    }
11786
11787    #[test]
11788    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
11789        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
11790        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
11791        // The pull request is still on the commit before the push.
11792        assert_eq!(bound_head("old", "old", Some("new")), None);
11793        // The checks are the previous commit's.
11794        assert_eq!(bound_head("new", "old", Some("new")), None);
11795        assert_eq!(bound_head("new", "old", None), None);
11796        // Nothing readable.
11797        assert_eq!(bound_head("", "", None), None);
11798        assert_eq!(bound_head("", "", Some("new")), None);
11799        assert_eq!(bound_head("abc", "", None), None);
11800    }
11801
11802    fn view_json(head: &str) -> String {
11803        format!(
11804            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
11805            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
11806            "reviews":[],"comments":[]}}"#
11807        )
11808    }
11809
11810    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
11811        format!(
11812            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
11813            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
11814            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
11815            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
11816        )
11817    }
11818
11819    #[test]
11820    fn rollup_is_bound_to_the_commit_in_the_same_node() {
11821        // The view already points at the new head, but the node still answers
11822        // for the old commit with its red check: the head stays unbound.
11823        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
11824        assert_eq!(s.rollup_head, "old");
11825        assert_eq!(s.pr.checks, Checks::Red);
11826        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
11827        assert_eq!(s.failing_urls.len(), 1);
11828    }
11829
11830    #[test]
11831    fn checks_come_from_the_node_not_the_view() {
11832        let view = view_json("new").replace(
11833            r#""reviews""#,
11834            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
11835        );
11836        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
11837        assert_eq!(s.pr.checks, Checks::Green);
11838        assert!(s.pr.failing.is_empty());
11839        assert_eq!(
11840            bound_head(&s.head, &s.rollup_head, Some("new")),
11841            Some("new")
11842        );
11843    }
11844
11845    #[test]
11846    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
11847        for node in [
11848            None,
11849            Some("not json".to_owned()),
11850            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
11851            Some(node_json("new", "SUCCESS", true)),
11852        ] {
11853            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
11854            assert!(s.rollup_head.is_empty());
11855            assert_eq!(s.pr.checks, Checks::Unknown);
11856            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
11857        }
11858    }
11859
11860    #[test]
11861    fn the_merge_command_is_pinned_to_the_observed_head() {
11862        let argv = merge_argv_at(7, "feat: x", "deadbeef");
11863        let at = argv
11864            .iter()
11865            .position(|a| a == "--match-head-commit")
11866            .unwrap();
11867        assert_eq!(argv[at + 1], "deadbeef");
11868    }
11869
11870    #[tokio::test]
11871    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
11872        let mut state = landing_state();
11873        // The pull request is on the pushed head but the rollup is still the
11874        // previous commit's red, non-required result.
11875        let mut stale = seen("new", Checks::Red, "CLEAN", false);
11876        stale.rollup_head = "old".to_owned();
11877        let forge = Scripted::new(
11878            vec![seen("old", Checks::Green, "CLEAN", true), stale],
11879            vec![],
11880        );
11881        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11882            head: "new".to_owned(),
11883        });
11884        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11885            .await
11886            .unwrap();
11887        assert!(!forge.calls().contains(&"merge"));
11888        assert_eq!(state.status, RunStatus::Blocked);
11889        let why = state.merge.as_ref().unwrap().detail.clone();
11890        assert!(why.contains("new") && why.contains("old"), "{why}");
11891    }
11892
11893    #[test]
11894    fn a_refusal_read_against_another_commits_checks_is_pending() {
11895        let mut after = seen("a", Checks::Green, "BLOCKED", false);
11896        after.rollup_head = "old".to_owned();
11897        assert_eq!(
11898            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
11899            Refused::Pending
11900        );
11901    }
11902
11903    #[tokio::test]
11904    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
11905        let mut state = landing_state();
11906        state.config.merge.ci = crate::config::MergeCi::None;
11907        state.config.graph.land_approval = true;
11908        let forge = Scripted::new(
11909            vec![seen("a", Checks::Unknown, "CLEAN", false)],
11910            vec![(true, "")],
11911        );
11912        land_with(&mut state, URL, &forge).await.unwrap();
11913        assert!(state.parked);
11914        assert_eq!(forge.calls(), ["view"]);
11915        let store = ask::Questions::open();
11916        let mut q = store
11917            .get(&state.land_approval.as_ref().unwrap().question)
11918            .unwrap();
11919        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11920        store.put(&mut q).unwrap();
11921
11922        land_with(&mut state, URL, &forge).await.unwrap();
11923        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
11924        assert_eq!(state.status, RunStatus::Merged);
11925        assert_eq!(
11926            value_of(&forge.argvs()[0], "--match-head-commit"),
11927            Some("a")
11928        );
11929    }
11930
11931    #[tokio::test]
11932    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
11933        let mut state = landing_state();
11934        state.config.merge.ci = crate::config::MergeCi::None;
11935        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
11936        land_with(&mut state, URL, &forge).await.unwrap();
11937        assert!(forge.reruns.lock().unwrap().is_empty());
11938        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11939        assert_eq!(state.status, RunStatus::Merged);
11940    }
11941
11942    #[test]
11943    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
11944        let shown = BTreeSet::new();
11945        let guard = |s: Option<&Seen>| {
11946            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11947        };
11948        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11949        assert!(guard(Some(&fresh)));
11950        assert!(!guard(None));
11951        fresh.rollup_head = "old".to_owned();
11952        assert!(!guard(Some(&fresh)));
11953        fresh.rollup_head = "a".to_owned();
11954        fresh.head = "b".to_owned();
11955        assert!(!guard(Some(&fresh)));
11956        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11957        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11958    }
11959
11960    #[test]
11961    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11962        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11963            let after = seen("a", checks, "BLOCKED", false);
11964            assert_eq!(
11965                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11966                Refused::Recheck
11967            );
11968            assert_eq!(
11969                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11970                Refused::Final
11971            );
11972        }
11973    }
11974
11975    #[tokio::test]
11976    async fn a_matching_head_with_red_non_required_checks_still_merges() {
11977        let mut state = landing_state();
11978        let forge = Scripted::new(
11979            vec![seen("a", Checks::Red, "CLEAN", false)],
11980            vec![(true, "")],
11981        );
11982        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11983            .await
11984            .unwrap();
11985        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11986        assert_eq!(state.status, RunStatus::Merged);
11987    }
11988
11989    #[tokio::test]
11990    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11991        let mut state = landing_state();
11992        let forge = Scripted::new(
11993            vec![
11994                seen("a", Checks::Green, "CLEAN", false),
11995                seen("a", Checks::Green, "CLEAN", false),
11996                // Re-viewed after the refusal: someone pushed.
11997                seen("b", Checks::Green, "BLOCKED", false),
11998                seen("b", Checks::Green, "CLEAN", false),
11999            ],
12000            vec![(false, REFUSED), (true, "")],
12001        );
12002        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
12003            .await
12004            .unwrap();
12005        assert_eq!(
12006            forge.calls(),
12007            [
12008                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
12009            ]
12010        );
12011        assert_eq!(state.status, RunStatus::Merged);
12012    }
12013
12014    fn merged_view(head: &str) -> Seen {
12015        let mut m = seen(head, Checks::Green, "CLEAN", false);
12016        m.pr.state = PrLifecycle::Merged;
12017        m
12018    }
12019
12020    fn has(argv: &[String], flag: &str) -> bool {
12021        argv.iter().any(|a| a == flag)
12022    }
12023
12024    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
12025        let at = argv.iter().position(|a| a == flag)?;
12026        argv.get(at + 1).map(String::as_str)
12027    }
12028
12029    const URL: &str = "https://github.com/o/r/pull/42";
12030
12031    #[tokio::test]
12032    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
12033        let mut state = landing_state();
12034        let forge = Scripted::new(
12035            vec![
12036                seen("abc", Checks::Green, "CLEAN", false),
12037                seen("abc", Checks::Green, "CLEAN", false),
12038            ],
12039            vec![(true, "")],
12040        );
12041        land_with(&mut state, URL, &forge).await.unwrap();
12042        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
12043        let argv = &forge.argvs()[0];
12044        assert!(has(argv, "--squash") && has(argv, "--subject"));
12045        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
12046        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
12047        assert_eq!(state.status, RunStatus::Merged);
12048        assert!(state.land_armed_head.is_none());
12049    }
12050
12051    #[tokio::test]
12052    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
12053        let mut state = landing_state();
12054        state.land_armed_head = Some("a".to_owned());
12055        let forge = Scripted::new(
12056            vec![seen("a", Checks::Green, "CLEAN", false)],
12057            vec![(true, ""), (true, "")],
12058        );
12059        land_with(&mut state, URL, &forge).await.unwrap();
12060        let argvs = forge.argvs();
12061        assert!(has(&argvs[0], "--disable-auto"));
12062        assert!(!has(&argvs[1], "--auto"));
12063        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
12064        assert_eq!(state.status, RunStatus::Merged);
12065        assert!(state.land_armed_head.is_none());
12066    }
12067
12068    #[tokio::test]
12069    async fn an_approval_never_carries_over_to_a_new_head() {
12070        crate::run::pin_test_home();
12071        let mut state = run_state();
12072        state.config.graph.land_approval = true;
12073        let pr = green_pr();
12074        let store = ask::Questions::open();
12075
12076        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
12077            .await
12078            .unwrap();
12079        let mut q = store
12080            .list()
12081            .into_iter()
12082            .find(|q| q.run == state.id)
12083            .unwrap();
12084        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
12085        store.put(&mut q).unwrap();
12086        assert_eq!(
12087            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
12088                .await
12089                .unwrap(),
12090            ApprovalGate::Approved,
12091            "the same head keeps its approval"
12092        );
12093
12094        // A new head is a new question, not the old word.
12095        assert_eq!(
12096            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
12097                .await
12098                .unwrap(),
12099            ApprovalGate::Pending
12100        );
12101        let all: Vec<_> = store
12102            .list()
12103            .into_iter()
12104            .filter(|q| q.run == state.id)
12105            .collect();
12106        assert_eq!(all.len(), 2);
12107
12108        // A question recorded before heads were tracked is not reused either.
12109        state.land_approval = None;
12110        assert_eq!(
12111            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
12112                .await
12113                .unwrap(),
12114            ApprovalGate::Pending
12115        );
12116        let open = store
12117            .list()
12118            .into_iter()
12119            .filter(|q| q.run == state.id && q.status.open())
12120            .count();
12121        assert_eq!(open, 1, "the superseded question was retired");
12122    }
12123
12124    #[tokio::test]
12125    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
12126        let mut state = landing_state();
12127        let forge = Scripted::new(
12128            vec![
12129                seen("a", Checks::Green, "CLEAN", false),
12130                // The fresh read before the merge: someone pushed.
12131                seen("b", Checks::Green, "CLEAN", false),
12132            ],
12133            vec![(true, "")],
12134        );
12135        land_with(&mut state, URL, &forge).await.unwrap();
12136        let argvs = forge.argvs();
12137        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
12138        assert!(!has(&argvs[0], "--auto"));
12139        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
12140        assert_eq!(state.status, RunStatus::Merged);
12141    }
12142
12143    fn passing(label: &str) -> CheckInfo {
12144        CheckInfo {
12145            label: label.to_owned(),
12146            verdict: Verdict::Pass,
12147            required: Some(false),
12148            run: None,
12149        }
12150    }
12151
12152    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
12153        (label.to_owned(), run.map(str::to_owned))
12154    }
12155
12156    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
12157        LandReruns {
12158            head: head.to_owned(),
12159            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
12160        }
12161    }
12162
12163    #[test]
12164    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
12165        let f = [failing("test (macos)", Some("7"))];
12166        assert_eq!(
12167            rerun_step(&f, None, "h", 100),
12168            RerunStep::Rerun(vec!["7".to_owned()])
12169        );
12170        let rec = reran("h", &[("7", 100)]);
12171        let grace = crate::release_watch::RERUN_GRACE;
12172        assert_eq!(
12173            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
12174            RerunStep::Grace
12175        );
12176        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
12177    }
12178
12179    #[test]
12180    fn a_failure_without_a_run_id_goes_to_the_fixer() {
12181        let f = [failing("a", Some("7")), failing("ci/external", None)];
12182        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
12183        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
12184    }
12185
12186    #[test]
12187    fn a_moved_head_forgets_the_reruns() {
12188        let f = [failing("a", Some("7"))];
12189        let rec = reran("old", &[("7", 100)]);
12190        assert_eq!(
12191            rerun_step(&f, Some(&rec), "new", 101),
12192            RerunStep::Rerun(vec!["7".to_owned()])
12193        );
12194    }
12195
12196    #[test]
12197    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
12198        let f = [
12199            failing("a", Some("7")),
12200            failing("b", Some("7")),
12201            failing("c", Some("8")),
12202        ];
12203        assert_eq!(
12204            rerun_step(&f, None, "h", 0),
12205            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
12206        );
12207        let rec = reran("h", &[("7", 0)]);
12208        assert_eq!(
12209            rerun_step(&f, Some(&rec), "h", 1),
12210            RerunStep::Rerun(vec!["8".to_owned()])
12211        );
12212    }
12213
12214    #[test]
12215    fn only_blocking_failures_are_candidates_for_a_rerun() {
12216        let check = |label: &str, verdict, required, run: &str| CheckInfo {
12217            label: label.to_owned(),
12218            verdict,
12219            required,
12220            run: Some(run.to_owned()),
12221        };
12222        let got = rerunnable(&[
12223            check("passed", Verdict::Pass, Some(true), "1"),
12224            check("optional", Verdict::Fail, Some(false), "2"),
12225            check("required", Verdict::Fail, Some(true), "3"),
12226            check("unknown", Verdict::Fail, None, "4"),
12227        ]);
12228        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
12229        assert_eq!(labels, ["required", "unknown"]);
12230    }
12231
12232    fn unrelated_ci_fixture() -> CiEvidence {
12233        let failure = CiFailure {
12234            path: "tests/web_render.rs".into(),
12235            start_line: 42,
12236            end_line: 42,
12237            title: "question_identity_disclosure_copy_and_live_updates".into(),
12238            message: "assertion failed".into(),
12239        };
12240        CiEvidence {
12241            head: "a".into(),
12242            base: "base-sha".into(),
12243            changed: vec![
12244                "AGENTS.md".into(),
12245                "src/talk.rs".into(),
12246                "tests/consult_investigation.rs".into(),
12247            ],
12248            checks: vec![CiCheckEvidence {
12249                label: "coverage".into(),
12250                head_check: 70,
12251                base_check: 60,
12252                app: 1,
12253                run: "7".into(),
12254                base_run: "6".into(),
12255                head_failures: vec![failure.clone()],
12256                base_failures: vec![failure],
12257                rerun_exhausted: true,
12258            }],
12259        }
12260    }
12261
12262    #[test]
12263    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
12264        let good = unrelated_ci_fixture();
12265        let red = vec!["coverage".into()];
12266        assert!(good.unrelated("a", &red));
12267        assert!(!good.unrelated("another-head", &red));
12268        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
12269        assert!(!good.unrelated("a", &[]));
12270        for mutation in 0..8 {
12271            let mut bad = good.clone();
12272            match mutation {
12273                0 => bad.checks[0].rerun_exhausted = false,
12274                1 => bad.checks[0].base_failures.clear(),
12275                2 => bad.checks[0].head_failures.clear(),
12276                3 => bad.changed.push("tests/web_render.rs".into()),
12277                4 => bad.changed.push(".github/workflows/ci.yml".into()),
12278                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
12279                6 => bad.checks.push(bad.checks[0].clone()),
12280                _ => bad.base.clear(),
12281            }
12282            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
12283        }
12284    }
12285
12286    #[test]
12287    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
12288        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
12289        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
12290        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
12291        assert!(matches!(
12292            decide(&pr, 2, 2, CHECKS_GRACE),
12293            Step::GiveUp { .. }
12294        ));
12295        let optional = CheckInfo {
12296            label: "coverage".into(),
12297            verdict: Verdict::Fail,
12298            required: Some(false),
12299            run: Some("7".into()),
12300        };
12301        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
12302        assert_eq!(
12303            rerunnable_with(&[optional], true),
12304            vec![("coverage".into(), Some("7".into()))]
12305        );
12306    }
12307
12308    #[tokio::test]
12309    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
12310        let mut state = landing_state();
12311        let mut red = coverage_unknown();
12312        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
12313        red.pr.failing = vec!["coverage".into()];
12314        let forge = Scripted::new(vec![red], vec![]);
12315        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
12316        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12317        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12318        assert!(forge.calls().contains(&"fix"));
12319        assert!(state.land_unrelated.is_some());
12320        assert!(state.parked);
12321        assert!(
12322            !state
12323                .events
12324                .iter()
12325                .any(|e| e.message.contains("fixer produced no commit"))
12326        );
12327    }
12328
12329    fn coverage_unknown() -> Seen {
12330        let mut s = red("a", Some("7"));
12331        s.pr.blocking = Blocking::Unsaid;
12332        s.merge_state = "UNKNOWN".into();
12333        s.pr.failing = vec!["coverage".into()];
12334        s.contexts[0].label = "coverage".into();
12335        s.contexts[0].required = Some(false);
12336        s
12337    }
12338
12339    #[tokio::test]
12340    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
12341        let mut state = landing_state();
12342        let unknown = coverage_unknown();
12343        let mut unstable = unknown.clone();
12344        unstable.pr.blocking = Blocking::of("UNSTABLE");
12345        unstable.merge_state = "UNSTABLE".into();
12346        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
12347        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12348        assert!(!forge.calls().contains(&"fix"));
12349        assert!(!forge.calls().contains(&"rerun"));
12350        assert_eq!(state.status, RunStatus::Merged);
12351        assert_eq!(state.pr.unwrap().round, 0);
12352    }
12353
12354    #[tokio::test]
12355    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
12356        let mut state = landing_state();
12357        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
12358        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
12359        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12360        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12361        assert!(!forge.calls().contains(&"fix"));
12362        assert!(state.parked);
12363        assert_eq!(state.status, RunStatus::Landing);
12364        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12365        let hold = state.land_unrelated.as_ref().unwrap();
12366        let q = ask::Questions::open().get(&hold.question).unwrap();
12367        assert!(
12368            q.actions
12369                .values()
12370                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
12371        );
12372        assert!(
12373            state
12374                .events
12375                .iter()
12376                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
12377        );
12378        let first = state.land_unsaid.clone();
12379        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
12380        state.parked = false;
12381        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12382        assert_eq!(state.land_unsaid, first);
12383        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12384    }
12385
12386    fn red(head: &str, run: Option<&str>) -> Seen {
12387        let mut s = seen(head, Checks::Red, "BLOCKED", false);
12388        s.pr.failing = vec!["test (macos)".to_owned()];
12389        s.contexts = vec![CheckInfo {
12390            label: "test (macos)".to_owned(),
12391            verdict: Verdict::Fail,
12392            required: Some(true),
12393            run: run.map(str::to_owned),
12394        }];
12395        s
12396    }
12397
12398    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
12399
12400    #[tokio::test]
12401    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
12402        let mut state = landing_state();
12403        let forge = Scripted::new(
12404            vec![
12405                red("a", Some("7")),
12406                seen("a", Checks::Pending, "BLOCKED", false),
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!(!forge.calls().contains(&"fix"));
12414        assert_eq!(state.status, RunStatus::Merged);
12415        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12416        let argvs = forge.argvs();
12417        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
12418        assert!(
12419            state
12420                .events
12421                .iter()
12422                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
12423        );
12424    }
12425
12426    #[tokio::test]
12427    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
12428        let mut state = landing_state();
12429        let forge = Scripted::new(
12430            vec![
12431                red("a", Some("7")),
12432                seen("a", Checks::Green, "CLEAN", false),
12433            ],
12434            vec![(true, "")],
12435        );
12436        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12437        // The red view repeats for the grace, then the fixer is asked once.
12438        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12439        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
12440        let calls = forge.calls();
12441        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
12442        let fix_at = calls.iter().position(|c| *c == "fix");
12443        assert!(fix_at.is_none_or(|f| f > rerun_at));
12444    }
12445
12446    #[tokio::test]
12447    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
12448        let mut state = landing_state();
12449        let mut v = red("a", Some("7"));
12450        v.pr.checks = Checks::Pending;
12451        v.contexts.push(CheckInfo {
12452            label: "slow".to_owned(),
12453            verdict: Verdict::Pending,
12454            required: Some(true),
12455            run: Some("8".to_owned()),
12456        });
12457        let forge = Scripted::new(
12458            vec![v, seen("a", Checks::Green, "CLEAN", false)],
12459            vec![(true, "")],
12460        );
12461        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12462        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12463        assert_eq!(state.status, RunStatus::Merged);
12464    }
12465
12466    #[test]
12467    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
12468        let mut v = red("a", Some("7"));
12469        v.contexts.push(CheckInfo {
12470            label: "same run, still going".to_owned(),
12471            verdict: Verdict::Pending,
12472            required: Some(true),
12473            run: Some("7".to_owned()),
12474        });
12475        assert!(rerunnable(&v.contexts).is_empty());
12476    }
12477
12478    #[tokio::test]
12479    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
12480        let mut state = landing_state();
12481        state.config.graph.land_rounds = 0;
12482        let forge = Scripted::new(
12483            vec![
12484                red("a", Some("7")),
12485                seen("a", Checks::Green, "CLEAN", false),
12486            ],
12487            vec![(true, "")],
12488        );
12489        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12490        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12491        assert_eq!(state.status, RunStatus::Merged);
12492        assert!(!forge.calls().contains(&"fix"));
12493        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12494    }
12495
12496    #[tokio::test]
12497    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
12498        let mut state = landing_state();
12499        state.config.graph.land_rounds = 1;
12500        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
12501        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
12502        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12503        assert_eq!(pr.state, PrLifecycle::Open);
12504        assert_eq!(state.status, RunStatus::Blocked);
12505        assert_eq!(state.pr.as_ref().unwrap().round, 0);
12506        assert!(
12507            state.merge_decision.is_none(),
12508            "no ordinary failure handoff"
12509        );
12510        assert!(forge.argvs().is_empty(), "no merge on outage");
12511
12512        let recovered = Scripted::new(
12513            vec![
12514                seen("a", Checks::Green, "CLEAN", true),
12515                seen("b", Checks::Green, "CLEAN", false),
12516            ],
12517            vec![(true, "")],
12518        );
12519        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
12520        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
12521        assert_eq!(state.status, RunStatus::Merged);
12522        assert_eq!(state.pr.as_ref().unwrap().round, 1);
12523        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
12524    }
12525
12526    #[tokio::test]
12527    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
12528        let mut state = landing_state();
12529        state.config.graph.land_rounds = 1;
12530        let forge = Scripted::new(
12531            vec![
12532                seen("a", Checks::Green, "CLEAN", true),
12533                red("b", Some("7")),
12534                seen("b", Checks::Green, "CLEAN", false),
12535            ],
12536            vec![(true, "")],
12537        );
12538        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
12539            head: "b".to_owned(),
12540        });
12541        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12542        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
12543        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
12544        assert_eq!(state.pr.as_ref().unwrap().round, 1);
12545        assert_eq!(state.status, RunStatus::Merged);
12546        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
12547        assert_eq!(
12548            value_of(&forge.argvs()[0], "--match-head-commit"),
12549            Some("b")
12550        );
12551    }
12552
12553    #[tokio::test]
12554    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
12555        let mut state = landing_state();
12556        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12557        *forge.rerun_fails.lock().unwrap() = true;
12558        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12559        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12560        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
12561        assert_eq!(
12562            forge.calls().iter().filter(|c| **c == "fix").count(),
12563            1,
12564            "{:?}",
12565            forge.calls()
12566        );
12567    }
12568
12569    #[tokio::test]
12570    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
12571        let mut state = landing_state();
12572        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12573        // The record was written just before the previous pass died.
12574        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
12575        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12576        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12577        assert!(forge.reruns.lock().unwrap().is_empty());
12578    }
12579
12580    #[tokio::test]
12581    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
12582        let mut state = landing_state();
12583        state.config.graph.rerun_flaky_checks = false;
12584        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12585        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12586        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12587        assert!(forge.reruns.lock().unwrap().is_empty());
12588        assert!(forge.calls().contains(&"fix"));
12589
12590        let mut state = landing_state();
12591        let forge = Scripted::new(vec![red("a", None)], vec![]);
12592        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12593        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12594        assert!(forge.reruns.lock().unwrap().is_empty());
12595        assert!(forge.calls().contains(&"fix"));
12596    }
12597
12598    fn names(xs: &[&str]) -> BTreeSet<String> {
12599        xs.iter().map(|x| (*x).to_owned()).collect()
12600    }
12601
12602    #[test]
12603    fn a_required_check_the_rollup_never_listed_is_named() {
12604        let req = names(&["build"]);
12605        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
12606        assert!(why.contains("never reported: build"), "{why}");
12607        assert!(!why.contains("probably waiting for a review"), "{why}");
12608    }
12609
12610    #[test]
12611    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
12612        let why = waiting_on("BLOCKED", &[passing("review")], None);
12613        assert!(why.contains("could not be read"), "{why}");
12614        assert!(!why.contains("probably waiting for a review"), "{why}");
12615    }
12616
12617    #[test]
12618    fn all_required_reported_keeps_the_review_guess() {
12619        let req = names(&["build"]);
12620        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12621        assert!(why.contains("probably waiting for a review"), "{why}");
12622        assert!(!why.contains("never reported"), "{why}");
12623    }
12624
12625    #[test]
12626    fn required_names_match_the_rollup_ignoring_case_only() {
12627        let req = names(&["Build"]);
12628        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12629        assert!(!why.contains("never reported"), "{why}");
12630    }
12631
12632    #[test]
12633    fn required_contexts_are_read_from_protection_and_rulesets() {
12634        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
12635        assert_eq!(
12636            parse_classic_required(classic),
12637            Some(names(&["build", "lint"]))
12638        );
12639        let rules = r#"[{"type":"pull_request","parameters":{}},
12640            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
12641        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
12642        assert_eq!(parse_ruleset_required("nope"), None);
12643        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
12644    }
12645
12646    #[test]
12647    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
12648        let shown = BTreeSet::new();
12649        let ok = seen("a", Checks::Green, "CLEAN", false);
12650        let guard = |s: Option<&Seen>| {
12651            direct_merge_is_safe(
12652                s,
12653                "A",
12654                &shown,
12655                0,
12656                4,
12657                Duration::ZERO,
12658                CiExpectation::Expected,
12659            )
12660        };
12661        assert!(guard(Some(&ok)));
12662        assert!(!guard(None));
12663        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
12664        let mut stale = ok.clone();
12665        stale.rollup_head = "old".to_owned();
12666        assert!(!guard(Some(&stale)));
12667        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
12668        assert!(!guard(Some(&merged_view("a"))));
12669    }
12670
12671    #[test]
12672    fn the_rollup_node_carries_whether_each_check_is_required() {
12673        let node = node_json("new", "SUCCESS", false)
12674            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
12675        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
12676        assert_eq!(s.contexts.len(), 1);
12677        assert_eq!(s.contexts[0].required, Some(true));
12678        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
12679        assert_eq!(s.contexts[0].required, None);
12680    }
12681
12682    #[tokio::test]
12683    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
12684        let mut state = landing_state();
12685        state.land_armed_head = Some("a".to_owned());
12686        let forge = Scripted::new(
12687            vec![seen("a", Checks::Green, "CLEAN", true)],
12688            vec![(false, "disable exploded")],
12689        );
12690        land_with(&mut state, URL, &forge).await.unwrap();
12691        assert!(!forge.calls().contains(&"fix"));
12692        assert_eq!(state.status, RunStatus::Blocked);
12693        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
12694        let why = state.merge.as_ref().unwrap().detail.clone();
12695        assert!(why.contains("disable exploded"), "{why}");
12696    }
12697
12698    /// Create a cross-platform fake `gh` executable in `dir` backed by exact
12699    /// fixture files, avoiding shell quoting differences and global `PATH`
12700    /// mutation.
12701    pub(crate) fn fake_gh_script(
12702        dir: &Path,
12703        name: &str,
12704        stdout: &str,
12705        stderr: &str,
12706        exit_code: i32,
12707    ) -> PathBuf {
12708        let out_path = dir.join(format!("{name}.stdout"));
12709        let err_path = dir.join(format!("{name}.stderr"));
12710        std::fs::write(&out_path, stdout).unwrap();
12711        std::fs::write(&err_path, stderr).unwrap();
12712        #[cfg(windows)]
12713        {
12714            let script = dir.join(format!("{name}.cmd"));
12715            let mut body = String::from("@echo off\r\n");
12716            if !stdout.is_empty() {
12717                body.push_str(&format!("type \"{}\"\r\n", out_path.display()));
12718            }
12719            if !stderr.is_empty() {
12720                body.push_str(&format!("type \"{}\" 1>&2\r\n", err_path.display()));
12721            }
12722            body.push_str(&format!("exit /b {exit_code}\r\n"));
12723            std::fs::write(&script, body).unwrap();
12724            script
12725        }
12726        #[cfg(unix)]
12727        {
12728            use std::os::unix::fs::PermissionsExt as _;
12729            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
12730            let script = dir.join(name);
12731            let mut body = String::from("#!/bin/sh\n");
12732            if !stdout.is_empty() {
12733                body.push_str(&format!("cat {}\n", quote(&out_path)));
12734            }
12735            if !stderr.is_empty() {
12736                body.push_str(&format!("cat {} >&2\n", quote(&err_path)));
12737            }
12738            body.push_str(&format!("exit {exit_code}\n"));
12739            let status = std::process::Command::new("sh")
12740                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
12741                .arg(&script)
12742                .arg(&body)
12743                .status()
12744                .unwrap();
12745            assert!(status.success());
12746            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
12747            script
12748        }
12749    }
12750
12751    #[test]
12752    fn gh_output_combined_preserves_and_separates_both_streams() {
12753        let mk = |ok, stdout: &str, stderr: &str| GhOutput {
12754            ok,
12755            stdout: stdout.into(),
12756            stderr: stderr.into(),
12757        };
12758        assert_eq!(mk(true, "  ", "\n").combined(), "");
12759        assert_eq!(mk(true, "  only out \n", " \t ").combined(), "only out");
12760        assert_eq!(mk(false, "", "  only err\n").combined(), "only err");
12761        assert_eq!(
12762            mk(false, "{\"status\":\"404\"}", "gh: Not Found (HTTP 404)\n").combined(),
12763            "{\"status\":\"404\"}\ngh: Not Found (HTTP 404)"
12764        );
12765    }
12766
12767    #[tokio::test]
12768    async fn gh_separates_json_stdout_from_stderr_diagnostics() {
12769        let tmp = tempfile::tempdir().unwrap();
12770        let hint = "hint: to listen to pull request events, run `gh pr view --web`\n";
12771        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"}"#;
12772        let valid_list = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: test","baseRefName":"main","isCrossRepository":false}]"#;
12773
12774        // Valid JSON stdout + nonempty stderr hint on exit 0: structured reads
12775        // parse stdout cleanly while stderr remains available via `combined()`.
12776        let ok_view = fake_gh_script(tmp.path(), "ok-view", &format!("{valid_view}\n"), hint, 0);
12777        let out = gh_with(&ok_view, tmp.path(), &["pr".into(), "view".into()])
12778            .await
12779            .unwrap();
12780        assert!(out.ok);
12781        assert_eq!(parse_pr(&out.stdout).unwrap().state, PrLifecycle::Open);
12782        assert!(out.stderr.contains("listen to pull request events"));
12783        assert!(out.combined().contains("listen to pull request events"));
12784        assert!(out.combined().contains("feat: test"));
12785
12786        let ok_list = fake_gh_script(tmp.path(), "ok-list", &format!("{valid_list}\n"), hint, 0);
12787        assert_eq!(
12788            find_open_pr_with(&ok_list, tmp.path(), "magi/task-t", "main")
12789                .await
12790                .unwrap(),
12791            OpenPr::One {
12792                url: "https://github.com/example/repo/pull/1".into(),
12793                title: "feat: test".into(),
12794            }
12795        );
12796
12797        // Malformed stdout with trailing characters still fails strict JSON parsing.
12798        let malformed = fake_gh_script(
12799            tmp.path(),
12800            "malformed",
12801            &format!("{valid_view}\ntrailing garbage\n"),
12802            "",
12803            0,
12804        );
12805        let out = gh_with(&malformed, tmp.path(), &["pr".into(), "view".into()])
12806            .await
12807            .unwrap();
12808        assert!(out.ok);
12809        let err = parse_pr(&out.stdout).unwrap_err();
12810        assert!(
12811            format!("{err:#}").contains("trailing characters"),
12812            "{err:#}"
12813        );
12814
12815        // Empty stdout + nonempty stderr on exit 0 never substitutes stderr.
12816        let empty = fake_gh_script(tmp.path(), "empty", "", hint, 0);
12817        let out = gh_with(&empty, tmp.path(), &["pr".into(), "view".into()])
12818            .await
12819            .unwrap();
12820        assert!(out.ok);
12821        assert!(out.stdout.trim().is_empty());
12822        assert!(parse_pr(&out.stdout).is_err());
12823
12824        // Non-zero exit with valid JSON on stdout and error on stderr reports
12825        // failure and preserves both streams in `combined()`.
12826        let failed = fake_gh_script(
12827            tmp.path(),
12828            "failed",
12829            &format!("{valid_view}\n"),
12830            "gh: HTTP 404 Not Found\n",
12831            1,
12832        );
12833        let out = gh_with(&failed, tmp.path(), &["pr".into(), "view".into()])
12834            .await
12835            .unwrap();
12836        assert!(!out.ok);
12837        let diag = out.combined();
12838        assert!(diag.contains("HTTP 404 Not Found"), "{diag}");
12839        assert!(diag.contains("feat: test"), "{diag}");
12840        let list_err = find_open_pr_with(&failed, tmp.path(), "magi/task-t", "main")
12841            .await
12842            .unwrap_err()
12843            .to_string();
12844        assert!(list_err.contains("HTTP 404 Not Found"), "{list_err}");
12845    }
12846
12847    struct StaticPrObserver(crate::land_sync_recovery::ObservedPr);
12848
12849    impl crate::land_sync_recovery::PrObserver for StaticPrObserver {
12850        async fn observe_pr(
12851            &self,
12852            _repo: &Path,
12853            _pr_url: &str,
12854        ) -> Result<crate::land_sync_recovery::ObservedPr> {
12855            Ok(self.0.clone())
12856        }
12857    }
12858
12859    const FIXTURE_PR_PREFIX: &str = "https://github.com/example/landing-sync-";
12860
12861    /// Tests share a process-wide home, so each recovery fixture needs a unique
12862    /// PR URL to prevent another test's `write_pr_state_through` from settling it.
12863    fn fixture_pr_url(state: &RunState) -> String {
12864        format!("{FIXTURE_PR_PREFIX}{}/pull/42", state.id)
12865    }
12866
12867    /// Build a real-shaped legacy landing base-sync exhaustion fixture backed by
12868    /// an isolated temp Git repo, bare origin, queue task, and open PR metadata.
12869    async fn legacy_exhausted_landing_fixture() -> (
12870        tempfile::TempDir,
12871        PathBuf,
12872        crate::queue::Queue,
12873        crate::queue::Task,
12874        RunState,
12875        String,
12876    ) {
12877        let (tmp, mut state, old) = landing_git_fixture().await;
12878        crate::run::pin_test_home();
12879        let home = crate::run::home();
12880        // Move run state under this isolated home so load_under/save_under match.
12881        state.config.graph.land_rounds = 4;
12882        state.config.graph.land_approval = true;
12883        state.config.verify.gate = vec!["git rev-parse HEAD".into()];
12884        state.config.verify.e2e = vec!["git rev-parse HEAD".into()];
12885        state.status = RunStatus::Blocked;
12886        state.driver_exited = true;
12887        state.pr = Some(crate::run::PrRecord {
12888            url: fixture_pr_url(&state),
12889            number: 42,
12890            state: "open".to_owned(),
12891            checks: "green".to_owned(),
12892            round: 0,
12893            rounds: 4,
12894            red_at_merge: Vec::new(),
12895        });
12896        state.merge = Some(MergeOutcome {
12897            mode: MergeMode::Pr,
12898            ok: false,
12899            detail:
12900                "could not synchronize landing base: landing base synchronization budget exhausted"
12901                    .to_owned(),
12902            empty: false,
12903        });
12904        state.reviews = vec![serde_json::from_value(serde_json::json!({
12905            "round": 1,
12906            "head": old,
12907            "expected": 2,
12908            "answered": 2,
12909            "reviews": [],
12910            "clean": true,
12911            "e2e": [{"command": "git rev-parse HEAD", "code": 0, "output_tail": old, "duration_ms": 10}],
12912            "verified_head": old,
12913            "verified_at": jiff::Timestamp::now(),
12914            "e2e_deferred": false
12915        }))
12916        .unwrap()];
12917        let pass_cmd: crate::run::CommandOutcome = serde_json::from_value(serde_json::json!({
12918            "command": "git rev-parse HEAD",
12919            "code": 0,
12920            "output_tail": old,
12921            "duration_ms": 10
12922        }))
12923        .unwrap();
12924        state.head_e2e = Some(crate::run::GateRepairE2e::new(
12925            old.clone(),
12926            true,
12927            vec![pass_cmd.clone()],
12928        ));
12929        state.gate = vec![pass_cmd];
12930        state.gate_ran = true;
12931        state.gate_head = Some(old.clone());
12932        state.land_sync_attempts = 4;
12933        state.land_sync_target = None;
12934        state.land_sync_pending = true;
12935        state.event(
12936            "land",
12937            "stopped: could not synchronize landing base: landing base synchronization budget exhausted",
12938        );
12939
12940        let queue = crate::queue::Queue::at(home.join("queue"));
12941        let mut task = crate::queue::Task::new(
12942            "landing sync".into(),
12943            state.instruction.clone(),
12944            state.repo.clone(),
12945            crate::queue::Source::Human,
12946        );
12947        task.link_run(&state.id);
12948        task.hold_machine(Some("landing base synchronization budget exhausted".into()));
12949        queue.put(&mut task).unwrap();
12950        state.origin = Some(crate::run::Origin::queue(&task.id));
12951        state.save_under(&home).unwrap();
12952        (tmp, home, queue, task, state, old)
12953    }
12954
12955    #[tokio::test]
12956    async fn land_sync_recovery_isolated_from_unrelated_pr_settlement() {
12957        let (_tmp, _home, _queue, _task, mut state, _old) =
12958            legacy_exhausted_landing_fixture().await;
12959        let home = tempfile::tempdir().unwrap();
12960        state.save_under(home.path()).unwrap();
12961        let mut source = run_state();
12962        source.pr = state.pr.clone();
12963        source.pr.as_mut().unwrap().url = green_pr().url;
12964        assert_eq!(
12965            write_pr_state_through_in(home.path(), &source, PrLifecycle::Merged),
12966            0
12967        );
12968        // The unrelated record must not be locked even during selection.
12969        assert_eq!(
12970            rewrite_open_prs(home.path(), &mut |candidate| {
12971                assert_eq!(candidate.id, state.id);
12972                let _owner = crate::pr_head::owner_lock(home.path(), &candidate.id)
12973                    .expect("unrelated PR scan must not hold the recovery owner lock");
12974                names_same_pr(
12975                    candidate,
12976                    &source.pr.as_ref().unwrap().url,
12977                    42,
12978                    &source.repo,
12979                )
12980                .then_some(PrLifecycle::Merged)
12981            }),
12982            0
12983        );
12984        let saved = RunState::load_under(&state.id, home.path()).unwrap();
12985        assert_eq!(saved.pr.as_ref().unwrap().state, "open");
12986        assert!(saved.land_sync_exhausted());
12987    }
12988
12989    #[tokio::test]
12990    async fn land_sync_recovery_preserves_previous_checkpoint_before_scratch_start() {
12991        let (_tmp, home, _queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
12992        state.land_sync_attempts = 2;
12993        advance_landing_base(&state).await;
12994        assert_eq!(
12995            rebase_landing_worktree(&mut state, "origin/main")
12996                .await
12997                .unwrap(),
12998            crate::rebase::Rebased::Applied
12999        );
13000        let previous = state.land_sync_checkpoint.clone().unwrap();
13001        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13002        std::fs::write(state.repo.join("advance2"), "advance2").unwrap();
13003        git::commit_all(&state.repo, "advance again").await.unwrap();
13004        git::git(&state.repo, &["push", "origin", "main"])
13005            .await
13006            .unwrap();
13007        git::git(&state.repo, &["checkout", "winner"])
13008            .await
13009            .unwrap();
13010        let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
13011        let scratch = state.dir().join("rebase");
13012        crate::rebase::prepare(&mut state, &scratch, "winner")
13013            .await
13014            .unwrap();
13015        state.land_sync_attempts += 1;
13016        save_landing_rebase_start(&mut state, &target, &previous.head).unwrap();
13017
13018        // Restart after the reservation, before executing the scratch rebase.
13019        state = RunState::load_under(&state.id, &home).unwrap();
13020        assert_eq!(state.land_sync_checkpoint.as_ref(), Some(&previous));
13021        assert_eq!(
13022            rebase_landing_worktree(&mut state, "origin/main")
13023                .await
13024                .unwrap(),
13025            crate::rebase::Rebased::Applied
13026        );
13027        assert_eq!(state.land_sync_attempts, 4);
13028        let retained = git::rev_parse(&state.repo, "HEAD").await.unwrap();
13029        assert_ne!(retained, previous.head);
13030        let checkpoint = state.land_sync_checkpoint.as_ref().unwrap();
13031        assert_eq!(checkpoint.previous.as_deref(), Some(&previous));
13032        assert_eq!(checkpoint.head, retained);
13033
13034        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13035        std::fs::write(state.repo.join("advance3"), "advance3").unwrap();
13036        git::commit_all(&state.repo, "advance third time")
13037            .await
13038            .unwrap();
13039        git::git(&state.repo, &["push", "origin", "main"])
13040            .await
13041            .unwrap();
13042        git::git(&state.repo, &["checkout", "winner"])
13043            .await
13044            .unwrap();
13045        let error = rebase_landing_worktree(&mut state, "origin/main")
13046            .await
13047            .unwrap_err();
13048        assert!(error.to_string().contains("budget exhausted"), "{error:#}");
13049        state = RunState::load_under(&state.id, &home).unwrap();
13050        crate::land_sync_recovery::validate_heads(
13051            &state,
13052            state.land_sync_recovery.stop.as_ref(),
13053            &retained,
13054            &old,
13055        )
13056        .await
13057        .unwrap();
13058    }
13059
13060    #[tokio::test]
13061    async fn land_sync_recovery_retains_unpublished_rebase() {
13062        let (_tmp, home, queue, task, mut state, old) = legacy_exhausted_landing_fixture().await;
13063        state.land_sync_attempts = 3;
13064        state.config.verify.gate = vec!["exit 1".into()];
13065        state.config.graph.gate_fix_rounds = 0;
13066        state.config.graph.land_approval = false;
13067        state.config.graph.hold_contested_merge = false;
13068        advance_landing_base(&state).await;
13069        assert!(resume_observed_head(&mut state, &old).await.is_err());
13070        let retained = git::rev_parse(&state.repo, "HEAD").await.unwrap();
13071        assert_ne!(retained, old);
13072        assert_eq!(state.land_sync_attempts, 4);
13073        state = RunState::load_under(&state.id, &home).unwrap();
13074        assert_eq!(state.land_sync_checkpoint.as_ref().unwrap().head, retained);
13075
13076        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13077        std::fs::write(state.repo.join("advance2"), "advance2").unwrap();
13078        git::commit_all(&state.repo, "advance again").await.unwrap();
13079        git::git(&state.repo, &["push", "origin", "main"])
13080            .await
13081            .unwrap();
13082        git::git(&state.repo, &["checkout", "winner"])
13083            .await
13084            .unwrap();
13085        let error = resume_observed_head(&mut state, &old).await.unwrap_err();
13086        assert!(error.to_string().contains("budget exhausted"), "{error:#}");
13087        assert_eq!(
13088            git::remote_head(&state.repo, "origin", "task-head")
13089                .await
13090                .unwrap(),
13091            Some(old.clone())
13092        );
13093        let stop = state.land_sync_recovery.stop.clone().unwrap();
13094        assert_eq!(stop.head, retained);
13095        assert_eq!(stop.pr_head, old);
13096        assert_eq!(stop.checkpoint, state.land_sync_checkpoint);
13097
13098        let pr_url = state.pr.as_ref().unwrap().url.clone();
13099        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13100            url: pr_url.clone(),
13101            number: 42,
13102            open: true,
13103            head: old.clone(),
13104            base_branch: Some("main".into()),
13105        });
13106        state.config.verify.gate = vec!["git rev-parse HEAD".into()];
13107        state.save_under(&home).unwrap();
13108        let request = crate::land_sync_recovery_control::Request {
13109            run: state.id.clone(),
13110            head: retained.clone(),
13111            actor: "cli".into(),
13112            request: format!("unpublished-{}", state.id),
13113        };
13114        // Missing or altered provenance cannot authorize a divergent retained head.
13115        let mut invalid = RunState::load_under(&state.id, &home).unwrap();
13116        invalid.land_sync_checkpoint = None;
13117        assert!(
13118            crate::land_sync_recovery::validate_heads(&invalid, Some(&stop), &retained, &old,)
13119                .await
13120                .is_err()
13121        );
13122        for field in ["published", "from", "base", "head"] {
13123            let mut checkpoint = stop.checkpoint.clone().unwrap();
13124            match field {
13125                "published" => checkpoint.published = retained.clone(),
13126                "from" => checkpoint.from = retained.clone(),
13127                "base" => checkpoint.base = old.clone(),
13128                "head" => checkpoint.head = old.clone(),
13129                _ => unreachable!(),
13130            }
13131            invalid.land_sync_checkpoint = Some(checkpoint);
13132            assert!(
13133                crate::land_sync_recovery::validate_heads(&invalid, Some(&stop), &retained, &old,)
13134                    .await
13135                    .is_err(),
13136                "{field}"
13137            );
13138        }
13139        let mut stale = request.clone();
13140        stale.head = old.clone();
13141        let wrong_remote = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13142            head: retained.clone(),
13143            ..observer.0.clone()
13144        });
13145        for (request, observer) in [(stale, &observer), (request.clone(), &wrong_remote)] {
13146            let error =
13147                crate::land_sync_recovery_control::recover_with(&queue, &home, request, observer)
13148                    .await
13149                    .unwrap_err();
13150            assert!(
13151                error.is::<crate::land_sync_recovery_control::BeforeWrite>(),
13152                "{error:#}"
13153            );
13154        }
13155        let accepted = crate::land_sync_recovery_control::recover_with(
13156            &queue,
13157            &home,
13158            request.clone(),
13159            &observer,
13160        )
13161        .await
13162        .unwrap();
13163        assert!(!accepted.repeated);
13164        let repeated =
13165            crate::land_sync_recovery_control::recover_with(&queue, &home, request, &observer)
13166                .await
13167                .unwrap();
13168        assert!(repeated.repeated);
13169        let task = queue.get(&task.id).unwrap();
13170        assert!(matches!(
13171            crate::land_sync_recovery::dispatch_check_with(&queue, &home, &task, &observer).await,
13172            crate::land_sync_recovery::DispatchDecision::Proceed
13173        ));
13174        let mut run = RunState::load_under(&state.id, &home).unwrap();
13175        let mut forge = Scripted::for_pr(
13176            &pr_url,
13177            vec![
13178                seen(&old, Checks::Green, "BEHIND", false),
13179                seen(&old, Checks::Green, "BEHIND", false),
13180                seen("@published", Checks::Green, "CLEAN", false),
13181            ],
13182        );
13183        forge.public_repo = Some(run.repo.clone());
13184        land_with(&mut run, &pr_url, &forge).await.unwrap();
13185        let head = git::rev_parse(&run.repo, "HEAD").await.unwrap();
13186        assert_eq!(
13187            std::fs::read_to_string(run.repo.join("change")).unwrap(),
13188            "change"
13189        );
13190        assert!(git::is_ancestor(&run.repo, "origin/main", &head).await);
13191        assert!(run.parked);
13192        assert_eq!(run.land_approval.as_ref().unwrap().head, head);
13193        assert_eq!(run.land_sync_attempts, 5);
13194        assert_eq!(run.land_sync_recovery.extra_attempts, 1);
13195        assert!(run.land_sync_checkpoint.is_none());
13196        assert_eq!(run.gate_head.as_deref(), Some(head.as_str()));
13197        assert!(
13198            run.head_e2e
13199                .as_ref()
13200                .is_some_and(|e| e.head == head && e.passed)
13201        );
13202        assert_eq!(
13203            git::remote_head(&run.repo, "origin", "task-head")
13204                .await
13205                .unwrap(),
13206            Some(head)
13207        );
13208    }
13209
13210    #[tokio::test]
13211    async fn land_sync_recovery_continues_legacy_real_shaped_stop_on_existing_pr() {
13212        let (_tmp, home, queue, task, mut state, old) = legacy_exhausted_landing_fixture().await;
13213        let home = home.as_path();
13214
13215        // Advance origin/main once so landing rebase has real work to replay.
13216        advance_landing_base(&state).await;
13217
13218        state.pre_gate = vec![
13219            serde_json::from_value(serde_json::json!({
13220                "command": "prepare sources",
13221                "code": 0,
13222                "output_tail": "prepared",
13223                "duration_ms": 15
13224            }))
13225            .unwrap(),
13226        ];
13227        let pre_gate_commit = git::rev_parse(&state.repo, "HEAD^").await.unwrap();
13228        assert_ne!(pre_gate_commit, old);
13229        state.pre_gate_commit = Some(pre_gate_commit.clone());
13230        let pre_gate = serde_json::to_value(&state.pre_gate).unwrap();
13231        state.save_under(home).unwrap();
13232
13233        // Pre-recovery: legacy shape recognized, recover-base refused, ordinary resume/release refused.
13234        assert!(state.land_sync_exhausted());
13235        assert!(!state.base_sync_blocked());
13236        assert!(crate::land_sync_recovery::held_task(&queue, &task));
13237        let base_err = crate::graph::Runner::authorize_base_recovery(home, &state.id, &task.id)
13238            .await
13239            .unwrap_err();
13240        assert!(
13241            base_err.to_string().contains("run has no base-sync stop"),
13242            "{base_err:#}"
13243        );
13244        assert!(crate::handover::resume_refusal_under(&state, Some(home)).is_none());
13245        assert!(crate::base_sync_recovery::ensure_generic_release(&queue, &task).is_err());
13246
13247        // Ordinary land_with without authorization refuses without refilling budget.
13248        let pr_url = state.pr.as_ref().unwrap().url.clone();
13249        let blocked_forge =
13250            Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13251        let err = land_with(&mut state, &pr_url, &blocked_forge)
13252            .await
13253            .unwrap_err();
13254        assert!(err.to_string().contains("budget exhausted"), "{err:#}");
13255        assert_eq!(state.land_sync_attempts, 4);
13256        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
13257
13258        // Attach a prior head-bound approval on `old` to prove fresh approval is required after recovery.
13259        let questions = ask::Questions::at(home.join("questions"));
13260        let mut old_q = ask::Question::new(
13261            state.id.clone(),
13262            APPROVAL_NODE.into(),
13263            "owner".into(),
13264            "old head approval".into(),
13265            String::new(),
13266            vec![APPROVE.into()],
13267        );
13268        old_q
13269            .answer(ask::Answer::Choice(APPROVE.to_owned()))
13270            .unwrap();
13271        questions.put(&mut old_q).unwrap();
13272        state.land_approval = Some(LandApproval {
13273            question: old_q.id.clone(),
13274            head: old.clone(),
13275        });
13276        state.save_under(home).unwrap();
13277
13278        // Admit explicit recover-land-sync via two-phase control.
13279        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13280            url: pr_url.clone(),
13281            number: 42,
13282            open: true,
13283            head: old.clone(),
13284            base_branch: Some("main".to_owned()),
13285        });
13286        let outcome = crate::land_sync_recovery_control::recover_with(
13287            &queue,
13288            home,
13289            crate::land_sync_recovery_control::Request {
13290                run: state.id.clone(),
13291                head: old.clone(),
13292                actor: "cli".into(),
13293                request: "req-legacy-1".into(),
13294            },
13295            &observer,
13296        )
13297        .await
13298        .unwrap();
13299        assert!(!outcome.repeated);
13300        assert_eq!(
13301            outcome
13302                .task
13303                .resume_override
13304                .as_ref()
13305                .and_then(|pin| pin.pinned_run.as_deref()),
13306            Some(state.id.as_str())
13307        );
13308
13309        // Ordinary fast-forward of origin/main between admission and dispatch is allowed.
13310        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13311        std::fs::write(state.repo.join("advance2"), "advance2").unwrap();
13312        git::git(&state.repo, &["add", "."]).await.unwrap();
13313        git::git(&state.repo, &["commit", "-m", "advance base again"])
13314            .await
13315            .unwrap();
13316        git::git(&state.repo, &["push", "origin", "main"])
13317            .await
13318            .unwrap();
13319        git::git(&state.repo, &["checkout", "winner"])
13320            .await
13321            .unwrap();
13322
13323        let reloaded_task = queue.get(&task.id).unwrap();
13324        assert!(matches!(
13325            crate::land_sync_recovery::dispatch_check_with(&queue, home, &reloaded_task, &observer)
13326                .await,
13327            crate::land_sync_recovery::DispatchDecision::Proceed
13328        ));
13329
13330        // Execute continuation on the existing PR using real rebase + fresh gate + fresh E2E.
13331        let mut run = RunState::load_under(&state.id, home).unwrap();
13332        assert!(run.land_sync_recovery_pending());
13333        let mut forge = Scripted::for_pr(
13334            &pr_url,
13335            vec![
13336                seen(&old, Checks::Green, "BEHIND", false),
13337                seen(&old, Checks::Green, "BEHIND", false),
13338                seen("@published", Checks::Green, "CLEAN", false),
13339            ],
13340        );
13341        forge.public_repo = Some(run.repo.clone());
13342        let pr = land_with(&mut run, &pr_url, &forge).await.unwrap();
13343        assert_eq!(pr.state, PrLifecycle::Open);
13344        assert!(run.parked, "must park awaiting fresh head-bound approval");
13345
13346        // Verify attempts preserved (4 -> 5), 1 grant consumed, fresh head published,
13347        // prior verification archived, fresh gate + E2E ran on new head, fresh approval asked.
13348        let new_head = git::rev_parse(&run.repo, "HEAD").await.unwrap();
13349        assert_ne!(new_head, old);
13350        assert_eq!(run.land_sync_attempts, 5);
13351        assert_eq!(run.land_sync_recovery.extra_attempts, 1);
13352        assert_eq!(run.land_sync_budget(), 5);
13353        assert!(!run.land_sync_pending);
13354        assert_eq!(run.pr_pushed_head.as_deref(), Some(new_head.as_str()));
13355        assert_eq!(
13356            git::remote_head(&run.repo, "origin", "task-head")
13357                .await
13358                .unwrap()
13359                .as_deref(),
13360            Some(new_head.as_str())
13361        );
13362        assert!(run.gate_ran);
13363        assert_eq!(run.gate_head.as_deref(), Some(new_head.as_str()));
13364        assert!(
13365            run.head_e2e
13366                .as_ref()
13367                .is_some_and(|e| e.head == new_head && e.passed)
13368        );
13369        assert_eq!(run.reviews.len(), 1);
13370        assert!(run.reviews[0].clean);
13371        assert_eq!(run.reviews[0].answered, 2);
13372        assert!(run.reviews[0].verified_head.is_none());
13373        assert!(!run.verification_history.is_empty());
13374        assert_eq!(run.land_sync_recovery.stops.len(), 1);
13375        assert_eq!(run.land_sync_recovery.authorizations.len(), 1);
13376        let auth = &run.land_sync_recovery.authorizations[0];
13377        assert!(auth.consumed);
13378        assert!(auth.invalidated.is_none());
13379        assert!(run.pre_gate.is_empty());
13380        assert!(run.pre_gate_commit.is_none());
13381        let saved = RunState::load_under(&run.id, home).unwrap();
13382        assert!(saved.pre_gate.is_empty());
13383        assert!(saved.pre_gate_commit.is_none());
13384        let archived = saved.land_sync_recovery.authorizations[0]
13385            .archived_verification
13386            .as_ref()
13387            .unwrap();
13388        assert_eq!(serde_json::to_value(&archived.pre_gate).unwrap(), pre_gate);
13389        assert_eq!(
13390            archived.pre_gate_commit.as_deref(),
13391            Some(pre_gate_commit.as_str())
13392        );
13393
13394        let mut legacy = serde_json::to_value(archived).unwrap();
13395        let fields = legacy.as_object_mut().unwrap();
13396        fields.remove("pre_gate");
13397        fields.remove("pre_gate_commit");
13398        let legacy: crate::land_sync_recovery::ArchivedVerification =
13399            serde_json::from_value(legacy).unwrap();
13400        assert!(legacy.pre_gate.is_empty());
13401        assert!(legacy.pre_gate_commit.is_none());
13402        let new_approval = run.land_approval.as_ref().unwrap();
13403        assert_ne!(new_approval.question, old_q.id);
13404        assert_eq!(new_approval.head, new_head);
13405    }
13406
13407    #[tokio::test]
13408    async fn land_sync_recovery_observes_external_merge_without_grant() {
13409        let (_tmp, home, queue, mut task, mut state, old) =
13410            legacy_exhausted_landing_fixture().await;
13411        let pr_url = state.pr.as_ref().unwrap().url.clone();
13412        task.resume_override = Some(crate::queue::OperatorResume {
13413            question_id: String::new(),
13414            at: jiff::Timestamp::now(),
13415            conductor_rehold: None,
13416            forced: true,
13417            pinned_run: Some(state.id.clone()),
13418        });
13419        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13420            url: pr_url.clone(),
13421            number: 42,
13422            open: false,
13423            head: old.clone(),
13424            base_branch: Some("main".into()),
13425        });
13426        assert!(matches!(
13427            crate::land_sync_recovery::dispatch_check_with(&queue, &home, &task, &observer).await,
13428            crate::land_sync_recovery::DispatchDecision::Proceed
13429        ));
13430        let forge = Scripted::for_pr(&pr_url, vec![merged_view(&old)]);
13431        land_with(&mut state, &pr_url, &forge).await.unwrap();
13432        assert_eq!(state.status, RunStatus::Merged);
13433        assert_eq!(state.land_sync_attempts, 4);
13434        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
13435        assert_eq!(forge.calls(), ["view"]);
13436    }
13437
13438    #[tokio::test]
13439    async fn land_sync_recovery_forces_fresh_e2e_and_gate_even_when_head_unchanged() {
13440        let (tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
13441        let home = home.as_path();
13442
13443        // Create marker-writing commands for gate and e2e so we prove both execute freshly
13444        // even when HEAD does not change (origin/main is already an ancestor of winner).
13445        let gate_marker = tmp.path().join("fresh-gate-ran");
13446        let e2e_marker = tmp.path().join("fresh-e2e-ran");
13447        state.config.verify.gate = vec![format!(
13448            "git rev-parse HEAD > \"{}\"",
13449            gate_marker.display().to_string().replace('\\', "/")
13450        )];
13451        state.config.verify.e2e = vec![format!(
13452            "git rev-parse HEAD > \"{}\"",
13453            e2e_marker.display().to_string().replace('\\', "/")
13454        )];
13455        let questions = ask::Questions::at(home.join("questions"));
13456        let mut old_q = ask::Question::new(
13457            state.id.clone(),
13458            APPROVAL_NODE.into(),
13459            "owner".into(),
13460            "prior approval on same head".into(),
13461            String::new(),
13462            vec![APPROVE.into()],
13463        );
13464        old_q
13465            .answer(ask::Answer::Choice(APPROVE.to_owned()))
13466            .unwrap();
13467        questions.put(&mut old_q).unwrap();
13468        state.land_approval = Some(LandApproval {
13469            question: old_q.id.clone(),
13470            head: old.clone(),
13471        });
13472        state.save_under(home).unwrap();
13473
13474        let pr_url = state.pr.as_ref().unwrap().url.clone();
13475        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13476            url: pr_url.clone(),
13477            number: 42,
13478            open: true,
13479            head: old.clone(),
13480            base_branch: Some("main".to_owned()),
13481        });
13482        crate::land_sync_recovery_control::recover_with(
13483            &queue,
13484            home,
13485            crate::land_sync_recovery_control::Request {
13486                run: state.id.clone(),
13487                head: old.clone(),
13488                actor: "cli".into(),
13489                request: "req-same-head".into(),
13490            },
13491            &observer,
13492        )
13493        .await
13494        .unwrap();
13495
13496        let mut run = RunState::load_under(&state.id, home).unwrap();
13497        let mut forge = Scripted::for_pr(
13498            &pr_url,
13499            vec![
13500                seen(&old, Checks::Green, "CLEAN", false),
13501                seen(&old, Checks::Green, "CLEAN", false),
13502                seen(&old, Checks::Green, "CLEAN", false),
13503            ],
13504        );
13505        forge.public_repo = Some(run.repo.clone());
13506        land_with(&mut run, &pr_url, &forge).await.unwrap();
13507
13508        assert!(
13509            gate_marker.exists(),
13510            "fresh gate must run even on unchanged HEAD"
13511        );
13512        assert!(
13513            e2e_marker.exists(),
13514            "fresh E2E must run even on unchanged HEAD"
13515        );
13516        assert!(
13517            run.parked,
13518            "old approval before recovery must not be reused"
13519        );
13520        assert_ne!(run.land_approval.as_ref().unwrap().question, old_q.id);
13521    }
13522
13523    #[tokio::test]
13524    async fn land_sync_recovery_resumes_after_gate_repair_before_push() {
13525        let (_tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
13526        landing_gate_fixer(
13527            &mut state,
13528            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
13529        );
13530        state.config.verify.gate =
13531            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
13532        state.save_under(&home).unwrap();
13533        let pr_url = state.pr.as_ref().unwrap().url.clone();
13534        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13535            url: pr_url.clone(),
13536            number: 42,
13537            open: true,
13538            head: old.clone(),
13539            base_branch: Some("main".into()),
13540        });
13541        crate::land_sync_recovery_control::recover_with(
13542            &queue,
13543            &home,
13544            crate::land_sync_recovery_control::Request {
13545                run: state.id.clone(),
13546                head: old.clone(),
13547                actor: "cli".into(),
13548                request: "req-interrupted-gate-repair".into(),
13549            },
13550            &observer,
13551        )
13552        .await
13553        .unwrap();
13554        let mut run = RunState::load_under(&state.id, &home).unwrap();
13555        let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "CLEAN", false)]);
13556        assert!(matches!(
13557            prepare_land_sync_recovery(&mut run, &pr_url, &forge)
13558                .await
13559                .unwrap(),
13560            LandSyncPrep::Continue(Some(_))
13561        ));
13562        // Interrupt at the publication check, after the real gate fixer commits.
13563        let changed = Scripted::for_pr(
13564            &pr_url,
13565            vec![seen("different", Checks::Green, "CLEAN", false)],
13566        );
13567        let error = resume_landing_head(&mut run, &old, &pr_url, &changed, None)
13568            .await
13569            .unwrap_err();
13570        assert!(
13571            error.to_string().contains("PR head changed while gating"),
13572            "{error}"
13573        );
13574        let repaired = git::rev_parse(&run.repo, "HEAD").await.unwrap();
13575        assert_ne!(repaired, old);
13576        assert_eq!(run.gate_fixes.len(), 1);
13577        assert!(run.gate_fixes[0].committed);
13578        assert_eq!(
13579            git::remote_head(&run.repo, "origin", "task-head")
13580                .await
13581                .unwrap(),
13582            Some(old.clone())
13583        );
13584
13585        run.status = RunStatus::Blocked;
13586        run.save().unwrap();
13587        let mut resumed = RunState::load_under(&run.id, &home).unwrap();
13588        assert_eq!(resumed.land_sync_attempts, 5);
13589        assert!(resumed.land_sync_pending);
13590        assert!(!resumed.land_sync_exhausted());
13591        assert!(!resumed.land_sync_unstarted_grant());
13592        assert!(matches!(
13593            prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
13594                .await
13595                .unwrap(),
13596            LandSyncPrep::Continue(None)
13597        ));
13598        assert_eq!(
13599            resume_landing_head(&mut resumed, &old, &pr_url, &forge, None)
13600                .await
13601                .unwrap(),
13602            repaired
13603        );
13604        assert_eq!(resumed.land_sync_attempts, 5);
13605        assert_eq!(resumed.gate_fixes.len(), 1);
13606        assert!(!resumed.land_sync_pending);
13607        assert!(
13608            resumed.land_sync_recovery.authorizations[0]
13609                .invalidated
13610                .is_none()
13611        );
13612        assert_eq!(
13613            git::remote_head(&resumed.repo, "origin", "task-head")
13614                .await
13615                .unwrap(),
13616            Some(repaired)
13617        );
13618    }
13619
13620    #[tokio::test]
13621    async fn land_sync_recovery_repeated_exhaustion_is_bounded_by_lifetime_cap() {
13622        let (_tmp, home, queue, task, mut state, mut head) =
13623            legacy_exhausted_landing_fixture().await;
13624        let home = home.as_path();
13625        state.config.graph.land_approval = false;
13626        state.save_under(home).unwrap();
13627
13628        let pr_url = state.pr.as_ref().unwrap().url.clone();
13629        let mut base_step = 0usize;
13630        let advance_step = |repo: PathBuf, step: usize| async move {
13631            git::git(&repo, &["checkout", "main"]).await.unwrap();
13632            std::fs::write(repo.join(format!("advance-{step}")), format!("step-{step}")).unwrap();
13633            git::git(&repo, &["add", "."]).await.unwrap();
13634            git::git(&repo, &["commit", "-m", &format!("advance base {step}")])
13635                .await
13636                .unwrap();
13637            git::git(&repo, &["push", "origin", "main"]).await.unwrap();
13638            git::git(&repo, &["checkout", "winner"]).await.unwrap();
13639        };
13640        for grant_num in 1..=crate::land_sync_recovery::MAX_GRANTS {
13641            base_step += 1;
13642            advance_step(state.repo.clone(), base_step).await;
13643            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13644                url: pr_url.clone(),
13645                number: 42,
13646                open: true,
13647                head: head.clone(),
13648                base_branch: Some("main".to_owned()),
13649            });
13650            crate::land_sync_recovery_control::recover_with(
13651                &queue,
13652                home,
13653                crate::land_sync_recovery_control::Request {
13654                    run: state.id.clone(),
13655                    head: head.clone(),
13656                    actor: "cli".into(),
13657                    request: format!("req-cap-{grant_num}"),
13658                },
13659                &observer,
13660            )
13661            .await
13662            .unwrap();
13663
13664            // Simulate execution consuming grant, spending the 1 attempt, and hitting exhaustion again.
13665            state = RunState::load_under(&state.id, home).unwrap();
13666            let mut forge = Scripted::for_pr(
13667                &pr_url,
13668                vec![
13669                    seen(&head, Checks::Green, "BEHIND", false),
13670                    seen(&head, Checks::Green, "BEHIND", false),
13671                    seen("@published", Checks::Green, "BEHIND", false),
13672                ],
13673            );
13674            forge.public_repo = Some(state.repo.clone());
13675            let prep = prepare_land_sync_recovery(&mut state, &pr_url, &forge)
13676                .await
13677                .unwrap();
13678            assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
13679            head = resume_landing_head(&mut state, &head, &pr_url, &forge, None)
13680                .await
13681                .unwrap();
13682            assert_eq!(state.land_sync_attempts, 4 + grant_num);
13683            assert_eq!(state.land_sync_recovery.extra_attempts, grant_num);
13684
13685            // Re-exhaust on another base advance.
13686            base_step += 1;
13687            advance_step(state.repo.clone(), base_step).await;
13688            let err = rebase_landing_worktree(&mut state, "origin/main")
13689                .await
13690                .unwrap_err();
13691            assert!(err.to_string().contains("budget exhausted"), "{err:#}");
13692            state.status = RunStatus::Blocked;
13693            state.save_under(home).unwrap();
13694            assert!(state.land_sync_exhausted());
13695
13696            // Put task back to Held so the next explicit authorization can queue it.
13697            let mut t = queue.get(&task.id).unwrap();
13698            t.hold_machine(Some("re-exhausted".into()));
13699            queue.put(&mut t).unwrap();
13700        }
13701
13702        assert_eq!(
13703            state.land_sync_attempts,
13704            4 + crate::land_sync_recovery::MAX_GRANTS
13705        );
13706        assert_eq!(state.land_sync_grants_remaining(), 0);
13707        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13708            url: pr_url,
13709            number: 42,
13710            open: true,
13711            head: head.clone(),
13712            base_branch: Some("main".to_owned()),
13713        });
13714        let err = 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,
13720                actor: "cli".into(),
13721                request: "req-cap-overflow".into(),
13722            },
13723            &observer,
13724        )
13725        .await
13726        .unwrap_err();
13727        assert!(
13728            err.to_string()
13729                .contains("lifetime landing base-sync recovery limit reached"),
13730            "{err:#}"
13731        );
13732    }
13733
13734    #[tokio::test]
13735    async fn land_sync_recovery_execution_revalidation_refuses_stale_pr_head_and_rewritten_base() {
13736        // Case A: PR head moves externally between admission and execution.
13737        {
13738            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13739            let pr_url = state.pr.as_ref().unwrap().url.clone();
13740            let home = home.as_path();
13741            advance_landing_base(&state).await;
13742            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13743                url: pr_url.clone(),
13744                number: 42,
13745                open: true,
13746                head: old.clone(),
13747                base_branch: Some("main".to_owned()),
13748            });
13749            crate::land_sync_recovery_control::recover_with(
13750                &queue,
13751                home,
13752                crate::land_sync_recovery_control::Request {
13753                    run: state.id.clone(),
13754                    head: old.clone(),
13755                    actor: "cli".into(),
13756                    request: "req-stale-pr".into(),
13757                },
13758                &observer,
13759            )
13760            .await
13761            .unwrap();
13762
13763            let mut run = RunState::load_under(&state.id, home).unwrap();
13764            let foreign_head = "f".repeat(40);
13765            let forge = Scripted::for_pr(
13766                &pr_url,
13767                vec![seen(&foreign_head, Checks::Green, "BEHIND", false)],
13768            );
13769            land_with(&mut run, &pr_url, &forge).await.unwrap();
13770            assert_eq!(run.status, RunStatus::Blocked);
13771            assert_eq!(run.land_sync_recovery.extra_attempts, 0);
13772            assert_eq!(run.land_sync_attempts, 4);
13773            let auth = run.land_sync_recovery.authorizations.last().unwrap();
13774            assert!(auth.consumed);
13775            assert!(
13776                auth.invalidated
13777                    .as_deref()
13778                    .is_some_and(|why| why.contains("published PR head changed")),
13779                "{:?}",
13780                auth.invalidated
13781            );
13782            assert_eq!(run.pr_pushed_head.as_deref(), Some(old.as_str()));
13783        }
13784
13785        // Case B: origin/main rewritten (non-fast-forward) between admission and execution.
13786        {
13787            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13788            let pr_url = state.pr.as_ref().unwrap().url.clone();
13789            let home = home.as_path();
13790            advance_landing_base(&state).await;
13791            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13792                url: pr_url.clone(),
13793                number: 42,
13794                open: true,
13795                head: old.clone(),
13796                base_branch: Some("main".to_owned()),
13797            });
13798            crate::land_sync_recovery_control::recover_with(
13799                &queue,
13800                home,
13801                crate::land_sync_recovery_control::Request {
13802                    run: state.id.clone(),
13803                    head: old.clone(),
13804                    actor: "cli".into(),
13805                    request: "req-rewritten-base".into(),
13806                },
13807                &observer,
13808            )
13809            .await
13810            .unwrap();
13811
13812            // Persist consumption before the rewrite, as if the driver crashed
13813            // between granting the attempt and starting the rebase.
13814            let mut consumed = RunState::load_under(&state.id, home).unwrap();
13815            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13816            assert!(matches!(
13817                prepare_land_sync_recovery(&mut consumed, &pr_url, &forge)
13818                    .await
13819                    .unwrap(),
13820                LandSyncPrep::Continue(Some(_))
13821            ));
13822            assert_eq!(consumed.land_sync_attempts, 4);
13823
13824            // Rewrite origin/main by amending the latest base commit and force-pushing.
13825            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13826            std::fs::write(state.repo.join("advance"), "rewritten").unwrap();
13827            git::git(&state.repo, &["add", "."]).await.unwrap();
13828            git::git(&state.repo, &["commit", "--amend", "-m", "rewritten base"])
13829                .await
13830                .unwrap();
13831            git::git(&state.repo, &["push", "--force", "origin", "main"])
13832                .await
13833                .unwrap();
13834            git::git(&state.repo, &["checkout", "winner"])
13835                .await
13836                .unwrap();
13837
13838            let mut run = RunState::load_under(&state.id, home).unwrap();
13839            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13840            land_with(&mut run, &pr_url, &forge).await.unwrap();
13841            assert_eq!(run.status, RunStatus::Blocked);
13842            assert_eq!(run.land_sync_recovery.extra_attempts, 1);
13843            assert_eq!(run.land_sync_attempts, 4);
13844            assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
13845            let auth = run.land_sync_recovery.authorizations.last().unwrap();
13846            assert!(auth.consumed);
13847            assert!(
13848                auth.invalidated
13849                    .as_deref()
13850                    .is_some_and(|why| why.contains("does not fast-forward")),
13851                "{:?}",
13852                auth.invalidated
13853            );
13854            assert!(run.land_sync_exhausted());
13855            assert_eq!(run.land_sync_budget(), 4);
13856            let mut held = queue
13857                .list()
13858                .into_iter()
13859                .find(|t| t.execution_runs().last() == Some(&run.id))
13860                .unwrap();
13861            held.hold_machine(Some("recovery scope changed".into()));
13862            queue.put(&mut held).unwrap();
13863            crate::land_sync_recovery_control::recover_with(
13864                &queue,
13865                home,
13866                crate::land_sync_recovery_control::Request {
13867                    run: run.id.clone(),
13868                    head: old.clone(),
13869                    actor: "cli".into(),
13870                    request: "req-rewritten-base-new-approval".into(),
13871                },
13872                &observer,
13873            )
13874            .await
13875            .unwrap();
13876            let mut resumed = RunState::load_under(&run.id, home).unwrap();
13877            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13878            assert!(matches!(
13879                prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
13880                    .await
13881                    .unwrap(),
13882                LandSyncPrep::Continue(Some(_))
13883            ));
13884            assert_eq!(resumed.land_sync_recovery.extra_attempts, 2);
13885            assert_eq!(resumed.land_sync_budget(), 5);
13886            assert_eq!(resumed.land_sync_attempts, 4);
13887            assert!(
13888                resumed.land_sync_recovery.authorizations[0]
13889                    .invalidated
13890                    .is_some()
13891            );
13892        }
13893    }
13894
13895    #[tokio::test]
13896    async fn land_sync_recovery_restart_after_consume_continues_without_double_grant() {
13897        let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13898        let home = home.as_path();
13899        let pr_url = state.pr.as_ref().unwrap().url.clone();
13900        advance_landing_base(&state).await;
13901        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13902            url: pr_url.clone(),
13903            number: 42,
13904            open: true,
13905            head: old.clone(),
13906            base_branch: Some("main".to_owned()),
13907        });
13908        crate::land_sync_recovery_control::recover_with(
13909            &queue,
13910            home,
13911            crate::land_sync_recovery_control::Request {
13912                run: state.id.clone(),
13913                head: old.clone(),
13914                actor: "cli".into(),
13915                request: "req-crash-after-consume".into(),
13916            },
13917            &observer,
13918        )
13919        .await
13920        .unwrap();
13921
13922        // Simulate consuming the authorization and crashing right before rebase starts.
13923        let mut crashed = RunState::load_under(&state.id, home).unwrap();
13924        let initial_forge =
13925            Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13926        let prep = prepare_land_sync_recovery(&mut crashed, &pr_url, &initial_forge)
13927            .await
13928            .unwrap();
13929        assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
13930        assert_eq!(crashed.land_sync_recovery.extra_attempts, 1);
13931        assert_eq!(crashed.land_sync_attempts, 4);
13932        assert!(crashed.land_sync_recovery.authorizations[0].consumed);
13933
13934        // An unreadable base is not proof that the authorized lineage changed.
13935        let remote = git::git(&state.repo, &["remote", "get-url", "origin"])
13936            .await
13937            .unwrap();
13938        git::git(
13939            &state.repo,
13940            &["remote", "set-url", "origin", "missing-local-origin"],
13941        )
13942        .await
13943        .unwrap();
13944        let mut interrupted = RunState::load_under(&state.id, home).unwrap();
13945        let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13946        assert!(matches!(
13947            prepare_land_sync_recovery(&mut interrupted, &pr_url, &forge)
13948                .await
13949                .unwrap(),
13950            LandSyncPrep::Stop(_)
13951        ));
13952        assert!(
13953            interrupted.land_sync_recovery.authorizations[0]
13954                .invalidated
13955                .is_none()
13956        );
13957        assert_eq!(interrupted.land_sync_attempts, 4);
13958        git::git(&state.repo, &["remote", "set-url", "origin", remote.trim()])
13959            .await
13960            .unwrap();
13961        let mut held = queue
13962            .list()
13963            .into_iter()
13964            .find(|t| t.execution_runs().last() == Some(&state.id))
13965            .unwrap();
13966        held.hold_machine(Some("base observation failed".into()));
13967        queue.put(&mut held).unwrap();
13968        assert!(crate::resume::pin_queued(&queue, &state.id, None, None).unwrap());
13969        let queued = queue.get(&held.id).unwrap();
13970        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, .. } =
13971            crate::land_sync_recovery::dispatch_check_with(&queue, home, &queued, &observer).await
13972        {
13973            panic!("dispatch refused recovery: {reason}");
13974        }
13975
13976        // Reload after restart and run land_with: uses the 1 already-granted attempt, never double-grants.
13977        let mut restarted = RunState::load_under(&state.id, home).unwrap();
13978        let mut forge = Scripted::for_pr(
13979            &pr_url,
13980            vec![
13981                seen(&old, Checks::Green, "BEHIND", false),
13982                seen(&old, Checks::Green, "BEHIND", false),
13983                seen("@published", Checks::Green, "CLEAN", false),
13984            ],
13985        );
13986        forge.public_repo = Some(restarted.repo.clone());
13987        land_with(&mut restarted, &pr_url, &forge).await.unwrap();
13988        assert_eq!(restarted.land_sync_recovery.extra_attempts, 1);
13989        assert_eq!(restarted.land_sync_attempts, 5);
13990        assert_eq!(restarted.land_sync_recovery.authorizations.len(), 1);
13991        assert!(!restarted.land_sync_pending);
13992    }
13993
13994    #[tokio::test]
13995    async fn land_sync_recovery_dispatch_revalidation_refuses_stale_and_superseded_state() {
13996        // 1. Without authorization, dispatch holds without spending budget.
13997        let (_tmp, home, queue, task, state, old) = legacy_exhausted_landing_fixture().await;
13998        let home = home.as_path();
13999        let pr_url = state.pr.as_ref().unwrap().url.clone();
14000        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
14001            url: pr_url,
14002            number: 42,
14003            open: true,
14004            head: old.clone(),
14005            base_branch: Some("main".to_owned()),
14006        });
14007        assert!(matches!(
14008            crate::land_sync_recovery::dispatch_check_with(&queue, home, &task, &observer).await,
14009            crate::land_sync_recovery::DispatchDecision::Hold { .. }
14010        ));
14011
14012        // 2. Admit authorization, then supersede with a newer owner decision before dispatch.
14013        crate::land_sync_recovery_control::recover_with(
14014            &queue,
14015            home,
14016            crate::land_sync_recovery_control::Request {
14017                run: state.id.clone(),
14018                head: old.clone(),
14019                actor: "cli".into(),
14020                request: "req-dispatch-superseded".into(),
14021            },
14022            &observer,
14023        )
14024        .await
14025        .unwrap();
14026        let mut t = queue.get(&task.id).unwrap();
14027        t.operator_decided_at = Some(
14028            t.operator_decided_at.unwrap_or_else(jiff::Timestamp::now)
14029                + jiff::SignedDuration::from_secs(10),
14030        );
14031        queue.put(&mut t).unwrap();
14032        let decision =
14033            crate::land_sync_recovery::dispatch_check_with(&queue, home, &t, &observer).await;
14034        match decision {
14035            crate::land_sync_recovery::DispatchDecision::Hold {
14036                reason,
14037                state: updated,
14038            } => {
14039                assert!(
14040                    reason.contains("newer owner decision superseded"),
14041                    "{reason}"
14042                );
14043                let auth = updated.land_sync_recovery.authorizations.last().unwrap();
14044                assert!(auth.consumed);
14045                assert!(auth.invalidated.is_some());
14046                assert_eq!(updated.land_sync_recovery.extra_attempts, 0);
14047            }
14048            crate::land_sync_recovery::DispatchDecision::Proceed => {
14049                panic!("superseded authorization must be refused at dispatch");
14050            }
14051        }
14052    }
14053}