Skip to main content

magi/
land.rs

1//! Landing the winner: watch the pull request, fix what it complains about,
2//! and merge it.
3//!
4//! Opening the pull request used to be where magi stopped and the operator
5//! started: watch the checks, read what the review bots found, push a fix,
6//! wait again, merge. That loop is mechanical, it takes an hour of wall-clock
7//! time per pull request, and doing it by hand six times in one session is how
8//! a queue that drains unattended stops being unattended. So it lives here.
9//!
10//! # Shape
11//!
12//! [`PrState`] is one observation of a pull request and [`decide`] is the whole
13//! policy as a *pure* function of it. Nothing in [`decide`] talks to `gh`,
14//! which is what makes "green with an unresolved comment is a fix, not a merge"
15//! an assertion in a test rather than a claim in a comment. [`land`] is the
16//! only part that performs I/O: observe, decide, act, repeat.
17//!
18//! # What it refuses to do
19//!
20//! Merging is the one irreversible thing magi can do to a repository, so the
21//! loop is built to stop rather than to guess:
22//!
23//! * A red pull request is never merged. When the budget runs out the pull
24//!   request is left open with a comment naming what is still failing, because
25//!   a magi that force-merges a red pull request is worse than one that stops.
26//! * A pull request whose checks cannot be read at all (`gh` reported no
27//!   rollup) is not merged either. Landing is for repositories with CI; with no
28//!   signal there is nothing to be green.
29//! * A pull request a human merged or closed underneath us is
30//!   [`Step::Done`] - the person won, and their decision is not an error.
31//!
32//! # Why `--subject` is not optional
33//!
34//! A candidate branch holds one commit whose subject is
35//! `magi: candidate A (uncommitted work)`, and `gh pr merge --squash` prefers a
36//! single commit's message over the pull request title. Merging without
37//! [`merge_argv`]'s explicit `--subject` therefore writes a `main` history that
38//! says nothing about what landed. `AGENTS.md` records the trap; this module is
39//! where it is prevented.
40
41use std::collections::{BTreeMap, BTreeSet};
42use std::fmt::Write as _;
43use std::path::{Path, PathBuf};
44use std::sync::Arc;
45use std::time::Duration;
46
47use anyhow::{Context as _, Result, bail};
48use jiff::Timestamp;
49use serde::{Deserialize, Serialize};
50
51use crate::agent::{self, Invocation, SeatState};
52use crate::ask;
53use crate::config::MergeMode;
54use crate::git;
55use crate::proc::Quiet as _;
56use crate::prompt;
57use crate::run::{
58    ContestedHandoff, LandApproval, LandReruns, MergeOutcome, RunState, RunStatus, tail,
59};
60
61/// How often the pull request is re-read while its checks are still running.
62///
63/// Thirty seconds: a CI matrix takes minutes, so anything shorter is spent
64/// entirely on `gh` invocations, and anything much longer adds latency to every
65/// single round of a loop that already waits for agents.
66pub const POLL: Duration = Duration::from_secs(30);
67
68/// How long one wait may last before landing gives up on the checks finishing.
69///
70/// A workflow that has not settled in forty-five minutes is stuck on a runner
71/// queue, a missing approval, or a hung job - none of which more polling fixes,
72/// and all of which a person needs to see.
73pub const WAIT_CEILING: Duration = Duration::from_secs(45 * 60);
74
75/// How long the checks may stay unreadable before landing gives up on them.
76///
77/// GitHub registers a workflow run some seconds after the branch is pushed, so
78/// immediately after a pull request is opened "no checks" and "no CI in this
79/// repository" look identical. Measured on run 01c2: magi opened pull request
80/// 22, read `unknown` four seconds later, refused to merge on a guess and
81/// marked the run blocked - and every check on that pull request was green
82/// minutes afterwards, with the whole competition then re-run from scratch for
83/// a task that was already finished. Three minutes is well past the observed
84/// registration delay and still bounded, so a repository that genuinely has no
85/// checks costs one three-minute wait and then says so.
86pub const CHECKS_GRACE: Duration = Duration::from_secs(3 * 60);
87
88/// Bytes of failing log kept per check. The fixer needs the assertion and the
89/// frame around it, not the forty thousand lines of `cargo` output above it.
90const LOG_TAIL: usize = 4_000;
91
92/// Failing checks whose logs are fetched. Beyond a handful the failures share a
93/// cause, and fetching each one costs a `gh` round trip.
94const MAX_LOGS: usize = 3;
95
96/// Marker carried by every comment magi posts on a pull request.
97///
98/// Without it magi's own "still failing" comment is indistinguishable from a
99/// reviewer's, and the next observation would hand magi's own prose to the
100/// fixer as a finding.
101pub const MARKER: &str = "<!-- magi:land -->";
102
103/// Markers a bot puts in a comment to say that the comment is not a review.
104///
105/// CodeRabbit labels its own machinery in HTML comments - the trigger notice,
106/// the walkthrough summary, the "thanks for using" footer - and its actual
107/// findings arrive as *inline* review comments with a path and a line. Taking
108/// the bot at its word is more honest than guessing from prose, and it is the
109/// difference between a fix round that has something to fix and one that asks
110/// an agent to act on a quota notice.
111const NOT_A_REVIEW: [&str; 3] = [
112    "skip review by coderabbit.ai",
113    "summarize by coderabbit.ai",
114    "<!-- tips_start -->",
115];
116
117/// Where a pull request is in its life.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum PrLifecycle {
120    /// Still ours to land.
121    Open,
122    /// Already merged, by us or by a person.
123    Merged,
124    /// Closed without merging.
125    Closed,
126}
127
128/// The aggregate verdict of a pull request's checks.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum Checks {
131    /// At least one check has not finished.
132    Pending,
133    /// Every check passed (a skipped check counts as passed: the review
134    /// workflow skips release and bot pull requests by design).
135    Green,
136    /// At least one check finished without passing.
137    Red,
138    /// Nothing readable - no rollup at all, or a status magi does not know.
139    Unknown,
140}
141
142impl PrLifecycle {
143    /// Stable lower-case name, as the API and the reports spell it.
144    pub fn as_str(self) -> &'static str {
145        match self {
146            Self::Open => "open",
147            Self::Merged => "merged",
148            Self::Closed => "closed",
149        }
150    }
151}
152
153impl Checks {
154    /// Stable lower-case name, as the API and the reports spell it.
155    pub fn as_str(self) -> &'static str {
156        match self {
157            Self::Pending => "pending",
158            Self::Green => "green",
159            Self::Red => "red",
160            Self::Unknown => "unknown",
161        }
162    }
163}
164
165/// One outstanding review comment, human or bot.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct ReviewComment {
168    /// Login of whoever wrote it.
169    pub author: String,
170    /// File it was left on, for inline review comments.
171    pub path: Option<String>,
172    /// Line it was left on, when the comment is inline and still anchored.
173    pub line: Option<u64>,
174    /// The comment itself, as written.
175    pub body: String,
176}
177
178/// One observation of a pull request.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct PrState {
181    /// Pull request url, as `gh` reports it.
182    pub url: String,
183    /// Pull request number.
184    pub number: u64,
185    /// Open, merged, or closed.
186    pub state: PrLifecycle,
187    /// Aggregate check verdict.
188    pub checks: Checks,
189    /// Names of the checks that finished without passing.
190    pub failing: Vec<String>,
191    /// Comments that still want an answer, human and bot.
192    pub review_comments: Vec<ReviewComment>,
193    /// Whether the forge itself considers the failures blocking.
194    pub blocking: Blocking,
195}
196
197/// Whether a failing check actually stands between the pull request and
198/// `main`, according to the forge.
199///
200/// The rollup lists every check equally, so `coverage` going red on a
201/// repository that deliberately does not require it looked exactly like a
202/// broken build - and magi answered by spending a fix round on a change that
203/// was fine. Pull request 37 had to be merged by hand for that reason: the
204/// only red check was `editorconfig`, which was failing because the *action*
205/// could not fetch its own binary, and which the repository does not require.
206///
207/// `mergeStateStatus` is where GitHub applies the required-check set, so it
208/// is the one field that can tell the difference.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Blocking {
211    /// Required checks are satisfied and the branch merges cleanly.
212    No,
213    /// Something required is failing or missing.
214    Yes,
215    /// The branch no longer merges: the base moved under it.
216    Conflict,
217    /// The forge requires the head to include the current base.
218    Behind,
219    /// The forge did not say - an older `gh`, or a token without the scope.
220    /// Treated as `Yes`, because refusing to guess is the rule everywhere
221    /// else in this module.
222    Unsaid,
223}
224
225impl Blocking {
226    /// Read `mergeStateStatus`, which is upper-case in `gh`'s output.
227    fn of(raw: &str) -> Self {
228        match raw.to_ascii_uppercase().as_str() {
229            // Mergeable. `UNSTABLE` is the interesting one: mergeable, with a
230            // non-required check failing or still running.
231            "CLEAN" | "UNSTABLE" | "HAS_HOOKS" => Self::No,
232            "DIRTY" => Self::Conflict,
233            "BEHIND" => Self::Behind,
234            "" | "UNKNOWN" => Self::Unsaid,
235            // BLOCKED, DRAFT: something has to change first.
236            _ => Self::Yes,
237        }
238    }
239
240    /// Does this stand between the pull request and the base branch?
241    #[must_use]
242    pub fn stops_a_merge(self) -> bool {
243        !matches!(self, Self::No)
244    }
245}
246
247/// What the loop decided to do next. Pure, so the policy is testable.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum Step {
250    /// Checks are still running; re-read the pull request after [`POLL`].
251    Wait,
252    /// The base moved and the branch no longer merges: rebase it.
253    ///
254    /// Not a fix round. Nothing is wrong with the change - a competition
255    /// that runs for two hours against a repository merging pull requests
256    /// all day conflicts on the way in, and that is arithmetic rather than a
257    /// defect. Pull requests 35 and 37 were both rebased by hand for exactly
258    /// this.
259    Rebase,
260    /// Red checks or unresolved comments; run a fix round.
261    Fix {
262        /// What is unhappy, in one line, for the run log and the fix prompt.
263        reason: String,
264    },
265    /// Green and nothing outstanding; merge it.
266    Merge,
267    /// The pull request left our hands.
268    Done {
269        /// Did it land, or was it closed?
270        merged: bool,
271    },
272    /// Stop and leave the pull request to a person.
273    GiveUp {
274        /// Why magi stopped, in one line.
275        reason: String,
276    },
277}
278
279/// The outcome to record when `gh pr merge` exits non-zero, given what the
280/// pull request looked like immediately afterwards.
281///
282/// `gh pr merge` merges server-side first and only then does local work -
283/// deleting the branch, switching back to a base branch - so a non-zero exit
284/// does not mean the merge did not happen. In a jj-colocated repository it
285/// reliably does not mean that: git HEAD is detached, and `--delete-branch`
286/// ends with "could not determine current branch: not on any branch" *after*
287/// the merge has landed. Run ec12 merged pull request 28 into `main` and
288/// recorded `ok: false`, and its task was held waiting for a merge that was
289/// already done.
290///
291/// So the forge is asked, and its answer wins - the same authority [`decide`]
292/// gives the pull request's own state over everything else. The recorded
293/// detail carries both facts, because "the command failed and the merge
294/// happened anyway" is exactly what someone reading the run later needs to
295/// know.
296///
297/// `None` means the merge really did not happen, including when the pull
298/// request could not be read at all: an unreadable answer is not evidence of
299/// success.
300pub(crate) fn merged_after_all(
301    argv: &[String],
302    stderr: &str,
303    after: Option<PrLifecycle>,
304) -> Option<MergeOutcome> {
305    if after? != PrLifecycle::Merged {
306        return None;
307    }
308    Some(MergeOutcome {
309        mode: MergeMode::Pr,
310        ok: true,
311        detail: format!(
312            "gh {} (the command reported `{}`, but the pull request is merged)",
313            argv.join(" "),
314            stderr.trim()
315        ),
316        empty: false,
317    })
318}
319
320/// Decide the next step. No I/O.
321///
322/// `round` counts the fix rounds already spent, so `round == budget` means the
323/// budget is gone. A wait never spends a round: waiting is free, and a slow CI
324/// must not consume the allowance meant for actual fixes.
325///
326/// The order of the tests is the policy:
327///
328/// 1. **The pull request's own state wins.** A merge or a close that happened
329///    underneath us is the end of the story regardless of what the checks say.
330/// 2. **Pending beats red.** A check that is still running may yet fail, and one
331///    fix round that addresses every failure is cheaper than two that each
332///    address half - the fix pushes and restarts the whole suite anyway.
333/// 3. **Comments outrank green.** An unresolved comment holds the merge even
334///    when CI is happy; that is what a review is for.
335/// 4. **Unreadable is not absent.** Checks that cannot be read yet are waited
336///    on for [`CHECKS_GRACE`], because a pull request opened a moment ago has
337///    not been given its workflow runs yet. Past the grace they are treated as
338///    genuinely missing and magi stops rather than merge on a guess.
339pub fn decide(pr: &PrState, round: usize, budget: usize, waited: Duration) -> Step {
340    decide_with(pr, round, budget, waited, CiExpectation::Expected)
341}
342
343/// Whether the repository's CI is expected to report on this pull request.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub enum CiExpectation {
346    /// Checks will come: wait for them, judge them (the default, and what
347    /// [`decide`] always uses).
348    Expected,
349    /// The repository explicitly disables CI expectations with `[merge] ci = "none"`.
350    /// Ignore all check statuses while retaining conflicts and review comments.
351    Absent,
352}
353
354/// [`decide`] with the CI expectation made explicit. `Absent` ignores the
355/// rollup, but still requires conflicts and review comments to be resolved.
356pub fn decide_with(
357    pr: &PrState,
358    round: usize,
359    budget: usize,
360    waited: Duration,
361    ci: CiExpectation,
362) -> Step {
363    match pr.state {
364        PrLifecycle::Merged => return Step::Done { merged: true },
365        PrLifecycle::Closed => return Step::Done { merged: false },
366        PrLifecycle::Open => {}
367    }
368
369    // Before the checks: every check on a branch that cannot land is an
370    // answer about a state that cannot land.
371    if matches!(pr.blocking, Blocking::Conflict | Blocking::Behind) {
372        return Step::Rebase;
373    }
374
375    let spent = round >= budget;
376    let checks = match ci {
377        CiExpectation::Expected => pr.checks,
378        CiExpectation::Absent => Checks::Green,
379    };
380    match checks {
381        Checks::Pending => Step::Wait,
382        Checks::Unknown if waited < CHECKS_GRACE => Step::Wait,
383        Checks::Unknown => Step::GiveUp {
384            reason: format!(
385                "no check status is readable on the pull request after {} minute(s); \
386                 refusing to merge on a guess",
387                CHECKS_GRACE.as_secs() / 60
388            ),
389        },
390        // Red, but the forge says it does not stand in the way: the failing
391        // checks are ones this repository chose not to require. Spending a fix
392        // round on them asks an agent to repair something nobody is gating on
393        // - and pull request 37's only red check was an *action* that could
394        // not fetch its own binary. Merge, and name them so the record is
395        // honest about what was red when it landed.
396        Checks::Red if pr.blocking == Blocking::Unsaid && waited < CHECKS_GRACE => Step::Wait,
397        Checks::Red if !pr.blocking.stops_a_merge() && pr.review_comments.is_empty() => Step::Merge,
398        Checks::Red => {
399            let what = format!(
400                "{} check(s) failing: {}",
401                pr.failing.len(),
402                pr.failing.join(", ")
403            );
404            if spent {
405                Step::GiveUp {
406                    reason: format!("{what} — still red after {budget} fix round(s)"),
407                }
408            } else {
409                Step::Fix { reason: what }
410            }
411        }
412        Checks::Green if pr.review_comments.is_empty() => Step::Merge,
413        Checks::Green => {
414            let what = format!(
415                "{} but {} review comment(s) are unresolved: {}",
416                if ci == CiExpectation::Absent {
417                    "CI is not expected"
418                } else {
419                    "checks are green"
420                },
421                pr.review_comments.len(),
422                authors(&pr.review_comments)
423            );
424            if spent {
425                Step::GiveUp {
426                    reason: format!("{what} — still unresolved after {budget} fix round(s)"),
427                }
428            } else {
429                Step::Fix { reason: what }
430            }
431        }
432    }
433}
434
435/// Distinct comment authors, in the order they first appear.
436fn authors(comments: &[ReviewComment]) -> String {
437    let mut seen: Vec<&str> = Vec::new();
438    for c in comments {
439        if !seen.contains(&c.author.as_str()) {
440            seen.push(&c.author);
441        }
442    }
443    seen.join(", ")
444}
445
446/// The argv magi merges with, minus the program name.
447///
448/// `--subject` is the point of this function existing: see the module docs.
449pub fn merge_argv(number: u64, subject: &str) -> Vec<String> {
450    vec![
451        "pr".to_owned(),
452        "merge".to_owned(),
453        number.to_string(),
454        "--squash".to_owned(),
455        "--delete-branch".to_owned(),
456        "--subject".to_owned(),
457        subject.to_owned(),
458    ]
459}
460
461/// [`merge_argv`] pinned to the commit the decision was made about.
462///
463/// `--match-head-commit` makes the forge refuse the merge if the branch moved
464/// after it was observed, so a push landing between the look and the merge is
465/// never merged unseen.
466pub fn merge_argv_at(number: u64, subject: &str, head: &str) -> Vec<String> {
467    let mut argv = merge_argv(number, subject);
468    argv.push("--match-head-commit".to_owned());
469    argv.push(head.to_owned());
470    argv
471}
472
473/// Take auto-merge back. magi no longer arms auto-merge, but a run recorded by
474/// an older build may still have one standing on the forge, so the disarm
475/// paths (and `RunState::land_armed_head`) stay. Run before anything that changes the head, so an
476/// armed merge never outlives the commit that was approved for it.
477pub fn disable_automerge_argv(number: u64) -> Vec<String> {
478    ["pr", "merge", &number.to_string(), "--disable-auto"]
479        .map(str::to_owned)
480        .to_vec()
481}
482
483/// May the direct merge go ahead, judged from a fresh read?
484///
485/// The pull request must still be open on the approved head, the checks must
486/// have been read for that very head, and the policy must still say merge.
487/// Pure, so the head guard is asserted without a forge.
488fn direct_merge_is_safe(
489    fresh: Option<&Seen>,
490    approved_head: &str,
491    shown: &BTreeSet<String>,
492    round: usize,
493    budget: usize,
494    waited: Duration,
495    ci: CiExpectation,
496) -> bool {
497    let Some(fresh) = fresh else {
498        return false;
499    };
500    if fresh.pr.state != PrLifecycle::Open {
501        return false;
502    }
503    let Some(bound) = bound_head(&fresh.head, &fresh.rollup_head, None) else {
504        return false;
505    };
506    if !bound.eq_ignore_ascii_case(approved_head) {
507        return false;
508    }
509    let mut pr = fresh.pr.clone();
510    pr.review_comments.retain(|c| !shown.contains(&c.body));
511    decide_with(&pr, round, budget, waited, ci) == Step::Merge
512}
513
514/// What GitHub is still waiting for, for the stop reason when an armed merge
515/// does not happen in time. No I/O.
516///
517/// Required checks that are pending or failing are named. A check whose
518/// required-ness could not be read is never assumed optional: every unsettled
519/// check is listed and the reason says so.
520fn waiting_on(
521    merge_state: &str,
522    contexts: &[CheckInfo],
523    required_set: Option<&BTreeSet<String>>,
524) -> String {
525    let state = if merge_state.is_empty() {
526        "unknown"
527    } else {
528        merge_state
529    };
530    let tag = |c: &CheckInfo| match c.verdict {
531        Verdict::Fail => "failed",
532        _ => "pending",
533    };
534    let unsettled: Vec<&CheckInfo> = contexts
535        .iter()
536        .filter(|c| c.verdict != Verdict::Pass)
537        .collect();
538    let required: Vec<String> = unsettled
539        .iter()
540        .filter(|c| c.required == Some(true))
541        .map(|c| format!("{} ({})", c.label, tag(c)))
542        .collect();
543    let unknown: Vec<String> = unsettled
544        .iter()
545        .filter(|c| c.required.is_none())
546        .map(|c| format!("{} ({})", c.label, tag(c)))
547        .collect();
548    // Required contexts the rollup never listed: nothing reported them, so no
549    // pending/failing entry exists to name. Matched case-insensitively against
550    // the labels as the rollup spells them, and no further.
551    let never: Vec<&str> = required_set
552        .map(|set| {
553            set.iter()
554                .filter(|name| !contexts.iter().any(|c| c.label.eq_ignore_ascii_case(name)))
555                .map(String::as_str)
556                .collect()
557        })
558        .unwrap_or_default();
559    let mut out = format!("merge state: {state}");
560    if !never.is_empty() {
561        let _ = write!(
562            out,
563            "; required checks never reported: {}",
564            never.join(", ")
565        );
566    }
567    if !required.is_empty() {
568        let _ = write!(
569            out,
570            "; required checks not passing: {}",
571            required.join(", ")
572        );
573    }
574    if !unknown.is_empty() {
575        let _ = write!(
576            out,
577            "; whether these are required could not be read, so they may be: {}",
578            unknown.join(", ")
579        );
580    }
581    if required.is_empty() && unknown.is_empty() && never.is_empty() {
582        if required_set.is_some() {
583            out.push_str(
584                "; no required check is pending, failing or unreported, so GitHub is probably \
585                 waiting for a review or another branch rule",
586            );
587        } else {
588            out.push_str(
589                "; the required check list could not be read, so a required check that was \
590                 never reported cannot be ruled out",
591            );
592        }
593    }
594    out
595}
596
597/// The squash subject to merge under.
598///
599/// The pull request title, unless it is empty or is a candidate branch's commit
600/// subject that leaked into the title - in which case the task's own first line
601/// is used, because `magi: candidate A (uncommitted work)` in `main` tells a
602/// reader nothing about what landed.
603pub fn merge_subject(pr_title: &str, instruction: &str) -> String {
604    let title = pr_title.trim();
605    if !title.is_empty() && !title.starts_with("magi: candidate") {
606        return title.to_owned();
607    }
608    let first = instruction
609        .lines()
610        .map(str::trim)
611        .find(|l| !l.is_empty())
612        .unwrap_or("magi: land the winning candidate");
613    first.trim_start_matches(['#', ' ']).to_owned()
614}
615
616/// The choice that lets the merge happen, verbatim as the owner taps it.
617pub const APPROVE: &str = "merge";
618
619/// The choice that leaves the pull request open.
620pub const HOLD: &str = "hold";
621
622/// A bounded repair followed by a new review and a fresh owner decision.
623pub const REPAIR: &str = "fix findings and re-review";
624
625/// Whether review evidence offers a meaningful repair choice. This does not
626/// decide whether owner approval is required.
627pub fn repair_available(state: &RunState) -> bool {
628    state.reviews.last().is_some_and(|r| {
629        state.open_findings().iter().any(|f| f.severity.blocks())
630            || r.final_votes()
631                .iter()
632                .any(|(_, _, v)| *v == crate::verdict::ReviewVote::Reject)
633    })
634}
635
636/// All applicable reasons for consulting the owner, independent of repair choices.
637#[derive(Debug, Clone, Copy, PartialEq, Eq)]
638pub enum ApprovalReason {
639    /// Universal owner approval is enabled for every merge.
640    EveryMerge,
641    /// Contested-merge approval is enabled and blocking findings remain open.
642    OpenBlockingFindings,
643    /// Contested-merge approval is enabled and a final reviewer vote rejects.
644    FinalReject,
645    /// An existing owner decision must be honored even if controls change.
646    ExistingDecision,
647    /// Merge repair requires a fresh owner decision, even on the same head.
648    AfterRepair,
649}
650
651/// Disabling fresh approval controls never bypasses an existing owner decision
652/// or the fresh decision owed after repair, even if repair kept the same head.
653pub fn approval_reasons(state: &RunState) -> Vec<ApprovalReason> {
654    let mut reasons = Vec::new();
655    if state.owner_hold(crate::config::OwnerHold::LandApproval) {
656        reasons.push(ApprovalReason::EveryMerge);
657    }
658    if state.owner_hold(crate::config::OwnerHold::HoldContestedMerge) {
659        if state.open_findings().iter().any(|f| f.severity.blocks()) {
660            reasons.push(ApprovalReason::OpenBlockingFindings);
661        }
662        if state.reviews.last().is_some_and(|r| {
663            r.final_votes()
664                .iter()
665                .any(|(_, _, v)| *v == crate::verdict::ReviewVote::Reject)
666        }) {
667            reasons.push(ApprovalReason::FinalReject);
668        }
669    }
670    if state.land_approval.is_some() {
671        reasons.push(ApprovalReason::ExistingDecision);
672    }
673    if !state.merge_repairs.is_empty() || !state.repair_grants.is_empty() {
674        reasons.push(ApprovalReason::AfterRepair);
675    }
676    reasons
677}
678
679/// Bound free-form approval evidence by characters, including an explicit
680/// ellipsis when abbreviated. Keep UTF-8 text intact in questions and panels.
681fn approval_excerpt(text: &str, max_chars: usize) -> String {
682    if text.chars().count() <= max_chars {
683        text.to_owned()
684    } else {
685        let mut excerpt: String = text.chars().take(max_chars.saturating_sub(1)).collect();
686        excerpt.push('…');
687        excerpt
688    }
689}
690
691/// Persisted verbatim in the question and panel at creation. Deputies and
692/// resumed questions use that snapshot, never reconstruct past policy from
693/// today's settings. Fixer claims and successful gates are not resolutions.
694fn approval_evidence(state: &RunState) -> String {
695    const TITLE_CHARS: usize = 100;
696    const REASON_CHARS: usize = 300;
697    let reason = |text: &str| approval_excerpt(text, REASON_CHARS);
698    let ja = words(&state.config.graph.language).html_lang == "ja";
699    let mut s = if ja {
700        "承認が必要な理由:\n"
701    } else {
702        "Approval required because:\n"
703    }
704    .to_owned();
705    for reason in approval_reasons(state) {
706        let label = match (reason, ja) {
707            (ApprovalReason::EveryMerge, false) => {
708                "land_approval=true: owner approval for every merge"
709            }
710            (ApprovalReason::EveryMerge, true) => {
711                "land_approval=true: すべてのマージに所有者の承認が必要"
712            }
713            (ApprovalReason::OpenBlockingFindings, false) => {
714                "hold_contested_merge=true: open Major-or-above internal findings"
715            }
716            (ApprovalReason::OpenBlockingFindings, true) => {
717                "hold_contested_merge=true: Major 以上の内部指摘が未解決"
718            }
719            (ApprovalReason::FinalReject, false) => {
720                "hold_contested_merge=true: final reviewer reject after reconsideration (even without Major findings)"
721            }
722            (ApprovalReason::FinalReject, true) => {
723                "hold_contested_merge=true: 再考後の最終票が reject(Major 指摘がなくても承認が必要)"
724            }
725            (ApprovalReason::ExistingDecision, false) => {
726                "existing owner decision: changing controls cannot bypass it"
727            }
728            (ApprovalReason::ExistingDecision, true) => {
729                "既存の所有者判断: 設定変更では迂回できません"
730            }
731            (ApprovalReason::AfterRepair, false) => {
732                "fresh owner approval after merge repair, even with an unchanged head"
733            }
734            (ApprovalReason::AfterRepair, true) => {
735                "マージ修復後の新しい所有者承認(head に変更がなくても必要)"
736            }
737        };
738        let control = match reason {
739            ApprovalReason::EveryMerge => Some(crate::config::OwnerHold::LandApproval),
740            ApprovalReason::OpenBlockingFindings | ApprovalReason::FinalReject => {
741                Some(crate::config::OwnerHold::HoldContestedMerge)
742            }
743            _ => None,
744        };
745        let source = control
746            .filter(|c| !c.base_value(&state.config.graph))
747            .and_then(|c| state.branch_owner_holds.iter().find(|h| h.control == c));
748        if let Some(source) = source {
749            if ja {
750                let _ = writeln!(
751                    s,
752                    "- {}=true(レビュー対象ブランチの {} 由来, {})",
753                    source.control.key(),
754                    source.file,
755                    source.head
756                );
757            } else {
758                let _ = writeln!(
759                    s,
760                    "- {}=true from the reviewed branch's {} ({})",
761                    source.control.key(),
762                    source.file,
763                    source.head
764                );
765            }
766        }
767        let _ = writeln!(s, "- {label}");
768    }
769    s.push_str(if ja {
770        "\n再考後の各レビュアーの最終票:\n"
771    } else {
772        "\nFinal reviewer votes after reconsideration:\n"
773    });
774    if let Some(round) = state.reviews.last() {
775        let votes = round.final_votes();
776        for r in &round.reviews {
777            let vote = votes
778                .iter()
779                .find(|(seat, _, _)| *seat == r.reviewer)
780                .map(|(_, _, v)| v.label())
781                .unwrap_or(if ja { "記録なし" } else { "not recorded" });
782            let _ = writeln!(s, "#{} ({}): {vote}", r.reviewer, r.agent);
783            let rv = round
784                .reconsideration
785                .iter()
786                .find(|rv| rv.reviewer == r.reviewer);
787            if let Some(rv) = rv.filter(|rv| rv.vote.is_some()) {
788                let initial = r.vote.map(|v| v.label()).unwrap_or("?");
789                let _ = writeln!(
790                    s,
791                    "  {}: {initial} → {vote}",
792                    if ja { "再考" } else { "reconsideration" }
793                );
794                let _ = writeln!(
795                    s,
796                    "  {}: {}",
797                    if ja { "理由" } else { "reason" },
798                    reason(if rv.reason.trim().is_empty() {
799                        if ja { "記録なし" } else { "not recorded" }
800                    } else {
801                        &rv.reason
802                    })
803                );
804            } else {
805                let _ = writeln!(
806                    s,
807                    "  {}: {}",
808                    if ja {
809                        "初回票を保持・理由"
810                    } else {
811                        "initial vote retained; reason"
812                    },
813                    reason(if r.summary.trim().is_empty() {
814                        if ja { "記録なし" } else { "not recorded" }
815                    } else {
816                        &r.summary
817                    })
818                );
819                if let Some(rv) = rv {
820                    let _ = writeln!(
821                        s,
822                        "  {}: {}",
823                        if ja {
824                            "再投票の回答なし"
825                        } else {
826                            "no reconsideration vote"
827                        },
828                        reason(rv.failed.as_deref().unwrap_or(if ja {
829                            "理由の記録なし"
830                        } else {
831                            "reason not recorded"
832                        }))
833                    );
834                }
835            }
836            if let Some(failed) = &r.failed {
837                let _ = writeln!(
838                    s,
839                    "  {}: {}",
840                    if ja { "回答なし" } else { "no answer" },
841                    reason(failed)
842                );
843            }
844        }
845    } else {
846        s.push_str(if ja {
847            "レビュー記録なし\n"
848        } else {
849            "No review recorded\n"
850        });
851    }
852    s.push_str(if ja { "\n内部レビュー指摘(最終ラウンド): 採用申告や gate 成功だけでは個別指摘の解決確認にはなりません。\n" } else { "\nInternal review findings (last round): adoption claims or a passing gate alone do not confirm individual resolution.\n" });
853    let findings = state.last_round_findings();
854    for f in &findings {
855        let _ = writeln!(
856            s,
857            "[{}] {} {}:{}: {}\n{}",
858            f.id,
859            f.severity,
860            f.file.as_deref().unwrap_or("?"),
861            f.line.map(|l| l.to_string()).unwrap_or_else(|| "?".into()),
862            approval_excerpt(&f.title, TITLE_CHARS),
863            reason(&f.detail)
864        );
865        let mut evidence = false;
866        for fix in state.reviews.iter().filter_map(|r| r.fix.as_ref()).chain(
867            state
868                .operator_fixes
869                .iter()
870                .filter_map(|request| request.fix.as_ref()),
871        ) {
872            if fix.addressed.contains(&f.id) {
873                evidence = true;
874                let _ = writeln!(
875                    s,
876                    "  {} ({}): {}",
877                    if ja {
878                        "採用申告(解決未確認)"
879                    } else {
880                        "claimed addressed (resolution unconfirmed)"
881                    },
882                    fix.agent,
883                    reason(&fix.notes)
884                );
885            }
886            for rejection in fix.rejected.iter().filter(|r| r.id == f.id) {
887                evidence = true;
888                let _ = writeln!(
889                    s,
890                    "  {}: {}",
891                    if ja { "不採用理由" } else { "declined" },
892                    reason(&rejection.why)
893                );
894            }
895        }
896        if !evidence {
897            s.push_str(if ja {
898                "  採用・解決確認の記録なし\n"
899            } else {
900                "  No adoption or resolution evidence recorded\n"
901            });
902        }
903    }
904    if findings.is_empty() {
905        s.push_str(if ja {
906            "最終ラウンドに指摘の記録なし\n"
907        } else {
908            "No findings recorded in the last round\n"
909        });
910    }
911    s
912}
913
914/// Shared choices for web, CLI and consultation questions.
915pub fn approval_choices(state: &RunState) -> Vec<String> {
916    let mut choices = vec![
917        APPROVE.to_owned(),
918        HOLD.to_owned(),
919        REPAIR.to_owned(),
920        crate::merge_decision::WITHDRAW.to_owned(),
921        crate::merge_decision::DISMISS.to_owned(),
922    ];
923    choices.extend(
924        state
925            .config
926            .agents
927            .iter()
928            .map(|a| format!("{}{id}", crate::merge_decision::REIMPLEMENT, id = a.id)),
929    );
930    choices
931}
932
933/// Extend unanswered legacy cards in place. Answered cards keep their choices;
934/// a legacy repair answer gains only its missing dispatch action.
935pub fn upgrade_repair_choice(q: &mut ask::Question, state: &RunState) -> bool {
936    if q.node != APPROVAL_NODE
937        || !state
938            .land_approval
939            .as_ref()
940            .is_some_and(|a| a.question == q.id)
941    {
942        return false;
943    }
944    let before = (q.choices.clone(), q.actions.clone(), q.merge_target.clone());
945    if q.status.open() {
946        // Older cards attached Resume to hold; a hold must remain answerable
947        // without dispatching a question action.
948        q.actions.remove(HOLD);
949        for choice in approval_choices(state) {
950            if !q.choices.contains(&choice) {
951                q.choices.push(choice);
952            }
953        }
954        if q.merge_target.is_none() {
955            q.merge_target = state.pr.as_ref().map(|pr| crate::merge_decision::Target {
956                pr: pr.url.clone(),
957                head: state.land_approval.as_ref().unwrap().head.clone(),
958                language: state.config.graph.language.clone(),
959            });
960        }
961    }
962    for choice in q.choices.clone() {
963        if (q.status.open()
964            && crate::merge_decision::stops(&choice)
965            && choice != HOLD
966            && choice != crate::merge_decision::DISMISS)
967            || (choice == REPAIR && (q.status.open() || q.resolution().as_deref() == Some(REPAIR)))
968        {
969            q.actions.insert(
970                choice,
971                ask::ChoiceAction::Resume {
972                    run: state.id.clone(),
973                },
974            );
975        }
976    }
977    before != (q.choices.clone(), q.actions.clone(), q.merge_target.clone())
978}
979
980/// Graph node recorded on the approval question.
981///
982/// The phone keys its high-stakes card off this rather than off the choice
983/// strings, so renaming a button cannot silently downgrade the card that
984/// guards the one irreversible action magi takes.
985pub const APPROVAL_NODE: &str = "land-approval";
986
987/// Unified diff lines carried in the panel before it is truncated.
988///
989/// Four hundred: the panel is read on a 390px phone, where a diff line often
990/// wraps to two rows, so this is already a few thousand rows of scrolling -
991/// past that nobody is reading, and the bytes still count against the panel's
992/// 8 MiB cap. A larger diff is not hidden: the note says how many lines were
993/// cut and which worktree holds the whole patch.
994pub const DIFF_MAX_LINES: usize = 400;
995
996/// What the owner's answer to the approval question means.
997#[derive(Debug, Clone, Copy, PartialEq, Eq)]
998pub enum Approval {
999    /// The owner said [`APPROVE`]. Merge.
1000    Merge,
1001    /// Repair the existing PR, then ask again; never approval to merge.
1002    Repair,
1003    /// Anything else, including silence. Leave the pull request open.
1004    Hold,
1005}
1006
1007/// Read the owner's answer, where `None` is an unanswered question.
1008///
1009/// Silence is a hold. A timed-out question means the owner never saw it or
1010/// never decided, and defaulting an irreversible merge to "yes" would make this
1011/// gate worse than no gate at all: it would merge unattended while claiming to
1012/// have asked. Only the exact [`APPROVE`] choice merges, so an answer this
1013/// function does not recognise holds too.
1014pub fn approval(answer: Option<&str>) -> Approval {
1015    match answer {
1016        Some(a) if a.trim().eq_ignore_ascii_case(APPROVE) => Approval::Merge,
1017        Some(a) if a.trim() == REPAIR => Approval::Repair,
1018        _ => Approval::Hold,
1019    }
1020}
1021
1022/// What [`approval_gate`] found on one check of the owner's merge decision.
1023#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1024enum ApprovalGate {
1025    /// The owner said [`APPROVE`]. Merge.
1026    Approved,
1027    /// The owner explicitly requested repair, without authorizing a merge.
1028    Repair,
1029    /// The owner said anything else, the question timed out, or it was
1030    /// closed with no decision recorded.
1031    Held,
1032    /// Filed and still waiting - the caller parks rather than blocking on it.
1033    Pending,
1034}
1035
1036/// Escape text for HTML, including both quote characters.
1037///
1038/// Every string in the panel is agent-influenced: a branch name, a file path, a
1039/// commit subject, a review comment. The sandboxed frame stops such text from
1040/// *running*, but it does not stop a `<` from ending the document early or a
1041/// `"` from ending an attribute and inventing a new one - the panel would then
1042/// render a lie, or not render at all. Both quotes are escaped because the same
1043/// function is used inside attributes, where remembering which quote style the
1044/// caller used is one mistake away from an injected attribute.
1045fn esc(s: &str) -> String {
1046    let mut out = String::with_capacity(s.len());
1047    for c in s.chars() {
1048        match c {
1049            '&' => out.push_str("&amp;"),
1050            '<' => out.push_str("&lt;"),
1051            '>' => out.push_str("&gt;"),
1052            '"' => out.push_str("&quot;"),
1053            '\'' => out.push_str("&#39;"),
1054            _ => out.push(c),
1055        }
1056    }
1057    out
1058}
1059
1060/// One row of the diffstat table.
1061#[derive(Debug, Clone, PartialEq, Eq)]
1062struct StatRow {
1063    path: String,
1064    /// `None` for a binary file, which `git` reports as `-`.
1065    added: Option<u64>,
1066    removed: Option<u64>,
1067}
1068
1069impl StatRow {
1070    /// Lines touched, for sorting. A binary file counts as zero rather than as
1071    /// unknown, which puts it at the bottom where it needs no attention.
1072    fn churn(&self) -> u64 {
1073        self.added.unwrap_or(0) + self.removed.unwrap_or(0)
1074    }
1075}
1076
1077/// Parse `git diff --numstat` into rows, biggest churn first.
1078///
1079/// `--numstat` and not `--stat`: the `+++---` bar in `--stat` is *scaled* to the
1080/// terminal width, so counting its characters would print fabricated numbers in
1081/// the one table an operator approves an irreversible action from.
1082fn parse_numstat(numstat: &str) -> Vec<StatRow> {
1083    let mut rows: Vec<StatRow> = numstat
1084        .lines()
1085        .filter_map(|line| {
1086            let mut parts = line.splitn(3, '\t');
1087            let added = parts.next()?.trim();
1088            let removed = parts.next()?.trim();
1089            let path = parts.next()?.trim();
1090            if path.is_empty() {
1091                return None;
1092            }
1093            Some(StatRow {
1094                path: path.to_owned(),
1095                added: added.parse().ok(),
1096                removed: removed.parse().ok(),
1097            })
1098        })
1099        .collect();
1100    // Path breaks the tie so the same change always renders the same table; an
1101    // operator comparing two panels should not see rows shuffle.
1102    rows.sort_by(|a, b| b.churn().cmp(&a.churn()).then_with(|| a.path.cmp(&b.path)));
1103    rows
1104}
1105
1106/// How one diff line is shown: a gutter character, a style, and the body to
1107/// print - which is the line minus its marker, so the marker appears exactly
1108/// once, in the gutter.
1109///
1110/// The gutter is why this exists at all. The operator may be colour blind, or
1111/// reading in sunlight with the screen dimmed, so an added line is never
1112/// distinguished by its background alone: `+` and `-` sit in a fixed column,
1113/// the same mark they already read in a terminal.
1114fn diff_row(line: &str) -> (&'static str, &'static str, &str) {
1115    if line.starts_with("+++") || line.starts_with("---") {
1116        (" ", "color:#57606a;font-weight:600", line)
1117    } else if let Some(body) = line.strip_prefix('+') {
1118        ("+", "background:#e6ffec;color:#0a3622", body)
1119    } else if let Some(body) = line.strip_prefix('-') {
1120        ("-", "background:#ffebe9;color:#5c1a17", body)
1121    } else if line.starts_with("@@") {
1122        ("~", "background:#eef2ff;color:#3730a3", line)
1123    } else if let Some(body) = line.strip_prefix(' ') {
1124        (" ", "", body)
1125    } else {
1126        (" ", "color:#57606a;font-weight:600", line)
1127    }
1128}
1129
1130/// The handful of words the approval panel says in its own voice.
1131///
1132/// magi's own text, not an agent's, so `[graph] language` has to reach it too:
1133/// the operator asked why the merge question spoke English on a repository
1134/// configured for Japanese, and "because that string is a literal in Rust" is
1135/// not an answer. Only the languages magi can actually check are translated;
1136/// anything else falls back to English rather than shipping a guess, and that
1137/// fallback is deliberate.
1138struct Words {
1139    html_lang: &'static str,
1140    task: &'static str,
1141    what_changed: &'static str,
1142    review_verdict: &'static str,
1143    reviewer: &'static str,
1144    reviewer_no_answer: &'static str,
1145    checks: &'static str,
1146    nothing_failing: &'static str,
1147    files_changed: &'static str,
1148    commits: &'static str,
1149    no_commits: &'static str,
1150    comments: &'static str,
1151    no_comments: &'static str,
1152    diff: &'static str,
1153    truncated: &'static str,
1154    lands_as: &'static str,
1155}
1156
1157const EN: Words = Words {
1158    html_lang: "en",
1159    task: "Task",
1160    what_changed: "What changed",
1161    review_verdict: "Review verdict",
1162    reviewer: "Reviewer",
1163    reviewer_no_answer: "produced no answer",
1164    checks: "Checks",
1165    nothing_failing: "Nothing failing.",
1166    files_changed: "file(s) changed",
1167    commits: "Commits being squashed",
1168    no_commits: "No commit subjects could be read from the branch.",
1169    comments: "External PR review comments",
1170    no_comments: "No unaddressed external PR comments at this observation. This does not mean internal findings are resolved.",
1171    diff: "Diff",
1172    truncated: "Truncated",
1173    lands_as: "They land as one commit titled",
1174};
1175
1176const JA: Words = Words {
1177    html_lang: "ja",
1178    task: "タスク",
1179    what_changed: "変更内容",
1180    review_verdict: "レビューの結論",
1181    reviewer: "レビュアー",
1182    reviewer_no_answer: "回答なし",
1183    checks: "チェック",
1184    nothing_failing: "失敗しているものはありません。",
1185    files_changed: "ファイル変更",
1186    commits: "squash されるコミット",
1187    no_commits: "ブランチからコミット件名を読めませんでした。",
1188    comments: "外部 PR レビューコメント",
1189    no_comments: "この時点で未対応の外部 PR コメントはありません。内部指摘の解決を意味するものではありません。",
1190    diff: "差分",
1191    truncated: "省略",
1192    lands_as: "これらは次の件名の1コミットとして入ります:",
1193};
1194
1195impl Words {
1196    /// The clause after the merge subject. Split out because word order moves:
1197    /// Japanese puts the subject before the verb, so a shared template with a
1198    /// hole in the middle would read as machine translation.
1199    fn lands_as_tail(&self) -> &'static str {
1200        if self.html_lang == "ja" {
1201            "。この件名も承認の対象です。"
1202        } else {
1203            ", which you are approving too."
1204        }
1205    }
1206
1207    /// The question's own one-line summary, which is what a phone shows first.
1208    fn approval_summary(&self, number: u64, subject: &str) -> String {
1209        if self.html_lang == "ja" {
1210            format!("プルリクエスト #{number} をマージ: {subject}")
1211        } else {
1212            format!("merge pull request #{number}: {subject}")
1213        }
1214    }
1215
1216    /// The body under the summary, above the panel.
1217    fn approval_detail(
1218        &self,
1219        url: &str,
1220        base: &str,
1221        subject: &str,
1222        contested: Option<&ContestedHandoff>,
1223    ) -> String {
1224        let body = if self.html_lang == "ja" {
1225            format!(
1226                "{url} はチェックが緑で、`{base}` へ `{subject}` として squash \
1227                 できる状態です。差分の要約・パッチ・squash されるコミットは\
1228                 下のパネルにあります。"
1229            )
1230        } else {
1231            format!(
1232                "{url} is green and ready to squash into `{base}` as `{subject}`. \
1233                 The panel holds the diffstat, the patch and the commits being squashed."
1234            )
1235        };
1236        match contested {
1237            Some(c) => format!("{}\n\n{body}", self.contested_reason(url, c)),
1238            None => body,
1239        }
1240    }
1241
1242    /// Why this question exists although merge approvals are off: the open
1243    /// blocking findings and who rejected. Short enough for a phone.
1244    fn contested_reason(&self, url: &str, c: &ContestedHandoff) -> String {
1245        const SHOWN: usize = 5;
1246        const TITLE_CHARS: usize = 100;
1247        let ja = self.html_lang == "ja";
1248        let mut out = if ja {
1249            format!(
1250                "{url} は、マージ承認がオフでも保留しています。レビューが予算切れで終わった\
1251                 時点で、却下票を伴う重大な未解決の指摘が残っているためです。\n"
1252            )
1253        } else {
1254            format!(
1255                "{url} is held for approval although merge approvals are off: the \
1256                 review ended with blocking findings still open and a reviewer \
1257                 voting reject.\n"
1258            )
1259        };
1260        for f in c.findings.iter().take(SHOWN) {
1261            let at = match (&f.file, f.line) {
1262                (Some(file), Some(line)) => format!("{file}:{line}"),
1263                (Some(file), None) => file.clone(),
1264                _ => (if ja { "場所未指定" } else { "no location" }).to_owned(),
1265            };
1266            let title: String = f.title.chars().take(TITLE_CHARS).collect();
1267            let _ = writeln!(out, "- {} {} {at}: {title}", f.id, f.severity);
1268        }
1269        if c.findings.len() > SHOWN {
1270            let more = c.findings.len() - SHOWN;
1271            let _ = writeln!(
1272                out,
1273                "{}",
1274                if ja {
1275                    format!("- ほか {more} 件")
1276                } else {
1277                    format!("- and {more} more")
1278                }
1279            );
1280        }
1281        let seats: Vec<String> = c
1282            .rejecters
1283            .iter()
1284            .map(|(seat, agent)| format!("#{seat} ({agent})"))
1285            .collect();
1286        let _ = write!(
1287            out,
1288            "{} {}",
1289            if ja {
1290                "却下したレビュアー:"
1291            } else {
1292                "Rejected by reviewer:"
1293            },
1294            seats.join(", ")
1295        );
1296        out
1297    }
1298
1299    /// The truncation note, written whole in each language for the same reason.
1300    fn truncated_note(
1301        &self,
1302        omitted: usize,
1303        total: usize,
1304        shown: usize,
1305        where_: &str,
1306        base: &str,
1307        head: &str,
1308    ) -> String {
1309        if self.html_lang == "ja" {
1310            format!(
1311                "先頭 {shown} 行のあと、差分 {total} 行のうち {omitted} 行を省略しました。\
1312                 全体は <code>{where_}</code>(<code>git diff {base}...{head}</code>)と\
1313                 プルリクエストにあります。"
1314            )
1315        } else {
1316            format!(
1317                "{omitted} of {total} diff lines omitted after the first {shown}. \
1318                 The whole patch is in <code>{where_}</code> \
1319                 (<code>git diff {base}...{head}</code>) and on the pull request."
1320            )
1321        }
1322    }
1323}
1324
1325/// Pick the panel's language. Codes and names both, because `[graph] language`
1326/// has always accepted either.
1327fn words(language: &str) -> &'static Words {
1328    if crate::lang::is_japanese(language) {
1329        &JA
1330    } else {
1331        &EN
1332    }
1333}
1334
1335/// The approval panel's html: what is about to land, and the evidence for it.
1336///
1337/// Pure, so the whole document is asserted in tests without `gh`, without a
1338/// network and without a repository. The caller gathers `diffstat`
1339/// (`git diff --numstat`), `diff` (the unified patch), `commits` (the subjects
1340/// being squashed) and `subject` (what the squash will be called) from the
1341/// winner's worktree.
1342///
1343/// It emits no `<script>`, no `<form>` and no remote url, because the frame's
1344/// content security policy blocks all three: anything of the sort here would be
1345/// dead markup that misleads the next reader into thinking it works.
1346pub fn approval_panel(
1347    state: &RunState,
1348    pr: &PrState,
1349    diffstat: &str,
1350    diff: &str,
1351    commits: &[String],
1352    subject: &str,
1353) -> String {
1354    let rows = parse_numstat(diffstat);
1355    let w = words(&state.config.graph.language);
1356    let mut h = String::with_capacity(4_096 + diff.len().min(200_000));
1357
1358    let _ = writeln!(
1359        h,
1360        "<!doctype html>\n<html lang=\"{}\">\n<head>\n<meta charset=\"utf-8\">\n\
1361         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
1362        w.html_lang
1363    );
1364    let _ = writeln!(
1365        h,
1366        "<title>merge #{} — {}</title>\n</head>",
1367        pr.number,
1368        esc(subject)
1369    );
1370    h.push_str(
1371        "<body style=\"margin:0;padding:12px;font:15px/1.5 -apple-system,\
1372         'Segoe UI',system-ui,sans-serif;color:#1f2328;background:#fff;\
1373         word-break:break-word\">\n",
1374    );
1375
1376    // The decision, in the words the operator is approving.
1377    let _ = writeln!(
1378        h,
1379        "<h1 style=\"margin:0 0 4px;font-size:19px\">Merge #{} into \
1380         <code style=\"background:#f6f8fa;padding:1px 4px;border-radius:4px\">{}</code></h1>\n\
1381         <p style=\"margin:0 0 4px;font-size:17px;font-weight:600\">{}</p>\n\
1382         <p style=\"margin:0 0 12px;font-size:13px;color:#57606a\">squash merge · run {} · \
1383         <a href=\"{}\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:#0969da\">{}</a></p>",
1384        pr.number,
1385        esc(&state.base_branch),
1386        esc(subject),
1387        esc(&state.id),
1388        esc(&pr.url),
1389        esc(&pr.url),
1390    );
1391
1392    let _ = writeln!(
1393        h,
1394        "<section style=\"padding:12px;background:#fff8c5;border:1px solid #9a6700;border-radius:6px;white-space:pre-wrap\">{}</section>",
1395        esc(&approval_evidence(state))
1396    );
1397
1398    // The task, verbatim: the operator's own words for what was asked, so the
1399    // panel does not make them reconstruct the request from a diffstat.
1400    let _ = writeln!(
1401        h,
1402        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>\n\
1403         <p style=\"margin:0;font-size:13px;white-space:pre-wrap\">{}</p>",
1404        w.task,
1405        esc(&state.instruction)
1406    );
1407
1408    // The winner's own account of what it did and why, when there is one.
1409    if let Some(summary) = state
1410        .winner()
1411        .map(|c| c.summary.as_str())
1412        .filter(|s| !s.is_empty())
1413    {
1414        let _ = writeln!(
1415            h,
1416            "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>\n\
1417             <p style=\"margin:0;font-size:13px;white-space:pre-wrap\">{}</p>",
1418            w.what_changed,
1419            esc(summary)
1420        );
1421    }
1422
1423    // Only the last round's reviewer prose is current. Its votes and
1424    // remaining findings are shown explicitly in the evidence above.
1425    if let Some(round) = state.reviews.last() {
1426        let _ = writeln!(
1427            h,
1428            "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1429            w.review_verdict
1430        );
1431        for r in &round.reviews {
1432            // A seat the review loop counted as answered has real prose in
1433            // `summary`; one it counted against `incomplete` (see
1434            // `graph::Runner::review_loop`) never produced any and left it
1435            // empty - which must not be read back as a blank verdict, since
1436            // an empty box here looks like "nothing to say" rather than
1437            // "never answered".
1438            let body = match &r.failed {
1439                Some(reason) => format!("{}: {}", w.reviewer_no_answer, esc(reason)),
1440                None => esc(&r.summary),
1441            };
1442            let _ = writeln!(
1443                h,
1444                "<div style=\"margin:0 0 8px;padding:8px;background:#f6f8fa;\
1445                 border-radius:6px\">\
1446                 <div style=\"font-size:12px;color:#57606a\">{} {} · {}</div>\
1447                 <div style=\"white-space:pre-wrap;font-size:13px\">{}</div></div>",
1448                w.reviewer,
1449                r.reviewer,
1450                esc(&r.agent),
1451                body,
1452            );
1453        }
1454    }
1455
1456    let _ = writeln!(
1457        h,
1458        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}: {}</h2>",
1459        w.checks,
1460        esc(pr.checks.as_str())
1461    );
1462    if pr.failing.is_empty() {
1463        let _ = writeln!(
1464            h,
1465            "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>",
1466            w.nothing_failing
1467        );
1468    } else {
1469        h.push_str("<ul style=\"margin:0;padding-left:20px;font-size:13px\">\n");
1470        for f in &pr.failing {
1471            let _ = writeln!(h, "<li>{}</li>", esc(f));
1472        }
1473        h.push_str("</ul>\n");
1474    }
1475
1476    // Diffstat as a real table, so a phone reads what moved without scrolling
1477    // sideways through a terminal bar chart.
1478    let _ = writeln!(
1479        h,
1480        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{} {}</h2>",
1481        rows.len(),
1482        w.files_changed
1483    );
1484    h.push_str(
1485        "<table style=\"width:100%;border-collapse:collapse;font-size:13px\">\n\
1486         <thead><tr>\
1487         <th style=\"text-align:left;border-bottom:1px solid #d0d7de;padding:4px 2px\">file</th>\
1488         <th style=\"text-align:right;border-bottom:1px solid #d0d7de;padding:4px 2px\">added</th>\
1489         <th style=\"text-align:right;border-bottom:1px solid #d0d7de;padding:4px 2px\">removed\
1490         </th></tr></thead>\n<tbody>\n",
1491    );
1492    let mut total_added = 0u64;
1493    let mut total_removed = 0u64;
1494    for r in &rows {
1495        total_added += r.added.unwrap_or(0);
1496        total_removed += r.removed.unwrap_or(0);
1497        let cell = |n: Option<u64>| match n {
1498            Some(n) => n.to_string(),
1499            None => "bin".to_owned(),
1500        };
1501        let _ = writeln!(
1502            h,
1503            "<tr>\
1504             <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;\
1505             font-family:ui-monospace,monospace\">{}</td>\
1506             <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;text-align:right;\
1507             color:#0a3622\">{}</td>\
1508             <td style=\"padding:4px 2px;border-bottom:1px solid #eaeef2;text-align:right;\
1509             color:#5c1a17\">{}</td></tr>",
1510            esc(&r.path),
1511            cell(r.added),
1512            cell(r.removed),
1513        );
1514    }
1515    let _ = writeln!(
1516        h,
1517        "</tbody>\n<tfoot><tr style=\"font-weight:600\">\
1518         <td style=\"padding:4px 2px\">total</td>\
1519         <td style=\"padding:4px 2px;text-align:right\">{total_added}</td>\
1520         <td style=\"padding:4px 2px;text-align:right\">{total_removed}</td>\
1521         </tr></tfoot>\n</table>"
1522    );
1523
1524    // The commits being squashed, and the subject that replaces them.
1525    let _ = writeln!(
1526        h,
1527        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1528        w.commits
1529    );
1530    if commits.is_empty() {
1531        h.push_str(&format!(
1532            "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>\n",
1533            w.no_commits
1534        ));
1535    } else {
1536        h.push_str("<ol style=\"margin:0;padding-left:20px;font-size:13px\">\n");
1537        for c in commits {
1538            let _ = writeln!(h, "<li>{}</li>", esc(c));
1539        }
1540        h.push_str("</ol>\n");
1541    }
1542    let _ = writeln!(
1543        h,
1544        "<p style=\"margin:8px 0 0;font-size:13px\">{} <strong>{}</strong>{}</p>",
1545        w.lands_as,
1546        esc(subject),
1547        w.lands_as_tail()
1548    );
1549
1550    // The review comments that shaped this branch, and who asked for them.
1551    let _ = writeln!(
1552        h,
1553        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1554        w.comments
1555    );
1556    if pr.review_comments.is_empty() {
1557        h.push_str(&format!(
1558            "<p style=\"margin:0;font-size:13px;color:#57606a\">{}</p>\n",
1559            w.no_comments
1560        ));
1561    } else {
1562        for c in &pr.review_comments {
1563            let anchor = match (&c.path, c.line) {
1564                (Some(p), Some(l)) => format!("{p}:{l}"),
1565                (Some(p), None) => p.clone(),
1566                _ => "pull request thread".to_owned(),
1567            };
1568            let _ = writeln!(
1569                h,
1570                "<div style=\"margin:0 0 8px;padding:8px;background:#f6f8fa;border-radius:6px\">\
1571                 <div style=\"font-size:12px;color:#57606a\">{} · {}</div>\
1572                 <div style=\"white-space:pre-wrap;font-size:13px\">{}</div></div>",
1573                esc(&c.author),
1574                esc(&anchor),
1575                esc(&tail(&c.body, 800)),
1576            );
1577        }
1578    }
1579
1580    // The patch itself.
1581    let total = diff.lines().count();
1582    let shown = total.min(DIFF_MAX_LINES);
1583    let _ = writeln!(
1584        h,
1585        "<h2 style=\"margin:16px 0 6px;font-size:15px\">{}</h2>",
1586        w.diff
1587    );
1588    h.push_str(
1589        "<div style=\"font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;\
1590         border:1px solid #d0d7de;border-radius:6px;overflow-x:auto\">\n",
1591    );
1592    for line in diff.lines().take(shown) {
1593        let (gutter, style, body) = diff_row(line);
1594        let _ = writeln!(
1595            h,
1596            "<div style=\"display:flex;{style}\">\
1597             <span style=\"flex:0 0 1.4em;text-align:center;user-select:none;\
1598             border-right:1px solid #d0d7de\">{gutter}</span>\
1599             <span style=\"white-space:pre;padding-left:6px\">{}</span></div>",
1600            esc(body),
1601        );
1602    }
1603    h.push_str("</div>\n");
1604    if total > shown {
1605        let omitted = total - shown;
1606        let head = state.winner().map_or("HEAD", |w| w.branch.as_str());
1607        let where_ = state.winner().map_or_else(
1608            || state.repo.display().to_string(),
1609            |w| w.worktree.display().to_string(),
1610        );
1611        let _ = writeln!(
1612            h,
1613            "<p style=\"margin:8px 0 0;padding:8px;background:#fff8c5;border-radius:6px;\
1614             font-size:13px\">{}: {}</p>",
1615            w.truncated,
1616            w.truncated_note(
1617                omitted,
1618                total,
1619                shown,
1620                &esc(&where_),
1621                &esc(&state.base_branch),
1622                &esc(head),
1623            ),
1624        );
1625    }
1626
1627    h.push_str("</body>\n</html>\n");
1628    h
1629}
1630
1631/// Historical contested hand-off evidence for the question detail. Approval
1632/// itself is decided by `approval_reasons`, including reject-only cases.
1633fn contested_to_ask(state: &RunState) -> Option<ContestedHandoff> {
1634    if state.owner_hold(crate::config::OwnerHold::HoldContestedMerge) {
1635        state.contested_handoff.clone()
1636    } else {
1637        None
1638    }
1639}
1640
1641/// What a merge-approval question's deputy is told: the pull request, the run,
1642/// what each answer does, and the evidence saved when the question was filed.
1643///
1644/// Rebuilt for every deputy turn, it is still a snapshot of that moment, so it
1645/// says so and points at `magi show` / `gh pr view` for anything current.
1646/// `state` is `None` for a run that cannot be read; what is missing is named as
1647/// missing, and no past approval basis is rebuilt from today's state.
1648pub fn deputy_brief(q: &ask::Question, state: Option<&RunState>) -> String {
1649    let mut s = format!(
1650        "This is the merge approval for run {run} (`magi show {run}`). The question's \
1651         own text above names the pull request. Answering `{APPROVE}` squash-merges \
1652         it into the base branch; `{HOLD}` leaves the pull request open. Silence is a \
1653         hold: the owner not answering never merges. When the owner tells you to \
1654         merge, in whatever words, settle `{APPROVE}`; when they ask for what another \
1655         offered choice does, settle that one. If you cannot tell what they want, ask \
1656         with `magi ask --thread`.\n\n\
1657         This brief is a snapshot from when your turn started: check `magi show {run}` \
1658         and `gh pr view` (read-only) before telling the owner anything current. The \
1659         driver carries out the merge, repair, withdrawal or replacement: do not \
1660         change files, branches or the pull request yourself.",
1661        run = q.run
1662    );
1663    if let Some(target) = &q.merge_target {
1664        s.push_str(&format!("\n\nThis decision names PR {} at head `{}`. A settled `{APPROVE}` merges exactly that head; a newer head is never merged on this answer. Withdrawal explicitly closes the PR and ends the task. Replacement closes the old PR before dispatching a new attempt with the selected implementer; do not start a separate task for it yourself.", target.pr, target.head));
1665    }
1666    if q.choices.iter().any(|c| c == REPAIR) {
1667        s.push_str("\n\n`fix findings and re-review` requests one repair and bounded re-review on the existing PR. It never approves a merge. The driver performs the repair; do not edit or queue another task for it. Updated review and gate results require a fresh merge decision.");
1668    }
1669    if q.detail.contains("Approval required because:") || q.detail.contains("承認が必要な理由:")
1670    {
1671        s.push_str("\n\nSaved approval evidence (at question creation):\n");
1672        s.push_str(&q.detail);
1673    } else {
1674        s.push_str("\n\nApproval reasons and final review evidence were not recorded in this legacy question. Do not infer its original trigger from current settings; consult the saved panel and review history.");
1675    }
1676    let Some(state) = state else {
1677        s.push_str(
1678            "\n\nThe run's record could not be read, so the pull request, the panel \
1679             summary and any contested findings are not known to you beyond the \
1680             question's own text. Say so to the owner rather than guessing.",
1681        );
1682        return s;
1683    };
1684    if let Some(pr) = &state.pr {
1685        s.push_str(&format!(
1686            "\n\nPull request #{} {} (recorded state: {}, last seen).",
1687            pr.number, pr.url, pr.state
1688        ));
1689    }
1690    s.push_str(&format!("\nBase branch: `{}`.", state.base_branch));
1691    if let Some(w) = state.winner() {
1692        s.push_str(&format!("\nWinning branch: `{}`.", w.branch));
1693    }
1694
1695    s
1696}
1697
1698// Releasing a task permits work to resume; it does not renew merge consent.
1699// Check the persisted operator decision both when reusing a card and at the
1700// final merge boundary, since a hold/release can arrive between those reads.
1701fn merge_consent_superseded(state: &RunState, question: &ask::Question) -> Result<bool> {
1702    if !question.status.open() && approval(question.resolution().as_deref()) != Approval::Merge {
1703        return Ok(false);
1704    }
1705    let Some(task_id) = state
1706        .origin
1707        .as_ref()
1708        .and_then(|origin| origin.task.as_ref())
1709    else {
1710        return Ok(false);
1711    };
1712    let task = crate::queue::Queue::open()
1713        .get(task_id)
1714        .context("cannot verify operator decisions for the merge approval")?;
1715    Ok(task
1716        .operator_decided_at
1717        .is_some_and(|at| at > question.answered_at.unwrap_or(question.asked_at)))
1718}
1719
1720/// Ask the owner before merging, with the whole case attached as a panel.
1721///
1722/// The evidence is gathered from the winner's own worktree with the `git` CLI,
1723/// never from the network, so a phone on a slow link gets the diff magi is
1724/// looking at rather than a link it has to go and open.
1725///
1726/// Never blocks. `land` used to sit inside [`ask::ask_and_wait`]'s poll loop
1727/// for up to a day right here, which held the whole run's task claim - and
1728/// the daemon's one slot with it - for exactly as long as the owner took to
1729/// notice their phone. [`ApprovalGate::Pending`] is the answer that lets the
1730/// caller park the run and hand the slot back instead: the question is on
1731/// disk either way, so nothing about the wait itself changes, only who is
1732/// blocked on it.
1733///
1734/// Idempotent across resumes: called again for a run already waiting on its
1735/// own question, this finds that question by [`crate::ask::Questions::list`]
1736/// rather than filing a second one - asking twice would double the
1737/// notification for one decision, and leave the first question's panel an
1738/// orphan nobody's answer ever reaches.
1739async fn approval_gate(
1740    state: &mut RunState,
1741    pr: &PrState,
1742    subject: &str,
1743    contested: Option<&ContestedHandoff>,
1744    head: &str,
1745) -> Result<ApprovalGate> {
1746    let _chat_merge = crate::chat_merge::target_lock_wait(&crate::run::home(), &pr.url).await?;
1747    let store = ask::Questions::open();
1748    // An answer belongs to the commit its panel showed. A question recorded
1749    // for another head - or none recorded at all, as for a question filed
1750    // before heads were tracked - is never reused: a fix or rebase push made
1751    // a commit the owner has not seen, and their word does not carry over.
1752    let reusable = state.land_approval.as_ref().and_then(|a| {
1753        store
1754            .list_for_effects()
1755            .into_iter()
1756            .find(|q| q.id == a.question)
1757            .filter(|q| {
1758                q.status != ask::QuestionStatus::Abandoned
1759                    && state
1760                        .repair_grants
1761                        .last()
1762                        .is_none_or(|g| q.asked_at > g.receipt.at)
1763                    && state
1764                        .land_sync_recovery
1765                        .authorizations
1766                        .iter()
1767                        .rev()
1768                        .find(|auth| auth.consumed && auth.invalidated.is_none())
1769                        .is_none_or(|auth| q.asked_at > auth.consumed_at.unwrap_or(auth.at))
1770                    && (a.head.eq_ignore_ascii_case(head)
1771                        || q.resolution()
1772                            .as_deref()
1773                            .is_some_and(crate::merge_decision::stops))
1774            })
1775    });
1776    let reusable = match reusable {
1777        Some(q) if merge_consent_superseded(state, &q)? => None,
1778        other => other,
1779    };
1780    if reusable.is_none() {
1781        for stale in store.list_for_effects().into_iter().filter(|q| {
1782            q.run == state.id
1783                && q.node == APPROVAL_NODE
1784                && q.status.open()
1785                && !store.held_reply(&q.id)
1786        }) {
1787            let why =
1788                "the pull request head or operator decision changed; asked again for approval";
1789            if let Err(e) = store.update(&stale.id, |q| {
1790                q.abandon(why);
1791                Ok(())
1792            }) {
1793                tracing::warn!("could not retire the superseded approval question: {e:#}");
1794            }
1795        }
1796    }
1797
1798    let q = match reusable {
1799        Some(mut q) => {
1800            if upgrade_repair_choice(&mut q, state) {
1801                q = store
1802                    .update(&q.id, |current| {
1803                        upgrade_repair_choice(current, state);
1804                        Ok(())
1805                    })?
1806                    .0;
1807            }
1808            q
1809        }
1810        None => {
1811            let worktree = match state.winner() {
1812                Some(w) => w.worktree.clone(),
1813                None => state.repo.clone(),
1814            };
1815            // The diff is built from the commit being approved, not from the
1816            // branch name, which may already point somewhere else.
1817            let head = if head.is_empty() {
1818                state
1819                    .winner()
1820                    .map_or_else(|| "HEAD".to_owned(), |w| w.branch.clone())
1821            } else {
1822                head.to_owned()
1823            };
1824            // The diff is against what the remote's base holds, never the
1825            // local branch of that name; unreadable means less evidence.
1826            let remote = &state.config.merge.remote;
1827            let tracking = format!("{remote}/{}", state.base_branch);
1828            let base = if git::rev_exists(&worktree, &tracking).await {
1829                tracking
1830            } else {
1831                String::new()
1832            };
1833            let range = format!("{base}...{head}");
1834            // A failed `git` must not decide the merge: the panel degrades to
1835            // less evidence and the owner still chooses. Merging because the
1836            // diff could not be read would be the worst of both.
1837            let numstat = if base.is_empty() {
1838                String::new()
1839            } else {
1840                git::git_raw(&worktree, &["diff", "--numstat", "-M", &range])
1841                    .await
1842                    .map(|o| o.stdout)
1843                    .unwrap_or_default()
1844            };
1845            let diff = if base.is_empty() {
1846                String::new()
1847            } else {
1848                git::diff(&worktree, &base, &head).await.unwrap_or_default()
1849            };
1850            let commits: Vec<String> = if base.is_empty() {
1851                Vec::new()
1852            } else {
1853                git::git_raw(
1854                    &worktree,
1855                    &[
1856                        "log",
1857                        "--reverse",
1858                        "--format=%s",
1859                        &format!("{base}..{head}"),
1860                    ],
1861                )
1862                .await
1863                .map(|o| o.stdout)
1864                .unwrap_or_default()
1865                .lines()
1866                .filter(|l| !l.trim().is_empty())
1867                .map(str::to_owned)
1868                .collect()
1869            };
1870
1871            let w = words(&state.config.graph.language);
1872            let html = approval_panel(state, pr, &numstat, &diff, &commits, subject);
1873            let mut fresh = ask::Question::new(
1874                state.id.clone(),
1875                APPROVAL_NODE.to_owned(),
1876                "land".to_owned(),
1877                w.approval_summary(pr.number, subject),
1878                format!(
1879                    "{}\n\n{}",
1880                    approval_evidence(state),
1881                    w.approval_detail(&pr.url, &state.base_branch, subject, contested)
1882                ),
1883                approval_choices(state),
1884            );
1885            fresh.merge_target = Some(crate::merge_decision::Target {
1886                pr: pr.url.clone(),
1887                head: head.clone(),
1888                language: state.config.graph.language.clone(),
1889            });
1890            if fresh.choices.iter().any(|c| c == REPAIR) {
1891                fresh.actions.insert(
1892                    REPAIR.to_owned(),
1893                    ask::ChoiceAction::Resume {
1894                        run: state.id.clone(),
1895                    },
1896                );
1897                fresh.detail.push_str("\n\n`fix findings and re-review` runs one repair and bounded review on this PR; it does not approve a merge. A fresh decision follows the updated review and gate.");
1898            }
1899            for choice in fresh.choices.clone() {
1900                if crate::merge_decision::stops(&choice)
1901                    && choice != HOLD
1902                    && choice != crate::merge_decision::DISMISS
1903                {
1904                    fresh.actions.insert(
1905                        choice,
1906                        ask::ChoiceAction::Resume {
1907                            run: state.id.clone(),
1908                        },
1909                    );
1910                }
1911            }
1912            store
1913                .put_panel(&mut fresh, &html, &[])
1914                .context("write the merge approval panel")?;
1915            store
1916                .put_executable(&mut fresh)
1917                .context("file the merge approval question")?;
1918            state.land_approval = Some(LandApproval {
1919                question: fresh.id.clone(),
1920                head: head.clone(),
1921            });
1922            state.event(
1923                "land",
1924                format!("asking for merge approval ({})", fresh.short()),
1925            );
1926            state.save()?;
1927            if let Err(e) = ask::notify(&state.config.notify, &fresh).await {
1928                // A broken webhook is not a reason to lose the merge: the
1929                // question is already on disk and the web UI already shows
1930                // it, so the operator still has a way in.
1931                tracing::warn!(
1932                    "could not notify about merge approval question {}: {e:#} - \
1933                     the web UI is the only surface for it now",
1934                    fresh.short()
1935                );
1936            }
1937            fresh
1938        }
1939    };
1940
1941    Ok(match q.status {
1942        ask::QuestionStatus::Open => ApprovalGate::Pending,
1943        // Nobody answered before `state.config.graph.answer_timeout` passed,
1944        // or the question was closed with no decision recorded underneath
1945        // this run - either way there is nothing left to wait on.
1946        ask::QuestionStatus::Abandoned => ApprovalGate::Held,
1947        // The merge gate does not speak `--thread`: an owner who talked back
1948        // instead of choosing never reaches `Answered`, so this arm only
1949        // ever sees an actual decision.
1950        ask::QuestionStatus::Answered => match approval(q.resolution().as_deref()) {
1951            Approval::Merge => ApprovalGate::Approved,
1952            Approval::Repair if !state.reviews.is_empty() => {
1953                if !state.merge_repairs.iter().any(|r| r.question == q.id) {
1954                    state.merge_repairs.push(crate::run::MergeRepair {
1955                        question: q.id.clone(),
1956                        head: head.to_owned(),
1957                        pr: pr.url.clone(),
1958                        reviews: state.reviews.clone(),
1959                        gate: state.gate.clone(),
1960                        gate_head: state.gate_head.clone(),
1961                        gate_fixes: state.gate_fixes.clone(),
1962                        pre_gate: state.pre_gate.clone(),
1963                        phase: crate::run::MergeRepairPhase::Requested,
1964                        failure: None,
1965                    });
1966                    state.land_approval = None;
1967                    state.event(
1968                        "repair",
1969                        "owner requested fix findings and re-review; merge is not approved",
1970                    );
1971                    state.save()?;
1972                }
1973                ApprovalGate::Repair
1974            }
1975            Approval::Repair | Approval::Hold => ApprovalGate::Held,
1976        },
1977    })
1978}
1979
1980/// Fold a rollup's entries into one verdict plus the failing checks' labels.
1981/// No I/O. An empty rollup is `Unknown`, never green.
1982fn rollup_verdict(rollup: &[GhCheck]) -> (Checks, Vec<String>) {
1983    let mut failing = Vec::new();
1984    let mut pending = false;
1985    let mut unknown = false;
1986    for check in rollup {
1987        match check.verdict() {
1988            Verdict::Pass => {}
1989            Verdict::Pending => pending = true,
1990            Verdict::Fail => failing.push(check.label()),
1991            Verdict::Unknown => unknown = true,
1992        }
1993    }
1994    let checks = if rollup.is_empty() {
1995        Checks::Unknown
1996    } else if pending {
1997        Checks::Pending
1998    } else if !failing.is_empty() {
1999        Checks::Red
2000    } else if unknown {
2001        Checks::Unknown
2002    } else {
2003        Checks::Green
2004    };
2005    (checks, failing)
2006}
2007
2008/// Parse `gh pr view --json url,number,state,statusCheckRollup,reviews,comments`
2009/// output into a [`PrState`]. No I/O.
2010pub fn parse_pr(json: &str) -> Result<PrState> {
2011    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2012    let state = match raw.state.to_ascii_uppercase().as_str() {
2013        "OPEN" => PrLifecycle::Open,
2014        "MERGED" => PrLifecycle::Merged,
2015        "CLOSED" => PrLifecycle::Closed,
2016        other => bail!("unknown pull request state `{other}`"),
2017    };
2018
2019    let (checks, failing) = rollup_verdict(&raw.status_check_rollup);
2020
2021    let mut review_comments = Vec::new();
2022    for r in raw.reviews {
2023        push_if_outstanding(
2024            &mut review_comments,
2025            ReviewComment {
2026                author: r.author.login,
2027                path: None,
2028                line: None,
2029                body: r.body,
2030            },
2031        );
2032    }
2033    for c in raw.comments {
2034        push_if_outstanding(
2035            &mut review_comments,
2036            ReviewComment {
2037                author: c.author.login,
2038                path: None,
2039                line: None,
2040                body: c.body,
2041            },
2042        );
2043    }
2044
2045    Ok(PrState {
2046        url: raw.url,
2047        number: raw.number,
2048        state,
2049        checks,
2050        failing,
2051        review_comments,
2052        blocking: Blocking::of(&raw.merge_state_status),
2053    })
2054}
2055
2056/// One rollup entry as the release watcher reads it.
2057#[derive(Debug, Clone, PartialEq, Eq)]
2058pub(crate) struct CheckView {
2059    pub name: String,
2060    pub verdict: Verdict,
2061    /// Workflow run behind the check, when its url names one.
2062    pub run: Option<String>,
2063    pub url: Option<String>,
2064}
2065
2066/// A pull request's lifecycle, head commit and per-check verdicts, without
2067/// [`rollup_verdict`]'s aggregation (a pending check anywhere hides a failure
2068/// from it, which is exactly what the release watcher must not inherit).
2069#[derive(Debug, Clone, PartialEq, Eq)]
2070pub(crate) struct RollupView {
2071    pub url: String,
2072    pub number: u64,
2073    pub state: PrLifecycle,
2074    pub head: String,
2075    pub checks: Vec<CheckView>,
2076}
2077
2078/// Parse `gh pr view --json url,number,state,headRefOid,statusCheckRollup`
2079/// output. No I/O.
2080pub(crate) fn parse_rollup(json: &str) -> Result<RollupView> {
2081    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2082    let state = match raw.state.to_ascii_uppercase().as_str() {
2083        "OPEN" => PrLifecycle::Open,
2084        "MERGED" => PrLifecycle::Merged,
2085        "CLOSED" => PrLifecycle::Closed,
2086        other => bail!("unknown pull request state `{other}`"),
2087    };
2088    let checks = raw
2089        .status_check_rollup
2090        .iter()
2091        .map(|c| CheckView {
2092            name: c.label(),
2093            verdict: c.verdict(),
2094            run: c.url().and_then(run_of),
2095            url: c.url().map(str::to_owned),
2096        })
2097        .collect();
2098    Ok(RollupView {
2099        url: raw.url,
2100        number: raw.number,
2101        state,
2102        head: raw.head_ref_oid,
2103        checks,
2104    })
2105}
2106
2107/// Read just a pull request's lifecycle state - open, merged, or closed -
2108/// with none of the checks/reviews/comments [`land`] itself needs to decide
2109/// what to do next.
2110///
2111/// For a caller that only ever wants one fact and must not risk anything
2112/// else: `magi fold --merged` uses this to confirm a URL the operator hands
2113/// it is actually a merged pull request *before* touching a run's state, so a
2114/// typo or a still-open PR fails loudly instead of quietly recording a merge
2115/// that never happened.
2116pub async fn lifecycle(repo: &Path, pr_url: &str) -> Result<PrLifecycle> {
2117    let view = gh(
2118        repo,
2119        &[
2120            "pr".to_owned(),
2121            "view".to_owned(),
2122            pr_url.to_owned(),
2123            "--json".to_owned(),
2124            "state".to_owned(),
2125        ],
2126    )
2127    .await?;
2128    if !view.ok {
2129        bail!("gh pr view {pr_url}: {}", view.combined());
2130    }
2131    // `parse_pr` reads every other field of `GhPr` as its serde default
2132    // (empty string, empty vec, zero) when this narrower `--json` selection
2133    // does not carry them - harmless, since only `.state` is read back.
2134    Ok(parse_pr(&view.stdout)?.state)
2135}
2136
2137/// A pull request the operator merged outside of `land::land`'s own loop,
2138/// found by asking GitHub about the run's own winning branch rather than
2139/// requiring the operator to go and find the URL themselves.
2140#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2141pub struct ExternalMerge {
2142    /// The pull request's URL, ready to hand to [`correct_manual_merge`].
2143    pub url: String,
2144    /// The pull request's number.
2145    pub number: u64,
2146}
2147
2148#[derive(Debug, Deserialize)]
2149#[serde(rename_all = "camelCase")]
2150struct GhMergedPr {
2151    url: String,
2152    number: u64,
2153    merged_at: String,
2154    base_ref_name: String,
2155}
2156
2157/// Pure half of [`find_external_merge`]: given the raw `gh pr list --head
2158/// <branch> --state merged --json url,number,mergedAt,baseRefName` output,
2159/// decide whether exactly one of the pull requests it lists could actually
2160/// be *this* run's.
2161///
2162/// A branch name alone does not prove it: [`RunState::branch_for`] derives it
2163/// from the run's own short id, so a collision with some other, unrelated
2164/// task's merged pull request from a same-named branch is rare but not
2165/// impossible once branches are deleted and ids run out. Filtering on
2166/// `base_ref_name` (the branch this run actually targets) and `merged_at`
2167/// (which cannot predate the run itself) rules that case out. More than one
2168/// survivor is exactly as uninformative as zero — something this run cannot
2169/// tell apart from another — so only a unique survivor is returned.
2170fn pick_merged_pr(
2171    json: &str,
2172    base_branch: &str,
2173    created_at: Timestamp,
2174) -> Result<Option<ExternalMerge>> {
2175    pick_merged_pr_with(json, base_branch, created_at, false)
2176}
2177
2178fn pick_merged_pr_with(
2179    json: &str,
2180    base_branch: &str,
2181    created_at: Timestamp,
2182    reject_ambiguous: bool,
2183) -> Result<Option<ExternalMerge>> {
2184    let raw: Vec<GhMergedPr> =
2185        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2186    let mut matches: Vec<ExternalMerge> = Vec::new();
2187    for pr in raw {
2188        if pr.base_ref_name != base_branch {
2189            continue;
2190        }
2191        let Ok(merged_at) = pr.merged_at.parse::<Timestamp>() else {
2192            continue;
2193        };
2194        if merged_at < created_at {
2195            continue;
2196        }
2197        matches.push(ExternalMerge {
2198            url: pr.url,
2199            number: pr.number,
2200        });
2201    }
2202    anyhow::ensure!(
2203        !reject_ambiguous || matches.len() <= 1,
2204        "multiple merged pull requests match this run; merge evidence is ambiguous"
2205    );
2206    if matches.len() == 1 {
2207        Ok(matches.pop())
2208    } else {
2209        Ok(None)
2210    }
2211}
2212
2213/// What `gh pr list --head <branch> --base <base> --state open` found.
2214#[derive(Debug, Clone, PartialEq, Eq)]
2215pub enum OpenPr {
2216    /// Nothing open: the caller creates one.
2217    None,
2218    /// Exactly one: the caller adopts it instead of creating a second.
2219    One {
2220        /// The pull request's URL.
2221        url: String,
2222        /// Its current title.
2223        title: String,
2224    },
2225    /// More than one: magi does not pick between them.
2226    Many(Vec<String>),
2227}
2228
2229#[derive(Debug, Deserialize)]
2230#[serde(rename_all = "camelCase")]
2231struct GhOpenPr {
2232    // `url` and `baseRefName` are required: a record missing either must be a
2233    // parse error, not a pull request that silently fails the base filter and
2234    // reads as "none open" (which would go on to create a duplicate).
2235    url: String,
2236    #[serde(default)]
2237    title: String,
2238    base_ref_name: String,
2239    // A fork's branch of the same name is not the task head; `gh pr list --head`
2240    // matches by branch name alone, so the filter has to be ours.
2241    #[serde(default)]
2242    is_cross_repository: bool,
2243}
2244
2245/// Pure half of [`find_open_pr`]: classify the raw `--json
2246/// number,url,title,baseRefName` output. Entries whose base is not `base` are
2247/// dropped even though the query already filtered on it, so a stub or an old
2248/// `gh` that ignores `--base` cannot get a pull request into the wrong branch
2249/// adopted.
2250pub fn pick_open_pr(json: &str, base: &str) -> Result<OpenPr> {
2251    let raw: Vec<GhOpenPr> =
2252        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2253    let mut hits: Vec<GhOpenPr> = raw
2254        .into_iter()
2255        .filter(|p| p.base_ref_name == base && !p.is_cross_repository)
2256        .collect();
2257    Ok(match hits.len() {
2258        0 => OpenPr::None,
2259        1 => {
2260            let p = hits.remove(0);
2261            OpenPr::One {
2262                url: p.url,
2263                title: p.title,
2264            }
2265        }
2266        _ => OpenPr::Many(hits.into_iter().map(|p| p.url).collect()),
2267    })
2268}
2269
2270/// Open pull requests whose head is `branch` and whose base is `base`. A
2271/// failing `gh` is an error carrying its own output, never "none": guessing
2272/// there is how a duplicate gets created.
2273pub async fn find_open_pr(repo: &Path, branch: &str, base: &str) -> Result<OpenPr> {
2274    find_open_pr_with(Path::new("gh"), repo, branch, base).await
2275}
2276
2277pub(crate) async fn find_open_pr_with(
2278    program: &Path,
2279    repo: &Path,
2280    branch: &str,
2281    base: &str,
2282) -> Result<OpenPr> {
2283    let out = gh_with(
2284        program,
2285        repo,
2286        &[
2287            "pr".to_owned(),
2288            "list".to_owned(),
2289            "--head".to_owned(),
2290            branch.to_owned(),
2291            "--base".to_owned(),
2292            base.to_owned(),
2293            "--state".to_owned(),
2294            "open".to_owned(),
2295            "--json".to_owned(),
2296            "number,url,title,baseRefName,isCrossRepository".to_owned(),
2297        ],
2298    )
2299    .await?;
2300    if !out.ok {
2301        bail!("gh pr list failed: {}", out.combined());
2302    }
2303    pick_open_pr(&out.stdout, base)
2304}
2305
2306#[derive(Debug, Deserialize)]
2307#[serde(rename_all = "camelCase")]
2308struct GhPrHead {
2309    head_ref_name: String,
2310    base_ref_name: String,
2311    state: String,
2312    // Required, like `GhOpenPr`'s fields: a record that cannot say whether the
2313    // head lives in a fork must be a parse error, never "same repository".
2314    is_cross_repository: bool,
2315    // Required too: it is what ties the pull request to the commits that were
2316    // actually proven to be on the base.
2317    head_ref_oid: String,
2318}
2319
2320/// Why [`closable`] said no, and whether asking again later could say yes.
2321#[derive(Debug, Clone, PartialEq, Eq)]
2322pub struct Refusal {
2323    /// A later attempt may succeed (the head moved, the view was unreadable);
2324    /// `false` means this pull request is simply not the run's to close.
2325    pub retry: bool,
2326    /// What was wrong.
2327    pub why: String,
2328}
2329
2330impl Refusal {
2331    fn final_(why: String) -> Self {
2332        Self { retry: false, why }
2333    }
2334}
2335
2336/// Pure half of [`close_superseded_pr`]: read `gh pr view --json
2337/// headRefName,baseRefName,state,isCrossRepository` and say whether closing
2338/// is safe, `Err` carrying the reason when it is not.
2339///
2340/// Closing is outward-facing, so every property is checked on what the forge
2341/// says now, not on what magi recorded: the head must be exactly `branch` in
2342/// this repository (a fork's branch of the same name is somebody else's), the
2343/// base must be `base`, and the pull request must still be open.
2344pub fn closable(
2345    json: &str,
2346    branch: &str,
2347    base: &str,
2348    verified: &[String],
2349) -> std::result::Result<(), Refusal> {
2350    let pr: GhPrHead = serde_json::from_str(json).map_err(|e| Refusal {
2351        retry: true,
2352        why: format!("could not read the pull request ({e})"),
2353    })?;
2354    if pr.head_ref_name != branch {
2355        return Err(Refusal::final_(format!(
2356            "its head is `{}`, not this run's `{branch}`",
2357            pr.head_ref_name
2358        )));
2359    }
2360    if pr.is_cross_repository {
2361        return Err(Refusal::final_("its head lives in a fork".to_owned()));
2362    }
2363    if pr.base_ref_name != base {
2364        return Err(Refusal::final_(format!(
2365            "it targets `{}`, not `{base}`",
2366            pr.base_ref_name
2367        )));
2368    }
2369    if !pr.state.eq_ignore_ascii_case("open") {
2370        return Err(Refusal::final_(format!(
2371            "it is already {}",
2372            pr.state.to_ascii_lowercase()
2373        )));
2374    }
2375    // Last, so a pull request that is not this run's at all is reported as
2376    // such. A head that is this branch but not a commit checked against the
2377    // base (somebody pushed since) may well get checked next time: retry.
2378    if !verified.contains(&pr.head_ref_oid) {
2379        return Err(Refusal {
2380            retry: true,
2381            why: format!(
2382                "its head {} is not a commit this run checked against the base",
2383                crate::already::short_sha(&pr.head_ref_oid)
2384            ),
2385        });
2386    }
2387    Ok(())
2388}
2389
2390/// Does `remote` point at something a forge could host - a URL or an scp-style
2391/// `user@host:path` - rather than a filesystem path or nothing at all? Judged
2392/// from the URL alone, so it answers the same on every machine, whatever `gh`
2393/// happens to be installed or logged in to.
2394async fn remote_is_forge(repo: &Path, remote: &str) -> bool {
2395    let Ok(url) = git::git(repo, &["remote", "get-url", remote]).await else {
2396        return false;
2397    };
2398    is_forge_url(url.trim())
2399}
2400
2401fn is_forge_url(url: &str) -> bool {
2402    url.contains("://") && !url.starts_with("file://")
2403        || url
2404            .split_once(':')
2405            .is_some_and(|(host, _)| host.contains('@') && !host.contains(['/', '\\']))
2406}
2407
2408/// Does this `gh` failure mean there is no GitHub to ask, as opposed to a
2409/// request that failed?
2410fn forge_unavailable(message: &str) -> bool {
2411    message.contains("known GitHub host") || message.contains("spawn gh")
2412}
2413
2414/// The comment left on a pull request closed because its change is already on
2415/// the base.
2416pub fn superseded_comment(base: &str, evidence: &crate::already::Evidence) -> String {
2417    let how = match evidence.proof {
2418        crate::already::Proof::PatchId => format!(
2419            "carried by commit {} on `{base}` with the same patch",
2420            evidence.names()
2421        ),
2422        crate::already::Proof::Ancestry => {
2423            format!("already in the history of `{base}` as {}", evidence.names())
2424        }
2425        crate::already::Proof::Tree => format!(
2426            "already part of `{base}` (merging this branch changes nothing at {})",
2427            crate::already::short_sha(&evidence.tip)
2428        ),
2429    };
2430    format!(
2431        "Closing: everything this branch adds is {how}, so there is nothing left to \
2432         land. This pull request was closed automatically after that was verified; \
2433         reopen it if you disagree."
2434    )
2435}
2436
2437/// Close the open pull request for `branch`, if there is one and it is
2438/// provably this run's, with a comment naming what supersedes it. `Ok(Ok(url))` is
2439/// the URL closed; `Ok(Err(why))` is a final "nothing to close" (no pull request,
2440/// not this run's, no forge); `Err` is anything a later attempt could resolve (a
2441/// failed `gh` call, a head that moved since it was checked), which the caller
2442/// must not treat as settled.
2443///
2444/// The recorded `state.pr` is preferred, else the forge is asked for an open
2445/// pull request on `branch`; either way the candidate is re-read and passed
2446/// through [`closable`] before anything is written; `verified` lists the
2447/// commits proven to be on the base, and the pull request's head must be one.
2448pub async fn close_superseded_pr(
2449    state: &mut RunState,
2450    branch: &str,
2451    evidence: &crate::already::Evidence,
2452    verified: &[String],
2453) -> Result<std::result::Result<String, String>> {
2454    let repo = state.repo.clone();
2455    let base = state.base_branch.clone();
2456    let url = match state.pr.as_ref().filter(|p| p.state == "open") {
2457        Some(p) => p.url.clone(),
2458        // No recorded pull request. A forge that cannot be asked at all (no
2459        // GitHub remote, no `gh`) says nothing about this run, so that is
2460        // "none found"; any other lookup failure is an error, because "could
2461        // not look" is not "nothing there" and the caller must retry.
2462        None if !remote_is_forge(&repo, &state.config.merge.remote).await => {
2463            return Ok(Err(
2464                "the remote is not a forge, so there is no pull request".to_owned(),
2465            ));
2466        }
2467        None => match find_open_pr(&repo, branch, &base).await {
2468            Err(e) if forge_unavailable(&format!("{e:#}")) => {
2469                return Ok(Err(format!("no forge to ask: {e:#}")));
2470            }
2471            Err(e) => return Err(e),
2472            Ok(OpenPr::One { url, .. }) => url,
2473            Ok(OpenPr::None) => return Ok(Err("no open pull request".to_owned())),
2474            Ok(OpenPr::Many(urls)) => {
2475                return Ok(Err(format!(
2476                    "{} open pull requests name it; not choosing between them",
2477                    urls.len()
2478                )));
2479            }
2480        },
2481    };
2482    let view = gh(
2483        &repo,
2484        &[
2485            "pr".to_owned(),
2486            "view".to_owned(),
2487            url.clone(),
2488            "--json".to_owned(),
2489            "headRefName,headRefOid,baseRefName,state,isCrossRepository".to_owned(),
2490        ],
2491    )
2492    .await?;
2493    if !view.ok {
2494        bail!("gh pr view {url} failed: {}", view.combined());
2495    }
2496    if let Err(refusal) = closable(&view.stdout, branch, &base, verified) {
2497        // A pull request whose head cannot be tied to what was proven is not
2498        // one to walk away from: the caller keeps the run resumable.
2499        if refusal.retry {
2500            bail!("left {url} open: {}", refusal.why);
2501        }
2502        return Ok(Err(format!("left {url} open: {}", refusal.why)));
2503    }
2504    let out = gh(
2505        &repo,
2506        &[
2507            "pr".to_owned(),
2508            "close".to_owned(),
2509            url.clone(),
2510            "--comment".to_owned(),
2511            superseded_comment(&base, evidence),
2512        ],
2513    )
2514    .await?;
2515    if !out.ok {
2516        bail!("gh pr close {url} failed: {}", out.combined());
2517    }
2518    if let Some(p) = state.pr.as_mut().filter(|p| p.url == url) {
2519        p.state = "closed".to_owned();
2520    }
2521    Ok(Ok(url))
2522}
2523
2524/// `gh pr edit <url> --title <title>`, for an adopted pull request whose title
2525/// differs from the one this run computed. Only the title: the body may have
2526/// been edited by the owner and cannot be compared.
2527pub async fn set_pr_title(state: &mut RunState, repo: &Path, url: &str, title: &str) -> Result<()> {
2528    let (title, _) = crate::github_text::prepare(state, title, "");
2529    edit_pr_title(repo, url, &title).await
2530}
2531
2532/// [`set_pr_title`] for a title the owner explicitly chose to post unmodified
2533/// (`github_text::POST_ORIGINAL` or `github_text::USE_REWRITE`): the posting
2534/// gate is skipped on purpose.
2535pub async fn set_pr_title_verbatim(repo: &Path, url: &str, title: &str) -> Result<()> {
2536    edit_pr_title(repo, url, title).await
2537}
2538
2539/// Post both fields of the owner's chosen rewrite to an adopted pull request,
2540/// unmodified and without the posting gate.
2541pub async fn set_pr_text_verbatim(repo: &Path, url: &str, title: &str, body: &str) -> Result<()> {
2542    let out = gh(
2543        repo,
2544        &[
2545            "pr".to_owned(),
2546            "edit".to_owned(),
2547            url.to_owned(),
2548            "--title".to_owned(),
2549            title.to_owned(),
2550            "--body".to_owned(),
2551            body.to_owned(),
2552        ],
2553    )
2554    .await
2555    .map_err(|_| anyhow::anyhow!("could not run gh pr edit for the chosen rewrite"))?;
2556    if !out.ok {
2557        // Command output may echo the chosen text; keep it out of run events.
2558        bail!("gh pr edit failed while posting the chosen rewrite");
2559    }
2560    Ok(())
2561}
2562
2563async fn edit_pr_title(repo: &Path, url: &str, title: &str) -> Result<()> {
2564    let out = gh(
2565        repo,
2566        &[
2567            "pr".to_owned(),
2568            "edit".to_owned(),
2569            url.to_owned(),
2570            "--title".to_owned(),
2571            title.to_owned(),
2572        ],
2573    )
2574    .await?;
2575    if !out.ok {
2576        bail!("gh pr edit failed: {}", out.combined());
2577    }
2578    Ok(())
2579}
2580
2581/// Ask GitHub whether this run's winning candidate branch was actually merged
2582/// somewhere `land::land`'s own loop never saw — the gap `magi fold
2583/// --merged` exists to close, minus the operator having to find the URL by
2584/// hand.
2585///
2586/// `Ok(None)` covers every case where nothing can be said with confidence: no
2587/// winner decided yet (nothing to check a branch for), no merged pull request
2588/// found, or [`pick_merged_pr`] found more than one candidate and would not
2589/// guess between them. Never wired to a weaker, URL-less signal like
2590/// [`branch_is_ancestor`] — a caller wanting that has to ask for it
2591/// separately, precisely because it cannot drive an automatic correction on
2592/// its own (see that function's own doc).
2593pub async fn find_external_merge(state: &RunState) -> Result<Option<ExternalMerge>> {
2594    let Some(winner) = state.winner() else {
2595        return Ok(None);
2596    };
2597    find_external_merge_with(
2598        state,
2599        state.pr_head.as_deref().unwrap_or(&winner.branch),
2600        false,
2601    )
2602    .await
2603}
2604
2605/// Reopening needs proof of absence, not merely failure to identify one PR.
2606pub(crate) async fn find_external_merge_for_reopen(
2607    state: &RunState,
2608) -> Result<Option<ExternalMerge>> {
2609    let Some(branch) = state.pr_branch() else {
2610        anyhow::ensure!(
2611            state.pr.is_none() && state.pr_pushed_head.is_none(),
2612            "run has public PR evidence but no known branch to check"
2613        );
2614        return Ok(None);
2615    };
2616    find_external_merge_with(state, branch, true).await
2617}
2618
2619async fn find_external_merge_with(
2620    state: &RunState,
2621    branch: &str,
2622    reject_ambiguous: bool,
2623) -> Result<Option<ExternalMerge>> {
2624    let out = gh(
2625        &state.repo,
2626        &[
2627            "pr".to_owned(),
2628            "list".to_owned(),
2629            "--head".to_owned(),
2630            branch.to_owned(),
2631            "--state".to_owned(),
2632            "merged".to_owned(),
2633            "--json".to_owned(),
2634            "url,number,mergedAt,baseRefName".to_owned(),
2635        ],
2636    )
2637    .await?;
2638    if !out.ok {
2639        bail!("gh pr list --head {branch}: {}", out.combined());
2640    }
2641    if reject_ambiguous {
2642        pick_merged_pr_with(&out.stdout, &state.base_branch, state.created_at, true)
2643    } else {
2644        pick_merged_pr(&out.stdout, &state.base_branch, state.created_at)
2645    }
2646}
2647
2648/// Whether `branch` is, right now, an ancestor of `base_branch` in the local
2649/// git graph — the weaker, URL-less signal that a branch landed somewhere.
2650///
2651/// Deliberately never consulted by [`find_external_merge`]: a base branch
2652/// that has moved since the run started can make an old, abandoned branch
2653/// look like an ancestor of the *current* base for reasons that have nothing
2654/// to do with a merge (a later commit that happens to supersede it, an
2655/// unrelated squash), and there is no pull request URL here to confirm
2656/// against or to land through anyway. Its only honest use is a weaker
2657/// notice — "this looks merged, go check" — never an automatic rewrite of
2658/// `status`/`merge`.
2659pub async fn branch_is_ancestor(repo: &Path, branch: &str, base_branch: &str) -> Result<bool> {
2660    let out = tokio::process::Command::new("git")
2661        .args(["merge-base", "--is-ancestor", branch, base_branch])
2662        .current_dir(repo)
2663        .quiet()
2664        .stdin(std::process::Stdio::null())
2665        .output()
2666        .await
2667        .context("spawn git merge-base --is-ancestor")?;
2668    Ok(out.status.success())
2669}
2670
2671/// Parse `host/owner/repo` out of a forge URL, with no network access.
2672///
2673/// The host is part of the slug, not discarded: `owner/repo` alone would
2674/// treat `github.example.com/o/r` and `github.com/o/r` as the same
2675/// repository, which is exactly the mix-up the same-repo guard exists to
2676/// catch. Returns `None` for anything that doesn't have a `<host>/<path>`
2677/// shape at all.
2678fn forge_slug(url: &str) -> Option<(String, &str)> {
2679    let rest = url.rsplit("://").next()?;
2680    let (host, path) = rest.split_once('/')?;
2681    if host.is_empty() {
2682        return None;
2683    }
2684    Some((host.to_ascii_lowercase(), path))
2685}
2686
2687/// Parse `host/owner/repo` out of a GitHub pull request URL, with no network
2688/// access - the first half of the same-repo guard [`correct_manual_merge`]
2689/// applies before it writes anything.
2690///
2691/// Returns `None` for anything that does not look like
2692/// `https://<host>/<owner>/<repo>/pull/<n>`, which the caller treats as
2693/// fail-closed: a URL this cannot make sense of refuses rather than guesses.
2694pub(crate) fn slug_of_pr_url(url: &str) -> Option<String> {
2695    let (host, path) = forge_slug(url)?;
2696    let mut segments = path.split('/');
2697    let owner = segments.next()?;
2698    let repo = segments.next()?;
2699    let kind = segments.next()?;
2700    if owner.is_empty() || repo.is_empty() || kind != "pull" {
2701        return None;
2702    }
2703    Some(format!("{host}/{owner}/{repo}"))
2704}
2705
2706/// Parse `host/owner/repo` out of a plain repository URL (no `/pull/<n>`
2707/// suffix), the shape `gh repo view --json url` returns - the other half of
2708/// the same-repo guard, matched against [`slug_of_pr_url`]'s output.
2709fn slug_of_repo_url(url: &str) -> Option<String> {
2710    let (host, path) = forge_slug(url)?;
2711    let mut segments = path.split('/');
2712    let owner = segments.next()?;
2713    let repo = segments.next()?;
2714    if owner.is_empty() || repo.is_empty() {
2715        return None;
2716    }
2717    Some(format!("{host}/{owner}/{repo}"))
2718}
2719
2720/// Refuse to correct a run against a pull request from a different
2721/// repository than the one it is recorded against.
2722///
2723/// This is the guard the shun/8c75 incident argued for: an operator ran
2724/// `magi fold --merged <shun PR url>` meaning to correct an old `Blocked` run
2725/// in a different repository, omitted the run id, and the id defaulted to
2726/// this machine's most recently created run - an unrelated, still-in-progress
2727/// run in a completely different repository - which then had its `status`
2728/// rewritten to `merged` from a pull request it had nothing to do with.
2729/// `correct_manual_merge` now requires an explicit id (see `magi fold`'s own
2730/// CLI help), but a mistyped or stale id could still name a run in a
2731/// different repository than the one the URL belongs to, so this checks that
2732/// independently rather than trusting the id alone.
2733///
2734/// Comparison is case-insensitive - GitHub owner/repo names are - and a
2735/// mismatch names both slugs rather than just refusing, so an operator whose
2736/// local checkout's `origin` is a fork of the repository the pull request was
2737/// opened against (a legitimate setup this cannot tell apart from a genuine
2738/// mix-up) can judge for themselves rather than being blocked with no way to
2739/// see why.
2740pub(crate) fn ensure_same_repo(run_repo_slug: &str, pr_repo_slug: &str) -> Result<()> {
2741    if run_repo_slug.eq_ignore_ascii_case(pr_repo_slug) {
2742        return Ok(());
2743    }
2744    bail!(
2745        "refusing to correct this run: it is recorded against {run_repo_slug}, but the pull \
2746         request URL belongs to {pr_repo_slug} - pass the run id whose repository the URL \
2747         actually belongs to (or, if `origin` is a fork opened against a different upstream, \
2748         verify by hand before treating this as a false positive)"
2749    );
2750}
2751
2752/// Ask the forge which `host/owner/repo` a local checkout's `origin` remote
2753/// actually resolves to, for the same-repo guard in [`correct_manual_merge`].
2754///
2755/// Asking `gh` rather than parsing `git remote -v` locally is deliberate: it
2756/// normalizes case, SSH vs. HTTPS remotes, and a renamed or transferred
2757/// repository the same way GitHub itself would recognize it, so the
2758/// comparison in [`ensure_same_repo`] is against the same canonical slug on
2759/// both sides. Reads `url` rather than `nameWithOwner` so the host is part of
2760/// the answer too - `nameWithOwner` alone cannot tell a `github.com` repo from
2761/// a same-named one on a GitHub Enterprise host.
2762async fn repo_slug(repo: &Path) -> Result<String> {
2763    let out = gh(
2764        repo,
2765        &[
2766            "repo".to_owned(),
2767            "view".to_owned(),
2768            "--json".to_owned(),
2769            "url".to_owned(),
2770        ],
2771    )
2772    .await?;
2773    if !out.ok {
2774        bail!("gh repo view --json url: {}", out.combined());
2775    }
2776    #[derive(Debug, Deserialize)]
2777    struct GhRepo {
2778        url: String,
2779    }
2780    let parsed: GhRepo = serde_json::from_str(&out.stdout)
2781        .with_context(|| format!("parse `gh repo view` output: {}", out.stdout.trim()))?;
2782    slug_of_repo_url(&parsed.url)
2783        .with_context(|| format!("could not parse a host/owner/repo out of {}", parsed.url))
2784}
2785
2786/// Confirm `url` is actually a merged pull request, then rewrite `state`'s
2787/// `status` and `merge` exactly as the automatic land loop (`land::land`)
2788/// would have written them had magi opened and merged this pull request
2789/// itself.
2790///
2791/// This is `magi fold --merged`'s whole implementation, and also what the
2792/// web `fold-merged` route calls once it has a URL in hand — an operator
2793/// recovery path for a merge magi could not finish on its own: a PR title too
2794/// long for the GraphQL mutation, `gh pr create` unreachable, a stale token -
2795/// closed by hand with a pull request magi never opened and so never
2796/// recorded. Reusing `land::land` rather than writing `status`/`merge`
2797/// directly keeps this one authoritative: a merged pull request decides
2798/// `Step::Done { merged: true }` on the very first read, before any of
2799/// `land`'s own checks/fix/rebase machinery can run, which is what makes it
2800/// safe to call here even though this pull request was never magi's own.
2801///
2802/// [`ensure_same_repo`] is checked before anything else: a pull request from
2803/// a different repository than the one `state` is recorded against is
2804/// refused outright, regardless of its lifecycle. This is the guard for a
2805/// URL an *operator* hands in - the CLI or the web route - where a stale or
2806/// mistyped run id could otherwise get corrected from an unrelated
2807/// repository's pull request (see the shun/8c75 incident in `magi fold`'s own
2808/// CLI help). The automatic janitor sweep (`clean::reconcile_external_merges`)
2809/// goes through [`correct_confirmed_external_merge`] instead, which skips
2810/// this check: its `url` was never operator-supplied, it comes from
2811/// [`find_external_merge`] querying `gh` from inside `state.repo` itself, so
2812/// it is already guaranteed to name a pull request in that same repository -
2813/// re-deriving and re-checking the repository here would only be a second
2814/// `gh repo view` call that can fail for reasons that have nothing to do with
2815/// correctness (a rate limit, a network blip), turning a self-heal that would
2816/// otherwise have succeeded into a run left `Blocked` for another pass.
2817///
2818/// [`lifecycle`] is checked next and separately so a mistyped or still-open
2819/// URL fails loudly without writing anything, rather than handing an open
2820/// pull request to the full autonomous loop by accident.
2821///
2822/// Correcting `status` this way does not run `bump::after_merge`
2823/// (`src/bump.rs`): that call is made only from `graph::Runner::run_land`,
2824/// which this path never goes through. A release version bump the change
2825/// might have earned is therefore not filed automatically and has to be
2826/// requested by hand - recorded as an event on the run so the gap is visible
2827/// to whoever reads it later, not just wherever this was called from. Follow-up
2828/// tasks for findings the merge left open (`crate::followup`) *are* filed here.
2829///
2830/// Returns the status before and after, so every caller (CLI, janitor, web
2831/// route) can build its own log line or response from the same pair rather
2832/// than each re-deriving it.
2833pub async fn correct_manual_merge(
2834    state: &mut RunState,
2835    url: &str,
2836) -> Result<(RunStatus, RunStatus)> {
2837    let Some(pr_slug) = slug_of_pr_url(url) else {
2838        bail!(
2839            "could not parse an owner/repo out of {url}; refusing to guess which repository \
2840             this pull request belongs to"
2841        );
2842    };
2843    let run_slug = repo_slug(&state.repo).await?;
2844    ensure_same_repo(&run_slug, &pr_slug)?;
2845    correct_merge(state, url).await
2846}
2847
2848/// The janitor's own entry point into the same correction
2849/// [`correct_manual_merge`] performs for an operator-supplied URL, minus the
2850/// same-repo guard - see that function's own doc for why skipping it here is
2851/// safe rather than a hole: [`clean::reconcile_external_merges`] only ever
2852/// calls this with a `url` [`find_external_merge`] already found by querying
2853/// `state.repo`'s own remote, so the guard could never do anything here but
2854/// fail on its own transient errors.
2855///
2856/// [`crate::clean`] is the only caller; `pub(crate)` rather than private only
2857/// because it lives in a different module.
2858pub(crate) async fn correct_confirmed_external_merge(
2859    state: &mut RunState,
2860    url: &str,
2861) -> Result<(RunStatus, RunStatus)> {
2862    correct_merge(state, url).await
2863}
2864
2865/// Same pull request, same repository: the url, or the number within one repo.
2866fn names_same_pr(a: &RunState, url: &str, number: u64, repo: &Path) -> bool {
2867    let Some(pr) = a.pr.as_ref() else {
2868        return false;
2869    };
2870    if !url.is_empty()
2871        && pr
2872            .url
2873            .trim_end_matches('/')
2874            .eq_ignore_ascii_case(url.trim_end_matches('/'))
2875    {
2876        return true;
2877    }
2878    number > 0
2879        && pr.number == number
2880        && match (a.repo.canonicalize(), repo.canonicalize()) {
2881            (Ok(x), Ok(y)) => x == y,
2882            _ => a.repo == repo,
2883        }
2884}
2885
2886/// Rewrite `pr.state` to a final state on every run record under `home` that
2887/// `decide` picks, and report how many were rewritten.
2888///
2889/// Lifecycle writes through to other runs are deliberately narrow (task-head
2890/// ownership is recorded separately): only a **terminal** run (never one a
2891/// driver may still be writing), only a proven-stopped driver with no daemon
2892/// claim (the shared liveness judge), only a record
2893/// whose `pr.state` is still `open`, and only `merged` / `closed` ever goes in.
2894/// The record is read as folding reads it (no schema check: every bump so far
2895/// only added fields, and the whole struct round-trips) and written through
2896/// [`RunState::save_under`], the path every record uses, so nothing but
2897/// `pr.state` and an event line changes (and `updated_at`, as for any save).
2898/// A run that cannot be read or written is skipped with a warning.
2899fn rewrite_open_prs(
2900    home: &Path,
2901    decide: &mut dyn FnMut(&RunState) -> Option<PrLifecycle>,
2902) -> usize {
2903    let now = Timestamp::now();
2904    let mut changed = 0;
2905    for id in crate::run::list_ids_in(&home.join("runs")) {
2906        let path = home.join("runs").join(&id).join("run.json");
2907        let read = || {
2908            let body = std::fs::read_to_string(&path).ok()?;
2909            serde_json::from_str::<RunState>(&body).ok()
2910        };
2911        // Do not contend with recovery of unrelated runs. This first read is
2912        // only a filter; every write still uses the record read under its lock.
2913        let Some(snapshot) = read() else {
2914            continue;
2915        };
2916        if !snapshot.status.done()
2917            || snapshot.pr.as_ref().is_none_or(|p| p.state != "open")
2918            || !matches!(
2919                decide(&snapshot),
2920                Some(PrLifecycle::Merged | PrLifecycle::Closed)
2921            )
2922        {
2923            continue;
2924        }
2925        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2926            continue;
2927        };
2928        let Some(mut state) = read() else {
2929            continue;
2930        };
2931        if !state.status.done()
2932            || state.pr.as_ref().is_none_or(|p| p.state != "open")
2933            || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2934                != crate::run::Liveness::Dead
2935        {
2936            continue;
2937        }
2938        let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2939            continue;
2940        };
2941        if let Some(pr) = state.pr.as_mut() {
2942            pr.state = to.as_str().to_owned();
2943        }
2944        let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2945        state.event(
2946            "land",
2947            format!("recorded {url} as {}: another run settled it", to.as_str()),
2948        );
2949        match state.save_under(home) {
2950            Ok(()) => changed += 1,
2951            Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2952        }
2953    }
2954    changed
2955}
2956
2957/// A run reached a final state for its pull request: tell every other terminal
2958/// run in the same repository that names the same pull request (handed-over
2959/// predecessors, blocked attempts, anything), so their records stop saying
2960/// `open`. Best effort; `run`'s own record is the caller's.
2961pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2962    if to == PrLifecycle::Open {
2963        return;
2964    }
2965    let Some(home) = crate::run::try_home() else {
2966        return;
2967    };
2968    write_pr_state_through_in(&home, run, to);
2969}
2970
2971pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2972    let Some(pr) = run.pr.as_ref() else {
2973        return 0;
2974    };
2975    let (url, number) = (pr.url.clone(), pr.number);
2976    rewrite_open_prs(home, &mut |other| {
2977        (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2978    })
2979}
2980
2981/// Terminal runs whose record still says their pull request is open, as
2982/// `(run id, repo, url)`, for [`repair_stale_pr_states`].
2983pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
2984    let now = Timestamp::now();
2985    let mut out = Vec::new();
2986    for id in crate::run::list_ids_in(&home.join("runs")) {
2987        let path = home.join("runs").join(&id).join("run.json");
2988        let Ok(body) = std::fs::read_to_string(&path) else {
2989            continue;
2990        };
2991        let Ok(state) = serde_json::from_str::<RunState>(&body) else {
2992            continue;
2993        };
2994        if let Some(pr) = state.pr.as_ref()
2995            && state.status.done()
2996            && pr.state == "open"
2997            && !pr.url.is_empty()
2998            && !crate::daemon::is_working_on(home, &id, now)
2999        {
3000            out.push((id, state.repo.clone(), pr.url.clone()));
3001        }
3002    }
3003    out
3004}
3005
3006/// Apply forge answers (`pr url -> state`) to every stale terminal record.
3007/// A url with no answer (the forge was unreadable) changes nothing.
3008pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
3009    rewrite_open_prs(home, &mut |s| {
3010        s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
3011    })
3012}
3013
3014/// One-time (and idempotent) repair of records that froze an `open` pull
3015/// request: ask the forge about each distinct pull request that a terminal run
3016/// still calls open - at most `max_lookups` of them - and rewrite the merged
3017/// and closed ones. A genuinely open pull request is left alone, and a lookup
3018/// that fails is "unknown, change nothing". Returns `(records rewritten,
3019/// lookups that failed)`.
3020pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
3021    let mut known = BTreeMap::new();
3022    let mut failed = 0;
3023    let mut seen = BTreeSet::new();
3024    for (_, repo, url) in stale_open_prs(home) {
3025        if known.len() + failed >= max_lookups || !seen.insert(url.clone()) {
3026            continue;
3027        }
3028        match lifecycle(&repo, &url).await {
3029            Ok(state) => {
3030                known.insert(url, state);
3031            }
3032            Err(e) => {
3033                tracing::warn!("repair pr state of {url}: {e:#}");
3034                failed += 1;
3035            }
3036        }
3037    }
3038    (apply_pr_states(home, &known), failed)
3039}
3040
3041async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
3042    match lifecycle(&state.repo, url).await? {
3043        PrLifecycle::Merged => {}
3044        other => bail!(
3045            "{url} is {}, not merged; refusing to record {} as merged on a guess",
3046            other.as_str(),
3047            state.id
3048        ),
3049    }
3050    let before = state.status;
3051    if let Err(e) = land(state, url).await {
3052        // `land` sets `status` to `Landing` and saves before its first read
3053        // of the pull request — see its own doc — so a failure here (a
3054        // transient `gh` hiccup between the two forge reads this function
3055        // makes) can leave the run stuck on that in-between value with
3056        // nothing left driving it. Land it on the same terminal shape an
3057        // automated `land` failure lands on instead of leaving it stuck.
3058        state.status = RunStatus::Blocked;
3059        state.event("fold", format!("manual-merge correction failed: {e:#}"));
3060        state.save()?;
3061        return Err(e).context(format!("confirming the merge of {url}"));
3062    }
3063    state.event(
3064        "fold",
3065        "operator recorded this pull request as a manual merge; this run never \
3066         re-entered `land`, so `bump::after_merge` did not run for it - a release \
3067         bump this change might warrant has to be filed by hand",
3068    );
3069    // Unlike the bump, the findings the merge left open are filed on this
3070    // path too: nothing else would ever carry them forward.
3071    if state.status == RunStatus::Merged {
3072        crate::followup::after_merge(state, url).await;
3073    }
3074    state.save()?;
3075    Ok((before, state.status))
3076}
3077
3078/// Parse `gh api repos/{owner}/{repo}/pulls/<n>/comments` into inline review
3079/// comments. No I/O.
3080///
3081/// `gh pr view` does not surface inline comments, and inline is exactly where
3082/// both review bots put their findings - a landing loop that read only the
3083/// top-level thread would never see the thing it is supposed to fix.
3084pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3085    let raw: Vec<GhInline> =
3086        serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3087    let mut out = Vec::new();
3088    for c in raw {
3089        push_if_outstanding(
3090            &mut out,
3091            ReviewComment {
3092                author: c.user.login,
3093                path: c.path,
3094                line: c.line,
3095                body: c.body,
3096            },
3097        );
3098    }
3099    Ok(out)
3100}
3101
3102/// Keep a comment only when it asks for something.
3103///
3104/// An inline comment always does: it names a file and a line. A top-level
3105/// comment is dropped when it is empty, when it is magi's own, or when it is
3106/// [noise](is_noise).
3107fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3108    if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3109        return;
3110    }
3111    if comment.path.is_none() && is_noise(&comment.body) {
3112        return;
3113    }
3114    out.push(comment);
3115}
3116
3117/// Is this comment body machinery rather than a finding?
3118///
3119/// Two tests, both structural, because guessing from prose is how a "looks
3120/// good to me" turns into a fix round:
3121///
3122/// 1. The bot said so - the body carries one of the [`NOT_A_REVIEW`] markers
3123///    with which CodeRabbit labels its trigger notice, its walkthrough, and its
3124///    footer.
3125/// 2. It asks for nothing - once HTML comments, `<details>` blocks, headings,
3126///    horizontal rules, and the bot's own status banner are removed, every
3127///    remaining line is a task-list item. That is exactly the shape of the
3128///    comment the Claude review job posts while it is still working.
3129///
3130/// Anything else is input, including bot prose. A bot that writes a paragraph
3131/// has said something, and the fix prompt tells the fixer it may decline a
3132/// comment with an argument - a wasted sentence in a prompt is cheaper than a
3133/// missed finding.
3134pub fn is_noise(body: &str) -> bool {
3135    if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3136        return true;
3137    }
3138    let mut content = false;
3139    for line in strip_blocks(body).lines() {
3140        let line = unquote(line);
3141        if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3142            continue;
3143        }
3144        content = true;
3145        break;
3146    }
3147    !content
3148}
3149
3150/// Remove HTML comments and collapsed `<details>` blocks.
3151fn strip_blocks(body: &str) -> String {
3152    let mut out = String::with_capacity(body.len());
3153    let mut rest = body;
3154    loop {
3155        let open = ["<!--", "<details>"]
3156            .iter()
3157            .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3158            .min_by_key(|(i, _)| *i);
3159        let Some((at, tag)) = open else {
3160            out.push_str(rest);
3161            return out;
3162        };
3163        out.push_str(&rest[..at]);
3164        let after = &rest[at + tag.len()..];
3165        let close = if tag == "<!--" { "-->" } else { "</details>" };
3166        match after.find(close) {
3167            Some(end) => rest = &after[end + close.len()..],
3168            // Unterminated: the rest of the body is inside the block.
3169            None => return out,
3170        }
3171    }
3172}
3173
3174/// Strip blockquote markers, which both bots wrap their callouts in.
3175fn unquote(line: &str) -> &str {
3176    let mut s = line.trim();
3177    while let Some(rest) = s.strip_prefix('>') {
3178        s = rest.trim_start();
3179    }
3180    s.trim()
3181}
3182
3183/// `- [ ]` / `- [x]`, in any of the bullet styles GitHub renders.
3184fn is_checklist(line: &str) -> bool {
3185    let rest = line
3186        .strip_prefix("- ")
3187        .or_else(|| line.strip_prefix("* "))
3188        .unwrap_or("");
3189    let rest = rest.trim_start();
3190    matches!(
3191        rest.get(..3),
3192        Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3193    )
3194}
3195
3196/// A heading, a horizontal rule, or a callout tag - shape, never content.
3197fn is_decoration(line: &str) -> bool {
3198    line.starts_with('#')
3199        || line.starts_with("[!")
3200        || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3201}
3202
3203/// A line that is nothing but emphasis and links.
3204///
3205/// Both review jobs open with a status banner
3206/// (`**Claude finished ... in 4m 14s** —— [View job](url)`). It reads as prose
3207/// to a line-based test and asks for nothing, so it is measured the same way a
3208/// heading is: strip the markup, and if no word survives, it was decoration.
3209fn is_banner(line: &str) -> bool {
3210    let plain = drop_spans(line, "**", "**");
3211    let plain = if plain.contains("](") {
3212        drop_spans(&plain, "[", ")")
3213    } else {
3214        plain
3215    };
3216    !plain.chars().any(char::is_alphanumeric)
3217}
3218
3219/// Remove every `open` .. `close` span, including the delimiters. An
3220/// unterminated span swallows the rest of the input, which is what a reader
3221/// sees too.
3222fn drop_spans(s: &str, open: &str, close: &str) -> String {
3223    let mut out = String::with_capacity(s.len());
3224    let mut rest = s;
3225    while let Some(at) = rest.find(open) {
3226        out.push_str(&rest[..at]);
3227        let after = &rest[at + open.len()..];
3228        match after.find(close) {
3229            Some(end) => rest = &after[end + close.len()..],
3230            None => return out,
3231        }
3232    }
3233    out.push_str(rest);
3234    out
3235}
3236
3237/// The lock that keeps at most one run per repository actually moving the
3238/// base branch at a time: a rebase push, or `gh pr merge`.
3239///
3240/// Deliberately narrow. Everything else in [`land`]'s loop - watching CI,
3241/// running a fix round in the winner's own worktree, waiting on the owner's
3242/// approval - touches nothing a *different* run in the same repository could
3243/// collide with, and holding a lock across any of that would serialise one
3244/// run's CI wait (up to [`WAIT_CEILING`]) against another run's land-approval
3245/// resume, which is precisely the "must not wait on another task" property
3246/// the daemon's slot-freeing exists to give a resume. Only the two moments
3247/// that actually write to the shared base branch need mutual exclusion, and
3248/// both are brief.
3249///
3250/// One entry per repository, each its own `tokio::sync::Mutex`, so two
3251/// different repositories' runs never wait on each other. The outer
3252/// `std::sync::Mutex` guards only the map itself, held long enough to find or
3253/// insert an entry and clone its `Arc`, never across an `.await`.
3254fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3255    static LOCKS: std::sync::LazyLock<
3256        std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3257    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3258    LOCKS
3259        .lock()
3260        .unwrap_or_else(std::sync::PoisonError::into_inner)
3261        .entry(repo.to_path_buf())
3262        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3263        .clone()
3264}
3265
3266/// `owner/repo` out of a pull request url, falling back to the checkout's
3267/// directory name when the url is not the usual `host/owner/repo/pull/N`.
3268fn repo_label(repo: &Path, pr_url: &str) -> String {
3269    let parts: Vec<&str> = pr_url.split('/').collect();
3270    if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3271        && at >= 2
3272        && !parts[at - 1].is_empty()
3273        && !parts[at - 2].is_empty()
3274    {
3275        return format!("{}/{}", parts[at - 2], parts[at - 1]);
3276    }
3277    repo.file_name()
3278        .map(|n| n.to_string_lossy().into_owned())
3279        .unwrap_or_default()
3280}
3281
3282/// The operator-facing sentence for a merge that went ahead with red checks,
3283/// or `None` when the checks were not red. Judged on `checks`, not on
3284/// `failing`, which can be non-empty on a green observation.
3285fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3286    (pr.checks == Checks::Red).then(|| {
3287        let details = crate::notices::format_list(&pr.failing)
3288            .map(|names| format!(": {names}"))
3289            .unwrap_or_default();
3290        format!(
3291            "Merged {repo_name} PR #{} with red checks{details} ({})",
3292            pr.number, pr.url
3293        )
3294    })
3295}
3296
3297/// After a merge that succeeded: record which checks were red and tell the
3298/// operator. The decision to merge is already made; this only makes it audible.
3299/// Best-effort - a broken notifier never fails the run.
3300async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3301    let repo_name = repo_label(&state.repo, &pr.url);
3302    let Some(summary) = red_merge_summary(&repo_name, pr) else {
3303        return;
3304    };
3305    if let Some(rec) = state.pr.as_mut() {
3306        rec.red_at_merge = pr.failing.clone();
3307    }
3308    state.event("land", summary.clone());
3309    // The notice pages through `[notify]` itself, once, unless a question
3310    // already carries the cause.
3311    crate::notices::raise_with(
3312        crate::notices::merged_red(&state.id, &summary),
3313        &state.config.notify,
3314    );
3315}
3316
3317/// Run the loop against a real pull request until it merges or the budget runs
3318/// out.
3319///
3320/// The caller decides whether landing happens at all: this is only reached when
3321/// `graph.land` is on. Returns the last observation, so the caller can report
3322/// what magi was looking at when it stopped.
3323pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3324    land_with(state, pr_url, &GhForge).await
3325}
3326
3327/// The forge calls whose timing the loop's decisions depend on, behind a seam
3328/// so a test can script what the pull request looks like from one observation
3329/// to the next. Comments, logs and rebases stay on `gh` and `git` directly.
3330trait Forge {
3331    async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3332        let out = gh(
3333            repo,
3334            &[
3335                "pr".into(),
3336                "close".into(),
3337                pr_url.into(),
3338                "--comment".into(),
3339                comment.into(),
3340            ],
3341        )
3342        .await?;
3343        if !out.ok {
3344            bail!("PR closure failed: {}", out.combined());
3345        }
3346        Ok(())
3347    }
3348    async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3349        None
3350    }
3351    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3352    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3353    async fn poll(&self);
3354    /// Rerun the failed jobs of one workflow run.
3355    async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3356    /// Unix seconds, behind the seam so a test owns the clock.
3357    fn now(&self) -> i64;
3358    /// The check contexts the base branch requires, for a stop reason only.
3359    /// `None` when they could not be read, which is not the same as none.
3360    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3361    #[allow(clippy::too_many_arguments)]
3362    async fn fix(
3363        &self,
3364        state: &mut RunState,
3365        pr: &PrState,
3366        round: usize,
3367        budget: usize,
3368        reason: &str,
3369        logs: &str,
3370    ) -> Result<Fixed>;
3371}
3372
3373struct GhForge;
3374
3375impl Forge for GhForge {
3376    async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3377        collect_ci_evidence(state, seen).await
3378    }
3379    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3380        observe(repo, pr_url).await
3381    }
3382    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3383        let out = gh(repo, argv).await?;
3384        Ok((out.ok, out.combined()))
3385    }
3386    async fn poll(&self) {
3387        tokio::time::sleep(POLL).await;
3388    }
3389    async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3390        let args = [
3391            "run".to_owned(),
3392            "rerun".to_owned(),
3393            run.to_owned(),
3394            "--failed".to_owned(),
3395        ];
3396        let out = gh(repo, &args).await?;
3397        if !out.ok {
3398            bail!("gh run rerun {run}: {}", out.combined());
3399        }
3400        Ok(())
3401    }
3402    fn now(&self) -> i64 {
3403        jiff::Timestamp::now().as_second()
3404    }
3405    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3406        required_contexts_of(repo, base).await
3407    }
3408    async fn fix(
3409        &self,
3410        state: &mut RunState,
3411        pr: &PrState,
3412        round: usize,
3413        budget: usize,
3414        reason: &str,
3415        logs: &str,
3416    ) -> Result<Fixed> {
3417        fix_round(state, pr, round, budget, reason, logs).await
3418    }
3419}
3420
3421/// Percent-encode a branch name for a URL path segment (`/` included).
3422fn encode_path_segment(s: &str) -> String {
3423    let mut out = String::new();
3424    for b in s.bytes() {
3425        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3426            out.push(b as char);
3427        } else {
3428            let _ = write!(out, "%{b:02X}");
3429        }
3430    }
3431    out
3432}
3433
3434/// Read the required contexts of `base` from classic branch protection and
3435/// from rulesets, once, for a stop reason. Organisation-level rulesets that
3436/// these two endpoints do not list are missed. Any unreadable source makes the
3437/// whole answer `None`: a partial set would read as a complete one.
3438async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3439    let enc = encode_path_segment(base);
3440    let mut all = BTreeSet::new();
3441    // Classic protection answers 404 for an unprotected branch, which is
3442    // "nothing required here", not a failure to read.
3443    let classic = gh(
3444        repo,
3445        &[
3446            "api".to_owned(),
3447            format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3448        ],
3449    )
3450    .await
3451    .ok()?;
3452    if classic.ok {
3453        all.extend(parse_classic_required(&classic.stdout)?);
3454    } else if !classic.combined().contains("404") {
3455        return None;
3456    }
3457    let rules = gh(
3458        repo,
3459        &[
3460            "api".to_owned(),
3461            format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3462        ],
3463    )
3464    .await
3465    .ok()?;
3466    if !rules.ok {
3467        return None;
3468    }
3469    all.extend(parse_ruleset_required(&rules.stdout)?);
3470    Some(all)
3471}
3472
3473/// `required_status_checks` of classic protection: `contexts` plus the
3474/// `checks[].context` form.
3475fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3476    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3477    let mut out = BTreeSet::new();
3478    for c in v.get("contexts")?.as_array()? {
3479        out.insert(c.as_str()?.to_owned());
3480    }
3481    for c in v
3482        .get("checks")
3483        .and_then(|c| c.as_array())
3484        .into_iter()
3485        .flatten()
3486    {
3487        if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3488            out.insert(name.to_owned());
3489        }
3490    }
3491    Some(out)
3492}
3493
3494/// `rules/branches/<base>`: every `required_status_checks` rule's contexts.
3495fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3496    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3497    let mut out = BTreeSet::new();
3498    for rule in v.as_array()? {
3499        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3500            continue;
3501        }
3502        let checks = rule
3503            .pointer("/parameters/required_status_checks")?
3504            .as_array()?;
3505        for c in checks {
3506            out.insert(c.get("context")?.as_str()?.to_owned());
3507        }
3508    }
3509    Some(out)
3510}
3511
3512/// Is the observation older than the commit a fix round pushed?
3513///
3514/// The forge takes a few seconds to move the pull request to a new head and
3515/// attach that head's check runs, and until it has, the rollup is the previous
3516/// head's - all green, which is exactly what a merge decision must not read.
3517/// An absent or different head counts as not yet: guessing "close enough"
3518/// would reopen the hole.
3519fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3520    awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3521}
3522
3523/// The commit an observation may be decided on, or `None` while it cannot be
3524/// trusted to describe one.
3525///
3526/// `None` when a pushed commit is awaited and the pull request is not on it,
3527/// when the head is unreadable, or when the rollup (`statusCheckRollup` is the
3528/// last commit's) is not the head's: that is the previous commit's checks. The
3529/// caller re-polls on `None`. A rollup that cannot be read (including one
3530/// longer than a page) leaves `rollup_head` empty, so the wait runs to
3531/// [`WAIT_CEILING`] and stops - a safe failure, never a merge.
3532fn bound_head<'a>(
3533    seen_head: &'a str,
3534    rollup_head: &str,
3535    awaiting: Option<&str>,
3536) -> Option<&'a str> {
3537    if seen_head.is_empty()
3538        || awaiting_new_head(awaiting, seen_head)
3539        || !rollup_head.eq_ignore_ascii_case(seen_head)
3540    {
3541        return None;
3542    }
3543    Some(seen_head)
3544}
3545
3546/// What a refused `gh pr merge` means.
3547#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3548enum Refused {
3549    /// An open PR on the observed head has a proven stale base.
3550    Behind,
3551    /// The branch policy is not satisfied *yet*: go back to waiting.
3552    Pending,
3553    /// Checks have settled and the merge state still says no, seen for the
3554    /// first time. The forge updates `mergeStateStatus` a moment after the last
3555    /// check finishes, so one more look is allowed before believing it.
3556    Recheck,
3557    /// Nothing is in flight and the policy still refuses: a person has to
3558    /// supply what it asks for (a review, say).
3559    Final,
3560}
3561
3562/// Judged from the pull request's state after the refusal, never from the
3563/// refusal's wording, which belongs to the forge and changes.
3564fn classify_refusal(
3565    after: Option<&Seen>,
3566    rechecked: bool,
3567    observed_head: &str,
3568    ci: CiExpectation,
3569) -> Refused {
3570    let Some(after) = after else {
3571        // Unreadable is not evidence of anything; the next loop reads again.
3572        return Refused::Pending;
3573    };
3574    if after.pr.state != PrLifecycle::Open {
3575        return Refused::Final;
3576    }
3577    // The branch moved after it was observed (the forge refuses a merge pinned
3578    // to the old commit): not a verdict on anything, look again.
3579    if !after.head.eq_ignore_ascii_case(observed_head) {
3580        return Refused::Pending;
3581    }
3582    if Blocking::of(&after.merge_state) == Blocking::Behind {
3583        return Refused::Behind;
3584    }
3585    // The same binding the loop applies: checks of another commit say nothing.
3586    if bound_head(&after.head, &after.rollup_head, None).is_none() {
3587        return Refused::Pending;
3588    }
3589    let state = after.merge_state.to_ascii_uppercase();
3590    if (ci == CiExpectation::Expected
3591        && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3592        || state.is_empty()
3593        || state == "UNKNOWN"
3594    {
3595        return Refused::Pending;
3596    }
3597    if rechecked {
3598        Refused::Final
3599    } else {
3600        Refused::Recheck
3601    }
3602}
3603
3604/// Take auto-merge back from the forge and forget that it was armed.
3605///
3606/// `Err` carries the forge's message: the caller must not push or move on, as
3607/// an armed merge left behind could still fire for a commit nobody approved.
3608async fn disarm<F: Forge>(
3609    forge: &F,
3610    state: &mut RunState,
3611    repo: &Path,
3612    number: u64,
3613) -> std::result::Result<(), String> {
3614    let argv = disable_automerge_argv(number);
3615    let out = {
3616        let merge_lock = repo_merge_lock(repo);
3617        let _merge_slot = merge_lock.lock().await;
3618        forge.merge(repo, &argv).await
3619    };
3620    match out {
3621        Ok((true, _)) => {
3622            state.land_armed_head = None;
3623            state.event("land", "auto-merge disabled");
3624            state.save().map_err(|e| format!("{e:#}"))?;
3625            Ok(())
3626        }
3627        Ok((false, msg)) => Err(msg),
3628        Err(e) => Err(format!("{e:#}")),
3629    }
3630}
3631
3632/// [`stop`], first taking back an armed auto-merge so a pull request magi
3633/// gave up on does not merge on its own later. A failure to disarm is added
3634/// to the reason rather than hiding it.
3635async fn stop_disarmed<F: Forge>(
3636    forge: &F,
3637    state: &mut RunState,
3638    repo: &Path,
3639    pr: &PrState,
3640    why: &str,
3641) -> Result<()> {
3642    if state.land_armed_head.is_none() {
3643        return stop(state, repo, pr, why).await;
3644    }
3645    match disarm(forge, state, repo, pr.number).await {
3646        Ok(()) => stop(state, repo, pr, why).await,
3647        Err(e) => {
3648            let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3649            stop(state, repo, pr, &why).await
3650        }
3651    }
3652}
3653
3654/// Check the persisted card again around awaits that can outlive an owner tap.
3655fn owner_requested_stop(state: &RunState) -> Result<bool> {
3656    let Some(binding) = &state.land_approval else {
3657        return Ok(false);
3658    };
3659    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3660    Ok(q.run == state.id
3661        && q.node == APPROVAL_NODE
3662        && q.resolution()
3663            .as_deref()
3664            .is_some_and(crate::merge_decision::stops))
3665}
3666
3667/// Read stop choices before checks, repair or rebase. These are about stopping
3668/// ownership, so a changed head never cancels them as it cancels merge consent.
3669async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3670    use crate::merge_decision as md;
3671    let Some(binding) = &state.land_approval else {
3672        return Ok(false);
3673    };
3674    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3675    let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3676        return Ok(false);
3677    };
3678    if q.run != state.id || q.node != APPROVAL_NODE {
3679        bail!("stop decision names another run");
3680    }
3681    let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3682        pr: pr.url.clone(),
3683        head: binding.head.clone(),
3684        language: state.config.graph.language.clone(),
3685    });
3686    if target.pr != pr.url {
3687        bail!("stop decision names another PR");
3688    }
3689    if state.merge_decision.is_none() {
3690        state.merge_decision = Some(md::Decision {
3691            question: q.id.clone(),
3692            target,
3693            choice: choice.clone(),
3694            closed: false,
3695            replacement_run: None,
3696            replacement_pr: None,
3697        });
3698        state.save()?;
3699    }
3700    let repo = state.repo.clone();
3701    // Always disable, including arms left by an older driver.
3702    if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3703        stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3704        return Ok(true);
3705    }
3706    if choice.eq_ignore_ascii_case(HOLD) {
3707        stop(
3708            state,
3709            &repo,
3710            pr,
3711            "owner held the decision: PR left open; no further repair or merge work",
3712        )
3713        .await?;
3714        return Ok(true);
3715    }
3716    if md::selected_agent(&choice).is_some()
3717        || state
3718            .origin
3719            .as_ref()
3720            .and_then(|o| o.task.as_ref())
3721            .is_some()
3722    {
3723        let owners: Vec<_> = crate::queue::Queue::open()
3724            .list()
3725            .into_iter()
3726            .filter(|task| task.execution_runs().last() == Some(&state.id))
3727            .collect();
3728        let owner = (owners.len() == 1).then(|| &owners[0]);
3729        if !owner.is_some_and(|task| {
3730            task.execution_runs().last() == Some(&state.id)
3731                && (!task
3732                    .operator_decided_at
3733                    .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3734                    || task.resumption.as_ref().is_some_and(|release| {
3735                        release.question_id.as_deref() == Some(q.id.as_str())
3736                            && task.operator_decided_at == Some(release.at)
3737                    }))
3738        }) {
3739            stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3740            return Ok(true);
3741        }
3742    }
3743    if pr.state == PrLifecycle::Merged {
3744        stop(
3745            state,
3746            &repo,
3747            pr,
3748            "PR already merged; withdrawal/replacement cannot be applied",
3749        )
3750        .await?;
3751        return Ok(true);
3752    }
3753    let comment = format!(
3754        "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3755        q.id, choice, state.id
3756    );
3757    if pr.state == PrLifecycle::Open {
3758        if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3759            stop(
3760                state,
3761                &repo,
3762                pr,
3763                &format!(
3764                    "owner requested closure but it failed: {e}; task held, no replacement started"
3765                ),
3766            )
3767            .await?;
3768            return Ok(true);
3769        }
3770    }
3771    let confirmed = forge.view(&repo, &pr.url).await?;
3772    if confirmed.pr.state != PrLifecycle::Closed {
3773        stop(
3774            state,
3775            &repo,
3776            pr,
3777            "PR closure was not confirmed; task held, no replacement started",
3778        )
3779        .await?;
3780        return Ok(true);
3781    }
3782    *pr = confirmed.pr;
3783    state.merge_decision.as_mut().unwrap().closed = true;
3784    if let Some(record) = &mut state.pr {
3785        record.state = "closed".into();
3786    }
3787    state.status = RunStatus::Superseded;
3788    state.merge = Some(MergeOutcome {
3789        mode: MergeMode::Pr,
3790        ok: false,
3791        detail: format!("owner decision: {choice}; PR closure confirmed"),
3792        empty: false,
3793    });
3794    state.event(
3795        "land",
3796        format!(
3797            "{} applied: PR closure confirmed; old execution retired",
3798            choice
3799        ),
3800    );
3801    state.save()?;
3802    Ok(true)
3803}
3804
3805/// Keep an unstarted verification resumable without charging a task attempt.
3806fn check_landing_resources(
3807    state: &mut RunState,
3808    node: &str,
3809    outcomes: &[crate::run::CommandOutcome],
3810) -> Result<()> {
3811    if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
3812        let detail = format!("{}: {}", blocked.command, blocked.output_tail);
3813        state
3814            .resource_block
3815            .get_or_insert_with(|| crate::run::ResourceBlock {
3816                cause: crate::run::ResourceBlockCause::Other,
3817                node: node.into(),
3818                kind: "shared build cache".into(),
3819                detail: detail.clone(),
3820                at: jiff::Timestamp::now(),
3821            });
3822        state.event("resource", &detail);
3823        state.save()?;
3824        bail!("landing verification could not start: {detail}");
3825    }
3826    Ok(())
3827}
3828
3829/// Gate the local winner and publish that exact SHA, retaining the saved lease.
3830/// A push completed before a crash is recoverable only when its SHA was gated.
3831async fn publish_landing_head<F: Forge>(
3832    state: &mut RunState,
3833    observed: &str,
3834    pr_url: &str,
3835    forge: &F,
3836) -> Result<String> {
3837    crate::pr_head::ensure_owner(state)?;
3838    let winner = state.winner().cloned().context("landing has no winner")?;
3839    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3840    let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
3841    anyhow::ensure!(
3842        observed == expected
3843            || (observed == head
3844                && state.gate_head.as_deref() == Some(&head)
3845                && state.gate_allows_progress()),
3846        "public head moved outside this run; refusing to overwrite it"
3847    );
3848    anyhow::ensure!(
3849        git::is_clean(&winner.worktree).await?,
3850        "landing worktree is dirty"
3851    );
3852    // Even without a rebase, verification can change HEAD through gate repair.
3853    // Persist the start before either verification or repair can run.
3854    if state.land_sync_unstarted_grant() {
3855        state.land_sync_attempts += 1;
3856        state.land_sync_pending = true;
3857        state.event(
3858            "land-sync-recovery",
3859            "started recovery attempt without rebase",
3860        );
3861        state.save()?;
3862    }
3863    if state.gate_head.as_deref() != Some(&head)
3864        || !state.gate_ran
3865        || !state.gate_commands_allow_progress()
3866    {
3867        state.reconcile_verification_head(&head);
3868        state.gate.clear();
3869        state.gate_head = None;
3870        state.gate_ran = false;
3871        state.pre_gate.clear();
3872        state.pre_gate_commit = None;
3873        state.save()?;
3874        let inherited = crate::repo_lock::WaitPolicy::current();
3875        let wait = crate::repo_lock::WaitPolicy::new(
3876            Duration::from_secs(state.config.graph.timeout_resource_wait),
3877            move || inherited.cancelled(),
3878        );
3879        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3880        loop {
3881            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
3882                state.gate = outcomes.clone();
3883                check_landing_resources(state, "gate", &outcomes)?;
3884            }
3885            if outcomes.iter().all(|o| o.ok()) {
3886                break;
3887            }
3888            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
3889                crate::graph::GateFix::Retry => {
3890                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3891                }
3892                crate::graph::GateFix::Stop => break,
3893                crate::graph::GateFix::Defer => {
3894                    // The repair checks e2e immediately, before the next gate.
3895                    // Preserve a cache wait here as well as below; otherwise
3896                    // the daemon charges an attempt for unstarted verification.
3897                    if let Some(e2e) = &state.gate_repair_e2e {
3898                        let outcomes = e2e.outcomes.clone();
3899                        check_landing_resources(state, "e2e", &outcomes)?;
3900                    }
3901                    bail!("landing gate repair deferred");
3902                }
3903            }
3904        }
3905        state.gate = outcomes;
3906        state.gate_ran = true;
3907        state.save()?;
3908    }
3909    let inherited = crate::repo_lock::WaitPolicy::current();
3910    let wait = crate::repo_lock::WaitPolicy::new(
3911        Duration::from_secs(state.config.graph.timeout_resource_wait),
3912        move || inherited.cancelled(),
3913    );
3914    let checked = state
3915        .gate_head
3916        .clone()
3917        .context("landing gate has no checked SHA")?;
3918    anyhow::ensure!(
3919        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3920            && git::is_clean(&winner.worktree).await?,
3921        "landing tree changed after gate"
3922    );
3923    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
3924    if matches!(e2e, crate::graph::GateFix::Defer) {
3925        let outcomes = state
3926            .gate_repair_e2e
3927            .as_ref()
3928            .context("deferred landing e2e has no outcomes")?
3929            .outcomes
3930            .clone();
3931        check_landing_resources(state, "e2e", &outcomes)?;
3932    }
3933    anyhow::ensure!(
3934        matches!(e2e, crate::graph::GateFix::Retry),
3935        "post-repair e2e has not passed on the landing head; nothing published"
3936    );
3937    anyhow::ensure!(
3938        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3939            && git::is_clean(&winner.worktree).await?,
3940        "landing tree changed during post-repair e2e"
3941    );
3942    anyhow::ensure!(
3943        crate::graph::verify_current_head(state, &winner, &wait).await?,
3944        "current head e2e has not passed; nothing published"
3945    );
3946    anyhow::ensure!(
3947        state.gate_allows_progress(),
3948        "landing gate failed; nothing published"
3949    );
3950    crate::pr_head::ensure_owner(state)?;
3951    if owner_requested_stop(state)? {
3952        bail!("owner requested stop before publication");
3953    }
3954    let current = forge.view(&state.repo, pr_url).await?;
3955    anyhow::ensure!(
3956        current.pr.state == PrLifecycle::Open,
3957        "PR closed or merged while gating; nothing published"
3958    );
3959    anyhow::ensure!(
3960        current.head == observed || current.head == checked,
3961        "PR head changed while gating; nothing published"
3962    );
3963    anyhow::ensure!(
3964        crate::foreign_checkout::write_back(state, &checked).await?,
3965        "foreign checkout delivery is blocked; see the run events"
3966    );
3967    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
3968    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
3969    let refspec = format!("{checked}:refs/heads/{public}");
3970    let lock = repo_merge_lock(&state.repo);
3971    let _slot = lock.lock().await;
3972    let pushed = git::git_raw(
3973        &winner.worktree,
3974        &["push", &lease, &state.config.merge.remote, &refspec],
3975    )
3976    .await?;
3977    anyhow::ensure!(
3978        pushed.ok(),
3979        "publishing gated landing head failed: {}",
3980        pushed.stderr
3981    );
3982    state.pr_pushed_head = Some(checked.clone());
3983    state.land_sync_pending = false;
3984    state.save()?;
3985    Ok(checked)
3986}
3987
3988/// A scratch rebase moves the winner ref before its index and files. Recover
3989/// only a tree proven unchanged since the saved start; never discard edits.
3990async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
3991    let winner = state.winner().cloned().context("landing has no winner")?;
3992    let inherited = crate::repo_lock::WaitPolicy::current();
3993    let wait = crate::repo_lock::WaitPolicy::new(
3994        Duration::from_secs(state.config.graph.timeout_resource_wait),
3995        move || inherited.cancelled(),
3996    );
3997    let _coordination = crate::repo_lock::SeatLease::operation_with(
3998        &winner.worktree,
3999        state.config.coordination.as_ref(),
4000        &wait,
4001    )
4002    .await?;
4003    if !git::is_clean(&winner.worktree).await? {
4004        let from = state
4005            .land_rebase_from
4006            .as_deref()
4007            .context("landing worktree is dirty")?;
4008        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
4009        anyhow::ensure!(head != from, "landing worktree is dirty");
4010        for args in [
4011            vec!["diff", "--cached", "--quiet", from],
4012            vec!["diff", "--quiet"],
4013        ] {
4014            anyhow::ensure!(
4015                git::git_raw(&winner.worktree, &args).await?.ok(),
4016                "landing worktree has edits beyond the interrupted rebase"
4017            );
4018        }
4019        // Preserve build artifacts and local files, including ignored ones.
4020        // read-tree can overwrite ignored paths, so reject collisions with
4021        // the new tree (including file/directory conflicts) before updating.
4022        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
4023        let tracked = git::git(
4024            &winner.worktree,
4025            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
4026        )
4027        .await?;
4028        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
4029            anyhow::ensure!(
4030                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
4031                    path == local
4032                        || path
4033                            .strip_prefix(local)
4034                            .is_some_and(|rest| rest.starts_with('/'))
4035                        || local
4036                            .strip_prefix(path)
4037                            .is_some_and(|rest| rest.starts_with('/'))
4038                }),
4039                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
4040            );
4041        }
4042        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
4043    }
4044    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
4045        anyhow::ensure!(
4046            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
4047            "landing synchronization started outside the foreign checkout history"
4048        );
4049        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
4050            // The rebase's tree already includes the base and the fixer's
4051            // resolutions. Retain that exact tree, but join the pre-sync
4052            // history so delivery remains fast-forward. Keep the checkpoint
4053            // until this succeeds: a crash after rebase (or after this merge)
4054            // must recover through this same idempotent path before gating.
4055            git::git(
4056                &winner.worktree,
4057                &[
4058                    "-c",
4059                    "core.hooksPath=/dev/null",
4060                    "merge",
4061                    "--strategy=ours",
4062                    "--no-ff",
4063                    "--no-autostash",
4064                    "--no-edit",
4065                    "-m",
4066                    "Merge pre-sync history into the repaired landing tree",
4067                    from,
4068                ],
4069            )
4070            .await?;
4071        }
4072    }
4073    crate::worktree_setup::prepare_with(
4074        &state.config,
4075        &state.repo,
4076        &winner.worktree,
4077        crate::build_target::Coordination::Held(_coordination.as_ref()),
4078    )
4079    .await?;
4080    state.land_rebase_from = None;
4081    state.save()?;
4082    Ok(())
4083}
4084
4085async fn rebase_landing_worktree(
4086    state: &mut RunState,
4087    onto: &str,
4088) -> Result<crate::rebase::Rebased> {
4089    restore_landing_worktree(state).await?;
4090    let winner = state.winner().cloned().context("landing has no winner")?;
4091    let scratch = state.dir().join("rebase");
4092    let target = match state.land_sync_target.clone() {
4093        Some(target) => {
4094            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4095            target
4096        }
4097        // Older records lack the target checkpoint, but Git retains the
4098        // exact target of an interrupted operation. It is a continuation too.
4099        None if crate::rebase::checked_progress(state, &scratch, "").await? => {
4100            crate::rebase::rebase_target(&scratch).await?
4101        }
4102        None => {
4103            if state.land_sync_attempts >= state.land_sync_budget() {
4104                let head = git::rev_parse(&winner.worktree, "HEAD")
4105                    .await
4106                    .unwrap_or_default();
4107                let tip = git::rev_parse(&state.repo, onto).await.unwrap_or_default();
4108                let pr_head = state.pr_pushed_head.clone().unwrap_or_else(|| head.clone());
4109                state.land_sync_pending = true;
4110                state.record_land_sync_exhausted_stop(&head, &pr_head, &tip);
4111                let _ = state.save();
4112                bail!("{}", crate::land_sync_recovery::EXHAUSTED_DETAIL);
4113            }
4114            let target = git::rev_parse(&state.repo, onto).await?;
4115            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4116            state.land_sync_attempts += 1;
4117            state.land_sync_target = Some(target.clone());
4118            target
4119        }
4120    };
4121    state.land_sync_target = Some(target.clone());
4122    state.land_sync_pending = true;
4123    state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4124    state.save()?;
4125    // A continuation owns the attempt already charged above, including a
4126    // crash before the scratch rebase started. Finish its pinned base first;
4127    // a newer base must use another attempt on the next observation.
4128    let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4129    state.land_sync_target = None;
4130    state.save()?;
4131    if result == crate::rebase::Rebased::Applied {
4132        restore_landing_worktree(state).await?;
4133    }
4134    Ok(result)
4135}
4136
4137/// Reconcile a stopped landing before changing its branch. This also handles
4138/// old records whose graph status or merge detail no longer identifies land.
4139async fn resume_landing_head<F: Forge>(
4140    state: &mut RunState,
4141    observed: &str,
4142    pr_url: &str,
4143    forge: &F,
4144    reason: Option<Blocking>,
4145) -> Result<String> {
4146    crate::pr_head::ensure_owner(state)?;
4147    let winner = state.winner().cloned().context("landing has no winner")?;
4148    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4149    let expected = state
4150        .pr_pushed_head
4151        .as_deref()
4152        .or(state.gate_head.as_deref())
4153        .context("missing public head lease")?;
4154    anyhow::ensure!(
4155        observed == expected
4156            || (observed == local
4157                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4158                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4159        "public head moved outside this run; refusing to sync"
4160    );
4161    // An operator may have extended and published the winner while approval
4162    // was pending. Matching local/public history can be adopted as the lease,
4163    // but publish_landing_head must gate its new SHA before proceeding. A
4164    // remote-only or divergent update still cannot be overwritten.
4165    // Save reconciliation before rebasing again; a prior push may have reached
4166    // the remote immediately before the previous driver's last save.
4167    state.pr_pushed_head = Some(observed.to_owned());
4168    state.save()?;
4169    restore_landing_worktree(state).await?;
4170    // Recover a rebase that finished before its completion checkpoint was
4171    // saved. Restoration above has already reconciled its files and ancestry.
4172    let scratch = state.dir().join("rebase");
4173    if let Some(target) = state.land_sync_target.clone()
4174        && !crate::rebase::checked_progress(state, &scratch, "").await?
4175        && git::ancestry(&winner.worktree, &target, &local).await?
4176    {
4177        state.land_sync_target = None;
4178        state.save()?;
4179    }
4180    let remote = state.config.merge.remote.clone();
4181    let base = state.base_branch.clone();
4182    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4183    anyhow::ensure!(
4184        fetched.ok(),
4185        "cannot fetch landing base: {}",
4186        fetched.stderr
4187    );
4188    anyhow::ensure!(
4189        !owner_requested_stop(state)?,
4190        "owner requested stop before base synchronization"
4191    );
4192    let onto = format!("{remote}/{base}");
4193    let tip = git::rev_parse(&state.repo, &onto).await?;
4194    if state.land_sync_unstarted_grant() {
4195        let auth = state
4196            .land_sync_recovery
4197            .authorizations
4198            .last()
4199            .context("missing recovery grant")?;
4200        anyhow::ensure!(
4201            auth.invalidated.is_none()
4202                && git::ancestry(&state.repo, &auth.scope.tip, &tip).await?
4203                && git::ancestry(&state.repo, &auth.stop.tip, &tip).await?,
4204            "fetched landing base is outside the authorized recovery lineage"
4205        );
4206    }
4207    let contains_base = git::ancestry(&state.repo, &tip, &local)
4208        .await
4209        .context("could not determine whether the landing head contains the fetched base")?;
4210    anyhow::ensure!(
4211        reason != Some(Blocking::Behind) || !contains_base,
4212        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4213    );
4214    if !contains_base || reason == Some(Blocking::Conflict) {
4215        match rebase_landing_worktree(state, &tip).await? {
4216            crate::rebase::Rebased::Applied => {}
4217            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4218        }
4219    }
4220    if reason == Some(Blocking::Behind) {
4221        anyhow::ensure!(
4222            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4223            "BEHIND synchronization left the head unchanged"
4224        );
4225    }
4226    publish_landing_head(state, observed, pr_url, forge).await
4227}
4228
4229/// Share the synchronization path with structured evidence retained after a refusal.
4230async fn synchronize_landing<F: Forge>(
4231    state: &mut RunState,
4232    pr: &mut PrState,
4233    observed: &str,
4234    pr_url: &str,
4235    forge: &F,
4236) -> Result<Option<String>> {
4237    if owner_stop(state, pr, forge).await? {
4238        return Ok(None);
4239    }
4240    state.event(
4241        "land",
4242        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4243    );
4244    state.save()?;
4245    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4246    if owner_stop(state, pr, forge).await? {
4247        return Ok(None);
4248    }
4249    match synced {
4250        Ok(head) => {
4251            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4252                crate::graph::refresh_reviewed_commits(state, &branch).await;
4253            }
4254            Ok(Some(head))
4255        }
4256        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4257        Err(e) => {
4258            let repo = state.repo.clone();
4259            stop(
4260                state,
4261                &repo,
4262                pr,
4263                &format!("could not synchronize landing base: {e:#}"),
4264            )
4265            .await?;
4266            Ok(None)
4267        }
4268    }
4269}
4270
4271enum LandSyncPrep {
4272    Continue(Option<Seen>),
4273    Stop(PrState),
4274}
4275
4276/// Revalidate and durably consume a pending landing base-sync recovery
4277/// authorization under the live execution lease before mutating landing status
4278/// or adopting any observed PR head.
4279async fn prepare_land_sync_recovery<F: Forge>(
4280    state: &mut RunState,
4281    pr_url: &str,
4282    forge: &F,
4283) -> Result<LandSyncPrep> {
4284    let has_unconsumed = state.has_unconsumed_land_sync_authorization();
4285    let unstarted = state.land_sync_unstarted_grant();
4286    let exhausted = state.land_sync_exhausted();
4287    if !has_unconsumed && !exhausted && !unstarted {
4288        return Ok(LandSyncPrep::Continue(None));
4289    }
4290    let repo = state.repo.clone();
4291    let seen = forge.view(&repo, pr_url).await?;
4292    if seen.pr.state != PrLifecycle::Open {
4293        anyhow::ensure!(
4294            state
4295                .pr
4296                .as_ref()
4297                .is_some_and(|pr| pr.url == seen.pr.url && pr.number == seen.pr.number),
4298            "terminal pull request does not match the retained run"
4299        );
4300        return Ok(LandSyncPrep::Continue(Some(seen)));
4301    }
4302    if !has_unconsumed && !unstarted {
4303        bail!(
4304            "{}; explicit recover-land-sync authorization required",
4305            crate::land_sync_recovery::EXHAUSTED_DETAIL
4306        );
4307    }
4308    let observed = crate::land_sync_recovery::ObservedPr {
4309        url: seen.pr.url.clone(),
4310        number: seen.pr.number,
4311        open: seen.pr.state == PrLifecycle::Open,
4312        head: seen.head.clone(),
4313        base_branch: (!seen.base.is_empty()).then(|| seen.base.clone()),
4314    };
4315    let home = crate::run::home();
4316    let validation = if owner_requested_stop(state)? {
4317        Err("owner requested stop before landing base-sync recovery".into())
4318    } else {
4319        crate::land_sync_recovery::validate_pending_authorization(
4320            &home,
4321            state,
4322            None,
4323            Some(&observed),
4324            &crate::land_sync_recovery::GhPrObserver,
4325        )
4326        .await
4327    };
4328    match validation {
4329        Ok((local_head, pr_head)) => {
4330            if unstarted {
4331                return Ok(LandSyncPrep::Continue(Some(seen)));
4332            }
4333            if let Err(reason) = state.consume_land_sync_recovery(&local_head, &pr_head) {
4334                state.status = RunStatus::Blocked;
4335                state.event("land-sync-recovery", format!("refused: {reason}"));
4336                state.save()?;
4337                return Ok(LandSyncPrep::Stop(seen.pr));
4338            }
4339            state.event(
4340                "land-sync-recovery",
4341                format!(
4342                    "consumed recovery grant {}/{}: authorized {} landing sync attempt ({}/{}); prior verification archived, fresh E2E and gate required",
4343                    state.land_sync_recovery.extra_attempts,
4344                    crate::land_sync_recovery::MAX_GRANTS,
4345                    crate::land_sync_recovery::GRANT_ATTEMPTS,
4346                    state.land_sync_attempts,
4347                    state.land_sync_budget()
4348                ),
4349            );
4350            state.save()?;
4351            Ok(LandSyncPrep::Continue(Some(seen)))
4352        }
4353        Err(failure) => {
4354            let reason = failure.reason;
4355            if !failure.observation_failed
4356                && let Some(auth) = state
4357                    .land_sync_recovery
4358                    .authorizations
4359                    .iter_mut()
4360                    .rev()
4361                    .find(|a| {
4362                        a.invalidated.is_none()
4363                            && (!a.consumed || unstarted && a.archived_verification.is_some())
4364                    })
4365            {
4366                auth.refuse(&reason);
4367            }
4368            state.status = RunStatus::Blocked;
4369            state.event("land-sync-recovery", format!("refused: {reason}"));
4370            state.save()?;
4371            Ok(LandSyncPrep::Stop(seen.pr))
4372        }
4373    }
4374}
4375
4376async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4377    crate::pr_head::ensure_owner(state)?;
4378    let mut initial_seen = match prepare_land_sync_recovery(state, pr_url, forge).await? {
4379        LandSyncPrep::Continue(seen) => seen,
4380        LandSyncPrep::Stop(pr) => return Ok(pr),
4381    };
4382    state.land_unrelated = None;
4383    let reopening_hold = crate::merge_decision::resumable_hold(state);
4384    let repo = state.repo.clone();
4385    let budget = state.config.graph.land_rounds;
4386    let mut round = 0usize;
4387    let ci = state.config.merge.ci.expectation();
4388    if ci == CiExpectation::Absent {
4389        state.event(
4390            "land",
4391            "CI not expected ([merge] ci = \"none\"); check status ignored",
4392        );
4393    }
4394    let mut waited = Duration::ZERO;
4395    // Comment bodies the fixer has already been shown. A comment is
4396    // outstanding until it has been handed over once; after that it is a
4397    // recorded decision, not an open question, and re-feeding it would loop the
4398    // budget away on a comment the fixer already declined with an argument.
4399    let mut shown: BTreeSet<String> = BTreeSet::new();
4400    // Await the last successfully published head, including across resumes.
4401    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4402    // Whether a settled-checks refusal has already been given its one re-look.
4403    let mut rechecked = false;
4404
4405    // Marks the run resumable through exactly this function, not through a
4406    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4407    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4408    // status specifically to know a resumed run belongs back in `land`
4409    // rather than at a second `gh pr create`. Set on every entry - fresh or
4410    // resumed - because a resume that parked here again must keep reading
4411    // `Landing`, not whatever a first pass through `merge` left behind.
4412    state.status = RunStatus::Landing;
4413    state.event("land", format!("watching {pr_url}"));
4414    state.save()?;
4415
4416    // An armed merge recorded by an earlier pass may or may not have reached
4417    // the forge (the record is written before the call). It is taken back on
4418    // the first observation, where a pull request is known to stop with.
4419    let mut resumed_armed = state.land_armed_head.is_some();
4420
4421    'landing: loop {
4422        let seen = match initial_seen.take() {
4423            Some(seen) => seen,
4424            None => forge.view(&repo, pr_url).await?,
4425        };
4426        let mut pr = seen.pr.clone();
4427        pr.review_comments.retain(|c| !shown.contains(&c.body));
4428        state.pr = Some(crate::run::PrRecord {
4429            url: pr.url.clone(),
4430            number: pr.number,
4431            state: pr.state.as_str().to_owned(),
4432            checks: pr.checks.as_str().to_owned(),
4433            round,
4434            rounds: budget,
4435            red_at_merge: Vec::new(),
4436        });
4437        state.save()?;
4438
4439        if pr.state == PrLifecycle::Open {
4440            state.observe_branch_owner_holds(&seen.head).await;
4441            state.save()?;
4442        }
4443        crate::pr_head::ensure_owner(state)?;
4444        if reopening_hold {
4445            anyhow::ensure!(
4446                pr.state == PrLifecycle::Open,
4447                "held PR is no longer open; cannot request a fresh decision"
4448            );
4449            // An explicit resume authorizes a fresh question only. Preserve the
4450            // answered card, and never enter repair/rebase/merge on this pass.
4451            disarm(forge, state, &repo, pr.number)
4452                .await
4453                .map_err(anyhow::Error::msg)?;
4454            let previous = state.merge_decision.take();
4455            let binding = state.land_approval.take();
4456            state.config.graph.land_approval = true;
4457            let subject = merge_subject(
4458                crate::graph::landing_title(state, &seen.title),
4459                &crate::graph::landing_subject_source(state),
4460            );
4461            let contested = contested_to_ask(state);
4462            if let Err(error) =
4463                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4464            {
4465                state.merge_decision = previous;
4466                state.land_approval = binding;
4467                return Err(error);
4468            }
4469            state.end_pass_parked(crate::run::ParkCause::Question);
4470            state.parked = true;
4471            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()));
4472            state.save()?;
4473            return Ok(pr);
4474        }
4475        if owner_stop(state, &mut pr, forge).await? {
4476            return Ok(pr);
4477        }
4478
4479        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4480            // An approval already given for the same head is reused, so
4481            // nothing is asked twice. A failed disable
4482            // stops the run with the record kept: pushing on could change the
4483            // head under an arm that is still live.
4484            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4485                let why = format!(
4486                    "a previous pass may have armed auto-merge and it could not be disabled \
4487                     on resume: {e}"
4488                );
4489                stop(state, &repo, &pr, &why).await?;
4490                return Ok(pr);
4491            }
4492        }
4493
4494        // The head moved away from the one auto-merge was armed on, by
4495        // someone other than this loop. The arm is pinned and would refuse to
4496        // merge the new commit, but the approval was for the old one: take it
4497        // back and go through the normal path again.
4498        if pr.state == PrLifecycle::Open
4499            && !seen.head.is_empty()
4500            && state
4501                .land_armed_head
4502                .as_deref()
4503                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4504        {
4505            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4506                let why = format!(
4507                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4508                );
4509                stop(state, &repo, &pr, &why).await?;
4510                return Ok(pr);
4511            }
4512        }
4513
4514        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4515            // Disarming can outlive an owner answer. Consume it before our
4516            // own rebase invalidates the head shown on the decision card.
4517            if owner_stop(state, &mut pr, forge).await? {
4518                return Ok(pr);
4519            }
4520            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4521                binding.head.eq_ignore_ascii_case(&seen.head)
4522                    && ask::Questions::open()
4523                        .get_for_effects(&binding.question)
4524                        .is_ok_and(|q| {
4525                            q.run == state.id
4526                                && q.node == APPROVAL_NODE
4527                                && q.status == ask::QuestionStatus::Answered
4528                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4529                        })
4530            });
4531            if repair_answer {
4532                let subject = merge_subject(
4533                    crate::graph::landing_title(state, &seen.title),
4534                    &crate::graph::landing_subject_source(state),
4535                );
4536                let contested = contested_to_ask(state);
4537                if matches!(
4538                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4539                    ApprovalGate::Repair
4540                ) {
4541                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4542                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4543                        state.save()?;
4544                    }
4545                    return Ok(pr);
4546                }
4547            }
4548            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4549            // A stop detected before publication must apply its durable
4550            // decision, even when verification returned an error meanwhile.
4551            if owner_stop(state, &mut pr, forge).await? {
4552                return Ok(pr);
4553            }
4554            let head = synced?;
4555            awaiting_head = Some(head);
4556            waited = Duration::ZERO;
4557            rechecked = false;
4558            // Read CI and approvals afresh, never from the pre-push observation.
4559            continue;
4560        }
4561
4562        // A stale base is independent of the CI rollup. Keep the public-head
4563        // lease, but synchronize before waiting for checks on the old tree.
4564        if pr.state == PrLifecycle::Open
4565            && pr.blocking == Blocking::Behind
4566            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4567        {
4568            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4569            let Some(head) = synced else {
4570                return Ok(pr);
4571            };
4572            awaiting_head = Some(head);
4573            rechecked = false;
4574            waited = Duration::ZERO;
4575            continue;
4576        }
4577
4578        if pr.state == PrLifecycle::Open {
4579            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4580                if waited >= WAIT_CEILING {
4581                    let want = awaiting_head.as_deref().unwrap_or_default();
4582                    let why = format!(
4583                        "the pull request's checks were still not about one readable head after \
4584                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4585                         someone may have pushed over it",
4586                        WAIT_CEILING.as_secs() / 60,
4587                        if want.is_empty() { "any" } else { want },
4588                        if seen.head.is_empty() {
4589                            "nothing readable"
4590                        } else {
4591                            &seen.head
4592                        },
4593                        if seen.rollup_head.is_empty() {
4594                            "nothing readable"
4595                        } else {
4596                            &seen.rollup_head
4597                        },
4598                    );
4599                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4600                    return Ok(pr);
4601                }
4602                waited += POLL;
4603                forge.poll().await;
4604                continue;
4605            }
4606            // Reset once, when the awaited head first shows up; resetting on
4607            // every re-observation would let a standing refusal wait forever.
4608            if awaiting_head.take().is_some() {
4609                // The checks now being read belong to the new head; give them
4610                // the same grace a fresh pull request gets.
4611                waited = Duration::ZERO;
4612            }
4613        }
4614
4615        // The merge-state grace is head-bound and durable. Reruns reset the
4616        // checks clock, but must not extend this deadline across resumes.
4617        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4618            let first = state
4619                .land_unsaid
4620                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4621            if !first.0.eq_ignore_ascii_case(&seen.head) {
4622                *first = (seen.head.clone(), forge.now());
4623            }
4624            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4625            state.save()?;
4626            elapsed
4627        } else {
4628            waited
4629        };
4630        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4631        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4632            if waited >= WAIT_CEILING {
4633                stop_disarmed(
4634                    forge,
4635                    state,
4636                    &repo,
4637                    &pr,
4638                    "merge state remained unreadable; refusing to merge on a guess",
4639                )
4640                .await?;
4641                return Ok(pr);
4642            }
4643            waited += POLL;
4644            forge.poll().await;
4645            continue;
4646        }
4647
4648        // A failed workflow run is rerun once, judged by its own run rather
4649        // than by the rollup's aggregate: another run still pending, or a fix
4650        // budget already spent, must not keep a flaky failure from its one
4651        // rerun. It spends no round and no attempt.
4652        if ci == CiExpectation::Expected
4653            && pr.state == PrLifecycle::Open
4654            && state.config.graph.rerun_flaky_checks
4655        {
4656            let include_optional = pr.checks == Checks::Red
4657                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4658            let failing = rerunnable_with(&seen.contexts, include_optional);
4659            let now = forge.now();
4660            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4661                RerunStep::Rerun(runs) => {
4662                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4663                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4664                        *rec = LandReruns {
4665                            head: seen.head.clone(),
4666                            runs: BTreeMap::new(),
4667                        };
4668                    }
4669                    for run in &runs {
4670                        rec.runs.insert(run.clone(), now);
4671                    }
4672                    // Durable before the call: a restart must not
4673                    // rerun the same run twice. A save that fails
4674                    // means no rerun.
4675                    state.save()?;
4676                    let mut any = false;
4677                    for run in &runs {
4678                        let names = failing
4679                            .iter()
4680                            .filter(|(_, r)| r.as_deref() == Some(run))
4681                            .map(|(l, _)| l.as_str())
4682                            .collect::<Vec<_>>()
4683                            .join(", ");
4684                        match forge.rerun(&repo, run).await {
4685                            Ok(()) => {
4686                                any = true;
4687                                state.event(
4688                                    "land",
4689                                    format!("reran failed check(s) {names} (run {run})"),
4690                                );
4691                            }
4692                            // Stays recorded: never a retry loop.
4693                            Err(e) => state.event(
4694                                "land",
4695                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4696                            ),
4697                        }
4698                    }
4699                    state.save()?;
4700                    if any {
4701                        waited = Duration::ZERO;
4702                        forge.poll().await;
4703                        continue;
4704                    }
4705                }
4706                RerunStep::Grace => {
4707                    if waited >= WAIT_CEILING {
4708                        let why = format!(
4709                            "checks were still failing after a rerun and {} minutes",
4710                            WAIT_CEILING.as_secs() / 60
4711                        );
4712                        stop(state, &repo, &pr, &why).await?;
4713                        return Ok(pr);
4714                    }
4715                    waited += POLL;
4716                    forge.poll().await;
4717                    continue;
4718                }
4719                RerunStep::Fix => {}
4720            }
4721        }
4722
4723        let step = proposed;
4724        // Armed on exactly this head: the forge is doing the waiting. A
4725        // decision to merge (or keep waiting) is only watched, never re-armed
4726        // and never re-approved; anything else - a red check, a comment, a
4727        // conflict - falls through to its own arm, which disarms first.
4728        let armed_here = state
4729            .land_armed_head
4730            .as_deref()
4731            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4732        if armed_here && matches!(step, Step::Merge | Step::Wait) {
4733            if waited >= WAIT_CEILING {
4734                let required = if seen.base.is_empty() {
4735                    None
4736                } else {
4737                    forge.required_contexts(&repo, &seen.base).await
4738                };
4739                let why = format!(
4740                    "auto-merge was armed on {} but the pull request did not merge within {} \
4741                     minutes ({})",
4742                    seen.head,
4743                    WAIT_CEILING.as_secs() / 60,
4744                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4745                );
4746                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4747                return Ok(pr);
4748            }
4749            waited += POLL;
4750            forge.poll().await;
4751            continue;
4752        }
4753        if armed_here && !matches!(step, Step::Done { .. }) {
4754            // Not merging or waiting any more: whatever is next may change the
4755            // head or give up, and neither may leave the arm standing.
4756            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4757                let why = format!("auto-merge could not be disabled: {e}");
4758                stop(state, &repo, &pr, &why).await?;
4759                return Ok(pr);
4760            }
4761        }
4762        if pr.checks == Checks::Red
4763            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4764            && pr.review_comments.is_empty()
4765            && let Some(evidence) = forge.attribution(state, &seen).await
4766            && evidence.unrelated(&seen.head, &pr.failing)
4767        {
4768            if owner_stop(state, &mut pr, forge).await? {
4769                return Ok(pr);
4770            }
4771            // Attribution does not authorize action against an unseen push.
4772            let fresh = forge.view(&repo, pr_url).await?;
4773            if fresh.head != seen.head
4774                || fresh.rollup_head != seen.rollup_head
4775                || fresh.pr.state != PrLifecycle::Open
4776                || fresh.pr.checks != Checks::Red
4777                || fresh.pr.failing != pr.failing
4778                || fresh
4779                    .pr
4780                    .review_comments
4781                    .iter()
4782                    .any(|c| !shown.contains(&c.body))
4783            {
4784                continue;
4785            }
4786            hold_unrelated(state, &pr, evidence).await?;
4787            return Ok(pr);
4788        }
4789        match step {
4790            Step::Wait => {
4791                if waited >= WAIT_CEILING {
4792                    let why = format!(
4793                        "checks were still running after {} minutes",
4794                        WAIT_CEILING.as_secs() / 60
4795                    );
4796                    stop(state, &repo, &pr, &why).await?;
4797                    return Ok(pr);
4798                }
4799                waited += POLL;
4800                forge.poll().await;
4801            }
4802            Step::Done { merged } => {
4803                if merged {
4804                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
4805                }
4806                // Auto-merge is pinned to the approved head, but the forge's
4807                // own handling of a later push is not something magi can
4808                // see: if the pull request merged on another commit, say so
4809                // loudly rather than record a clean landing.
4810                if let Some(armed) = state.land_armed_head.take() {
4811                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
4812                        let msg = format!(
4813                            "{} merged on {} but the owner approved {armed}; review what landed",
4814                            pr.url, seen.head
4815                        );
4816                        tracing::warn!("{msg}");
4817                        state.event("land", msg);
4818                        // Only an arm left by an older build can get here.
4819                        // The wording is fixed so a repeat does not relight
4820                        // the notice.
4821                        crate::notices::raise_with(
4822                            crate::notices::Notice::warn(
4823                                &format!("merged-unapproved-head:{}", state.id),
4824                                "A pull request merged on a commit the owner did not approve; \
4825                                 review what landed",
4826                            )
4827                            .link(crate::notices::Link::Run {
4828                                id: state.id.clone(),
4829                            }),
4830                            &state.config.notify,
4831                        );
4832                    }
4833                }
4834                state.status = if merged {
4835                    RunStatus::Merged
4836                } else {
4837                    RunStatus::Ready
4838                };
4839                let detail = if merged {
4840                    format!("{} was merged", pr.url)
4841                } else {
4842                    format!("{} was closed without merging", pr.url)
4843                };
4844                state.merge = Some(MergeOutcome {
4845                    mode: MergeMode::Pr,
4846                    ok: merged,
4847                    detail: detail.clone(),
4848                    empty: false,
4849                });
4850                state.event("land", detail);
4851                state.save()?;
4852                write_pr_state_through(state, pr.state);
4853                return Ok(pr);
4854            }
4855            Step::Merge => {
4856                state.check_delivery_evidence(&seen.head)?;
4857                let subject = merge_subject(
4858                    crate::graph::landing_title(state, &seen.title),
4859                    &crate::graph::landing_subject_source(state),
4860                );
4861                // The owner sees the panel before the one irreversible step,
4862                // and an unanswered question is a hold: silence never merges.
4863                //
4864                // The dedicated policy includes existing consent and post-repair
4865                // decisions; repair choice availability never grants merge authority.
4866                let contested = contested_to_ask(state);
4867                if !approval_reasons(state).is_empty() {
4868                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
4869                        .await?
4870                    {
4871                        ApprovalGate::Approved => {}
4872                        ApprovalGate::Repair => {
4873                            // The driver consumes the saved request under the existing
4874                            // run/task claim. No merge, no second run or task.
4875                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4876                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4877                                state.save()?;
4878                            }
4879                            return Ok(pr);
4880                        }
4881                        ApprovalGate::Held => {
4882                            // Another entry point may have saved a stop after
4883                            // the first read above. Apply its durable action.
4884                            if owner_stop(state, &mut pr, forge).await? {
4885                                return Ok(pr);
4886                            }
4887                            stop(
4888                                state,
4889                                &repo,
4890                                &pr,
4891                                "the owner did not approve the merge (held or unanswered)",
4892                            )
4893                            .await?;
4894                            return Ok(pr);
4895                        }
4896                        // Filed (or still standing from an earlier visit) and
4897                        // not yet answered. Park here rather than wait: the
4898                        // question survives on disk, the daemon hands this
4899                        // run's slot to something else, and a later resume
4900                        // re-enters `land`, finds the same question, and
4901                        // either merges or stops depending on what it says
4902                        // by then.
4903                        ApprovalGate::Pending => {
4904                            state.end_pass_parked(crate::run::ParkCause::Question);
4905                            state.parked = true;
4906                            state.event(
4907                                "land",
4908                                "parked awaiting merge approval - resumes once answered",
4909                            );
4910                            state.save()?;
4911                            return Ok(pr);
4912                        }
4913                    }
4914                }
4915                // Open and past the gate above, so `seen.head` is the commit
4916                // the checks were bound to and the owner approved.
4917                //
4918                // Merge directly, bound to that commit. Auto-merge is not
4919                // armed any more: the forge checks `--match-head-commit` only
4920                // when the request is made, so an arm outlives the head it
4921                // was made for, and a push of another commit whose
4922                // requirements are met first would merge without approval.
4923                // A direct merge is checked by the forge at the moment it
4924                // happens, so only the approved head can land.
4925                let observed_head = seen.head.clone();
4926                // Read the pull request again just before: the state seen
4927                // above can be a moment old.
4928                {
4929                    let fresh = forge.view(&repo, pr_url).await.ok();
4930                    if fresh.as_ref().is_some_and(|current| {
4931                        current.pr.state == PrLifecycle::Open
4932                            && current.head.eq_ignore_ascii_case(&observed_head)
4933                            && Blocking::of(&current.merge_state) == Blocking::Behind
4934                    }) {
4935                        pr.blocking = Blocking::Behind;
4936                        let synced =
4937                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4938                                .await?;
4939                        let Some(head) = synced else {
4940                            return Ok(pr);
4941                        };
4942                        awaiting_head = Some(head);
4943                        rechecked = false;
4944                        waited = Duration::ZERO;
4945                        continue 'landing;
4946                    }
4947                    if !direct_merge_is_safe(
4948                        fresh.as_ref(),
4949                        &observed_head,
4950                        &shown,
4951                        round,
4952                        budget,
4953                        waited,
4954                        ci,
4955                    ) {
4956                        if waited >= WAIT_CEILING {
4957                            let why = "the pull request did not settle on the approved head \
4958                                       before it could be merged";
4959                            stop(state, &repo, &pr, why).await?;
4960                            return Ok(pr);
4961                        }
4962                        state.event(
4963                            "land",
4964                            "the pull request changed before merging; looking again",
4965                        );
4966                        waited += POLL;
4967                        forge.poll().await;
4968                        continue;
4969                    }
4970                }
4971                let argv = merge_argv_at(pr.number, &subject, &observed_head);
4972                let out = {
4973                    let merge_lock = repo_merge_lock(&repo);
4974                    let _merge_slot = merge_lock.lock().await;
4975                    crate::pr_head::ensure_owner(state)?;
4976                    if let Some(task_id) = state
4977                        .origin
4978                        .as_ref()
4979                        .and_then(|origin| origin.task.as_ref())
4980                    {
4981                        let task = crate::queue::Queue::open()
4982                            .get(task_id)
4983                            .context("cannot verify the task owner immediately before merge")?;
4984                        if task.execution_runs().last() != Some(&state.id)
4985                            || task.operator_held()
4986                            || task.status == crate::queue::TaskStatus::Done
4987                        {
4988                            bail!(
4989                                "task ownership or an operator hold superseded this merge approval"
4990                            );
4991                        }
4992                    }
4993                    if let Some(binding) = &state.land_approval {
4994                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
4995                        if merge_consent_superseded(state, &current)?
4996                            || current.run != state.id
4997                            || !binding.head.eq_ignore_ascii_case(&observed_head)
4998                            || approval(current.resolution().as_deref()) != Approval::Merge
4999                            || current.merge_target.as_ref().is_some_and(|t| {
5000                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
5001                            })
5002                        {
5003                            bail!(
5004                                "merge decision is stale or no longer authorizes the reviewed head"
5005                            );
5006                        }
5007                    }
5008                    forge.merge(&repo, &argv).await?
5009                };
5010                if out.0 {
5011                    // Exit 0 is not proof of a merge: with a merge queue `gh`
5012                    // enqueues (or reports the pull request already queued)
5013                    // and succeeds while it is still open. Ask the forge; an
5014                    // unreadable answer is not a confirmation either, so it
5015                    // is looked at again rather than recorded as merged.
5016                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
5017                        if c.pr.state == PrLifecycle::Merged {
5018                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
5019                            true
5020                        } else {
5021                            false
5022                        }
5023                    });
5024                    if !confirmed {
5025                        if waited >= WAIT_CEILING {
5026                            let why = "the merge request succeeded but the pull request \
5027                                       could not be confirmed merged after waiting";
5028                            stop(state, &repo, &pr, why).await?;
5029                            return Ok(pr);
5030                        }
5031                        state.event(
5032                            "land",
5033                            "merge accepted but the pull request is not confirmed merged yet; waiting",
5034                        );
5035                        state.save()?;
5036                        waited += POLL;
5037                        forge.poll().await;
5038                        continue;
5039                    }
5040                    pr.state = PrLifecycle::Merged;
5041                    state.status = RunStatus::Merged;
5042                    state.merge = Some(MergeOutcome {
5043                        mode: MergeMode::Pr,
5044                        ok: true,
5045                        detail: format!("gh {}", argv.join(" ")),
5046                        empty: false,
5047                    });
5048                    // The last `state.pr` snapshot is whatever the poll before
5049                    // this merge observed - still `open` - and nothing below
5050                    // refreshes it from GitHub again, so the UI's round rail
5051                    // would otherwise keep animating a merged run forever.
5052                    if let Some(pr_record) = state.pr.as_mut() {
5053                        pr_record.state = pr.state.as_str().to_owned();
5054                    }
5055                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5056                    announce_red_merge(state, &pr).await;
5057                    state.save()?;
5058                    write_pr_state_through(state, pr.state);
5059                    return Ok(pr);
5060                }
5061                let after_seen = forge.view(&repo, pr_url).await.ok();
5062                let after = after_seen.as_ref().map(|s| s.pr.state);
5063                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
5064                    state.pr_merged_head = after_seen
5065                        .as_ref()
5066                        .map(|s| s.head.clone())
5067                        .filter(|h| !h.is_empty());
5068                    pr.state = PrLifecycle::Merged;
5069                    state.status = RunStatus::Merged;
5070                    state.merge = Some(outcome);
5071                    if let Some(pr_record) = state.pr.as_mut() {
5072                        pr_record.state = pr.state.as_str().to_owned();
5073                    }
5074                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5075                    announce_red_merge(state, &pr).await;
5076                    state.save()?;
5077                    write_pr_state_through(state, pr.state);
5078                    return Ok(pr);
5079                }
5080                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
5081                match verdict {
5082                    Refused::Behind => {
5083                        pr.blocking = Blocking::Behind;
5084                        let synced =
5085                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5086                                .await?;
5087                        let Some(head) = synced else {
5088                            return Ok(pr);
5089                        };
5090                        awaiting_head = Some(head);
5091                        rechecked = false;
5092                        waited = Duration::ZERO;
5093                        continue 'landing;
5094                    }
5095                    Refused::Final => {
5096                        let merge_state = after_seen
5097                            .as_ref()
5098                            .map(|s| s.merge_state.as_str())
5099                            .filter(|m| !m.is_empty())
5100                            .unwrap_or("unknown");
5101                        // Which refusal this was decides what a person has to
5102                        // do about it, so the two are worded apart; both carry
5103                        // the forge's own message.
5104                        let why = format!(
5105                            "the merge was refused: {} (merge state: {merge_state})",
5106                            out.1
5107                        );
5108                        stop(state, &repo, &pr, &why).await?;
5109                        return Ok(pr);
5110                    }
5111                    verdict => {
5112                        // Back to the top, which re-decides and passes the
5113                        // approval gate again, a poll later. `waited` is not
5114                        // reset here: only a pushed fix restarts it, or a
5115                        // standing refusal would wait forever.
5116                        if waited >= WAIT_CEILING {
5117                            let why = format!(
5118                                "the merge was still refused after {} minutes: {}",
5119                                WAIT_CEILING.as_secs() / 60,
5120                                out.1
5121                            );
5122                            stop(state, &repo, &pr, &why).await?;
5123                            return Ok(pr);
5124                        }
5125                        if verdict == Refused::Recheck {
5126                            rechecked = true;
5127                        }
5128                        state.event(
5129                            "land",
5130                            "merge refused while the branch policy is not satisfied yet; waiting",
5131                        );
5132                        state.save()?;
5133                        waited += POLL;
5134                        forge.poll().await;
5135                    }
5136                }
5137            }
5138            Step::Rebase => {
5139                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
5140                let Some(head) = synced else {
5141                    return Ok(pr);
5142                };
5143                awaiting_head = Some(head);
5144                rechecked = false;
5145                waited = Duration::ZERO;
5146                continue 'landing;
5147            }
5148            Step::GiveUp { reason } => {
5149                stop(state, &repo, &pr, &reason).await?;
5150                return Ok(pr);
5151            }
5152            Step::Fix { reason } => {
5153                round += 1;
5154                waited = Duration::ZERO;
5155                for c in &pr.review_comments {
5156                    shown.insert(c.body.clone());
5157                }
5158                state.event("land", format!("round {round}: {reason}"));
5159                state.save()?;
5160
5161                let logs = failing_logs(&repo, &seen.failing_urls).await;
5162                let was_red = pr.checks == Checks::Red;
5163                if owner_stop(state, &mut pr, forge).await? {
5164                    return Ok(pr);
5165                }
5166                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
5167                if owner_stop(state, &mut pr, forge).await? {
5168                    return Ok(pr);
5169                }
5170                match fixed {
5171                    Fixed::Committed { head } => {
5172                        // Whatever the next look shows may still be the
5173                        // previous head; see `awaiting_new_head`.
5174                        state.pr_pushed_head = Some(head.clone());
5175                        awaiting_head = Some(head);
5176                        rechecked = false;
5177                        waited = Duration::ZERO;
5178                        forge.poll().await;
5179                    }
5180                    Fixed::Declined if was_red => {
5181                        // Review comments may have required this round even
5182                        // when CI was unrelated. Once the fixer has read them,
5183                        // use the same structural attribution before charging
5184                        // a no-commit stop to the task.
5185                        if let Some(evidence) = forge.attribution(state, &seen).await
5186                            && evidence.unrelated(&seen.head, &pr.failing)
5187                        {
5188                            let fresh = forge.view(&repo, pr_url).await?;
5189                            if fresh.head != seen.head
5190                                || fresh.rollup_head != seen.rollup_head
5191                                || fresh.pr.state != PrLifecycle::Open
5192                                || fresh.pr.checks != Checks::Red
5193                                || fresh.pr.failing != pr.failing
5194                                || fresh
5195                                    .pr
5196                                    .review_comments
5197                                    .iter()
5198                                    .any(|c| !shown.contains(&c.body))
5199                            {
5200                                continue;
5201                            }
5202                            if owner_stop(state, &mut pr, forge).await? {
5203                                return Ok(pr);
5204                            }
5205                            hold_unrelated(state, &pr, evidence).await?;
5206                            return Ok(pr);
5207                        }
5208                        let why = format!(
5209                            "the fixer produced no commit while {} check(s) were failing \
5210                             ({}); stopping instead of looping on an unchanged tree",
5211                            pr.failing.len(),
5212                            pr.failing.join(", ")
5213                        );
5214                        stop(state, &repo, &pr, &why).await?;
5215                        return Ok(pr);
5216                    }
5217                    // Comment-driven round with no commit: the fixer read the
5218                    // comments and changed nothing, which is a decision it is
5219                    // allowed to make. The comments are recorded as shown, so
5220                    // the next observation sees a clean pull request.
5221                    Fixed::Declined => state.event(
5222                        "land",
5223                        format!("round {round}: fixer declined the comments, nothing committed"),
5224                    ),
5225                    Fixed::Deferred => {
5226                        // No fixer was available to judge these comments or
5227                        // checks. Keep the previous completed-round count and
5228                        // return without handing the PR off as a task failure.
5229                        state.status = RunStatus::Blocked;
5230                        state.save()?;
5231                        return Ok(pr);
5232                    }
5233                    Fixed::Failed(why) => {
5234                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5235                        return Ok(pr);
5236                    }
5237                }
5238                state.save()?;
5239            }
5240        }
5241    }
5242}
5243
5244/// Owner decision for a CI failure independently reproduced on the base.
5245pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5246
5247/// Durable machine-hold evidence, bound to one observed PR head.
5248#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5249pub struct CiHold {
5250    /// Head that exhibited the independently reproduced failures.
5251    pub head: String,
5252    /// Typed owner question controlling resumption.
5253    pub question: String,
5254    /// Complete structured facts used to attribute the failures.
5255    pub evidence: CiEvidence,
5256}
5257
5258/// Only structured forge annotations are compared, never log prose.
5259#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5260struct CiFailure {
5261    path: String,
5262    start_line: u64,
5263    end_line: u64,
5264    title: String,
5265    message: String,
5266}
5267
5268#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5269struct CiCheckEvidence {
5270    label: String,
5271    head_check: u64,
5272    base_check: u64,
5273    app: u64,
5274    run: String,
5275    base_run: String,
5276    head_failures: Vec<CiFailure>,
5277    base_failures: Vec<CiFailure>,
5278    rerun_exhausted: bool,
5279}
5280
5281/// Pinned Git diff and forge failure annotations used for CI attribution.
5282#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5283pub struct CiEvidence {
5284    head: String,
5285    base: String,
5286    changed: Vec<String>,
5287    checks: Vec<CiCheckEvidence>,
5288}
5289
5290impl CiEvidence {
5291    /// Every red check must have the same located failure on the base, outside
5292    /// the diff. Changes to CI/build configuration invalidate this inference.
5293    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5294        if self.head != head
5295            || self.base.is_empty()
5296            || failing.is_empty()
5297            || self.changed.iter().any(|p| {
5298                p.starts_with(".github/")
5299                    || p.starts_with(".config/")
5300                    || p.starts_with(".cargo/")
5301                    || matches!(
5302                        p.rsplit('/').next().unwrap_or(p),
5303                        "Cargo.toml"
5304                            | "Cargo.lock"
5305                            | "Makefile.toml"
5306                            | "build.rs"
5307                            | "rust-toolchain.toml"
5308                    )
5309            })
5310        {
5311            return false;
5312        }
5313        failing.iter().all(|label| {
5314            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5315            matches.len() == 1
5316                && matches[0].rerun_exhausted
5317                && !matches[0].head_failures.is_empty()
5318                && matches[0].head_failures.iter().all(|f| {
5319                    // Workflow-level exit-code annotations do not identify a
5320                    // failing test or source file, and prove nothing here.
5321                    !f.path.is_empty()
5322                        && !f.path.starts_with('.')
5323                        && !f.path.contains("..")
5324                        && !f.path.starts_with('/')
5325                        && !self.changed.contains(&f.path)
5326                        && matches[0].base_failures.contains(f)
5327                })
5328        })
5329    }
5330}
5331
5332async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5333    let out = gh(repo, &["api".into(), endpoint]).await.ok()?;
5334    if !out.ok {
5335        return None;
5336    }
5337    serde_json::from_str(&out.stdout).ok()
5338}
5339
5340async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5341    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5342    if count == 0 || count >= 100 {
5343        return None;
5344    }
5345    let id = check.get("id")?.as_u64()?;
5346    let value = ci_json(
5347        repo,
5348        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5349    )
5350    .await?;
5351    let annotations = value.as_array()?;
5352    if annotations.len() != count as usize {
5353        return None;
5354    }
5355    annotations
5356        .iter()
5357        .filter(|a| a["annotation_level"] == "failure")
5358        .map(|a| {
5359            Some(CiFailure {
5360                path: a["path"].as_str()?.into(),
5361                start_line: a["start_line"].as_u64()?,
5362                end_line: a["end_line"].as_u64()?,
5363                title: a["title"].as_str()?.into(),
5364                message: a["message"].as_str()?.into(),
5365            })
5366        })
5367        .collect()
5368}
5369
5370async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5371    let value = ci_json(
5372        repo,
5373        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5374    )
5375    .await?;
5376    let runs = value["check_runs"].as_array()?;
5377    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5378        return None;
5379    }
5380    Some(runs.clone())
5381}
5382
5383async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5384    let repo = &state.repo;
5385    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5386    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5387        .await
5388        .ok()?;
5389    if !base.ok() {
5390        return None;
5391    }
5392    let range = format!("{}...{}", base.stdout, seen.head);
5393    // No rename detection: both old and new paths must count as changed.
5394    let diff = git::git_raw(
5395        repo,
5396        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5397    )
5398    .await
5399    .ok()?;
5400    if !diff.ok() {
5401        return None;
5402    }
5403    let head_runs = ci_runs(repo, &seen.head).await?;
5404    let base_runs = ci_runs(repo, &base.stdout).await?;
5405    let mut checks = Vec::new();
5406    for label in &seen.pr.failing {
5407        let matching = |runs: &[serde_json::Value]| {
5408            runs.iter()
5409                .filter(|r| r["name"].as_str() == Some(label))
5410                .cloned()
5411                .collect::<Vec<_>>()
5412        };
5413        let heads = matching(&head_runs);
5414        let bases = matching(&base_runs);
5415        if heads.len() != 1 || bases.len() != 1 {
5416            return None;
5417        }
5418        let h = &heads[0];
5419        let b = &bases[0];
5420        if h["conclusion"] != "failure"
5421            || b["conclusion"] != "failure"
5422            || h["status"] != "completed"
5423            || b["status"] != "completed"
5424            || h["head_sha"].as_str()? != seen.head
5425            || b["head_sha"].as_str()? != base.stdout
5426            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5427        {
5428            return None;
5429        }
5430        let run = run_of(h["details_url"].as_str()?)?;
5431        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5432        if contexts.len() != 1
5433            || contexts[0].run.as_ref() != Some(&run)
5434            || contexts[0].verdict != Verdict::Fail
5435        {
5436            return None;
5437        }
5438        // A persisted request alone is not a completed rerun: require the
5439        // workflow's structured attempt number as well.
5440        let workflow =
5441            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5442        let base_run = run_of(b["details_url"].as_str()?)?;
5443        let base_workflow = ci_json(
5444            repo,
5445            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5446        )
5447        .await?;
5448        if base_workflow["head_sha"].as_str()? != base.stdout
5449            || base_workflow["head_branch"].as_str()? != seen.base
5450            || base_workflow["status"] != "completed"
5451            || base_workflow["conclusion"] != "failure"
5452            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5453        {
5454            return None;
5455        }
5456        let exhausted = state
5457            .land_reruns
5458            .as_ref()
5459            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5460            && workflow["head_sha"].as_str()? == seen.head
5461            && workflow["run_attempt"].as_u64()? > 1
5462            && workflow["status"] == "completed";
5463        checks.push(CiCheckEvidence {
5464            label: label.clone(),
5465            head_check: h["id"].as_u64()?,
5466            base_check: b["id"].as_u64()?,
5467            app: h.pointer("/app/id")?.as_u64()?,
5468            run,
5469            base_run,
5470            head_failures: ci_annotations(repo, h).await?,
5471            base_failures: ci_annotations(repo, b).await?,
5472            rerun_exhausted: exhausted,
5473        });
5474    }
5475    Some(CiEvidence {
5476        head: seen.head.clone(),
5477        base: base.stdout,
5478        changed: diff
5479            .stdout
5480            .split('\0')
5481            .filter(|p| !p.is_empty())
5482            .map(str::to_owned)
5483            .collect(),
5484        checks,
5485    })
5486}
5487
5488async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5489    let detail = serde_json::to_string(&evidence)?;
5490    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5491    let hold = "operator: 保留して後で判断する".to_owned();
5492    let mut q = ask::Question::new(
5493        state.id.clone(),
5494        CI_HOLD_NODE.into(),
5495        "land".into(),
5496        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5497        format!(
5498            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5499        ),
5500        vec![resume.clone(), hold.clone()],
5501    );
5502    q.actions.insert(
5503        resume,
5504        ask::ChoiceAction::Resume {
5505            run: state.id.clone(),
5506        },
5507    );
5508    q.actions.insert(hold, ask::ChoiceAction::Hold);
5509    ask::Questions::open().put_executable(&mut q)?;
5510    state.land_unrelated = Some(CiHold {
5511        head: evidence.head.clone(),
5512        question: q.id.clone(),
5513        evidence,
5514    });
5515    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5516    state.end_pass_parked(crate::run::ParkCause::Question);
5517    state.parked = true;
5518    state.save()?;
5519    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5520        tracing::warn!("could not notify about CI hold: {e:#}");
5521    }
5522    // A durable question and evidence are sufficient even if commenting fails.
5523    let body = stop_comment(
5524        &state.id,
5525        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5526    );
5527    let (_, body) = crate::github_text::prepare(state, "", &body);
5528    gh(
5529        &state.repo,
5530        &[
5531            "pr".into(),
5532            "comment".into(),
5533            pr.number.to_string(),
5534            "--body".into(),
5535            body,
5536        ],
5537    )
5538    .await
5539    .ok();
5540    Ok(())
5541}
5542
5543/// One observation, plus the two things [`PrState`] deliberately does not carry:
5544/// the title (needed for the squash subject) and where the failing checks'
5545/// logs live.
5546#[derive(Clone)]
5547struct Seen {
5548    pr: PrState,
5549    title: String,
5550    failing_urls: Vec<(String, String)>,
5551    /// `headRefOid`: the commit this observation, checks included, is about.
5552    head: String,
5553    /// The commit the checks belong to, read from the same GraphQL node as
5554    /// the checks themselves. Empty when unreadable.
5555    rollup_head: String,
5556    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5557    /// and DRAFT together, and a stop reason has to say which.
5558    merge_state: String,
5559    /// Every check of the rollup, for naming what an armed merge waits on.
5560    contexts: Vec<CheckInfo>,
5561    /// `baseRefName`, to look up which contexts the base requires.
5562    base: String,
5563}
5564
5565/// One check of the rollup as far as a stop reason needs it.
5566#[derive(Clone)]
5567struct CheckInfo {
5568    label: String,
5569    verdict: Verdict,
5570    required: Option<bool>,
5571    /// The workflow run the check belongs to; `None` for an external status.
5572    run: Option<String>,
5573}
5574
5575/// What to do with a red head before a fix round is spent on it.
5576#[derive(Debug, Clone, PartialEq, Eq)]
5577enum RerunStep {
5578    /// Rerun these workflow runs (each not yet rerun for this head).
5579    Rerun(Vec<String>),
5580    /// Reran already and the forge may still report the old failure: wait.
5581    Grace,
5582    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5583    Fix,
5584}
5585
5586/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5587/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5588/// pending checks in another run do not delay this run's rerun.
5589#[cfg(test)]
5590fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5591    rerunnable_with(contexts, false)
5592}
5593
5594fn rerunnable_with(
5595    contexts: &[CheckInfo],
5596    include_optional: bool,
5597) -> Vec<(String, Option<String>)> {
5598    contexts
5599        .iter()
5600        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5601        // `gh run rerun --failed` refuses a run with a job still going.
5602        .filter(|c| {
5603            c.run.as_ref().is_none_or(|r| {
5604                !contexts.iter().any(|o| {
5605                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5606                        && o.run.as_ref() == Some(r)
5607                })
5608            })
5609        })
5610        .map(|c| (c.label.clone(), c.run.clone()))
5611        .collect()
5612}
5613
5614/// Pure: rerun once per run id, wait out the grace, then hand over.
5615fn rerun_step(
5616    failing: &[(String, Option<String>)],
5617    record: Option<&LandReruns>,
5618    head: &str,
5619    now: i64,
5620) -> RerunStep {
5621    // A failure with no workflow run (an external status) cannot be rerun, and
5622    // the fixer's push re-runs everything anyway.
5623    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5624        return RerunStep::Fix;
5625    }
5626    // Reruns belong to the head they were made on.
5627    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5628    let mut fresh: Vec<String> = Vec::new();
5629    let mut recent = false;
5630    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5631        match record.and_then(|r| r.runs.get(run)) {
5632            None => {
5633                if !fresh.iter().any(|f| f == run) {
5634                    fresh.push(run.to_owned());
5635                }
5636            }
5637            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5638            Some(_) => {}
5639        }
5640    }
5641    if !fresh.is_empty() {
5642        RerunStep::Rerun(fresh)
5643    } else if recent {
5644        RerunStep::Grace
5645    } else {
5646        RerunStep::Fix
5647    }
5648}
5649
5650/// Read minimal live PR metadata (`url`, `number`, `state`, `headRefOid`,
5651/// `baseRefName`) for landing base-sync recovery admission and dispatch checks.
5652pub(crate) async fn observe_pr_summary(
5653    repo: &Path,
5654    pr_url: &str,
5655) -> Result<crate::land_sync_recovery::ObservedPr> {
5656    #[derive(serde::Deserialize)]
5657    struct Summary {
5658        #[serde(default)]
5659        url: String,
5660        #[serde(default)]
5661        number: u64,
5662        #[serde(default)]
5663        state: String,
5664        #[serde(default, rename = "headRefOid")]
5665        head_ref_oid: String,
5666        #[serde(default, rename = "baseRefName")]
5667        base_ref_name: String,
5668    }
5669    let view = gh(
5670        repo,
5671        &[
5672            "pr".to_owned(),
5673            "view".to_owned(),
5674            pr_url.to_owned(),
5675            "--json".to_owned(),
5676            "url,number,state,headRefOid,baseRefName".to_owned(),
5677        ],
5678    )
5679    .await?;
5680    if !view.ok {
5681        bail!("gh pr view {pr_url}: {}", view.combined());
5682    }
5683    let parsed: Summary = serde_json::from_str(&view.stdout).context("parse pull request json")?;
5684    Ok(crate::land_sync_recovery::ObservedPr {
5685        url: parsed.url,
5686        number: parsed.number,
5687        open: parsed.state.eq_ignore_ascii_case("OPEN"),
5688        head: parsed.head_ref_oid,
5689        base_branch: (!parsed.base_ref_name.is_empty()).then_some(parsed.base_ref_name),
5690    })
5691}
5692
5693/// Read the pull request: `gh pr view` for the top-level thread and merge
5694/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5695/// inline review comments `gh pr view` does not report.
5696async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5697    let view = gh(
5698        repo,
5699        &[
5700            "pr".to_owned(),
5701            "view".to_owned(),
5702            pr_url.to_owned(),
5703            "--json".to_owned(),
5704            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5705                .to_owned(),
5706        ],
5707    )
5708    .await?;
5709    if !view.ok {
5710        bail!("gh pr view {pr_url}: {}", view.combined());
5711    }
5712    let number = parse_pr(&view.stdout)?.number;
5713    let node = last_commit_node(repo, number).await;
5714    let mut seen = seen_from(&view.stdout, node.as_deref())?;
5715
5716    let inline = gh(
5717        repo,
5718        &[
5719            "api".to_owned(),
5720            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5721        ],
5722    )
5723    .await?;
5724    if inline.ok {
5725        match parse_inline_comments(&inline.stdout) {
5726            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5727            // An unreadable inline thread must not end a landing: the rollup
5728            // and the top-level thread are still real signal.
5729            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5730        }
5731    } else {
5732        tracing::warn!(
5733            "gh api pulls/{}/comments: {}",
5734            seen.pr.number,
5735            inline.combined()
5736        );
5737    }
5738    Ok(seen)
5739}
5740
5741/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
5742/// response. No I/O.
5743///
5744/// The commit oid and the checks are read from the *same* node, so the rollup
5745/// is bound to the commit it belongs to by construction; two reads that agree
5746/// before and after another response prove nothing about what that response
5747/// held. The view's own rollup is never used. A node that is missing,
5748/// unreadable, carries GraphQL errors, or whose checks run past the page
5749/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
5750/// as "look again" and never as a reason to merge.
5751fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5752    let mut pr = parse_pr(view_json)?;
5753    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5754
5755    let mut rollup_head = String::new();
5756    let mut failing_urls = Vec::new();
5757    let mut contexts = Vec::new();
5758    let mut checks = Checks::Unknown;
5759    let mut failing = Vec::new();
5760    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5761        (checks, failing) = rollup_verdict(&rollup);
5762        failing_urls = rollup
5763            .iter()
5764            .filter(|c| c.verdict() == Verdict::Fail)
5765            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5766            .collect();
5767        contexts = rollup
5768            .iter()
5769            .map(|c| CheckInfo {
5770                label: c.label(),
5771                verdict: c.verdict(),
5772                required: c.is_required,
5773                run: c.url().and_then(run_of),
5774            })
5775            .collect();
5776        rollup_head = oid;
5777    }
5778    pr.checks = checks;
5779    pr.failing = failing;
5780
5781    Ok(Seen {
5782        pr,
5783        title: raw.title,
5784        failing_urls,
5785        head: raw.head_ref_oid,
5786        rollup_head,
5787        merge_state: raw.merge_state_status,
5788        contexts,
5789        base: raw.base_ref_name,
5790    })
5791}
5792
5793/// The last commit's oid and its checks from one GraphQL response, `None`
5794/// when anything about it cannot be trusted.
5795fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
5796    let v: serde_json::Value = serde_json::from_str(json).ok()?;
5797    if v.get("errors").is_some_and(|e| !e.is_null()) {
5798        return None;
5799    }
5800    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
5801    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
5802    let contexts = commit.pointer("/statusCheckRollup/contexts");
5803    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
5804        // No rollup at all: the commit has no checks.
5805        return Some((oid.to_owned(), Vec::new()));
5806    };
5807    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
5808        return None;
5809    }
5810    let nodes = contexts.get("nodes")?.as_array()?;
5811    let rollup = nodes
5812        .iter()
5813        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
5814        .collect::<Result<Vec<_>, _>>()
5815        .ok()?;
5816    Some((oid.to_owned(), rollup))
5817}
5818
5819/// The pull request's last commit and its checks, in one response. `None`
5820/// when the forge could not be asked.
5821async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
5822    let out = gh(
5823        repo,
5824        &[
5825            "api".to_owned(),
5826            "graphql".to_owned(),
5827            "-F".to_owned(),
5828            "owner={owner}".to_owned(),
5829            "-F".to_owned(),
5830            "repo={repo}".to_owned(),
5831            "-F".to_owned(),
5832            format!("number={number}"),
5833            "-f".to_owned(),
5834            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
5835             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
5836             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
5837             ... on CheckRun{name status conclusion detailsUrl \
5838             isRequired(pullRequestNumber:$number)} \
5839             ... on StatusContext{context state targetUrl \
5840             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
5841                .to_owned(),
5842        ],
5843    )
5844    .await
5845    .ok()?;
5846    out.ok.then_some(out.stdout)
5847}
5848
5849/// What a fix round did.
5850#[doc(hidden)]
5851#[derive(Debug, PartialEq)]
5852pub enum Fixed {
5853    /// The fixer committed something, and this is the head that was pushed.
5854    Committed {
5855        /// The commit now at the tip of the pushed branch.
5856        head: String,
5857    },
5858    /// The fixer ran and chose to change nothing.
5859    Declined,
5860    /// Machine availability prevented a result; retry this round on resume.
5861    Deferred,
5862    /// The fixer could not run, or said nothing usable.
5863    Failed(String),
5864}
5865
5866/// Hand the failures and the comments to the fixer, then commit and push.
5867///
5868/// The fixer works in the winner's own worktree so its commits land on the
5869/// branch the pull request is built from, and it runs with `allow_write` for
5870/// the same reason.
5871#[doc(hidden)]
5872pub async fn fix_round(
5873    state: &mut RunState,
5874    pr: &PrState,
5875    round: usize,
5876    budget: usize,
5877    reason: &str,
5878    logs: &str,
5879) -> Result<Fixed> {
5880    let winner = state
5881        .winner()
5882        .cloned()
5883        .context("landing needs a winning candidate; none is recorded on this run")?;
5884    let roles = state
5885        .config
5886        .resolve_roles()
5887        .context("resolve the roster for the fix round")?;
5888    // Same chain as the review loop (see `crate::fixer`): the configured
5889    // fixers in order, otherwise the winner's own author continuing its own
5890    // conversation - the competition is over, so its context is pure benefit.
5891    let attempts = crate::fixer::attempts(state, &roles, &winner);
5892    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
5893
5894    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
5895    let mut artifacts = agent::artifacts_dir(&state.dir());
5896    if let Some(request) = state
5897        .merge_repairs
5898        .last()
5899        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
5900    {
5901        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
5902    }
5903    let prompt =
5904        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
5905            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
5906        } else {
5907            prompt
5908        };
5909    // Read before the fixer runs: it normally commits for itself, so HEAD has
5910    // already moved by the time it returns and a later read would see no
5911    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
5912    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5913    // Each id at most once, forward only: the next one is asked only when the
5914    // call advances, and only the last attempt's result is judged below, so an
5915    // exhausted chain ends as a single failed fixer does.
5916    let mut last = None;
5917    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
5918        if owner_requested_stop(state)? {
5919            return Ok(Fixed::Declined);
5920        }
5921        let mut seat = seat_of(state, &seat_key, &spec.id);
5922        let stem = if i == 0 {
5923            format!("land-{round}")
5924        } else {
5925            format!("land-{round}-{}", spec.id)
5926        };
5927        let out = agent::invoke(
5928            &spec,
5929            &mut seat,
5930            &Invocation {
5931                coordination: state.config.coordination.as_ref(),
5932                fetched_base: state.fetched_base.as_ref(),
5933                cwd: &winner.worktree,
5934                prompt: &prompt,
5935                timeout: Duration::from_secs(state.config.graph.timeout_fix),
5936                allow_write: true,
5937                sessions: state.config.graph.sessions,
5938                artifacts: &artifacts,
5939                stem: &stem,
5940                run: &state.id,
5941                node: "land",
5942                cache_dir: state.config.cache_dir().as_deref(),
5943                attachments: &[],
5944                writable: &[],
5945            },
5946        )
5947        .await;
5948        state.seats.insert(seat.key.clone(), seat);
5949        if let Some(next) = ids.get(i + 1)
5950            && agent::chain_advances(&out)
5951        {
5952            let (class, why) = crate::fixer::failure_of(&out);
5953            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
5954            continue;
5955        }
5956        last = Some((seat_key, out));
5957        break;
5958    }
5959    let (seat_key, out) = last.expect("the fixer chain always has an entry");
5960
5961    match out {
5962        Ok(o) if o.quota_exhausted() => {
5963            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
5964            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
5965            state.quota.push(loss);
5966            state.status = RunStatus::Blocked;
5967            state.save()?;
5968            // Keep partial edits reachable on the winner branch and leave a
5969            // clean tree for resume_landing_head. The resumed landing gates
5970            // this new commit before it can publish it; no push happens here.
5971            let inherited = crate::repo_lock::WaitPolicy::current();
5972            let wait = crate::repo_lock::WaitPolicy::new(
5973                Duration::from_secs(state.config.graph.timeout_resource_wait),
5974                move || inherited.cancelled(),
5975            );
5976            let _coordination = crate::repo_lock::SeatLease::operation_with(
5977                &winner.worktree,
5978                state.config.coordination.as_ref(),
5979                &wait,
5980            )
5981            .await?;
5982            let rescue = git::rescue_commit(
5983                &winner.worktree,
5984                &format!("magi: deferred land round {round} (uncommitted work)"),
5985            )
5986            .await?;
5987            state.note_withheld("land", &rescue.withheld);
5988            state.save()?;
5989            return Ok(Fixed::Deferred);
5990        }
5991        Ok(o) if !o.usable() => {
5992            return Ok(Fixed::Failed(format!(
5993                "the fixer produced nothing usable ({})",
5994                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
5995            )));
5996        }
5997        Ok(_) => {}
5998        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
5999        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
6000    }
6001
6002    if owner_requested_stop(state)? {
6003        return Ok(Fixed::Declined);
6004    }
6005
6006    // An agent that edited files but never committed would otherwise push
6007    // nothing and look like a refusal.
6008    let wait = crate::repo_lock::WaitPolicy::new(
6009        Duration::from_secs(state.config.graph.timeout_resource_wait),
6010        || false,
6011    );
6012    let coordination = crate::repo_lock::SeatLease::operation_with(
6013        &winner.worktree,
6014        state.config.coordination.as_ref(),
6015        &wait,
6016    )
6017    .await?;
6018    match git::rescue_commit(
6019        &winner.worktree,
6020        &format!("magi: land round {round} fixes (uncommitted work)"),
6021    )
6022    .await
6023    {
6024        Ok(r) => state.note_withheld("land", &r.withheld),
6025        Err(e)
6026            if state
6027                .merge_repairs
6028                .last()
6029                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
6030        {
6031            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
6032        }
6033        Err(_) => {}
6034    }
6035    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
6036    drop(coordination);
6037    if after == before {
6038        return Ok(Fixed::Declined);
6039    }
6040
6041    if owner_requested_stop(state)? {
6042        return Ok(Fixed::Declined);
6043    }
6044    crate::pr_head::ensure_owner(state)?;
6045    let remote = state.config.merge.remote.clone();
6046    anyhow::ensure!(
6047        crate::foreign_checkout::write_back(state, &after).await?,
6048        "foreign checkout delivery is blocked; see the run events"
6049    );
6050    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
6051    let push = if state.pr_head.is_some() {
6052        let expected = state
6053            .pr_pushed_head
6054            .as_deref()
6055            .context("missing public head lease")?;
6056        git::push_as(
6057            &winner.worktree,
6058            &remote,
6059            &winner.branch,
6060            &public_head,
6061            expected,
6062        )
6063        .await?
6064    } else {
6065        git::push(&winner.worktree, &remote, &winner.branch).await?
6066    };
6067    if !push.ok() {
6068        return Ok(Fixed::Failed(format!(
6069            "pushing {} to {remote} failed: {}",
6070            public_head, push.stderr
6071        )));
6072    }
6073    state.event(
6074        "land",
6075        format!("round {round}: pushed a fix to {public_head}"),
6076    );
6077    state.pr_pushed_head = Some(after.clone());
6078    state.save()?;
6079    Ok(Fixed::Committed { head: after })
6080}
6081
6082/// Fetch or create a seat, keeping its conversation across nodes.
6083pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
6084    crate::fixer::seat_for(state, key, agent)
6085}
6086
6087/// Recheck the live PR and local worktree before spending the requested fix.
6088/// A moved/closed PR is held, never repaired using obsolete evidence.
6089pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
6090    let seen = observe(&state.repo, url).await?;
6091    let winner = state.winner().context("no winning branch to repair")?;
6092    if seen.pr.state != PrLifecycle::Open || seen.head != head {
6093        anyhow::bail!(
6094            "PR is closed or its head changed; review the current head before requesting repair again"
6095        );
6096    }
6097    if git::rev_parse(&winner.worktree, "HEAD").await? != head
6098        || !git::is_clean(&winner.worktree).await?
6099    {
6100        anyhow::bail!(
6101            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
6102        );
6103    }
6104    // Always disable any forge-side reservation, including one not recorded
6105    // by this run. A repair request is never merge authorization.
6106    let view = gh(
6107        &state.repo,
6108        &[
6109            "pr".into(),
6110            "view".into(),
6111            url.into(),
6112            "--json".into(),
6113            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
6114        ],
6115    )
6116    .await?;
6117    if !view.ok {
6118        bail!("cannot check auto-merge: {}", view.combined());
6119    }
6120    let live: serde_json::Value = serde_json::from_str(&view.stdout)?;
6121    let public = state.pr_branch().unwrap_or(&winner.branch);
6122    if live["state"] != "OPEN"
6123        || live["headRefOid"] != head
6124        || live["headRefName"] != public
6125        || live["baseRefName"] != state.base_branch
6126        || live["isCrossRepository"] != false
6127    {
6128        bail!("PR changed during repair preflight; review its current head explicitly");
6129    }
6130    let auto_merge = live
6131        .get("autoMergeRequest")
6132        .context("cannot read the PR auto-merge reservation; repair held")?;
6133    if !auto_merge.is_null() {
6134        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
6135        if !out.ok {
6136            bail!("cannot disable auto-merge; repair held: {}", out.combined());
6137        }
6138    }
6139    Ok(seen.pr)
6140}
6141
6142/// What the fixer is told.
6143fn fix_prompt(
6144    state: &RunState,
6145    pr: &PrState,
6146    round: usize,
6147    budget: usize,
6148    reason: &str,
6149    logs: &str,
6150) -> String {
6151    let mut s = format!(
6152        "Your patch is open as a pull request and it is not landing. Land round \
6153         {round} of {budget}.\n\n\
6154         Pull request: {}\n\n\
6155         What is holding it: {reason}\n\n\
6156         # The task\n\n{}\n",
6157        pr.url, state.instruction
6158    );
6159
6160    if pr.failing.is_empty() {
6161        s.push_str("\n# Failing checks\n\n(none)\n");
6162    } else {
6163        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
6164        if logs.trim().is_empty() {
6165            s.push_str(
6166                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
6167            );
6168        } else {
6169            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
6170        }
6171    }
6172
6173    if pr.review_comments.is_empty() {
6174        s.push_str("\n# Review comments\n\n(none)\n");
6175    } else {
6176        s.push_str("\n# Review comments\n");
6177        for c in &pr.review_comments {
6178            let where_ = match (&c.path, c.line) {
6179                (Some(p), Some(l)) => format!(" ({p}:{l})"),
6180                (Some(p), None) => format!(" ({p})"),
6181                _ => String::new(),
6182            };
6183            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
6184        }
6185    }
6186
6187    s.push_str(
6188        "\n# Rules\n\n\
6189         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
6190            failing test; do not silence a lint with an allow attribute; do not \
6191            stretch a timeout to hide a race. If the check is right, the code is \
6192            wrong.\n\
6193         2. Change nothing the checks and the comments did not raise. A \
6194            drive-by refactor turns a one-line fix into a pull request that \
6195            needs reviewing again.\n\
6196         3. If a comment is wrong, say so with a checkable argument and change \
6197            nothing for it. A declined comment with a reason is a correct \
6198            outcome; a change made to appease a reviewer is not.\n\
6199         4. Commit in this worktree. magi pushes to the pull request's branch \
6200            for you; do not push, merge, or close anything yourself.\n\
6201         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
6202         # Output\n\n\
6203         Say what you changed and why, and what you declined and why.",
6204    );
6205
6206    let language = &state.config.graph.language;
6207    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
6208        let _ = write!(s, "\n\nWrite all prose in {language}.");
6209    }
6210    // After the language line, so the exception is the last word on it.
6211    s.push_str(&crate::prompt::github_rule(
6212        language,
6213        &state.config.graph.github_language,
6214    ));
6215    if let Some(overlay) = state.config.prompts.overlay("fix") {
6216        let _ = write!(s, "\n\n{overlay}");
6217    }
6218    s.push('\n');
6219    s.push_str(crate::prompt::child_run_ownership());
6220    s
6221}
6222
6223/// Failing log tails, the way the operator collects them by hand:
6224/// `gh run view --log-failed`.
6225async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6226    let mut out = String::new();
6227    for (name, url) in failing.iter().take(MAX_LOGS) {
6228        let args = match (job_of(url), run_of(url)) {
6229            (Some(job), _) => vec![
6230                "run".to_owned(),
6231                "view".to_owned(),
6232                "--log-failed".to_owned(),
6233                "--job".to_owned(),
6234                job,
6235            ],
6236            (None, Some(run)) => vec![
6237                "run".to_owned(),
6238                "view".to_owned(),
6239                run,
6240                "--log-failed".to_owned(),
6241            ],
6242            // Not a GitHub Actions check - an external status has no log here.
6243            (None, None) => continue,
6244        };
6245        let (ok, body) = match gh(repo, &args).await {
6246            Ok(v) => (v.ok, v.combined()),
6247            Err(e) => (false, format!("{e:#}")),
6248        };
6249        if !ok && body.trim().is_empty() {
6250            continue;
6251        }
6252        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6253    }
6254    out
6255}
6256
6257/// Job id out of a check's `detailsUrl`
6258/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
6259fn job_of(details_url: &str) -> Option<String> {
6260    let after = details_url.split("/job/").nth(1)?;
6261    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6262    (!id.is_empty()).then_some(id)
6263}
6264
6265/// Workflow run id out of a check's `detailsUrl`.
6266pub(crate) fn run_of(details_url: &str) -> Option<String> {
6267    let after = details_url.split("/actions/runs/").nth(1)?;
6268    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6269    (!id.is_empty()).then_some(id)
6270}
6271
6272/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6273/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6274/// it to that.
6275fn stop_comment(run_id: &str, why: &str) -> String {
6276    format!(
6277        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6278         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6279    )
6280}
6281
6282/// Leave the pull request open, say why on it, and mark the run blocked.
6283///
6284/// The comment is what makes an unattended stop actionable: the operator wakes
6285/// up to a pull request that explains itself rather than to a silent queue.
6286async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6287    let body = stop_comment(&state.id, why);
6288    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6289    if !body.contains(MARKER) {
6290        body = format!("{MARKER}\n{body}");
6291    }
6292    let posted = gh(
6293        repo,
6294        &[
6295            "pr".to_owned(),
6296            "comment".to_owned(),
6297            pr.number.to_string(),
6298            "--body".to_owned(),
6299            body,
6300        ],
6301    )
6302    .await;
6303    match posted {
6304        Ok(out) if out.ok => {}
6305        Ok(out) => tracing::warn!("could not comment on {}: {}", pr.url, out.combined()),
6306        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6307    }
6308    state.status = RunStatus::Blocked;
6309    state.merge = Some(MergeOutcome {
6310        mode: MergeMode::Pr,
6311        ok: false,
6312        detail: why.to_owned(),
6313        empty: false,
6314    });
6315    state.event("land", format!("stopped: {why}"));
6316    state.save()?;
6317    Ok(())
6318}
6319
6320/// Output of a `gh` subprocess, keeping machine-readable `stdout` separate from
6321/// diagnostic `stderr`.
6322///
6323/// Newer `gh` releases (for example `gh` 2.105.0) can emit advisory hints on
6324/// `stderr` even when a read-only `--json` or API command succeeds with exit
6325/// status 0. Appending `stderr` onto `stdout` before deserialization breaks
6326/// strict JSON parsing (for example `trailing characters at line 2 column 1`).
6327///
6328/// Output contract:
6329/// - **Successful structured reads** (`--json`, REST `gh api`, GraphQL, etc.):
6330///   check [`Self::ok`], then pass [`Self::stdout`] straight to a strict parser.
6331///   Never fall back to [`Self::stderr`] when `stdout` is empty, and never strip
6332///   specific hint text or heuristically extract JSON substrings.
6333/// - **Failed invocations (`!ok`)**: use [`Self::combined`] so both `stdout`
6334///   and `stderr` diagnostics stay actionable (for example `404` detection and
6335///   refused-merge details).
6336/// - **Human-facing or mutating commands** (`pr merge`, `pr close`, `pr edit`,
6337///   `pr comment`, `run rerun`, `run view --log-failed`): use
6338///   [`Self::combined`] for failure diagnostics or human-readable output.
6339#[derive(Debug, Clone, PartialEq, Eq)]
6340pub(crate) struct GhOutput {
6341    /// Whether `gh` exited with status 0.
6342    pub(crate) ok: bool,
6343    /// Process `stdout`, decoded lossily as UTF-8.
6344    pub(crate) stdout: String,
6345    /// Process `stderr`, decoded lossily as UTF-8.
6346    pub(crate) stderr: String,
6347}
6348
6349impl GhOutput {
6350    /// Build from a completed subprocess output and log non-empty `stderr`
6351    /// emitted on exit status 0 at debug level without logging command
6352    /// arguments.
6353    pub(crate) fn from_output(output: std::process::Output) -> Self {
6354        let parsed = Self {
6355            ok: output.status.success(),
6356            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
6357            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
6358        };
6359        if parsed.ok && !parsed.stderr.trim().is_empty() {
6360            tracing::debug!(
6361                stderr = parsed.stderr.trim(),
6362                "gh exited successfully with stderr diagnostics"
6363            );
6364        }
6365        parsed
6366    }
6367
6368    /// Combined trimmed `stdout` and `stderr` for failure diagnostics and
6369    /// human-facing commands.
6370    pub(crate) fn combined(&self) -> String {
6371        let out = self.stdout.trim();
6372        let err = self.stderr.trim();
6373        match (out.is_empty(), err.is_empty()) {
6374            (true, true) => String::new(),
6375            (false, true) => out.to_owned(),
6376            (true, false) => err.to_owned(),
6377            (false, false) => format!("{out}\n{err}"),
6378        }
6379    }
6380}
6381
6382/// Run `gh` in `cwd`, returning exit status with separated `stdout` and
6383/// `stderr` in [`GhOutput`].
6384///
6385/// Structured callers must check [`GhOutput::ok`] and parse [`GhOutput::stdout`]
6386/// strictly without substituting [`GhOutput::stderr`]. Failed invocations and
6387/// human-facing or mutating commands should use [`GhOutput::combined`] so both
6388/// streams remain available as diagnostics.
6389///
6390/// `GH_REPO` is stripped from the child's environment: every call site here
6391/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6392/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6393/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6394/// `GH_REPO` the operator happens to have exported for an unrelated script
6395/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6396/// below) to a different repository than the one actually on disk - which
6397/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6398/// could be made to agree with whatever repository a forged `--merged` URL
6399/// claims, defeating it entirely.
6400pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<GhOutput> {
6401    gh_with(Path::new("gh"), cwd, args).await
6402}
6403
6404pub(crate) async fn gh_with(program: &Path, cwd: &Path, args: &[String]) -> Result<GhOutput> {
6405    let out = tokio::process::Command::new(program)
6406        .args(args)
6407        .current_dir(cwd)
6408        .env_remove("GH_REPO")
6409        .quiet()
6410        .stdin(std::process::Stdio::null())
6411        .output()
6412        .await
6413        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6414    Ok(GhOutput::from_output(out))
6415}
6416
6417/// Verdict of one entry in the status rollup.
6418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6419pub(crate) enum Verdict {
6420    Pass,
6421    Fail,
6422    Pending,
6423    Unknown,
6424}
6425
6426impl Verdict {
6427    /// Short operator-facing check result.
6428    pub(crate) fn label(self) -> &'static str {
6429        match self {
6430            Self::Pass => "passed",
6431            Self::Fail => "failed",
6432            Self::Pending => "pending",
6433            Self::Unknown => "unknown",
6434        }
6435    }
6436}
6437
6438#[derive(Debug, Deserialize)]
6439#[serde(rename_all = "camelCase")]
6440struct GhPr {
6441    #[serde(default)]
6442    url: String,
6443    #[serde(default)]
6444    number: u64,
6445    #[serde(default)]
6446    state: String,
6447    #[serde(default)]
6448    title: String,
6449    #[serde(default)]
6450    status_check_rollup: Vec<GhCheck>,
6451    /// GitHub's own verdict on whether the pull request can be merged.
6452    ///
6453    /// Worth asking for because it is the only place the *required* check set
6454    /// is applied: the rollup lists every check equally, so a repository that
6455    /// deliberately does not require `coverage` still looks red here. See
6456    /// [`Blocking`].
6457    #[serde(default)]
6458    merge_state_status: String,
6459    /// The commit the pull request currently points at. Compared with the
6460    /// commit a fix round pushed, it is how the loop knows the forge has moved
6461    /// on and the rollup belongs to the new head.
6462    #[serde(default)]
6463    head_ref_oid: String,
6464    #[serde(default)]
6465    base_ref_name: String,
6466    #[serde(default)]
6467    reviews: Vec<GhReview>,
6468    #[serde(default)]
6469    comments: Vec<GhComment>,
6470}
6471
6472/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6473/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6474/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6475/// conclusion at all.
6476#[derive(Debug, Deserialize)]
6477#[serde(rename_all = "camelCase")]
6478struct GhCheck {
6479    #[serde(default)]
6480    name: Option<String>,
6481    #[serde(default)]
6482    context: Option<String>,
6483    #[serde(default)]
6484    status: Option<String>,
6485    #[serde(default)]
6486    conclusion: Option<String>,
6487    #[serde(default)]
6488    state: Option<String>,
6489    #[serde(default)]
6490    details_url: Option<String>,
6491    #[serde(default)]
6492    target_url: Option<String>,
6493    /// Whether the base branch requires this check. Only the GraphQL node
6494    /// carries it; `None` is "not read", never "not required".
6495    #[serde(default)]
6496    is_required: Option<bool>,
6497}
6498
6499impl GhCheck {
6500    /// Name to show a human and hand to the fixer.
6501    fn label(&self) -> String {
6502        self.name
6503            .clone()
6504            .or_else(|| self.context.clone())
6505            .unwrap_or_else(|| "(unnamed check)".to_owned())
6506    }
6507
6508    /// Where this check's logs live, when it has any.
6509    fn url(&self) -> Option<&str> {
6510        self.details_url
6511            .as_deref()
6512            .or(self.target_url.as_deref())
6513            .filter(|u| !u.is_empty())
6514    }
6515
6516    /// Did it pass?
6517    ///
6518    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6519    /// skips release and bot pull requests by design, and a skip that blocked
6520    /// landing would block exactly the pull requests that need no review.
6521    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6522    /// merging over one is merging over a check that never ran.
6523    fn verdict(&self) -> Verdict {
6524        if let Some(status) = self.status.as_deref() {
6525            if !status.eq_ignore_ascii_case("COMPLETED") {
6526                return Verdict::Pending;
6527            }
6528        }
6529        let outcome = self
6530            .conclusion
6531            .as_deref()
6532            .or(self.state.as_deref())
6533            .unwrap_or("");
6534        match outcome.to_ascii_uppercase().as_str() {
6535            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6536            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6537            | "ACTION_REQUIRED" => Verdict::Fail,
6538            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6539                Verdict::Pending
6540            }
6541            _ => Verdict::Unknown,
6542        }
6543    }
6544}
6545
6546#[derive(Debug, Deserialize)]
6547struct GhAuthor {
6548    #[serde(default)]
6549    login: String,
6550}
6551
6552#[derive(Debug, Deserialize)]
6553struct GhReview {
6554    #[serde(default)]
6555    author: GhAuthor,
6556    #[serde(default)]
6557    body: String,
6558}
6559
6560#[derive(Debug, Deserialize)]
6561struct GhComment {
6562    #[serde(default)]
6563    author: GhAuthor,
6564    #[serde(default)]
6565    body: String,
6566}
6567
6568#[derive(Debug, Deserialize)]
6569struct GhUser {
6570    #[serde(default)]
6571    login: String,
6572}
6573
6574#[derive(Debug, Deserialize)]
6575struct GhInline {
6576    #[serde(default)]
6577    user: GhUser,
6578    #[serde(default)]
6579    path: Option<String>,
6580    #[serde(default)]
6581    line: Option<u64>,
6582    #[serde(default)]
6583    body: String,
6584}
6585
6586impl Default for GhAuthor {
6587    fn default() -> Self {
6588        Self {
6589            login: "(unknown)".to_owned(),
6590        }
6591    }
6592}
6593
6594impl Default for GhUser {
6595    fn default() -> Self {
6596        Self {
6597            login: "(unknown)".to_owned(),
6598        }
6599    }
6600}
6601
6602#[cfg(test)]
6603pub(crate) mod tests {
6604    use super::*;
6605    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6606
6607    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6608        format!(
6609            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6610        )
6611    }
6612
6613    #[test]
6614    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6615        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6616        assert_eq!(
6617            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6618            Ok(())
6619        );
6620        for (json, why) in [
6621            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6622            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6623            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6624            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6625            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6626            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6627        ] {
6628            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6629                .unwrap_err()
6630                .why;
6631            assert!(err.contains(why), "{json}: {err}");
6632        }
6633        // A head that moved on past what was verified is left alone.
6634        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6635        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6636        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6637        assert!(
6638            !closable(
6639                &head_json("x", "main", "OPEN", false),
6640                "magi/27b2/A",
6641                "main",
6642                &[]
6643            )
6644            .unwrap_err()
6645            .retry
6646        );
6647        assert!(is_forge_url("https://github.com/o/r.git"));
6648        assert!(is_forge_url("git@github.com:o/r.git"));
6649        assert!(!is_forge_url("/tmp/origin.git"));
6650        assert!(!is_forge_url("C:\\work\\origin.git"));
6651        assert!(!is_forge_url("file:///tmp/origin.git"));
6652        assert!(forge_unavailable(
6653            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6654        ));
6655        assert!(!forge_unavailable(
6656            "gh pr list failed: error connecting to api.github.com"
6657        ));
6658        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6659        // A record that does not say whether it is a fork is not trusted.
6660        assert!(
6661            closable(
6662                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6663                "b",
6664                "main",
6665                &["aaa".to_owned()]
6666            )
6667            .is_err()
6668        );
6669    }
6670
6671    #[test]
6672    fn the_close_comment_names_the_commit_on_the_base() {
6673        let e = crate::already::Evidence {
6674            proof: crate::already::Proof::PatchId,
6675            tip: "1234567890".to_owned(),
6676            commits: vec!["0e368de0000".to_owned()],
6677        };
6678        let c = superseded_comment("main", &e);
6679        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6680    }
6681
6682    /// 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.
6683    const GREEN_OPEN: &str = r####"{
6684  "url": "https://github.com/yukimemi/magi/pull/10",
6685  "number": 10,
6686  "state": "OPEN",
6687  "mergeStateStatus": "CLEAN",
6688  "statusCheckRollup": [
6689    {
6690      "__typename": "CheckRun",
6691      "conclusion": "SKIPPED",
6692      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6693      "name": "review",
6694      "status": "COMPLETED",
6695      "workflowName": "claude-review"
6696    },
6697    {
6698      "__typename": "CheckRun",
6699      "conclusion": "SUCCESS",
6700      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6701      "name": "check (ubuntu-latest)",
6702      "status": "COMPLETED",
6703      "workflowName": "CI"
6704    },
6705    {
6706      "__typename": "CheckRun",
6707      "conclusion": "SUCCESS",
6708      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6709      "name": "rustfmt",
6710      "status": "COMPLETED",
6711      "workflowName": "CI"
6712    },
6713    {
6714      "__typename": "StatusContext",
6715      "context": "CodeRabbit",
6716      "state": "SUCCESS",
6717      "targetUrl": ""
6718    }
6719  ],
6720  "reviews": [],
6721  "comments": [
6722    {
6723      "author": {
6724        "login": "coderabbitai"
6725      },
6726      "authorAssociation": "NONE",
6727      "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"
6728    }
6729  ]
6730}"####;
6731
6732    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
6733    const RED_OPEN: &str = r####"{
6734  "url": "https://github.com/yukimemi/magi/pull/9",
6735  "number": 9,
6736  "state": "OPEN",
6737  "mergeStateStatus": "UNSTABLE",
6738  "statusCheckRollup": [
6739    {
6740      "__typename": "CheckRun",
6741      "conclusion": "SUCCESS",
6742      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6743      "name": "check (ubuntu-latest)",
6744      "status": "COMPLETED",
6745      "workflowName": "CI"
6746    },
6747    {
6748      "__typename": "CheckRun",
6749      "conclusion": "SUCCESS",
6750      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6751      "name": "rustfmt",
6752      "status": "COMPLETED",
6753      "workflowName": "CI"
6754    },
6755    {
6756      "__typename": "CheckRun",
6757      "conclusion": "FAILURE",
6758      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6759      "name": "editorconfig",
6760      "status": "COMPLETED",
6761      "workflowName": "CI"
6762    },
6763    {
6764      "__typename": "StatusContext",
6765      "context": "CodeRabbit",
6766      "state": "SUCCESS",
6767      "targetUrl": ""
6768    }
6769  ],
6770  "reviews": [],
6771  "comments": [
6772    {
6773      "author": {
6774        "login": "coderabbitai"
6775      },
6776      "authorAssociation": "NONE",
6777      "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"
6778    }
6779  ]
6780}"####;
6781
6782    /// 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.
6783    const PENDING_OPEN: &str = r####"{
6784  "url": "https://github.com/yukimemi/magi/pull/9",
6785  "number": 9,
6786  "state": "OPEN",
6787  "statusCheckRollup": [
6788    {
6789      "__typename": "CheckRun",
6790      "conclusion": "SUCCESS",
6791      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6792      "name": "check (ubuntu-latest)",
6793      "status": "COMPLETED",
6794      "workflowName": "CI"
6795    },
6796    {
6797      "__typename": "CheckRun",
6798      "conclusion": "SUCCESS",
6799      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6800      "name": "rustfmt",
6801      "status": "COMPLETED",
6802      "workflowName": "CI"
6803    },
6804    {
6805      "__typename": "CheckRun",
6806      "conclusion": null,
6807      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6808      "name": "editorconfig",
6809      "status": "IN_PROGRESS",
6810      "workflowName": "CI"
6811    },
6812    {
6813      "__typename": "StatusContext",
6814      "context": "CodeRabbit",
6815      "state": "SUCCESS",
6816      "targetUrl": ""
6817    }
6818  ],
6819  "reviews": [],
6820  "comments": []
6821}"####;
6822
6823    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
6824    const MERGED: &str = r####"{
6825  "url": "https://github.com/yukimemi/magi/pull/16",
6826  "number": 16,
6827  "state": "MERGED",
6828  "statusCheckRollup": [
6829    {
6830      "__typename": "CheckRun",
6831      "conclusion": "SUCCESS",
6832      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
6833      "name": "check (ubuntu-latest)",
6834      "status": "COMPLETED",
6835      "workflowName": "CI"
6836    },
6837    {
6838      "__typename": "CheckRun",
6839      "conclusion": "SUCCESS",
6840      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
6841      "name": "review",
6842      "status": "COMPLETED",
6843      "workflowName": "claude-review"
6844    }
6845  ],
6846  "reviews": [],
6847  "comments": []
6848}"####;
6849
6850    /// 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.
6851    const REVIEWED_OPEN: &str = r####"{
6852  "url": "https://github.com/yukimemi/magi/pull/12",
6853  "number": 12,
6854  "state": "OPEN",
6855  "statusCheckRollup": [
6856    {
6857      "__typename": "CheckRun",
6858      "conclusion": "SUCCESS",
6859      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
6860      "name": "check (ubuntu-latest)",
6861      "status": "COMPLETED",
6862      "workflowName": "CI"
6863    },
6864    {
6865      "__typename": "CheckRun",
6866      "conclusion": "SUCCESS",
6867      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
6868      "name": "review",
6869      "status": "COMPLETED",
6870      "workflowName": "claude-review"
6871    }
6872  ],
6873  "reviews": [
6874    {
6875      "author": {
6876        "login": "claude"
6877      },
6878      "state": "COMMENTED",
6879      "body": ""
6880    }
6881  ],
6882  "comments": [
6883    {
6884      "author": {
6885        "login": "coderabbitai"
6886      },
6887      "authorAssociation": "NONE",
6888      "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"
6889    },
6890    {
6891      "author": {
6892        "login": "claude"
6893      },
6894      "authorAssociation": "NONE",
6895      "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"
6896    }
6897  ]
6898}"####;
6899
6900    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
6901    const INLINE: &str = r####"[
6902  {
6903    "user": {
6904      "login": "claude[bot]"
6905    },
6906    "path": "src/graph.rs",
6907    "line": 231,
6908    "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"
6909  }
6910]"####;
6911
6912    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
6913    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
6914<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
6915
6916> [!IMPORTANT]
6917> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
6918> 
6919> This repository does not receive automatic reviews because it has fewer than 10 stars.
6920> 
6921> <details>
6922> <summary>⚙️ Run configuration</summary>
6923> 
6924> **Configuration used**: defaults
6925> 
6926> **Review profile**: CHILL
6927> 
6928> **Plan**: Team
6929> 
6930> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
6931> 
6932> </details>
6933
6934<!-- end of auto-generated comment: skip review by coderabbit.ai -->
6935
6936<!-- tips_start -->
6937
6938---
6939
6940Thanks 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.
6941
6942<details>
6943<summary>❤️ Share</summary>
6944
6945- [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"####;
6946
6947    /// 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.
6948    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
6949
6950---
6951### Reviewing PR #16
6952
6953- [x] Read AGENTS.md conventions
6954- [x] Review `src/daemon.rs` changes
6955- [x] Review `src/main.rs` changes (new `doctor` reporting)
6956- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
6957- [x] Check test coverage for new behavior
6958- [x] Run verification commands (blocked — see note)
6959- [x] Post findings"####;
6960
6961    /// The same job's real comment on pull request #12 once it had something to say.
6962    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
6963
6964---
6965### Review: `magi review <branch>` — cheap-half-only graph
6966
6967Read 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.
6968
6969**Correctness**
6970
6971- 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"####;
6972
6973    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
6974        PrState {
6975            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
6976            number: 16,
6977            state: PrLifecycle::Open,
6978            checks,
6979            // These tests are about red-means-fix, so a red here is one the
6980            // forge gates on. Without saying so they would assert the new
6981            // "merge past a check nobody requires" path by accident.
6982            blocking: if matches!(checks, Checks::Red) {
6983                Blocking::Yes
6984            } else {
6985                Blocking::No
6986            },
6987            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
6988            review_comments: (0..comments)
6989                .map(|i| ReviewComment {
6990                    author: "coderabbitai".to_owned(),
6991                    path: Some("src/graph.rs".to_owned()),
6992                    line: Some(231),
6993                    body: format!("finding {i}"),
6994                })
6995                .collect(),
6996        }
6997    }
6998
6999    #[test]
7000    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
7001        use CiExpectation::{Absent, Expected};
7002        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
7003            let p = pr(checks, &["x"], 0);
7004            for waited in [Duration::ZERO, CHECKS_GRACE] {
7005                assert_eq!(
7006                    decide_with(&p, 0, 4, waited, Expected),
7007                    decide(&p, 0, 4, waited)
7008                );
7009            }
7010        }
7011        // Nothing will ever report: no wait, no give-up, no fix round.
7012        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
7013            let p = pr(checks, &["x"], 0);
7014            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
7015            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
7016        }
7017        // Third-party statuses never change the review decision, even at budget.
7018        for comments in [0, 1] {
7019            for round in [0, 4] {
7020                let absent = decide_with(
7021                    &pr(Checks::Unknown, &[], comments),
7022                    round,
7023                    4,
7024                    CHECKS_GRACE,
7025                    Absent,
7026                );
7027                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
7028                    assert_eq!(
7029                        decide_with(
7030                            &pr(checks, &["third-party"], comments),
7031                            round,
7032                            4,
7033                            Duration::ZERO,
7034                            Absent
7035                        ),
7036                        absent
7037                    );
7038                }
7039                if comments != 0 {
7040                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
7041                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
7042                }
7043            }
7044        }
7045        let empty = pr(Checks::Unknown, &[], 0);
7046        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
7047            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
7048        }
7049        assert_eq!(
7050            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
7051            Step::Wait
7052        );
7053        assert_eq!(
7054            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
7055            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
7056        );
7057        // A conflict is not a check: it still wants the rebase.
7058        let mut p = pr(Checks::Unknown, &[], 0);
7059        p.blocking = Blocking::Conflict;
7060        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
7061        // And a pull request that left our hands is still done.
7062        p.state = PrLifecycle::Merged;
7063        assert_eq!(
7064            decide_with(&p, 0, 4, Duration::ZERO, Absent),
7065            Step::Done { merged: true }
7066        );
7067    }
7068
7069    #[test]
7070    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
7071        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
7072        assert_eq!(state.number, 10);
7073        assert_eq!(state.state, PrLifecycle::Open);
7074        assert_eq!(state.checks, Checks::Green);
7075        assert!(state.failing.is_empty());
7076        assert!(
7077            state.review_comments.is_empty(),
7078            "the only comment is CodeRabbit's trigger notice: {:?}",
7079            state.review_comments
7080        );
7081        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
7082    }
7083
7084    #[test]
7085    fn a_failing_check_parses_as_red_and_is_named() {
7086        let state = parse_pr(RED_OPEN).expect("red fixture parses");
7087        assert_eq!(state.checks, Checks::Red);
7088        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
7089        // The captured payload says `UNSTABLE` - mergeable, with a check
7090        // nobody requires red - which is exactly the shape that had to be
7091        // merged by hand. Asserted separately, in
7092        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
7093        // test is about is that a red check is *named*, so the reason a fixer
7094        // is handed says which one; so it asks the blocking question here.
7095        let mut blocking = state.clone();
7096        blocking.blocking = Blocking::Yes;
7097        match decide(&blocking, 0, 4, Duration::ZERO) {
7098            Step::Fix { reason } => {
7099                assert!(reason.contains("editorconfig"), "reason: {reason}");
7100                assert!(reason.contains("failing"), "reason: {reason}");
7101            }
7102            other => panic!("expected a fix round, got {other:?}"),
7103        }
7104    }
7105
7106    #[test]
7107    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
7108        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
7109        assert_eq!(state.checks, Checks::Pending);
7110        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
7111    }
7112
7113    #[test]
7114    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
7115        let state = parse_pr(MERGED).expect("merged fixture parses");
7116        assert_eq!(state.state, PrLifecycle::Merged);
7117        assert_eq!(
7118            decide(&state, 0, 4, Duration::ZERO),
7119            Step::Done { merged: true }
7120        );
7121    }
7122
7123    #[test]
7124    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
7125        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
7126        assert_eq!(state.checks, Checks::Green);
7127        let authors: Vec<&str> = state
7128            .review_comments
7129            .iter()
7130            .map(|c| c.author.as_str())
7131            .collect();
7132        assert_eq!(
7133            authors,
7134            vec!["claude"],
7135            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
7136        );
7137        match decide(&state, 0, 4, Duration::ZERO) {
7138            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
7139            other => panic!("expected a fix round, got {other:?}"),
7140        }
7141    }
7142
7143    #[test]
7144    fn inline_review_comments_keep_their_file_and_line() {
7145        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
7146        assert_eq!(comments.len(), 1);
7147        assert_eq!(comments[0].author, "claude[bot]");
7148        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
7149        assert_eq!(comments[0].line, Some(231));
7150        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
7151    }
7152
7153    #[test]
7154    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
7155        assert!(
7156            is_noise(CODERABBIT_TRIGGER),
7157            "CodeRabbit's trigger notice declares itself not a review"
7158        );
7159        assert!(
7160            is_noise(CLAUDE_CHECKLIST),
7161            "a progress checklist asks for nothing"
7162        );
7163        assert!(
7164            !is_noise(CLAUDE_FINDING),
7165            "a review that names a bug is input, not noise"
7166        );
7167
7168        let mut clean = pr(Checks::Green, &[], 0);
7169        clean.review_comments.push(ReviewComment {
7170            author: "coderabbitai".to_owned(),
7171            path: None,
7172            line: None,
7173            body: CODERABBIT_TRIGGER.to_owned(),
7174        });
7175        clean.review_comments.retain(|c| !is_noise(&c.body));
7176        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
7177
7178        let mut found = pr(Checks::Green, &[], 0);
7179        found.review_comments.push(ReviewComment {
7180            author: "claude".to_owned(),
7181            path: None,
7182            line: None,
7183            body: CLAUDE_FINDING.to_owned(),
7184        });
7185        found.review_comments.retain(|c| !is_noise(&c.body));
7186        assert!(matches!(
7187            decide(&found, 0, 4, Duration::ZERO),
7188            Step::Fix { .. }
7189        ));
7190    }
7191
7192    #[test]
7193    fn the_policy_table_holds_for_every_combination_that_matters() {
7194        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
7195            (
7196                "pending checks are waited for, even on the last round",
7197                pr(Checks::Pending, &[], 0),
7198                4,
7199                4,
7200                Duration::ZERO,
7201                Step::Wait,
7202            ),
7203            (
7204                "red checks are fixed",
7205                pr(Checks::Red, &["editorconfig"], 0),
7206                0,
7207                4,
7208                Duration::ZERO,
7209                Step::Fix {
7210                    reason: "1 check(s) failing: editorconfig".to_owned(),
7211                },
7212            ),
7213            (
7214                "green with comments is fixed, not merged",
7215                pr(Checks::Green, &[], 2),
7216                1,
7217                4,
7218                Duration::ZERO,
7219                Step::Fix {
7220                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
7221                        .to_owned(),
7222                },
7223            ),
7224            (
7225                "green and clean merges",
7226                pr(Checks::Green, &[], 0),
7227                3,
7228                4,
7229                Duration::ZERO,
7230                Step::Merge,
7231            ),
7232            (
7233                "an unreadable rollup is waited on while the grace lasts",
7234                pr(Checks::Unknown, &[], 0),
7235                0,
7236                4,
7237                Duration::ZERO,
7238                Step::Wait,
7239            ),
7240            (
7241                "an unreadable rollup is never merged once the grace is spent",
7242                pr(Checks::Unknown, &[], 0),
7243                0,
7244                4,
7245                CHECKS_GRACE,
7246                Step::GiveUp {
7247                    reason: "no check status is readable on the pull request after 3 minute(s); \
7248                             refusing to merge on a guess"
7249                        .to_owned(),
7250                },
7251            ),
7252        ];
7253        for (what, state, round, budget, waited, want) in cases {
7254            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
7255        }
7256    }
7257
7258    #[test]
7259    fn the_forge_verdict_survives_the_round_trip_from_gh() {
7260        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
7261        // requested but never parsed is the kind of thing that looks wired up
7262        // and answers `Unsaid` forever.
7263        let green = parse_pr(GREEN_OPEN).expect("parse");
7264        assert_eq!(green.blocking, Blocking::No);
7265        let red = parse_pr(RED_OPEN).expect("parse");
7266        assert_eq!(
7267            red.blocking,
7268            Blocking::No,
7269            "`UNSTABLE` is mergeable: the red check is one nobody requires"
7270        );
7271        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
7272        // A payload from an older `gh` has no such field at all.
7273        let quiet =
7274            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
7275        assert_eq!(quiet.blocking, Blocking::Unsaid);
7276    }
7277
7278    #[test]
7279    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
7280        // Pull request 37's only red check was `editorconfig`, failing
7281        // because the action could not fetch its own binary after
7282        // editorconfig-checker v4 renamed its release assets. The repository
7283        // does not require it. magi answered by asking a fixer to repair a
7284        // change that was fine, and the pull request had to be merged by hand.
7285        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7286        nonblocking.blocking = Blocking::No;
7287        assert_eq!(
7288            decide(&nonblocking, 0, 4, Duration::ZERO),
7289            Step::Merge,
7290            "the forge says nothing is in the way, so nothing is"
7291        );
7292
7293        // The same red, gated on: that is a fix round, as before.
7294        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7295        blocking.blocking = Blocking::Yes;
7296        assert!(matches!(
7297            decide(&blocking, 0, 4, Duration::ZERO),
7298            Step::Fix { .. }
7299        ));
7300
7301        // A review comment still outranks green-enough: a non-required red
7302        // must not become a way to merge past an unanswered reviewer.
7303        let mut commented = pr(Checks::Red, &["coverage"], 1);
7304        commented.blocking = Blocking::No;
7305        assert!(matches!(
7306            decide(&commented, 0, 4, Duration::ZERO),
7307            Step::Fix { .. }
7308        ));
7309
7310        // And silence from the forge is not consent.
7311        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7312        unsaid.blocking = Blocking::Unsaid;
7313        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7314        assert!(matches!(
7315            decide(&unsaid, 0, 4, CHECKS_GRACE),
7316            Step::Fix { .. }
7317        ));
7318    }
7319
7320    #[test]
7321    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7322        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7323        red.blocking = Blocking::No;
7324        assert_eq!(
7325            decide(&red, 0, 4, Duration::ZERO),
7326            Step::Merge,
7327            "announcing must not change the decision"
7328        );
7329        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7330        assert!(said.contains("yukimemi/magi"), "{said}");
7331        assert!(said.contains("#16"), "{said}");
7332        assert!(
7333            said.contains("https://github.com/yukimemi/magi/pull/16"),
7334            "{said}"
7335        );
7336        assert!(
7337            said.contains("test (windows-latest)") && said.contains("coverage"),
7338            "{said}"
7339        );
7340
7341        // `failing` can be left over on a green observation; only `checks` counts.
7342        let green = pr(Checks::Green, &["stale"], 0);
7343        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7344    }
7345
7346    #[test]
7347    fn red_merge_notices_omit_empty_check_details() {
7348        for checks in [vec![], vec!["", "  "]] {
7349            let red = pr(Checks::Red, &checks, 0);
7350            let summary = red_merge_summary("owner/repo", &red).unwrap();
7351            let notice = crate::notices::merged_red("run-1", &summary);
7352            assert_eq!(
7353                notice.message,
7354                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7355            );
7356            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7357        }
7358        let red = pr(Checks::Red, &["", " test ", " "], 0);
7359        let summary = red_merge_summary("owner/repo", &red).unwrap();
7360        assert!(summary.contains("with red checks: test ("), "{summary}");
7361    }
7362
7363    #[test]
7364    fn the_repo_label_comes_from_the_pull_request_url() {
7365        let p = Path::new("/tmp/checkout");
7366        assert_eq!(
7367            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7368            "yukimemi/magi"
7369        );
7370        assert_eq!(repo_label(p, "not a url"), "checkout");
7371    }
7372
7373    #[test]
7374    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7375        // Pull requests 35 and 37 were both rebased by hand: a competition
7376        // that runs for two hours against a repository merging pull requests
7377        // all day conflicts on the way in, and that is arithmetic rather
7378        // than a defect in the change.
7379        let mut conflicted = pr(Checks::Green, &[], 0);
7380        conflicted.blocking = Blocking::Conflict;
7381        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7382
7383        // Decided before the checks, and even with the rounds spent: every
7384        // check on a branch that cannot land is an answer about a state that
7385        // cannot land, and a conflict is not the change's fault.
7386        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7387        red.blocking = Blocking::Conflict;
7388        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7389
7390        // The lifecycle still wins over everything, conflict included.
7391        let mut merged = pr(Checks::Red, &[], 0);
7392        merged.blocking = Blocking::Conflict;
7393        merged.state = PrLifecycle::Merged;
7394        assert_eq!(
7395            decide(&merged, 0, 4, Duration::ZERO),
7396            Step::Done { merged: true }
7397        );
7398    }
7399
7400    #[test]
7401    fn the_forge_verdict_is_read_off_merge_state_status() {
7402        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7403        // matters: mergeable, with a non-required check red or still running.
7404        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7405            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7406            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7407        }
7408        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7409        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7410        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7411        // An older `gh`, or a token without the scope, says nothing - and
7412        // refusing to guess is the rule everywhere else in this module.
7413        for quiet in ["", "UNKNOWN"] {
7414            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7415            assert!(Blocking::of(quiet).stops_a_merge());
7416        }
7417    }
7418
7419    #[test]
7420    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7421        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7422        // The exact stderr from run ec12, in a jj-colocated repository.
7423        let jj = "could not determine current branch: failed to run git: not on any branch";
7424
7425        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7426            .expect("the forge says merged, so it merged");
7427        assert!(landed.ok);
7428        assert!(
7429            landed.detail.contains("but the pull request is merged"),
7430            "the record must not read as a clean success: {}",
7431            landed.detail
7432        );
7433        assert!(
7434            landed.detail.contains("not on any branch"),
7435            "and it must keep what the command actually said: {}",
7436            landed.detail
7437        );
7438
7439        // A pull request still open means the merge really failed.
7440        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7441        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7442        // And an unreadable answer is not evidence of success.
7443        assert!(merged_after_all(&argv, jj, None).is_none());
7444    }
7445
7446    #[test]
7447    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7448        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7449        state.state = PrLifecycle::Closed;
7450        assert_eq!(
7451            decide(&state, 0, 4, Duration::ZERO),
7452            Step::Done { merged: false },
7453            "a human closing the pull request ends the loop, whatever CI says"
7454        );
7455    }
7456
7457    #[test]
7458    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7459        let red = decide(
7460            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7461            4,
7462            4,
7463            Duration::ZERO,
7464        );
7465        match red {
7466            Step::GiveUp { reason } => {
7467                assert!(reason.contains("editorconfig"), "reason: {reason}");
7468                assert!(reason.contains("test (macos)"), "reason: {reason}");
7469                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7470            }
7471            other => panic!("expected a give-up, got {other:?}"),
7472        }
7473
7474        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7475        match commented {
7476            Step::GiveUp { reason } => {
7477                assert!(reason.contains("unresolved"), "reason: {reason}");
7478                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7479            }
7480            other => panic!("expected a give-up, got {other:?}"),
7481        }
7482    }
7483
7484    #[test]
7485    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7486        let candidate_commit = "magi: candidate A (uncommitted work)";
7487        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7488        let argv = merge_argv(16, &subject);
7489
7490        assert!(argv.contains(&"--squash".to_owned()));
7491        assert!(argv.contains(&"--delete-branch".to_owned()));
7492        assert!(argv.contains(&"--subject".to_owned()));
7493        assert_eq!(
7494            argv.last().map(String::as_str),
7495            Some("add retries to the uploader"),
7496            "the subject must not be the candidate commit message"
7497        );
7498        assert_ne!(subject, candidate_commit);
7499    }
7500
7501    #[test]
7502    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7503        assert_eq!(
7504            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7505            "feat: a queue, an unattended loop, and a phone UI"
7506        );
7507        assert_eq!(
7508            merge_subject("", "# port the retry logic\n\ndetails"),
7509            "port the retry logic",
7510            "an empty title falls back to the task's first line, heading marks stripped"
7511        );
7512    }
7513
7514    #[test]
7515    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7516        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7517        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7518        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7519        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7520        assert_eq!(run_of(""), None);
7521    }
7522
7523    #[test]
7524    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7525        let mut out = Vec::new();
7526        push_if_outstanding(
7527            &mut out,
7528            ReviewComment {
7529                author: "yukimemi".to_owned(),
7530                path: None,
7531                line: None,
7532                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7533            },
7534        );
7535        assert!(out.is_empty());
7536    }
7537
7538    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7539    /// falls back to the repository - which keeps these tests free of a
7540    /// worktree, a `git` invocation and a network.
7541    fn run_state() -> RunState {
7542        let mut state = RunState::new(
7543            std::path::PathBuf::from("/repo/magi"),
7544            "main".to_owned(),
7545            "abcdef1234".to_owned(),
7546            "add retries to the uploader".to_owned(),
7547            crate::config::Config::default(),
7548        );
7549        // These fixtures test execution flow, independent of host disk capacity.
7550        state.config.disk.min_free_bytes = 0;
7551        // Tests run in parallel against one persistent home and the ids
7552        // `RunState::new` draws from the clock can repeat, so two tests would
7553        // share a run's questions. The home also outlives the process, so the
7554        // counter alone would reuse an earlier run's ids.
7555        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7556        let nanos = std::time::SystemTime::now()
7557            .duration_since(std::time::UNIX_EPOCH)
7558            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7559        state.id = format!(
7560            "20261004-{nanos:06}-{:04x}",
7561            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7562        );
7563        state
7564    }
7565
7566    fn green_pr() -> PrState {
7567        PrState {
7568            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7569            number: 42,
7570            state: PrLifecycle::Open,
7571            checks: Checks::Green,
7572            // The forge sees nothing in the way unless a test says otherwise.
7573            blocking: Blocking::No,
7574            failing: Vec::new(),
7575            review_comments: vec![ReviewComment {
7576                author: "coderabbitai".to_owned(),
7577                path: Some("src/land.rs".to_owned()),
7578                line: Some(212),
7579                body: "this branch never checks the exit code".to_owned(),
7580            }],
7581        }
7582    }
7583
7584    #[test]
7585    fn land_fixer_defers_review_and_verification_without_a_cache() {
7586        let state = run_state();
7587        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7588        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7589        assert!(p.contains("Commit in this worktree"), "{p}");
7590    }
7591
7592    #[test]
7593    fn github_facing_land_text_is_english_whatever_the_language() {
7594        let mut state = run_state();
7595        state.config.graph.language = "ja".to_owned();
7596        let comment = stop_comment(&state.id, "checks are still red");
7597        assert!(crate::github_text::check("", &comment).is_empty());
7598        assert!(comment.is_ascii(), "{comment}");
7599        assert!(comment.starts_with(MARKER));
7600
7601        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7602        let ja_at = p.find("Write all prose in ja").unwrap();
7603        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7604        assert!(ja_at < rule_at, "{p}");
7605        assert!(p.contains("stays in Japanese"), "{p}");
7606
7607        state.config.graph.language = "en".to_owned();
7608        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7609        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7610        assert!(!p.contains("does not apply"), "{p}");
7611    }
7612
7613    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7614
7615    fn panel() -> String {
7616        approval_panel(
7617            &run_state(),
7618            &green_pr(),
7619            NUMSTAT,
7620            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7621            &[
7622                "land: ask before merging".to_owned(),
7623                "land: colour the diff".to_owned(),
7624            ],
7625            "feat: merge approval from the phone",
7626        )
7627    }
7628
7629    #[test]
7630    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7631        let html = panel();
7632        for needle in [
7633            "42",
7634            "main",
7635            "src/land.rs",
7636            "src/web.rs",
7637            "assets/logo.png",
7638            "feat: merge approval from the phone",
7639            "land: ask before merging",
7640            "land: colour the diff",
7641            "coderabbitai",
7642            "this branch never checks the exit code",
7643            "green",
7644        ] {
7645            assert!(html.contains(needle), "the panel must state `{needle}`");
7646        }
7647    }
7648
7649    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7650        crate::run::pin_test_home();
7651        let tmp = tempfile::tempdir().unwrap();
7652        let repo = tmp.path().join("repo");
7653        let remote = tmp.path().join("remote.git");
7654        std::fs::create_dir(&repo).unwrap();
7655        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7656            .await
7657            .unwrap();
7658        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7659        git::git(&repo, &["config", "user.name", "Test"])
7660            .await
7661            .unwrap();
7662        git::git(&repo, &["config", "user.email", "test@example.test"])
7663            .await
7664            .unwrap();
7665        std::fs::write(repo.join("base"), "base").unwrap();
7666        git::git(&repo, &["add", "."]).await.unwrap();
7667        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7668        git::git(
7669            &repo,
7670            &["remote", "add", "origin", remote.to_str().unwrap()],
7671        )
7672        .await
7673        .unwrap();
7674        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7675        git::git(&repo, &["checkout", "-b", "winner"])
7676            .await
7677            .unwrap();
7678        std::fs::write(repo.join("change"), "change").unwrap();
7679        git::git(&repo, &["add", "."]).await.unwrap();
7680        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7681        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7682        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7683            .await
7684            .unwrap();
7685        let mut state = run_state();
7686        state.repo = repo.clone();
7687        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7688        state.config.graph.land = true;
7689        state.config.graph.land_approval = true;
7690        state.pr_head = Some("task-head".into());
7691        state.pr_pushed_head = Some(head.clone());
7692        state.candidates = vec![winning_candidate("change")];
7693        state.candidates[0].worktree = repo;
7694        state.candidates[0].branch = "winner".into();
7695        state.tally = Some(uncontested_tally());
7696        state.gate_ran = true;
7697        state.gate_head = Some(head.clone());
7698        state.land_sync_pending = true;
7699        state.save().unwrap();
7700        (tmp, state, head)
7701    }
7702
7703    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7704        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7705        resume_landing_head(state, head, &green_pr().url, &forge, None).await
7706    }
7707
7708    async fn advance_landing_base(state: &RunState) {
7709        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7710        std::fs::write(state.repo.join("advance"), "advance").unwrap();
7711        git::git(&state.repo, &["add", "."]).await.unwrap();
7712        git::git(&state.repo, &["commit", "-m", "advance base"])
7713            .await
7714            .unwrap();
7715        git::git(&state.repo, &["push", "origin", "main"])
7716            .await
7717            .unwrap();
7718        git::git(&state.repo, &["checkout", "winner"])
7719            .await
7720            .unwrap();
7721    }
7722
7723    #[tokio::test]
7724    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
7725        let (_tmp, mut state, head) = landing_git_fixture().await;
7726        advance_landing_base(&state).await;
7727        let scratch = state.dir().join("rebase");
7728        std::fs::create_dir_all(&scratch).unwrap();
7729        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
7730        let attempts = state.land_sync_attempts;
7731        let error = rebase_landing_worktree(&mut state, "origin/main")
7732            .await
7733            .unwrap_err();
7734        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
7735        assert_eq!(state.land_sync_attempts, attempts);
7736        assert!(state.land_sync_target.is_none());
7737        assert!(state.rebase_fixes.is_empty());
7738        assert!(
7739            state
7740                .base_sync
7741                .as_ref()
7742                .is_none_or(|sync| sync.conflict.is_none())
7743        );
7744        let block = state.resource_block.as_ref().unwrap();
7745        assert_eq!(block.kind, crate::rebase::SEQUENCER_INFRASTRUCTURE);
7746        assert!(
7747            block.detail.contains("inspect scratch Git backlink"),
7748            "{}",
7749            block.detail
7750        );
7751        assert_eq!(
7752            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
7753            "keep"
7754        );
7755        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
7756        std::fs::remove_dir_all(&scratch).unwrap();
7757        state.resource_block = None;
7758        assert_eq!(
7759            rebase_landing_worktree(&mut state, "origin/main")
7760                .await
7761                .unwrap(),
7762            crate::rebase::Rebased::Applied
7763        );
7764        assert_eq!(state.land_sync_attempts, attempts + 1);
7765        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
7766        assert!(git::is_clean(&state.repo).await.unwrap());
7767        assert!(state.rebase_fixes.is_empty());
7768    }
7769
7770    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7771    {
7772        let (tmp, mut state, old) = landing_git_fixture().await;
7773        let path = tmp.path().join("foreign");
7774        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7775            .await
7776            .unwrap();
7777        state.foreign_checkout = Some(
7778            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7779                .await
7780                .unwrap(),
7781        );
7782        state.config.merge.mode = crate::config::MergeMode::Pr;
7783        state.save().unwrap();
7784        (tmp, state, old, path)
7785    }
7786
7787    #[tokio::test]
7788    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
7789        for phase in 0..4 {
7790            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7791            advance_landing_base(&state).await;
7792            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
7793            if phase == 0 {
7794                // The live Step::Rebase path uses this same synchronization
7795                // and publication pair, without going through resume.
7796                assert_eq!(
7797                    rebase_landing_worktree(&mut state, "origin/main")
7798                        .await
7799                        .unwrap(),
7800                    crate::rebase::Rebased::Applied
7801                );
7802            } else {
7803                interrupt_landing_rebase(&mut state).await;
7804                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
7805                if phase == 2 {
7806                    git::sync_to_head(&state.repo).await.unwrap();
7807                } else if phase == 3 {
7808                    // Crash after joining history, before clearing its saved
7809                    // start. Repeating restoration must not add another merge.
7810                    restore_landing_worktree(&mut state).await.unwrap();
7811                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7812                    state.land_rebase_from = Some(old.clone());
7813                    state.save().unwrap();
7814                    restore_landing_worktree(&mut state).await.unwrap();
7815                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
7816                }
7817                state.save().unwrap();
7818                state = RunState::load(&state.id).unwrap();
7819                restore_landing_worktree(&mut state).await.unwrap();
7820                assert_eq!(
7821                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
7822                    repaired_tree
7823                );
7824            }
7825            let head = if phase == 0 {
7826                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
7827                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
7828                    .await
7829                    .unwrap()
7830            } else {
7831                resume_observed_head(&mut state, &old).await.unwrap()
7832            };
7833            assert!(git::is_ancestor(&state.repo, &old, &head).await);
7834            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7835            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7836            assert_eq!(
7837                git::remote_head(&state.repo, "origin", "task-head")
7838                    .await
7839                    .unwrap(),
7840                Some(head.clone())
7841            );
7842            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7843            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
7844            assert!(state.gate_allows_progress());
7845            assert!(state.land_rebase_from.is_none());
7846            assert!(!state.land_sync_pending);
7847            assert!(git::is_clean(&path).await.unwrap());
7848        }
7849    }
7850
7851    #[tokio::test]
7852    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
7853        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7854        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7855        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7856        git::commit_all(&state.repo, "conflicting base")
7857            .await
7858            .unwrap();
7859        git::git(&state.repo, &["push", "origin", "main"])
7860            .await
7861            .unwrap();
7862        git::git(&state.repo, &["checkout", "winner"])
7863            .await
7864            .unwrap();
7865        landing_gate_fixer(
7866            &mut state,
7867            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7868        );
7869        state.config.graph.gate_fix_rounds = 0;
7870        state.config.verify.gate = vec!["exit 1".into()];
7871        assert!(resume_observed_head(&mut state, &old).await.is_err());
7872        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
7873        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7874        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
7875        assert_eq!(
7876            std::fs::read_to_string(state.repo.join("change")).unwrap(),
7877            "resolved"
7878        );
7879        // A red gate must neither deliver nor publish the repaired tree.
7880        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
7881        assert_eq!(
7882            git::remote_head(&state.repo, "origin", "task-head")
7883                .await
7884                .unwrap(),
7885            Some(old.clone())
7886        );
7887        state = RunState::load(&state.id).unwrap();
7888        state.config.verify.gate = vec!["grep -q resolved change".into()];
7889        let head = resume_observed_head(&mut state, &old).await.unwrap();
7890        assert_eq!(head, repaired);
7891        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7892        assert_eq!(
7893            std::fs::read_to_string(path.join("change")).unwrap(),
7894            "resolved"
7895        );
7896        assert_eq!(
7897            git::remote_head(&state.repo, "origin", "task-head")
7898                .await
7899                .unwrap(),
7900            Some(head.clone())
7901        );
7902        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7903        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7904        assert!(git::is_clean(&path).await.unwrap());
7905    }
7906
7907    #[tokio::test]
7908    async fn landing_resume_completes_the_last_charged_sync_attempt() {
7909        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
7910            let (_tmp, mut state, old) = landing_git_fixture().await;
7911            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7912            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7913            git::commit_all(&state.repo, "conflicting base")
7914                .await
7915                .unwrap();
7916            git::git(&state.repo, &["push", "origin", "main"])
7917                .await
7918                .unwrap();
7919            git::git(&state.repo, &["checkout", "winner"])
7920                .await
7921                .unwrap();
7922            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
7923            state.config.graph.land_rounds = 1;
7924            state.land_sync_attempts = 1;
7925            state.land_sync_target = saved_target.then(|| target.clone());
7926            state.land_rebase_from = Some(old.clone());
7927            landing_gate_fixer(
7928                &mut state,
7929                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7930            );
7931            state.config.verify.gate = vec!["grep -q resolved change".into()];
7932            state.save().unwrap();
7933            // Simulate interruption before the scratch start and at a conflict.
7934            if scratch_started {
7935                assert!(matches!(
7936                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
7937                        .await
7938                        .unwrap(),
7939                    git::RebaseStart::Conflicted(_)
7940                ));
7941            }
7942            state = RunState::load(&state.id).unwrap();
7943            let head = resume_observed_head(&mut state, &old).await.unwrap();
7944            assert_ne!(head, old);
7945            assert_eq!(state.land_sync_attempts, 1);
7946            assert!(state.land_sync_target.is_none());
7947            assert!(state.land_rebase_from.is_none());
7948            assert!(!state.land_sync_pending);
7949            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7950            assert!(state.gate_allows_progress());
7951            assert_eq!(
7952                git::remote_head(&state.repo, "origin", "task-head")
7953                    .await
7954                    .unwrap(),
7955                Some(head)
7956            );
7957            assert!(
7958                rebase_landing_worktree(&mut state, "origin/main")
7959                    .await
7960                    .unwrap_err()
7961                    .to_string()
7962                    .contains("budget exhausted")
7963            );
7964        }
7965    }
7966
7967    #[tokio::test]
7968    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
7969        let (_tmp, mut state, old) = landing_git_fixture().await;
7970        advance_landing_base(&state).await;
7971        state.config.verify.gate = vec!["test -f advance".into()];
7972        let head = resume_observed_head(&mut state, &old).await.unwrap();
7973        assert_ne!(head, old);
7974        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7975        assert!(state.gate_allows_progress());
7976        assert_eq!(
7977            git::remote_head(&state.repo, "origin", "task-head")
7978                .await
7979                .unwrap(),
7980            Some(head.clone())
7981        );
7982        assert_eq!(state.pr_pushed_head, Some(head));
7983        assert!(!state.land_sync_pending);
7984        assert!(state.config.graph.land_approval);
7985    }
7986
7987    fn landing_gate_fixer(state: &mut RunState, script: &str) {
7988        state.config.disk.min_free_bytes = 0;
7989        state.config.graph.gate_fix_rounds = 1;
7990        state.config.agents = vec![crate::config::AgentSpec {
7991            id: "mock".into(),
7992            kind: crate::config::AgentKind::Command,
7993            model: None,
7994            command: vec!["sh".into(), "-c".into(), script.into()],
7995            extra_args: Vec::new(),
7996            env: Default::default(),
7997            prompt_delivery: None,
7998            max_turn_secs: None,
7999        }];
8000        state.candidates[0].agent = "mock".into();
8001    }
8002
8003    #[tokio::test]
8004    async fn rebase_fixer_invocation_cap_survives_fallback_and_reload() {
8005        let (tmp, mut state, original) = landing_git_fixture().await;
8006        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8007        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
8008        git::commit_all(&state.repo, "conflicting base")
8009            .await
8010            .unwrap();
8011        let target = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8012        git::git(&state.repo, &["checkout", "winner"])
8013            .await
8014            .unwrap();
8015        let scratch = state.dir().join("rebase");
8016        let counter = tmp.path().join("calls");
8017        landing_gate_fixer(
8018            &mut state,
8019            "echo \"$REBASE_AGENT\" >> \"$REBASE_COUNTER\"; exit 1",
8020        );
8021        let template = state.config.agents[0].clone();
8022        let ids = ["mock", "fallback1", "fallback2", "fallback3"].map(str::to_owned);
8023        state.config.agents = ids
8024            .iter()
8025            .map(|id| {
8026                let mut spec = template.clone();
8027                spec.id.clone_from(id);
8028                spec.env.insert("REBASE_AGENT".into(), id.clone());
8029                spec.env
8030                    .insert("REBASE_COUNTER".into(), git::path_arg(&counter));
8031                spec
8032            })
8033            .collect();
8034        state.config.roles.fixer = Some(crate::config::AgentChoice::Chain(ids.to_vec()));
8035        state.config.graph.review_rounds = 3;
8036        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8037        state.config.graph.timeout_resource_wait = 0;
8038        let started = git::rebase_start(&state.repo, &scratch, "winner", &target)
8039            .await
8040            .unwrap();
8041        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
8042        let home = crate::run::home();
8043        let cache = crate::build_target::resolve(&home, &scratch).unwrap();
8044        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", &scratch, &original);
8045        let crate::cache::AcquireOutcome::Acquired(lease) =
8046            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
8047        else {
8048            panic!("test target was already leased");
8049        };
8050        let error = crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8051            .await
8052            .unwrap_err();
8053        assert!(error.is::<crate::agent::IsolatedSeatWait>(), "{error:#}");
8054        assert!(!counter.exists());
8055        assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), ["change"]);
8056        drop(lease);
8057        state = RunState::load(&state.id).unwrap();
8058        for _ in 0..2 {
8059            let crate::rebase::Rebased::Stopped(why) =
8060                crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8061                    .await
8062                    .unwrap()
8063            else {
8064                panic!("the unresolved conflict must stop");
8065            };
8066            assert!(why.contains("after 3 of 3 fixer round(s)"), "{why}");
8067            assert_eq!(
8068                std::fs::read_to_string(&counter)
8069                    .unwrap()
8070                    .lines()
8071                    .collect::<Vec<_>>(),
8072                ["mock", "fallback1", "fallback2"]
8073            );
8074            assert_eq!(
8075                git::rev_parse(&state.repo, "winner").await.unwrap(),
8076                original
8077            );
8078            state = RunState::load(&state.id).unwrap();
8079        }
8080    }
8081
8082    #[tokio::test]
8083    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
8084        let (_tmp, mut state, old) = landing_git_fixture().await;
8085        std::fs::write(state.repo.join("change"), "operator update").unwrap();
8086        git::commit_all(&state.repo, "extend winner").await.unwrap();
8087        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8088        git::git(
8089            &state.repo,
8090            &["push", "origin", "HEAD:refs/heads/task-head"],
8091        )
8092        .await
8093        .unwrap();
8094        state.config.verify.gate = vec!["exit 1".into()];
8095        state.config.graph.gate_fix_rounds = 0;
8096        assert!(resume_observed_head(&mut state, &updated).await.is_err());
8097        assert_ne!(old, updated);
8098        assert_eq!(state.gate_head.as_ref(), Some(&updated));
8099        assert!(!state.gate_allows_progress());
8100        assert!(state.land_sync_pending);
8101        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
8102        let head = resume_observed_head(&mut state, &updated).await.unwrap();
8103        assert_eq!(head, updated);
8104        assert!(state.gate_allows_progress());
8105        assert!(!state.land_sync_pending);
8106        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8107        land_with(&mut state, &green_pr().url, &forge)
8108            .await
8109            .unwrap();
8110        assert!(state.parked);
8111        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8112        assert!(forge.argvs().is_empty());
8113    }
8114
8115    #[tokio::test]
8116    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
8117        for divergent in [false, true] {
8118            let (_tmp, mut state, old) = landing_git_fixture().await;
8119            if divergent {
8120                git::git(&state.repo, &["reset", "--hard", "origin/main"])
8121                    .await
8122                    .unwrap();
8123            }
8124            std::fs::write(state.repo.join("external"), "external").unwrap();
8125            git::commit_all(&state.repo, "external update")
8126                .await
8127                .unwrap();
8128            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8129            git::git(
8130                &state.repo,
8131                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
8132            )
8133            .await
8134            .unwrap();
8135            if !divergent {
8136                git::git(&state.repo, &["reset", "--hard", &old])
8137                    .await
8138                    .unwrap();
8139            }
8140            let error = resume_observed_head(&mut state, &external)
8141                .await
8142                .unwrap_err();
8143            assert!(
8144                error
8145                    .to_string()
8146                    .contains("public head moved outside this run")
8147            );
8148            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
8149            assert_eq!(
8150                git::remote_head(&state.repo, "origin", "task-head")
8151                    .await
8152                    .unwrap(),
8153                Some(external)
8154            );
8155        }
8156    }
8157
8158    #[tokio::test]
8159    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
8160        let (_tmp, mut state, old) = landing_git_fixture().await;
8161        advance_landing_base(&state).await;
8162        landing_gate_fixer(
8163            &mut state,
8164            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8165        );
8166        state.config.verify.gate =
8167            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8168        state.config.verify.e2e = vec!["test -f advance".into()];
8169        // First save a red gate without spending a fixer round. Resume must
8170        // still offer the remaining budget for this exact same failed head.
8171        state.config.graph.gate_fix_rounds = 0;
8172        assert!(resume_observed_head(&mut state, &old).await.is_err());
8173        assert_eq!(
8174            git::remote_head(&state.repo, "origin", "task-head")
8175                .await
8176                .unwrap(),
8177            Some(old.clone())
8178        );
8179        state.config.graph.gate_fix_rounds = 1;
8180        let head = resume_observed_head(&mut state, &old).await.unwrap();
8181        assert_eq!(state.gate_fixes.len(), 1);
8182        assert!(state.gate_fixes[0].committed);
8183        assert!(state.gate_allows_progress());
8184        assert_eq!(state.gate_head.as_ref(), Some(&head));
8185        assert_eq!(
8186            git::remote_head(&state.repo, "origin", "task-head")
8187                .await
8188                .unwrap(),
8189            Some(head.clone())
8190        );
8191        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8192        land_with(&mut state, &green_pr().url, &forge)
8193            .await
8194            .unwrap();
8195        assert!(state.parked);
8196        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8197        assert!(forge.argvs().is_empty());
8198    }
8199
8200    #[tokio::test]
8201    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
8202        let (_tmp, mut state, old) = landing_git_fixture().await;
8203        advance_landing_base(&state).await;
8204        landing_gate_fixer(
8205            &mut state,
8206            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8207        );
8208        state.config.verify.gate = vec!["echo still red; exit 1".into()];
8209        for _ in 0..2 {
8210            assert!(resume_observed_head(&mut state, &old).await.is_err());
8211            assert_eq!(state.gate_fixes.len(), 1);
8212            assert_eq!(
8213                git::remote_head(&state.repo, "origin", "task-head")
8214                    .await
8215                    .unwrap(),
8216                Some(old.clone())
8217            );
8218        }
8219    }
8220
8221    #[tokio::test]
8222    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
8223        let (_tmp, mut state, old) = landing_git_fixture().await;
8224        advance_landing_base(&state).await;
8225        landing_gate_fixer(
8226            &mut state,
8227            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8228        );
8229        state.config.verify.gate =
8230            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8231        // The repair makes the gate green while breaking an e2e invariant.
8232        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
8233        let mut saved_comparison = None;
8234        for resume in 0..3 {
8235            assert!(resume_observed_head(&mut state, &old).await.is_err());
8236            state = RunState::load(&state.id).unwrap();
8237            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8238            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8239            assert_eq!(evidence.head, head);
8240            assert!(!evidence.passed);
8241            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
8242            let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
8243            if let Some(saved) = &saved_comparison {
8244                assert_eq!(comparison, saved);
8245            } else {
8246                saved_comparison = Some(comparison.clone());
8247            }
8248            assert_eq!(state.gate_fixes.len(), 1);
8249            assert_eq!(
8250                git::remote_head(&state.repo, "origin", "task-head")
8251                    .await
8252                    .unwrap(),
8253                Some(old.clone())
8254            );
8255            if resume > 0 {
8256                assert!(
8257                    state.gate_allows_progress(),
8258                    "a green gate must not bypass red e2e"
8259                );
8260            }
8261        }
8262        // A changed command is not new evidence about the already checked SHA.
8263        state.config.verify.e2e = vec!["grep -q fixed change".into()];
8264        assert!(resume_observed_head(&mut state, &old).await.is_err());
8265        assert_eq!(
8266            state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
8267            saved_comparison
8268        );
8269    }
8270
8271    #[tokio::test]
8272    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
8273        for phase in 0..3 {
8274            let (_tmp, mut state, old) = landing_git_fixture().await;
8275            advance_landing_base(&state).await;
8276            let head = resume_observed_head(&mut state, &old).await.unwrap();
8277            // Persist the shapes left by interruption, resource deferral,
8278            // and a successful check for a different (older) SHA.
8279            state.land_sync_pending = true;
8280            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
8281            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8282                if phase == 2 {
8283                    old.clone()
8284                } else {
8285                    head.clone()
8286                },
8287                phase == 2,
8288                if phase == 1 {
8289                    vec![crate::run::CommandOutcome {
8290                        command: state.config.verify.e2e[0].clone(),
8291                        code: None,
8292                        output_tail: "verification resource unavailable".into(),
8293                        duration_ms: 0,
8294                        resource_blocked: true,
8295                        ..Default::default()
8296                    }]
8297                } else {
8298                    Vec::new()
8299                },
8300            ));
8301            state.save().unwrap();
8302            for _ in 0..2 {
8303                state = RunState::load(&state.id).unwrap();
8304                assert!(resume_observed_head(&mut state, &head).await.is_err());
8305                let evidence = state.gate_repair_e2e.as_ref().unwrap();
8306                assert_eq!(evidence.head, head);
8307                assert!(!evidence.passed);
8308                assert!(!evidence.outcomes.is_empty());
8309                assert_eq!(
8310                    git::remote_head(&state.repo, "origin", "task-head")
8311                        .await
8312                        .unwrap(),
8313                    Some(head.clone())
8314                );
8315                assert!(state.land_sync_pending);
8316            }
8317        }
8318    }
8319
8320    #[tokio::test]
8321    async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
8322        for code in [None, Some(126), Some(127)] {
8323            let (_tmp, mut state, old) = landing_git_fixture().await;
8324            advance_landing_base(&state).await;
8325            let head = resume_observed_head(&mut state, &old).await.unwrap();
8326            state.land_sync_pending = true;
8327            state.config.verify.e2e = vec!["true".into()];
8328            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8329                head.clone(),
8330                false,
8331                vec![crate::run::CommandOutcome {
8332                    command: state.config.verify.e2e[0].clone(),
8333                    code,
8334                    output_tail: "verification command did not complete".into(),
8335                    ..Default::default()
8336                }],
8337            ));
8338            state.save().unwrap();
8339            state = RunState::load(&state.id).unwrap();
8340            assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
8341            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8342            assert_eq!(evidence.head, head);
8343            assert!(evidence.passed);
8344            assert_eq!(evidence.outcomes[0].code, Some(0));
8345        }
8346    }
8347
8348    async fn interrupt_landing_rebase(state: &mut RunState) {
8349        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
8350        state.save().unwrap();
8351        let scratch = state.dir().join("rebase");
8352        assert_eq!(
8353            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
8354                .await
8355                .unwrap(),
8356            crate::rebase::Rebased::Applied
8357        );
8358        assert!(!git::is_clean(&state.repo).await.unwrap());
8359    }
8360
8361    async fn landing_setup(state: &mut RunState) {
8362        git::git(
8363            &state.repo,
8364            &["config", "extensions.worktreeConfig", "true"],
8365        )
8366        .await
8367        .unwrap();
8368        state.config.worktree.setup =
8369            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8370        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8371            .await
8372            .unwrap();
8373        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8374    }
8375
8376    #[tokio::test]
8377    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8378        let (tmp, mut state, head) = landing_git_fixture().await;
8379        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8380        git::acquire_worktree_config(&state.repo).await.unwrap();
8381        let winner = tmp.path().join("landing");
8382        git::worktree_add_existing(&state.repo, &winner, "winner", false)
8383            .await
8384            .unwrap();
8385        state.candidates[0].worktree = winner.clone();
8386        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8387        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8388        state.config.disk.min_free_bytes = 0;
8389        state.config.worktree.setup = vec![crate::config::SetupStep {
8390            run: Some("touch setup-completed".into()),
8391            ..Default::default()
8392        }];
8393        #[cfg(unix)]
8394        {
8395            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8396            state.config.coordination = Some(crate::config::Coordination {
8397                contract_file: "fixture-contract".into(),
8398                contract_token: "fixture-v1".into(),
8399                lock_file: "fixture-lock".into(),
8400            });
8401        }
8402        state.land_rebase_from = Some(head);
8403        let restore = restore_landing_worktree(&mut state);
8404        // Only the registered Unix fixture can deadlock by reacquiring its
8405        // own operation lease. Don't time the whole Git/setup path elsewhere.
8406        #[cfg(unix)]
8407        let restore = async {
8408            tokio::time::timeout(Duration::from_secs(15), restore)
8409                .await
8410                .expect("landing setup must not wait for its own repository operation")
8411        };
8412        restore.await.unwrap();
8413        assert!(winner.join("setup-completed").is_file());
8414        assert!(git::is_clean(&winner).await.unwrap());
8415        assert!(state.land_rebase_from.is_none());
8416    }
8417
8418    #[tokio::test]
8419    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8420        for phase in 0..3 {
8421            let (_tmp, mut state, old) = landing_git_fixture().await;
8422            advance_landing_base(&state).await;
8423            landing_setup(&mut state).await;
8424            if phase > 0 {
8425                interrupt_landing_rebase(&mut state).await;
8426                if phase == 2 {
8427                    // Crash after clean removed setup products, before setup.
8428                    git::sync_to_head(&state.repo).await.unwrap();
8429                    assert!(!state.repo.join(".env").exists());
8430                }
8431                state = RunState::load(&state.id).unwrap();
8432            }
8433            let head = resume_observed_head(&mut state, &old).await.unwrap();
8434            assert_ne!(head, old);
8435            assert!(state.gate_allows_progress());
8436            assert!(state.land_rebase_from.is_none());
8437            assert_eq!(
8438                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8439                "secret"
8440            );
8441            assert!(git::is_clean(&state.repo).await.unwrap());
8442            assert!(
8443                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8444                    .await
8445                    .unwrap()
8446                    .contains(".env")
8447            );
8448        }
8449    }
8450
8451    #[tokio::test]
8452    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8453        let (_tmp, mut state, _) = landing_git_fixture().await;
8454        advance_landing_base(&state).await;
8455        landing_setup(&mut state).await;
8456        interrupt_landing_rebase(&mut state).await;
8457        // Exercise unusual names without asking Windows to create an invalid
8458        // control-character filename. Unix also covers embedded newlines.
8459        let locals = [
8460            "local notes",
8461            #[cfg(unix)]
8462            "local\nnotes",
8463        ];
8464        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8465            .await
8466            .unwrap();
8467        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8468        for local in locals {
8469            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8470            assert!(
8471                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8472                    .await
8473                    .unwrap()
8474                    .ok()
8475            );
8476        }
8477        restore_landing_worktree(&mut state).await.unwrap();
8478        for local in locals {
8479            assert_eq!(
8480                std::fs::read_to_string(state.repo.join(local)).unwrap(),
8481                "keep these notes"
8482            );
8483        }
8484        assert_eq!(
8485            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8486            "secret"
8487        );
8488        assert!(git::is_clean(&state.repo).await.unwrap());
8489        assert!(state.land_rebase_from.is_none());
8490    }
8491
8492    #[tokio::test]
8493    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8494        for local in ["advance", "advance/notes", "new-directory"] {
8495            let (_tmp, mut state, _) = landing_git_fixture().await;
8496            advance_landing_base(&state).await;
8497            // Also cover a local file blocking a new tracked directory.
8498            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8499            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8500            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8501            git::git(&state.repo, &["add", "."]).await.unwrap();
8502            git::git(&state.repo, &["commit", "-m", "add directory"])
8503                .await
8504                .unwrap();
8505            git::git(&state.repo, &["push", "origin", "main"])
8506                .await
8507                .unwrap();
8508            git::git(&state.repo, &["checkout", "winner"])
8509                .await
8510                .unwrap();
8511            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8512                .await
8513                .unwrap();
8514            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8515            let path = state.repo.join(local);
8516            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8517            std::fs::write(&path, "local notes").unwrap();
8518            interrupt_landing_rebase(&mut state).await;
8519            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8520            let checkpoint = state.land_rebase_from.clone();
8521            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8522            assert!(
8523                error.to_string().contains("conflicting with HEAD"),
8524                "{error:#}"
8525            );
8526            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8527            assert_eq!(
8528                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8529                before
8530            );
8531            assert_eq!(state.land_rebase_from, checkpoint);
8532        }
8533    }
8534
8535    #[tokio::test]
8536    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8537        for interrupted in [false, true] {
8538            let (_tmp, mut state, old) = landing_git_fixture().await;
8539            assert!(state.config.worktree.setup.is_empty());
8540            // A gate product exists before the base moves, without setup metadata.
8541            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8542                .await
8543                .unwrap();
8544            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8545            state.config.verify.gate =
8546                vec!["mkdir -p target && printf artifact > target/probe".into()];
8547            state.gate_ran = false;
8548            resume_observed_head(&mut state, &old).await.unwrap();
8549            assert_eq!(
8550                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8551                "artifact"
8552            );
8553            advance_landing_base(&state).await;
8554            if interrupted {
8555                interrupt_landing_rebase(&mut state).await;
8556                state = RunState::load(&state.id).unwrap();
8557            }
8558            state.config.verify.gate =
8559                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8560            let head = resume_observed_head(&mut state, &old).await.unwrap();
8561            assert_ne!(head, old);
8562            assert!(state.gate_allows_progress());
8563            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8564            assert_eq!(
8565                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8566                "artifact"
8567            );
8568            assert!(state.land_rebase_from.is_none());
8569            assert_eq!(
8570                git::remote_head(&state.repo, "origin", "task-head")
8571                    .await
8572                    .unwrap(),
8573                Some(head.clone())
8574            );
8575            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8576            land_with(&mut state, &green_pr().url, &forge)
8577                .await
8578                .unwrap();
8579            assert!(state.parked);
8580            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8581            assert!(forge.argvs().is_empty());
8582        }
8583    }
8584
8585    #[tokio::test]
8586    #[cfg(unix)]
8587    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8588        use std::os::fd::AsRawFd as _;
8589
8590        for interrupted in [false, true] {
8591            let (_tmp, mut state, _) = landing_git_fixture().await;
8592            advance_landing_base(&state).await;
8593            landing_setup(&mut state).await;
8594            if interrupted {
8595                interrupt_landing_rebase(&mut state).await;
8596            }
8597            state.config.worktree.setup =
8598                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8599            let common = crate::repo_lock::common_dir(&state.repo)
8600                .await
8601                .unwrap()
8602                .unwrap();
8603            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8604            state.config.coordination = crate::config::test_coordination();
8605            state.config.graph.timeout_resource_wait = 0;
8606            let external = std::fs::OpenOptions::new()
8607                .read(true)
8608                .write(true)
8609                .create(true)
8610                .truncate(false)
8611                .open(common.join("updater.lock"))
8612                .unwrap();
8613            // SAFETY: the descriptor belongs to `external` and remains open.
8614            let locked =
8615                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8616            assert_eq!(locked, 0);
8617            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8618            let checkpoint = state.land_rebase_from.clone();
8619            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8620            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8621            assert_eq!(
8622                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8623                before
8624            );
8625            assert_eq!(state.land_rebase_from, checkpoint);
8626            assert_eq!(
8627                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8628                "secret"
8629            );
8630
8631            drop(external);
8632            state.config.graph.timeout_resource_wait = 2;
8633            restore_landing_worktree(&mut state).await.unwrap();
8634            assert!(git::is_clean(&state.repo).await.unwrap());
8635            assert!(state.land_rebase_from.is_none());
8636            assert_eq!(
8637                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8638                "restored"
8639            );
8640        }
8641    }
8642
8643    #[tokio::test]
8644    #[cfg(unix)]
8645    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8646        use std::sync::atomic::{AtomicBool, Ordering};
8647
8648        let (_tmp, mut state, _) = landing_git_fixture().await;
8649        advance_landing_base(&state).await;
8650        landing_setup(&mut state).await;
8651        interrupt_landing_rebase(&mut state).await;
8652        let common = crate::repo_lock::common_dir(&state.repo)
8653            .await
8654            .unwrap()
8655            .unwrap();
8656        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8657        state.config.coordination = crate::config::test_coordination();
8658        let holder = crate::repo_lock::SeatLease::for_checkout(
8659            &state.repo,
8660            true,
8661            state.config.coordination.as_ref(),
8662        )
8663        .await
8664        .unwrap();
8665        assert!(holder.is_some());
8666        let cancelled = Arc::new(AtomicBool::new(false));
8667        let signal = cancelled.clone();
8668        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8669            signal.load(Ordering::SeqCst)
8670        });
8671        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8672        let checkpoint = state.land_rebase_from.clone();
8673        let (result, ()) = tokio::join!(
8674            tokio::time::timeout(
8675                Duration::from_secs(2),
8676                wait.scope(restore_landing_worktree(&mut state)),
8677            ),
8678            async {
8679                tokio::time::sleep(Duration::from_millis(100)).await;
8680                cancelled.store(true, Ordering::SeqCst);
8681            }
8682        );
8683        let error = result
8684            .expect("cancellation must release the waiting driver")
8685            .unwrap_err();
8686        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8687        assert_eq!(
8688            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8689            before
8690        );
8691        assert_eq!(state.land_rebase_from, checkpoint);
8692        assert_eq!(
8693            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8694            "secret"
8695        );
8696        drop(holder);
8697        restore_landing_worktree(&mut state).await.unwrap();
8698        assert!(state.land_rebase_from.is_none());
8699        assert!(git::is_clean(&state.repo).await.unwrap());
8700    }
8701
8702    #[tokio::test]
8703    #[cfg(unix)]
8704    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8705        use std::sync::atomic::{AtomicBool, Ordering};
8706
8707        for e2e in [false, true] {
8708            let (_tmp, mut state, head) = landing_git_fixture().await;
8709            let common = crate::repo_lock::common_dir(&state.repo)
8710                .await
8711                .unwrap()
8712                .unwrap();
8713            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8714            state.config.coordination = crate::config::test_coordination();
8715            if e2e {
8716                state.config.verify.e2e = vec!["true".into()];
8717                state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8718                    head.clone(),
8719                    false,
8720                    Vec::new(),
8721                ));
8722            } else {
8723                state.config.verify.gate = vec!["true".into()];
8724                state.gate_ran = false;
8725            }
8726            let holder = crate::repo_lock::SeatLease::for_checkout(
8727                &state.repo,
8728                true,
8729                state.config.coordination.as_ref(),
8730            )
8731            .await
8732            .unwrap();
8733            assert!(holder.is_some());
8734            let cancelled = Arc::new(AtomicBool::new(false));
8735            let signal = cancelled.clone();
8736            let waiting = Arc::new(tokio::sync::Notify::new());
8737            let observed = waiting.clone();
8738            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8739                observed.notify_one();
8740                signal.load(Ordering::SeqCst)
8741            });
8742            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8743            let url = green_pr().url;
8744            let result = {
8745                let mut publishing =
8746                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8747                // Git and fixture I/O precede local coordination. Start the
8748                // cancellation deadline only once the inherited wait policy
8749                // is polled, rather than timing those unrelated subprocesses.
8750                tokio::time::timeout(Duration::from_secs(30), async {
8751                    tokio::select! {
8752                        result = &mut publishing => panic!(
8753                            "verification must wait behind the held seat: {result:?}"
8754                        ),
8755                        () = waiting.notified() => {}
8756                    }
8757                })
8758                .await
8759                .expect("verification must reach the inherited coordination wait");
8760                cancelled.store(true, Ordering::SeqCst);
8761                tokio::time::timeout(Duration::from_secs(2), publishing).await
8762            };
8763            let error = result
8764                .expect("cancellation must release the verification waiter")
8765                .unwrap_err();
8766            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8767            assert!(error.to_string().contains("cancelled"), "{error:#}");
8768            assert!(forge.argvs().is_empty());
8769            assert_eq!(
8770                git::remote_head(&state.repo, "origin", "task-head")
8771                    .await
8772                    .unwrap(),
8773                Some(head.clone())
8774            );
8775            drop(holder);
8776            // Cancellation must release its reservation so another attempt can verify.
8777            assert_eq!(
8778                publish_landing_head(&mut state, &head, &url, &forge)
8779                    .await
8780                    .unwrap(),
8781                head
8782            );
8783        }
8784    }
8785
8786    #[tokio::test]
8787    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
8788        for staged in [false, true] {
8789            let (_tmp, mut state, old) = landing_git_fixture().await;
8790            advance_landing_base(&state).await;
8791            interrupt_landing_rebase(&mut state).await;
8792            std::fs::write(state.repo.join("change"), "user edit").unwrap();
8793            if staged {
8794                git::git(&state.repo, &["add", "change"]).await.unwrap();
8795            }
8796            assert!(resume_observed_head(&mut state, &old).await.is_err());
8797            assert_eq!(
8798                std::fs::read_to_string(state.repo.join("change")).unwrap(),
8799                "user edit"
8800            );
8801            assert_eq!(
8802                git::remote_head(&state.repo, "origin", "task-head")
8803                    .await
8804                    .unwrap(),
8805                Some(old)
8806            );
8807        }
8808    }
8809
8810    #[tokio::test]
8811    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
8812        let (_tmp, mut state, head) = landing_git_fixture().await;
8813        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8814        let id = state.id.clone();
8815        let pr = land_with(&mut state, &green_pr().url, &forge)
8816            .await
8817            .unwrap();
8818        assert_eq!(pr.state, PrLifecycle::Open);
8819        assert_eq!(state.id, id);
8820        assert!(state.parked);
8821        assert_eq!(state.status, RunStatus::Landing);
8822        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8823        assert!(forge.argvs().is_empty());
8824
8825        state.land_sync_pending = true;
8826        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
8827        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
8828        closed.pr.state = PrLifecycle::Closed;
8829        let forge = Scripted::new(vec![closed], vec![]);
8830        assert_eq!(
8831            land_with(&mut state, &green_pr().url, &forge)
8832                .await
8833                .unwrap()
8834                .state,
8835            PrLifecycle::Closed
8836        );
8837        assert_eq!(
8838            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
8839            "do not touch"
8840        );
8841        assert!(forge.argvs().is_empty());
8842    }
8843
8844    #[tokio::test]
8845    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
8846        let (_tmp, mut state, old) = landing_git_fixture().await;
8847        advance_landing_base(&state).await;
8848        state.config.verify.gate = vec!["exit 1".into()];
8849        assert!(resume_observed_head(&mut state, &old).await.is_err());
8850        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
8851        assert!(!state.gate_allows_progress());
8852        assert_eq!(
8853            git::remote_head(&state.repo, "origin", "task-head")
8854                .await
8855                .unwrap(),
8856            Some(old)
8857        );
8858        assert!(state.land_sync_pending);
8859    }
8860
8861    #[tokio::test]
8862    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
8863        let (_tmp, mut state, old) = landing_git_fixture().await;
8864        advance_landing_base(&state).await;
8865        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
8866        // Model a crash after the push but before saving its published SHA.
8867        state.pr_pushed_head = Some(old.clone());
8868        state.land_sync_pending = true;
8869        assert_eq!(
8870            resume_observed_head(&mut state, &pushed).await.unwrap(),
8871            pushed
8872        );
8873        // A writer races the observed PR snapshot: the explicit remote lease
8874        // must reject the push even though preflight saw our expected head.
8875        git::git(
8876            &state.repo,
8877            &["push", "--force", "origin", "main:refs/heads/task-head"],
8878        )
8879        .await
8880        .unwrap();
8881        assert!(
8882            publish_landing_head(
8883                &mut state,
8884                &pushed,
8885                &green_pr().url,
8886                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
8887            )
8888            .await
8889            .unwrap_err()
8890            .to_string()
8891            .contains("publishing gated")
8892        );
8893        assert!(
8894            resume_observed_head(&mut state, "foreign-head")
8895                .await
8896                .is_err()
8897        );
8898    }
8899    #[tokio::test]
8900    async fn landing_publication_refuses_a_pr_closed_during_gate() {
8901        let (_tmp, mut state, head) = landing_git_fixture().await;
8902        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
8903        closed.pr.state = PrLifecycle::Closed;
8904        let forge = Scripted::new(vec![closed], vec![]);
8905        assert!(
8906            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
8907                .await
8908                .unwrap_err()
8909                .to_string()
8910                .contains("PR closed or merged")
8911        );
8912    }
8913
8914    /// A candidate selected by the uncontested tally.
8915    fn winning_candidate(summary: &str) -> Candidate {
8916        Candidate {
8917            index: 0,
8918            label: 'A',
8919            agent: "opus".to_owned(),
8920            branch: "magi/x/A".to_owned(),
8921            worktree: PathBuf::from("/wt/A"),
8922            summary: summary.to_owned(),
8923            stat: String::new(),
8924            files: 1,
8925            commits: 1,
8926            empty: false,
8927            failed: None,
8928            verified_noop: None,
8929            duration_ms: 0,
8930            folded: false,
8931        }
8932    }
8933
8934    fn uncontested_tally() -> Tally {
8935        Tally {
8936            first_choice: BTreeMap::from([('A', 1)]),
8937            borda: BTreeMap::new(),
8938            winner: 'A',
8939            rankings: 1,
8940            unanimous_initial: true,
8941            deliberated: false,
8942            changed_votes: 0,
8943            unanimous_final: true,
8944            tie_break: None,
8945            judges: 1,
8946            present: 1,
8947            quorum: 1,
8948            met_quorum: true,
8949            uncontested: None,
8950        }
8951    }
8952
8953    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
8954        ReviewRecord {
8955            attempts: 0,
8956            reviewer,
8957            agent: agent.to_owned(),
8958            summary: summary.to_owned(),
8959            findings: Vec::new(),
8960            vote: None,
8961            failed: None,
8962            duration_ms: 0,
8963        }
8964    }
8965
8966    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
8967        let answered = reviews.len();
8968        ReviewRound {
8969            round,
8970            head: "abc1234".to_owned(),
8971            verified_head: None,
8972            verified_at: None,
8973            reviews,
8974            e2e: Vec::new(),
8975            verify_retried: false,
8976            e2e_deferred: false,
8977            e2e_defer_reason: None,
8978            fix: None,
8979            blocking: 0,
8980            answered,
8981            expected: answered,
8982            clean: true,
8983            progressed: false,
8984            vote_split: false,
8985            reconsideration: Vec::new(),
8986            verdict: None,
8987        }
8988    }
8989
8990    #[test]
8991    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
8992        let en = panel();
8993        assert!(en.contains("Task"), "{en}");
8994        assert!(en.contains("add retries to the uploader"), "{en}");
8995
8996        let mut state = run_state();
8997        state.config.graph.language = "ja".to_owned();
8998        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8999        assert!(ja.contains("タスク"), "{ja}");
9000        assert!(
9001            ja.contains("add retries to the uploader"),
9002            "the task itself is not translated: {ja}"
9003        );
9004    }
9005
9006    #[test]
9007    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
9008        // `run_state()` has no candidates, no tally and no reviews - exactly
9009        // the shape a run has before anything has judged or reviewed it, and
9010        // the panel must not print an empty box for either.
9011        let html = panel();
9012        assert!(!html.contains("What changed"), "{html}");
9013        assert!(!html.contains("Review verdict"), "{html}");
9014    }
9015
9016    #[test]
9017    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
9018        let mut state = run_state();
9019        state.candidates = vec![winning_candidate("")];
9020        state.tally = Some(uncontested_tally());
9021        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9022        assert!(
9023            !html.contains("What changed"),
9024            "an empty summary must not render an empty box: {html}"
9025        );
9026    }
9027
9028    #[test]
9029    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
9030        let mut state = run_state();
9031        state.candidates = vec![winning_candidate(
9032            "Added a retry loop around the uploader PUT call.",
9033        )];
9034        state.tally = Some(uncontested_tally());
9035        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9036        assert!(en.contains("What changed"), "{en}");
9037        assert!(
9038            en.contains("Added a retry loop around the uploader PUT call."),
9039            "{en}"
9040        );
9041
9042        state.config.graph.language = "ja".to_owned();
9043        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9044        assert!(ja.contains("変更内容"), "{ja}");
9045        assert!(
9046            ja.contains("Added a retry loop around the uploader PUT call."),
9047            "{ja}"
9048        );
9049    }
9050
9051    #[test]
9052    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
9053        let mut state = run_state();
9054        state.reviews = vec![
9055            review_round(
9056                1,
9057                vec![review_record(1, "alpha", "found a race, sent back")],
9058            ),
9059            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
9060        ];
9061        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9062        assert!(en.contains("Review verdict"), "{en}");
9063        assert!(en.contains("race is fixed, clean"), "{en}");
9064        assert!(
9065            !en.contains("found a race, sent back"),
9066            "only the round that actually cleared the merge should show: {en}"
9067        );
9068
9069        state.config.graph.language = "ja".to_owned();
9070        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9071        assert!(ja.contains("レビューの結論"), "{ja}");
9072        assert!(ja.contains("レビュアー"), "{ja}");
9073        assert!(ja.contains("race is fixed, clean"), "{ja}");
9074    }
9075
9076    /// The `incomplete_review = "warn"` policy (see
9077    /// `graph::Runner::review_loop`) can push a `clean` round to
9078    /// `state.reviews` while one seat's own record still has `failed: Some`
9079    /// and an empty `summary` - a seat that never answered, not one that
9080    /// answered with nothing to say.
9081    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
9082        ReviewRecord {
9083            attempts: 0,
9084            reviewer,
9085            agent: agent.to_owned(),
9086            summary: String::new(),
9087            findings: Vec::new(),
9088            vote: None,
9089            failed: Some(reason.to_owned()),
9090            duration_ms: 0,
9091        }
9092    }
9093
9094    #[test]
9095    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
9096        let mut state = run_state();
9097        state.reviews = vec![review_round(
9098            1,
9099            vec![
9100                review_record(1, "alpha", "clean, nothing to add"),
9101                unanswered_review_record(2, "beta", "timed out"),
9102            ],
9103        )];
9104        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9105        assert!(en.contains("clean, nothing to add"), "{en}");
9106        assert!(
9107            en.contains("produced no answer: timed out"),
9108            "a seat that never answered must say so, not render a blank box: {en}"
9109        );
9110        assert!(
9111            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
9112            "no reviewer box may be left empty: {en}"
9113        );
9114
9115        state.config.graph.language = "ja".to_owned();
9116        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9117        assert!(ja.contains("回答なし: timed out"), "{ja}");
9118    }
9119
9120    #[test]
9121    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
9122        let html = panel();
9123        assert!(!html.contains("<script"), "no script survives the csp");
9124        assert!(!html.contains("<form"), "form-action is 'none'");
9125        let pr = green_pr();
9126        assert_eq!(
9127            html.matches("http").count(),
9128            html.matches(pr.url.as_str()).count(),
9129            "the only http url in the panel is the pull request's own link"
9130        );
9131        assert!(
9132            html.contains("target=\"_blank\""),
9133            "the PR link must open in a new tab so it escapes the iframe"
9134        );
9135        assert!(
9136            html.contains("rel=\"noopener noreferrer\""),
9137            "external links opening in new tabs must carry noopener noreferrer"
9138        );
9139    }
9140
9141    #[test]
9142    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
9143        let html = panel();
9144        assert!(
9145            html.contains(">+</span>"),
9146            "an added line carries a `+` in the gutter, not only a background"
9147        );
9148        assert!(
9149            html.contains(">-</span>"),
9150            "a removed line carries a `-` in the gutter, not only a background"
9151        );
9152        assert!(
9153            html.contains(">new line</span>"),
9154            "the marker is moved to the gutter, so the body is printed once without it"
9155        );
9156    }
9157
9158    #[test]
9159    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
9160        let total = DIFF_MAX_LINES + 100;
9161        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
9162        let html = approval_panel(
9163            &run_state(),
9164            &green_pr(),
9165            NUMSTAT,
9166            &diff,
9167            &[],
9168            "feat: something long",
9169        );
9170        assert!(
9171            html.contains(&format!("100 of {total} diff lines omitted")),
9172            "the note must say exactly how much was cut"
9173        );
9174        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
9175        assert!(
9176            !html.contains(&format!("line {DIFF_MAX_LINES}")),
9177            "nothing past the threshold is rendered"
9178        );
9179        assert!(
9180            html.contains("/repo/magi"),
9181            "the note says where the rest is"
9182        );
9183    }
9184
9185    #[test]
9186    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
9187        let html = approval_panel(
9188            &run_state(),
9189            &green_pr(),
9190            "1\t2\tsrc/<b>&\"x\"'.rs",
9191            "",
9192            &[],
9193            "subject",
9194        );
9195        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
9196        assert!(
9197            !html.contains("<b>"),
9198            "an agent-influenced path must never become markup"
9199        );
9200    }
9201
9202    #[tokio::test]
9203    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
9204        let a = std::path::PathBuf::from("/repo/a");
9205        let b = std::path::PathBuf::from("/repo/b");
9206
9207        let held = repo_merge_lock(&a).lock_owned().await;
9208
9209        // A second, concurrent land run against the *same* repository must
9210        // wait - `try_lock` fails while `held` is alive.
9211        assert!(
9212            repo_merge_lock(&a).try_lock().is_err(),
9213            "a second merge into the same repository must not proceed concurrently"
9214        );
9215
9216        // A run against a *different* repository must not be blocked by it -
9217        // this is what keeps a slow rebase or `gh pr merge` in one
9218        // repository from also stalling a land-approval resume in another.
9219        assert!(
9220            repo_merge_lock(&b).try_lock().is_ok(),
9221            "a different repository's merge lock must be independent"
9222        );
9223
9224        drop(held);
9225        assert!(
9226            repo_merge_lock(&a).try_lock().is_ok(),
9227            "the lock is released once the holder is done"
9228        );
9229    }
9230
9231    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
9232        let mut state = landing_state();
9233        let mut rec = review_record(1, "alpha", "precise rejection reason");
9234        rec.vote = Some(if reject {
9235            crate::verdict::ReviewVote::Reject
9236        } else {
9237            crate::verdict::ReviewVote::Approve
9238        });
9239        if major {
9240            rec.findings = contested().findings;
9241        }
9242        let mut round = review_round(1, vec![rec]);
9243        round.clean = false;
9244        round.blocking = usize::from(major);
9245        state.reviews.push(round);
9246        state.config.graph.review_rounds = 1;
9247        state
9248    }
9249
9250    #[test]
9251    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
9252        for every in [false, true] {
9253            for contested in [false, true] {
9254                for major in [false, true] {
9255                    for reject in [false, true] {
9256                        let mut state = repair_state(major, reject);
9257                        state.config.graph.land_approval = every;
9258                        state.config.graph.hold_contested_merge = contested;
9259                        let reasons = approval_reasons(&state);
9260                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
9261                        assert_eq!(
9262                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
9263                            contested && major
9264                        );
9265                        assert_eq!(
9266                            reasons.contains(&ApprovalReason::FinalReject),
9267                            contested && reject
9268                        );
9269                        assert_eq!(
9270                            reasons.len(),
9271                            usize::from(every)
9272                                + usize::from(contested && major)
9273                                + usize::from(contested && reject)
9274                        );
9275                    }
9276                }
9277            }
9278        }
9279    }
9280
9281    #[test]
9282    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
9283        use crate::verdict::ReviewVote::{Approve, Reject};
9284        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
9285            let mut state = repair_state(false, initial_reject);
9286            state.reviews[0]
9287                .reconsideration
9288                .push(crate::run::ReviewRevoteRecord {
9289                    reviewer: 1,
9290                    agent: "alpha".into(),
9291                    vote: Some(final_vote),
9292                    reason: "changed after reading the panel <evidence>".into(),
9293                    failed: None,
9294                });
9295            assert_eq!(
9296                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9297                final_vote == Reject
9298            );
9299            for language in ["en", "ja"] {
9300                state.config.graph.language = language.into();
9301                let evidence = approval_evidence(&state);
9302                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
9303                assert!(evidence.contains("changed after reading the panel <evidence>"));
9304                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9305                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
9306                assert!(!html.contains("<evidence>"));
9307            }
9308            state.reviews[0].reconsideration[0].vote = None;
9309            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
9310            assert_eq!(
9311                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9312                initial_reject
9313            );
9314            assert!(approval_evidence(&state).contains("timed out"));
9315        }
9316    }
9317
9318    #[tokio::test]
9319    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
9320        for every in [false, true] {
9321            for contested in [false, true] {
9322                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
9323                {
9324                    let mut state = repair_state(major, reject);
9325                    state.config.graph.land_approval = every;
9326                    state.config.graph.hold_contested_merge = contested;
9327                    let forge = Scripted::new(
9328                        vec![seen("abc", Checks::Green, "CLEAN", false)],
9329                        vec![(true, "")],
9330                    );
9331                    land_with(&mut state, URL, &forge).await.unwrap();
9332                    let expected = every || (contested && (major || reject));
9333                    assert_eq!(state.land_approval.is_some(), expected);
9334                    assert_eq!(forge.calls().contains(&"merge"), !expected);
9335                    if expected {
9336                        assert!(state.parked);
9337                    }
9338                }
9339            }
9340        }
9341    }
9342
9343    #[tokio::test]
9344    async fn reviewed_branch_hold_is_read_before_landing_decision() {
9345        for (base, control) in [
9346            (false, "land_approval"),
9347            (true, "land_approval"),
9348            (false, "hold_contested_merge"),
9349        ] {
9350            let (_tmp, mut state, _) = landing_git_fixture().await;
9351            state.config.graph.land_approval = base;
9352            state.config.graph.hold_contested_merge = false;
9353            state.reviewed_commits = Some(Vec::new());
9354            if control == "hold_contested_merge" {
9355                state.reviews = repair_state(false, true).reviews;
9356            }
9357            std::fs::write(
9358                state.repo.join("magi.toml"),
9359                format!("[graph]\n{control} = {}\n", !base),
9360            )
9361            .unwrap();
9362            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
9363            git::git(&state.repo, &["commit", "-m", "approval policy"])
9364                .await
9365                .unwrap();
9366            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9367            state.land_sync_pending = false;
9368            state.pr_pushed_head = Some(head.clone());
9369            state.gate_head = Some(head.clone());
9370            let forge = Scripted::new(
9371                vec![seen(&head, Checks::Green, "CLEAN", false)],
9372                vec![(true, "")],
9373            );
9374            land_with(&mut state, URL, &forge).await.unwrap();
9375            assert!(
9376                state.land_approval.is_some(),
9377                "base={base}, control={control}"
9378            );
9379            assert!(!forge.calls().contains(&"merge"));
9380            if !base {
9381                let question = ask::Questions::open()
9382                    .get(&state.land_approval.as_ref().unwrap().question)
9383                    .unwrap();
9384                assert!(question.detail.contains(&format!(
9385                    "{control}=true from the reviewed branch's magi.toml"
9386                )));
9387            }
9388        }
9389    }
9390
9391    #[tokio::test]
9392    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9393        for file in ["magi.toml", ".magi/config.toml"] {
9394            for control in crate::config::OwnerHold::ALL {
9395                let (_tmp, mut state, _) = landing_git_fixture().await;
9396                state.config.graph.land_approval = false;
9397                state.config.graph.hold_contested_merge = false;
9398                state.reviewed_commits = Some(Vec::new());
9399                if control == crate::config::OwnerHold::HoldContestedMerge {
9400                    state.reviews = repair_state(false, true).reviews;
9401                }
9402                let config = state.repo.join(file);
9403                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9404                std::fs::write(
9405                    &config,
9406                    format!(
9407                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9408                        control.key()
9409                    ),
9410                )
9411                .unwrap();
9412                git::git(&state.repo, &["add", file]).await.unwrap();
9413                git::git(&state.repo, &["commit", "-m", "require approval"])
9414                    .await
9415                    .unwrap();
9416                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9417                let gate = state.config.verify.gate.clone();
9418                state.observe_branch_owner_holds(&head).await;
9419                assert_eq!(state.config.verify.gate, gate);
9420                assert!(state.owner_hold(control));
9421                let holds = state.branch_owner_holds.clone();
9422                git::git(&state.repo, &["rm", file]).await.unwrap();
9423                git::git(&state.repo, &["commit", "-m", "remove config"])
9424                    .await
9425                    .unwrap();
9426                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9427                state.save().unwrap();
9428                state = RunState::load(&state.id).unwrap();
9429                state.observe_branch_owner_holds(&later).await;
9430                assert_eq!(state.branch_owner_holds, holds);
9431                assert_eq!(state.branch_owner_holds[0].head, head);
9432                state.land_sync_pending = false;
9433                state.pr_pushed_head = Some(later.clone());
9434                state.gate_head = Some(later.clone());
9435                let forge = Scripted::new(
9436                    vec![seen(&later, Checks::Green, "CLEAN", false)],
9437                    vec![(true, "")],
9438                );
9439                land_with(&mut state, URL, &forge).await.unwrap();
9440                assert!(!forge.calls().contains(&"merge"));
9441                assert!(state.parked);
9442                let question = ask::Questions::open()
9443                    .get(&state.land_approval.as_ref().unwrap().question)
9444                    .unwrap();
9445                assert!(question.detail.contains("Approval required because:"));
9446                assert!(question.detail.contains(&format!(
9447                    "{}=true from the reviewed branch's {file}",
9448                    control.key()
9449                )));
9450                assert_eq!(state.branch_owner_holds, holds);
9451                state.save().unwrap();
9452                let resumed = RunState::load(&state.id).unwrap();
9453                assert!(resumed.owner_hold(control));
9454                assert_eq!(resumed.branch_owner_holds, holds);
9455                assert_eq!(
9456                    resumed.land_approval.unwrap().question,
9457                    state.land_approval.unwrap().question
9458                );
9459            }
9460        }
9461    }
9462
9463    #[tokio::test]
9464    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9465        let mut state = repair_state(false, true);
9466        state.reviews[0].clean = true;
9467        let mut finding = contested().findings.remove(0);
9468        finding.severity = crate::verdict::Severity::Minor;
9469        state.reviews[0].reviews[0].findings.push(finding);
9470        assert!(state.open_findings().is_empty());
9471        let mut pr = green_pr();
9472        pr.review_comments.clear();
9473        for language in ["en", "ja"] {
9474            state.config.graph.language = language.into();
9475            let html = approval_panel(&state, &pr, "", "", &[], "subject");
9476            assert!(html.contains("[R3-1-1] minor"));
9477            assert!(html.contains(if language == "ja" {
9478                "内部指摘の解決を意味するものではありません"
9479            } else {
9480                "This does not mean internal findings are resolved"
9481            }));
9482            assert!(
9483                html.find(if language == "ja" {
9484                    "承認が必要な理由:"
9485                } else {
9486                    "Approval required because:"
9487                })
9488                .unwrap()
9489                    < html.find("[R3-1-1]").unwrap()
9490            );
9491        }
9492        state.config.graph.language = "en".into();
9493        let observed = seen("abc", Checks::Green, "CLEAN", false);
9494        assert_eq!(
9495            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9496                .await
9497                .unwrap(),
9498            ApprovalGate::Pending
9499        );
9500        let id = state.land_approval.as_ref().unwrap().question.clone();
9501        let q = ask::Questions::open().get(&id).unwrap();
9502        assert!(q.detail.starts_with("Approval required because:"));
9503        assert!(q.detail.contains("final reviewer reject"));
9504        assert!(q.detail.contains("[R3-1-1] minor"));
9505        assert!(
9506            q.detail
9507                .contains("No adoption or resolution evidence recorded")
9508        );
9509        state.config.graph.land_approval = false;
9510        state.config.graph.hold_contested_merge = false;
9511        state.reviews.clear();
9512        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9513        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9514        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9515        let forge = Scripted::new(vec![observed], vec![]);
9516        land_with(&mut state, URL, &forge).await.unwrap();
9517        assert!(!forge.calls().contains(&"merge"));
9518        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9519        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9520    }
9521
9522    #[tokio::test]
9523    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9524        let mut state = repair_state(false, true);
9525        state.config.graph.land_approval = false;
9526        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9527        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9528        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9529        state.reviews[0].reviews[0].summary = long_reason.clone();
9530        for i in 1..=10 {
9531            let mut finding = contested().findings.remove(0);
9532            finding.id = format!("R1-1-{i}");
9533            finding.severity = if i == 9 {
9534                crate::verdict::Severity::Major
9535            } else {
9536                crate::verdict::Severity::Minor
9537            };
9538            finding.title = long_title.clone();
9539            finding.detail = long_detail.clone();
9540            state.reviews[0].reviews[0].findings.push(finding);
9541        }
9542        state.reviews[0].fix = Some(crate::run::FixRecord {
9543            agent: "fixer".into(),
9544            addressed: vec!["R1-1-9".into()],
9545            rejected: vec![crate::verdict::Rejection {
9546                id: "R1-1-10".into(),
9547                why: long_reason.clone(),
9548            }],
9549            notes: long_detail.clone(),
9550            committed: false,
9551            failed: None,
9552            duration_ms: 0,
9553            continuation: None,
9554        });
9555        assert_eq!(
9556            approval_reasons(&state),
9557            [
9558                ApprovalReason::OpenBlockingFindings,
9559                ApprovalReason::FinalReject
9560            ]
9561        );
9562        let excerpt = approval_excerpt(&long_reason, 300);
9563        assert_eq!(excerpt.chars().count(), 300);
9564        assert!(excerpt.ends_with('…'));
9565        let boundary = "拒".repeat(300);
9566        assert_eq!(approval_excerpt(&boundary, 300), boundary);
9567        for language in ["en", "ja"] {
9568            state.config.graph.language = language.into();
9569            for revote in [
9570                None,
9571                Some(crate::verdict::ReviewVote::Reject),
9572                Some(crate::verdict::ReviewVote::Approve),
9573            ] {
9574                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9575                state.reviews[0].reconsideration.clear();
9576                if let Some(vote) = revote {
9577                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9578                    state.reviews[0]
9579                        .reconsideration
9580                        .push(crate::run::ReviewRevoteRecord {
9581                            reviewer: 1,
9582                            agent: "alpha".into(),
9583                            vote: Some(vote),
9584                            reason: long_reason.clone(),
9585                            failed: None,
9586                        });
9587                }
9588                let evidence = approval_evidence(&state);
9589                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9590                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9591                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9592                assert_eq!(
9593                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9594                    final_vote == crate::verdict::ReviewVote::Reject
9595                );
9596                assert!(evidence.contains(&excerpt));
9597                assert!(evidence.contains("[R1-1-8] minor"));
9598                assert!(evidence.contains("[R1-1-9] major"));
9599                assert!(evidence.contains("[R1-1-10] minor"));
9600                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9601                    assert!(!evidence.contains(tail));
9602                }
9603                assert!(evidence.contains(if language == "ja" {
9604                    "採用申告(解決未確認)"
9605                } else {
9606                    "claimed addressed (resolution unconfirmed)"
9607                }));
9608                assert!(evidence.contains(if language == "ja" {
9609                    "不採用理由"
9610                } else {
9611                    "declined"
9612                }));
9613                let major_evidence = evidence
9614                    .split("[R1-1-9] major")
9615                    .nth(1)
9616                    .unwrap()
9617                    .split("[R1-1-10]")
9618                    .next()
9619                    .unwrap();
9620                assert!(major_evidence.contains(if language == "ja" {
9621                    "採用申告(解決未確認)"
9622                } else {
9623                    "claimed addressed (resolution unconfirmed)"
9624                }));
9625                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9626                assert!(last_evidence.contains(if language == "ja" {
9627                    "不採用理由"
9628                } else {
9629                    "declined"
9630                }));
9631                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9632                assert!(html.contains(&esc(&evidence)));
9633                assert_eq!(
9634                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9635                        .await
9636                        .unwrap(),
9637                    ApprovalGate::Pending
9638                );
9639                let id = &state.land_approval.take().unwrap().question;
9640                let q = ask::Questions::open().get(id).unwrap();
9641                assert!(q.detail.starts_with(&evidence));
9642            }
9643            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9644        }
9645    }
9646
9647    #[test]
9648    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9649        for (major, reject) in [(true, false), (false, true), (true, true)] {
9650            let state = repair_state(major, reject);
9651            assert!(repair_available(&state));
9652            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9653        }
9654        assert!(!repair_available(&repair_state(false, false)));
9655        let mut clean = repair_state(true, false);
9656        clean.reviews[0].clean = true;
9657        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9658        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9659    }
9660
9661    #[tokio::test]
9662    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9663        let mut state = repair_state(true, false);
9664        let pr = green_pr();
9665        approval_gate(&mut state, &pr, "feat: x", None, "abc")
9666            .await
9667            .unwrap();
9668        let store = ask::Questions::open();
9669        let id = state.land_approval.as_ref().unwrap().question.clone();
9670        // Simulate an unanswered two-choice question created by an older build.
9671        store
9672            .update(&id, |q| {
9673                q.choices = vec![APPROVE.into(), HOLD.into()];
9674                Ok(())
9675            })
9676            .unwrap();
9677        let upgraded = store.get(&id).unwrap();
9678        assert_eq!(upgraded.choices, approval_choices(&state));
9679        assert!(!upgraded.actions.contains_key(HOLD));
9680        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9681        assert!(
9682            store
9683                .list()
9684                .iter()
9685                .any(|q| q.id == id && q.choices == upgraded.choices)
9686        );
9687        assert!(
9688            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9689        );
9690        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9691        store
9692            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9693            .unwrap();
9694        // An earlier build may have recorded the repair answer and stopped
9695        // before any driver consumed it. Reconcile that durable decision too.
9696        store
9697            .update(&id, |q| {
9698                q.actions.clear();
9699                Ok(())
9700            })
9701            .unwrap();
9702        assert_eq!(
9703            store.get(&id).unwrap().chosen_action(),
9704            Some(&ask::ChoiceAction::Resume {
9705                run: state.id.clone()
9706            })
9707        );
9708        let binding = state.land_approval.clone();
9709        assert_eq!(
9710            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9711                .await
9712                .unwrap(),
9713            ApprovalGate::Repair
9714        );
9715        assert!(state.land_approval.is_none());
9716        assert_eq!(state.merge_repairs.len(), 1);
9717        let request = &state.merge_repairs[0];
9718        assert_eq!(request.question, id);
9719        assert_eq!(request.head, "abc");
9720        assert_eq!(request.pr, pr.url);
9721        assert_eq!(
9722            request.reviews[0].reviews[0].summary,
9723            "precise rejection reason"
9724        );
9725        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9726        assert_eq!(
9727            request.reviews[0].reviews[0].findings[0].detail,
9728            state.reviews[0].reviews[0].findings[0].detail
9729        );
9730        // A repeated consumption of the same answer never dispatches another repair.
9731        state.land_approval = binding;
9732        assert_eq!(
9733            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9734                .await
9735                .unwrap(),
9736            ApprovalGate::Repair
9737        );
9738        assert_eq!(state.merge_repairs.len(), 1);
9739        state.land_approval = None;
9740        state.config.graph.land_approval = false;
9741        state.config.graph.hold_contested_merge = false;
9742        state.reviews.clear();
9743        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9744        assert_eq!(
9745            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9746                .await
9747                .unwrap(),
9748            ApprovalGate::Pending
9749        );
9750        let fresh_id = &state.land_approval.as_ref().unwrap().question;
9751        assert_ne!(fresh_id, &id);
9752        let fresh = store.get(fresh_id).unwrap();
9753        assert!(
9754            fresh
9755                .detail
9756                .contains("fresh owner approval after merge repair")
9757        );
9758        assert!(fresh.detail.contains("No review recorded"));
9759        assert!(!fresh.detail.contains("precise rejection reason"));
9760    }
9761
9762    #[tokio::test]
9763    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9764        for choice in [REPAIR, HOLD] {
9765            let mut state = repair_state(false, true);
9766            let observed = seen("abc", Checks::Green, "CLEAN", false);
9767            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9768                .await
9769                .unwrap();
9770            let id = state.land_approval.as_ref().unwrap().question.clone();
9771            ask::Questions::open()
9772                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9773                .unwrap();
9774            let forge = Scripted::new(vec![observed], vec![(true, "")]);
9775            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9776                .await
9777                .unwrap();
9778            assert!(
9779                forge
9780                    .argvs()
9781                    .iter()
9782                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
9783            );
9784            assert!(!forge.calls().contains(&"fix"));
9785            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
9786            assert_ne!(state.status, RunStatus::Merged);
9787        }
9788    }
9789
9790    #[test]
9791    fn only_the_merge_choice_merges_and_silence_holds() {
9792        let table = [
9793            (None, Approval::Hold),
9794            (Some("merge"), Approval::Merge),
9795            (Some(" merge\n"), Approval::Merge),
9796            (Some("hold"), Approval::Hold),
9797            (Some(""), Approval::Hold),
9798            (Some("yes"), Approval::Hold),
9799        ];
9800        for (answer, want) in table {
9801            assert_eq!(
9802                approval(answer),
9803                want,
9804                "answer {answer:?} must resolve to {want:?}"
9805            );
9806        }
9807    }
9808
9809    #[tokio::test]
9810    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
9811        let mut state = landing_state();
9812        state.config.graph.land_approval = true;
9813        let pr = green_pr();
9814
9815        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9816            .await
9817            .unwrap();
9818        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
9819        assert!(
9820            !state.parked,
9821            "approval_gate itself never sets `parked`; only its caller does"
9822        );
9823
9824        let store = ask::Questions::open();
9825        let filed: Vec<_> = store
9826            .list()
9827            .into_iter()
9828            .filter(|q| q.run == state.id)
9829            .collect();
9830        assert_eq!(filed.len(), 1, "exactly one question is filed");
9831        assert_eq!(filed[0].node, APPROVAL_NODE);
9832        assert_eq!(filed[0].choices, approval_choices(&state));
9833        assert!(filed[0].status.open());
9834
9835        // A second visit - standing in for a resumed run whose slot the
9836        // daemon handed to something else while nobody had answered - must
9837        // find the same question rather than filing a second one.
9838        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9839            .await
9840            .unwrap();
9841        assert_eq!(again, ApprovalGate::Pending);
9842        let still_one = store
9843            .list()
9844            .into_iter()
9845            .filter(|q| q.run == state.id)
9846            .count();
9847        assert_eq!(
9848            still_one, 1,
9849            "asking twice must not double-file the question"
9850        );
9851    }
9852
9853    #[tokio::test]
9854    async fn approving_the_existing_question_is_read_back_as_approved() {
9855        crate::run::pin_test_home();
9856        let mut state = run_state();
9857        state.config.graph.land_approval = true;
9858        let pr = green_pr();
9859        assert_eq!(
9860            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9861                .await
9862                .unwrap(),
9863            ApprovalGate::Pending
9864        );
9865
9866        let store = ask::Questions::open();
9867        let mut q = store
9868            .list()
9869            .into_iter()
9870            .find(|q| q.run == state.id)
9871            .expect("filed above");
9872        let talks = crate::talk::Talks::open();
9873        let cfg = crate::config::Config {
9874            agents: vec![crate::config::AgentSpec {
9875                id: "mock".into(),
9876                kind: crate::config::AgentKind::Command,
9877                model: None,
9878                command: vec!["true".into()],
9879                extra_args: Vec::new(),
9880                env: Default::default(),
9881                prompt_delivery: None,
9882                max_turn_secs: None,
9883            }],
9884            ..crate::config::Config::default()
9885        };
9886        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
9887        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
9888        crate::talk::drain(&mut talk, &talks).unwrap();
9889        assert_eq!(
9890            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9891                .await
9892                .unwrap(),
9893            ApprovalGate::Pending,
9894            "consultation cannot approve or hold the merge"
9895        );
9896        q = store.get(&q.id).unwrap();
9897        assert!(q.answer.is_none());
9898        // The owner's merge answer (from the chat or the card) is the approval.
9899        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9900        store.put(&mut q).unwrap();
9901
9902        assert_eq!(
9903            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9904                .await
9905                .unwrap(),
9906            ApprovalGate::Approved
9907        );
9908    }
9909
9910    #[tokio::test]
9911    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
9912        crate::run::pin_test_home();
9913        let store = ask::Questions::open();
9914        for via_list in [false, true] {
9915            let mut state = repair_state(false, true);
9916            let pr = green_pr();
9917            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9918                .await
9919                .unwrap();
9920            let id = state.land_approval.as_ref().unwrap().question.clone();
9921            store
9922                .update(&id, |q| {
9923                    q.actions.insert(
9924                        HOLD.to_owned(),
9925                        ask::ChoiceAction::Resume {
9926                            run: state.id.clone(),
9927                        },
9928                    );
9929                    Ok(())
9930                })
9931                .unwrap();
9932            let q = if via_list {
9933                store.list().into_iter().find(|q| q.id == id).unwrap()
9934            } else {
9935                store.get(&id).unwrap()
9936            };
9937            assert!(!q.actions.contains_key(HOLD));
9938            store
9939                .update(&id, |q| {
9940                    // Check the persisted migration, without another read upgrade.
9941                    assert!(!q.actions.contains_key(HOLD));
9942                    assert!(!upgrade_repair_choice(q, &state));
9943                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
9944                })
9945                .unwrap();
9946            assert!(store.get(&id).unwrap().chosen_action().is_none());
9947            assert_eq!(
9948                approval_gate(&mut state, &pr, "feat: x", None, "abc")
9949                    .await
9950                    .unwrap(),
9951                ApprovalGate::Held
9952            );
9953        }
9954    }
9955
9956    #[tokio::test]
9957    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
9958        crate::run::pin_test_home();
9959        let store = ask::Questions::open();
9960
9961        let mut held_state = run_state();
9962        held_state.config.graph.land_approval = true;
9963        let pr = green_pr();
9964        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9965            .await
9966            .unwrap();
9967        let mut q = store
9968            .list()
9969            .into_iter()
9970            .find(|q| q.run == held_state.id)
9971            .expect("filed above");
9972        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
9973        store.put(&mut q).unwrap();
9974        assert_eq!(
9975            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9976                .await
9977                .unwrap(),
9978            ApprovalGate::Held
9979        );
9980
9981        let mut abandoned_state = run_state();
9982        abandoned_state.config.graph.land_approval = true;
9983        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9984            .await
9985            .unwrap();
9986        let mut q = store
9987            .list()
9988            .into_iter()
9989            .find(|q| q.run == abandoned_state.id)
9990            .expect("filed above");
9991        q.abandon("no answer within the timeout");
9992        store.put(&mut q).unwrap();
9993        assert_eq!(
9994            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9995                .await
9996                .unwrap(),
9997            ApprovalGate::Pending,
9998            "an expired approval must ask again without merging"
9999        );
10000        assert_eq!(
10001            store.get(&q.id).unwrap().status,
10002            ask::QuestionStatus::Abandoned
10003        );
10004        assert_ne!(
10005            abandoned_state.land_approval.as_ref().unwrap().question,
10006            q.id
10007        );
10008    }
10009
10010    fn contested() -> ContestedHandoff {
10011        let finding = |id: &str, n: u32| crate::verdict::Finding {
10012            id: id.to_owned(),
10013            severity: crate::verdict::Severity::Major,
10014            file: Some("src/a.rs".to_owned()),
10015            line: Some(n),
10016            title: format!("problem {id}"),
10017            detail: String::new(),
10018        };
10019        ContestedHandoff {
10020            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
10021            rejecters: vec![(1, "alpha".to_owned())],
10022        }
10023    }
10024
10025    #[test]
10026    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
10027        let mut state = run_state();
10028        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
10029        state.contested_handoff = Some(contested());
10030        assert!(contested_to_ask(&state).is_some());
10031        state.config.graph.hold_contested_merge = false;
10032        assert!(
10033            contested_to_ask(&state).is_none(),
10034            "the switch restores today"
10035        );
10036    }
10037
10038    #[test]
10039    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
10040        let q = ask::Question::new(
10041            "run-1".to_owned(),
10042            APPROVAL_NODE.to_owned(),
10043            "land".to_owned(),
10044            "Merge?".to_owned(),
10045            String::new(),
10046            vec![APPROVE.to_owned(), HOLD.to_owned()],
10047        );
10048        let none = deputy_brief(&q, None);
10049        assert!(none.contains("could not be read"), "{none}");
10050        assert!(none.contains("Silence is a hold"), "{none}");
10051
10052        let mut state = run_state();
10053        state.pr = Some(crate::run::PrRecord {
10054            url: "https://example.test/pull/7".to_owned(),
10055            number: 7,
10056            state: "open".to_owned(),
10057            checks: "green".to_owned(),
10058            round: 0,
10059            rounds: 3,
10060            red_at_merge: Vec::new(),
10061        });
10062        state.contested_handoff = Some(contested());
10063        let b = deputy_brief(&q, Some(&state));
10064        assert!(b.contains("https://example.test/pull/7"), "{b}");
10065        assert!(b.contains("not recorded in this legacy question"), "{b}");
10066        assert!(!b.contains("This question was filed although"));
10067        state.contested_handoff = None;
10068        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
10069    }
10070
10071    #[test]
10072    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
10073        for lang in ["en", "ja"] {
10074            let mut cfg = crate::config::Config::default();
10075            cfg.graph.language = lang.to_owned();
10076            let w = words(&cfg.graph.language);
10077            let text = w.approval_detail(
10078                "https://github.com/yukimemi/magi/pull/42",
10079                "main",
10080                "feat: x",
10081                Some(&contested()),
10082            );
10083            assert!(text.contains("pull/42"), "{text}");
10084            assert!(
10085                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
10086                "{text}"
10087            );
10088            assert!(text.contains("R3-1-5"), "{text}");
10089            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
10090            assert!(text.contains("2"), "the rest are counted: {text}");
10091            assert!(text.contains("#1 (alpha)"), "{text}");
10092        }
10093        let plain = words("en").approval_detail("u", "main", "s", None);
10094        assert!(!plain.contains("reject"), "{plain}");
10095    }
10096
10097    #[tokio::test]
10098    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
10099        crate::run::pin_test_home();
10100        let mut state = run_state();
10101        state.config.graph.land_approval = false;
10102        state.contested_handoff = Some(contested());
10103        let pr = green_pr();
10104        let c = contested_to_ask(&state);
10105        assert_eq!(
10106            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10107                .await
10108                .unwrap(),
10109            ApprovalGate::Pending,
10110            "silence is a hold"
10111        );
10112        let store = ask::Questions::open();
10113        let filed: Vec<_> = store
10114            .list()
10115            .into_iter()
10116            .filter(|q| q.run == state.id)
10117            .collect();
10118        assert_eq!(filed.len(), 1);
10119        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
10120
10121        assert_eq!(
10122            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10123                .await
10124                .unwrap(),
10125            ApprovalGate::Pending
10126        );
10127        let mut q = store
10128            .list()
10129            .into_iter()
10130            .find(|q| q.run == state.id)
10131            .unwrap();
10132        assert_eq!(q.id, filed[0].id, "the same question after a resume");
10133        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10134        store.put(&mut q).unwrap();
10135        assert_eq!(
10136            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10137                .await
10138                .unwrap(),
10139            ApprovalGate::Approved
10140        );
10141    }
10142
10143    #[test]
10144    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
10145        let rows = parse_numstat(NUMSTAT);
10146        assert_eq!(
10147            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
10148            ["src/web.rs", "src/land.rs", "assets/logo.png"]
10149        );
10150        assert_eq!(rows[2].added, None, "a binary file has no line counts");
10151    }
10152    #[test]
10153    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
10154        // Reported from a real run: the merge question arrived in English on a
10155        // repository with `language = "ja"`. magi's own strings have to follow
10156        // that setting too - "it is a literal in Rust" is not an answer.
10157        let mut state = run_state();
10158        state.config.graph.language = "ja".to_owned();
10159        let pr = green_pr();
10160        let commits = ["c1".to_owned()];
10161
10162        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10163        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
10164        assert!(ja.contains("squash されるコミット"), "{ja}");
10165        assert!(ja.contains("レビューコメント"), "{ja}");
10166        assert!(ja.contains("差分"), "{ja}");
10167        assert!(
10168            !ja.contains("Commits being squashed"),
10169            "no English left over"
10170        );
10171
10172        let w = words("ja");
10173        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
10174        assert!(
10175            w.approval_detail("http://x/1", "main", "feat: x", None)
10176                .contains("パネル")
10177        );
10178
10179        // The evidence itself is language-neutral and must survive either way.
10180        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
10181        assert!(ja.contains("feat: x"), "nor is the merge subject");
10182
10183        // English stays the default, and a language magi cannot check falls
10184        // back to it rather than shipping a guess.
10185        state.config.graph.language = "en".to_owned();
10186        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10187        assert!(en.contains("Commits being squashed"), "{en}");
10188        assert_eq!(words("Klingon").html_lang, "en");
10189    }
10190
10191    /// A `gh pr list` result naming exactly one pull request whose base and
10192    /// merge time both fit the run is exactly the case
10193    /// [`find_external_merge`] exists to act on.
10194    #[test]
10195    fn pick_open_pr_classifies_by_count_and_base() {
10196        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
10197        assert_eq!(
10198            pick_open_pr(one, "main").unwrap(),
10199            OpenPr::One {
10200                url: "https://x/pull/58".into(),
10201                title: "t".into()
10202            }
10203        );
10204        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
10205        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
10206        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
10207                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
10208        assert_eq!(
10209            pick_open_pr(two, "main").unwrap(),
10210            OpenPr::Many(vec!["u1".into(), "u2".into()])
10211        );
10212        // A fork's same-named branch is not a pull request for this head.
10213        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
10214        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
10215        assert!(pick_open_pr("not json", "main").is_err());
10216        // An incomplete record is an error, never "nothing open".
10217        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
10218        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
10219    }
10220
10221    #[test]
10222    fn pick_merged_pr_picks_the_unique_match() {
10223        let json = r#"[
10224            {"url": "https://github.com/o/r/pull/42", "number": 42,
10225             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
10226        ]"#;
10227        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10228        let found = pick_merged_pr(json, "main", created_at)
10229            .expect("valid json")
10230            .expect("one unambiguous match");
10231        assert_eq!(found.url, "https://github.com/o/r/pull/42");
10232        assert_eq!(found.number, 42);
10233    }
10234
10235    /// Two candidates surviving the filter is exactly as uninformative as
10236    /// zero — a branch name can be reused across runs — so neither is
10237    /// preferred over the other and nothing is recorded automatically.
10238    #[test]
10239    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
10240        let json = r#"[
10241            {"url": "https://github.com/o/r/pull/42", "number": 42,
10242             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
10243            {"url": "https://github.com/o/r/pull/43", "number": 43,
10244             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
10245        ]"#;
10246        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10247        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10248        let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
10249        assert!(error.to_string().contains("ambiguous"), "{error:#}");
10250    }
10251
10252    /// A pull request that targets a different base branch cannot be this
10253    /// run's, whatever its head branch is named — a reused branch name from
10254    /// an unrelated task must not be recorded as this run's merge.
10255    #[test]
10256    fn pick_merged_pr_ignores_a_different_base_branch() {
10257        let json = r#"[
10258            {"url": "https://github.com/o/r/pull/42", "number": 42,
10259             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
10260        ]"#;
10261        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10262        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10263    }
10264
10265    /// A pull request merged before this run was even created cannot be this
10266    /// run's winner, no matter how its head branch is spelled.
10267    #[test]
10268    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
10269        let json = r#"[
10270            {"url": "https://github.com/o/r/pull/42", "number": 42,
10271             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
10272        ]"#;
10273        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10274        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10275    }
10276
10277    #[test]
10278    fn slug_of_pr_url_reads_host_owner_and_repo() {
10279        assert_eq!(
10280            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
10281            Some("github.com/yukimemi/shun")
10282        );
10283    }
10284
10285    #[test]
10286    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
10287        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
10288        assert_eq!(slug_of_pr_url("not a url at all"), None);
10289        assert_eq!(slug_of_pr_url("https://github.com"), None);
10290    }
10291
10292    #[test]
10293    fn slug_of_repo_url_reads_host_owner_and_repo() {
10294        assert_eq!(
10295            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
10296            Some("github.com/yukimemi/magi")
10297        );
10298        assert_eq!(slug_of_repo_url("https://github.com"), None);
10299    }
10300
10301    #[test]
10302    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
10303        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
10304            .expect("same repo, different case");
10305    }
10306
10307    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
10308    /// own in-progress run and rewrote its status from a pull request in a
10309    /// completely different repository. This is the guard that must catch
10310    /// that even when an explicit (but wrong) id is given.
10311    #[test]
10312    fn ensure_same_repo_refuses_a_different_repo() {
10313        let err =
10314            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
10315        let msg = format!("{err:#}");
10316        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10317        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
10318    }
10319
10320    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
10321    /// instance mirroring a `github.com` repository's name, say) must not be
10322    /// treated as the same repository just because the trailing path
10323    /// matches.
10324    #[test]
10325    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
10326        let err = ensure_same_repo(
10327            "github.com/yukimemi/magi",
10328            "github.example.com/yukimemi/magi",
10329        )
10330        .unwrap_err();
10331        let msg = format!("{err:#}");
10332        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10333        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
10334    }
10335
10336    /// No winner decided yet means there is no branch to ask GitHub about at
10337    /// all — `find_external_merge` must return `None` without ever spawning
10338    /// `gh`, which this proves by never providing a real repository to spawn
10339    /// it in.
10340    #[tokio::test]
10341    async fn find_external_merge_returns_none_without_a_winner() {
10342        let state = RunState::new(
10343            PathBuf::from("/no/such/repo"),
10344            "main".to_owned(),
10345            "0000000000000000000000000000000000000000".to_owned(),
10346            "irrelevant".to_owned(),
10347            crate::config::Config::default(),
10348        );
10349        assert_eq!(find_external_merge(&state).await.unwrap(), None);
10350    }
10351
10352    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
10353        let mut run = RunState::new(
10354            PathBuf::from(repo),
10355            "main".to_owned(),
10356            "abcdef1234".to_owned(),
10357            "x".to_owned(),
10358            crate::config::Config::default(),
10359        );
10360        run.id = id.to_owned();
10361        run.status = status;
10362        run.driver_exited = true;
10363        run.pr = Some(crate::run::PrRecord {
10364            number: url.rsplit('/').next().unwrap().parse().unwrap(),
10365            url: url.to_owned(),
10366            state: state.to_owned(),
10367            checks: "red".to_owned(),
10368            round: 0,
10369            rounds: 2,
10370            red_at_merge: Vec::new(),
10371        });
10372        run.save_under(home).unwrap();
10373    }
10374
10375    fn recorded(home: &Path, id: &str) -> String {
10376        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10377        serde_json::from_str::<RunState>(&body)
10378            .unwrap()
10379            .pr
10380            .unwrap()
10381            .state
10382    }
10383
10384    const PR: &str = "https://github.com/o/r/pull/7";
10385
10386    #[test]
10387    fn write_through_updates_predecessors_and_siblings_only() {
10388        let tmp = tempfile::tempdir().unwrap();
10389        let h = tmp.path();
10390        pr_run(
10391            h,
10392            "20261004-100000-aaaa",
10393            "/repo/r",
10394            RunStatus::Superseded,
10395            PR,
10396            "open",
10397        );
10398        pr_run(
10399            h,
10400            "20261004-100100-bbbb",
10401            "/repo/r",
10402            RunStatus::Blocked,
10403            PR,
10404            "open",
10405        );
10406        // Not terminal: a driver may be writing it.
10407        pr_run(
10408            h,
10409            "20261004-100200-cccc",
10410            "/repo/r",
10411            RunStatus::Landing,
10412            PR,
10413            "open",
10414        );
10415        // Another repository's pull request with the same number.
10416        pr_run(
10417            h,
10418            "20261004-100300-dddd",
10419            "/repo/other",
10420            RunStatus::Blocked,
10421            "https://github.com/o/other/pull/7",
10422            "open",
10423        );
10424        // A different pull request of the same repository.
10425        pr_run(
10426            h,
10427            "20261004-100400-eeee",
10428            "/repo/r",
10429            RunStatus::Blocked,
10430            "https://github.com/o/r/pull/8",
10431            "open",
10432        );
10433        pr_run(
10434            h,
10435            "20261004-100500-ffff",
10436            "/repo/r",
10437            RunStatus::Merged,
10438            PR,
10439            "open",
10440        );
10441        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10442
10443        assert_eq!(
10444            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10445            2
10446        );
10447        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10448        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10449        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10450        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10451        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10452        // The source's own record is the caller's to write.
10453        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10454        // Idempotent.
10455        assert_eq!(
10456            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10457            0
10458        );
10459        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10460        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10461    }
10462
10463    #[test]
10464    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10465        let home = tempfile::tempdir().unwrap();
10466        let live_id = "20261004-100000-aaaa";
10467        let unknown_id = "20261004-100100-bbbb";
10468        for id in [live_id, unknown_id] {
10469            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10470            let mut s = RunState::load_under(id, home.path()).unwrap();
10471            s.driver_exited = false;
10472            // Model legacy driver evidence, not a newly reserved unstarted run.
10473            s.driver_claimed = None;
10474            if id == live_id {
10475                s.driver_pid = Some(std::process::id());
10476                s.driver_started_at = crate::proc::process_started_at(std::process::id());
10477            }
10478            s.save_under(home.path()).unwrap();
10479            if id == unknown_id {
10480                assert_eq!(
10481                    s.liveness_under(home.path(), false),
10482                    crate::run::Liveness::Unknown
10483                );
10484            }
10485        }
10486        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10487        assert_eq!(apply_pr_states(home.path(), &known), 0);
10488        for id in [live_id, unknown_id] {
10489            assert_eq!(recorded(home.path(), id), "open");
10490        }
10491    }
10492
10493    #[test]
10494    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10495        let tmp = tempfile::tempdir().unwrap();
10496        let h = tmp.path();
10497        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10498        pr_run(
10499            h,
10500            "20261004-100000-aaaa",
10501            "/repo/r",
10502            RunStatus::Superseded,
10503            &url(1),
10504            "open",
10505        );
10506        pr_run(
10507            h,
10508            "20261004-100100-bbbb",
10509            "/repo/r",
10510            RunStatus::Blocked,
10511            &url(2),
10512            "open",
10513        );
10514        pr_run(
10515            h,
10516            "20261004-100200-cccc",
10517            "/repo/r",
10518            RunStatus::Ready,
10519            &url(3),
10520            "open",
10521        );
10522        pr_run(
10523            h,
10524            "20261004-100300-dddd",
10525            "/repo/r",
10526            RunStatus::Ready,
10527            &url(4),
10528            "open",
10529        );
10530        pr_run(
10531            h,
10532            "20261004-100400-eeee",
10533            "/repo/r",
10534            RunStatus::Implementing,
10535            &url(1),
10536            "open",
10537        );
10538        assert_eq!(stale_open_prs(h).len(), 4);
10539
10540        let mut known = BTreeMap::new();
10541        known.insert(url(1), PrLifecycle::Merged);
10542        known.insert(url(2), PrLifecycle::Closed);
10543        known.insert(url(3), PrLifecycle::Open);
10544        // #4: the forge could not be read, so it has no answer.
10545        assert_eq!(apply_pr_states(h, &known), 2);
10546        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10547        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10548        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10549        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10550        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10551        assert_eq!(apply_pr_states(h, &known), 0);
10552    }
10553
10554    // --- the land loop against a scripted forge -------------------------
10555
10556    use std::collections::VecDeque;
10557    use std::sync::Mutex;
10558
10559    /// Answers views from a script (the last one repeats), merges from a
10560    /// queue, and records every call so a test can assert the order.
10561    struct Scripted {
10562        public_repo: Option<PathBuf>,
10563        evidence: Mutex<Option<CiEvidence>>,
10564        views: Mutex<VecDeque<Seen>>,
10565        merges: Mutex<VecDeque<(bool, String)>>,
10566        fix: Mutex<Option<Fixed>>,
10567        log: Mutex<Vec<&'static str>>,
10568        argvs: Mutex<Vec<Vec<String>>>,
10569        required: Mutex<Option<BTreeSet<String>>>,
10570        /// Set once a merge answered ok: the forge then reports `merged`,
10571        /// unless `queued` says the merge only entered a queue.
10572        merged: Mutex<bool>,
10573        queued: Mutex<bool>,
10574        /// Views fail once a merge answered ok.
10575        unreadable_after_merge: Mutex<bool>,
10576        /// Workflow runs asked to rerun, and whether that call fails.
10577        reruns: Mutex<Vec<String>>,
10578        rerun_fails: Mutex<bool>,
10579        /// Unix seconds; every poll moves it on by `POLL`.
10580        clock: Mutex<i64>,
10581    }
10582
10583    impl Scripted {
10584        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10585            Self {
10586                public_repo: None,
10587                evidence: Mutex::new(None),
10588                views: Mutex::new(views.into()),
10589                merges: Mutex::new(
10590                    merges
10591                        .into_iter()
10592                        .map(|(ok, m)| (ok, m.to_owned()))
10593                        .collect(),
10594                ),
10595                fix: Mutex::new(None),
10596                log: Mutex::new(Vec::new()),
10597                argvs: Mutex::new(Vec::new()),
10598                required: Mutex::new(None),
10599                merged: Mutex::new(false),
10600                queued: Mutex::new(false),
10601                unreadable_after_merge: Mutex::new(false),
10602                reruns: Mutex::new(Vec::new()),
10603                rerun_fails: Mutex::new(false),
10604                clock: Mutex::new(1_000),
10605            }
10606        }
10607        fn for_pr(url: &str, mut views: Vec<Seen>) -> Self {
10608            for view in &mut views {
10609                view.pr.url = url.to_owned();
10610            }
10611            Self::new(views, vec![])
10612        }
10613        fn argvs(&self) -> Vec<Vec<String>> {
10614            self.argvs.lock().unwrap().clone()
10615        }
10616        fn calls(&self) -> Vec<&'static str> {
10617            self.log.lock().unwrap().clone()
10618        }
10619    }
10620
10621    impl Forge for Scripted {
10622        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10623            self.evidence.lock().unwrap().clone()
10624        }
10625        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10626            self.log.lock().unwrap().push("view");
10627            if *self.unreadable_after_merge.lock().unwrap()
10628                && !self.argvs.lock().unwrap().is_empty()
10629            {
10630                anyhow::bail!("forge unreachable");
10631            }
10632            let mut seen = {
10633                let mut v = self.views.lock().unwrap();
10634                if v.len() > 1 {
10635                    v.pop_front().unwrap()
10636                } else {
10637                    v[0].clone()
10638                }
10639            };
10640            if seen.head == "@published" {
10641                let head =
10642                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10643                        .await?
10644                        .context("missing published head")?;
10645                seen.head.clone_from(&head);
10646                seen.rollup_head = head;
10647            }
10648            if *self.merged.lock().unwrap() {
10649                seen.pr.state = PrLifecycle::Merged;
10650            }
10651            Ok(seen)
10652        }
10653        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10654            self.log.lock().unwrap().push("merge");
10655            self.argvs.lock().unwrap().push(argv.to_vec());
10656            let out = self
10657                .merges
10658                .lock()
10659                .unwrap()
10660                .pop_front()
10661                .expect("unscripted merge");
10662            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10663            {
10664                *self.merged.lock().unwrap() = true;
10665            }
10666            Ok(out)
10667        }
10668        async fn poll(&self) {
10669            self.log.lock().unwrap().push("poll");
10670            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10671        }
10672        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10673            self.log.lock().unwrap().push("rerun");
10674            self.reruns.lock().unwrap().push(run.to_owned());
10675            if *self.rerun_fails.lock().unwrap() {
10676                anyhow::bail!("gh run rerun: no");
10677            }
10678            Ok(())
10679        }
10680        fn now(&self) -> i64 {
10681            *self.clock.lock().unwrap()
10682        }
10683        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10684            self.required.lock().unwrap().clone()
10685        }
10686        async fn fix(
10687            &self,
10688            _state: &mut RunState,
10689            _pr: &PrState,
10690            _round: usize,
10691            _budget: usize,
10692            _reason: &str,
10693            _logs: &str,
10694        ) -> Result<Fixed> {
10695            self.log.lock().unwrap().push("fix");
10696            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10697        }
10698    }
10699
10700    const REFUSED: &str =
10701        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10702
10703    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10704        let mut pr = green_pr();
10705        pr.checks = checks;
10706        pr.blocking = Blocking::of(merge_state);
10707        if !comments {
10708            pr.review_comments.clear();
10709        }
10710        Seen {
10711            pr,
10712            title: "feat: x".to_owned(),
10713            failing_urls: Vec::new(),
10714            head: head.to_owned(),
10715            rollup_head: head.to_owned(),
10716            merge_state: merge_state.to_owned(),
10717            contexts: Vec::new(),
10718            base: "main".to_owned(),
10719        }
10720    }
10721
10722    fn landing_state() -> RunState {
10723        crate::run::pin_test_home();
10724        let mut state = run_state();
10725        state.config.graph.land_approval = false;
10726        state
10727    }
10728
10729    #[test]
10730    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10731        assert!(!awaiting_new_head(None, "aaa"));
10732        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10733        assert!(awaiting_new_head(Some("abc123"), "def456"));
10734        assert!(awaiting_new_head(Some("abc123"), ""));
10735    }
10736
10737    #[test]
10738    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10739        let open = |c, m: &str| seen("a", c, m, false);
10740        let table = [
10741            (None, false, Refused::Pending),
10742            (
10743                Some(open(Checks::Pending, "BLOCKED")),
10744                false,
10745                Refused::Pending,
10746            ),
10747            (
10748                Some(open(Checks::Unknown, "BLOCKED")),
10749                false,
10750                Refused::Pending,
10751            ),
10752            (
10753                Some(open(Checks::Green, "UNKNOWN")),
10754                false,
10755                Refused::Pending,
10756            ),
10757            (Some(open(Checks::Green, "")), false, Refused::Pending),
10758            (
10759                Some(open(Checks::Green, "BLOCKED")),
10760                false,
10761                Refused::Recheck,
10762            ),
10763            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10764        ];
10765        for (after, rechecked, want) in table {
10766            assert_eq!(
10767                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10768                want
10769            );
10770        }
10771        let mut closed = open(Checks::Green, "CLEAN");
10772        closed.pr.state = PrLifecycle::Closed;
10773        assert_eq!(
10774            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10775            Refused::Final
10776        );
10777    }
10778
10779    #[test]
10780    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10781        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10782            let pr = seen("a", checks, "BEHIND", false).pr;
10783            assert_eq!(
10784                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10785                Step::Rebase
10786            );
10787        }
10788        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
10789            let current = seen("a", Checks::Green, status, false);
10790            assert_ne!(
10791                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10792                Step::Rebase
10793            );
10794            assert_ne!(
10795                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
10796                Refused::Behind
10797            );
10798        }
10799        let mut current = seen("a", Checks::Pending, "BEHIND", false);
10800        current.rollup_head = "old".into();
10801        assert_eq!(
10802            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10803            Refused::Behind
10804        );
10805        assert_eq!(
10806            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
10807            Refused::Pending
10808        );
10809        current.pr.state = PrLifecycle::Closed;
10810        assert_eq!(
10811            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10812            Refused::Final
10813        );
10814    }
10815
10816    #[tokio::test]
10817    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
10818        for boundary in ["initial", "premerge", "refusal"] {
10819            let (_tmp, mut state, old) = landing_git_fixture().await;
10820            state.land_sync_pending = false;
10821            advance_landing_base(&state).await;
10822            state.config.verify.gate = vec!["test -f advance".into()];
10823            state.config.verify.e2e = vec!["test -f advance".into()];
10824            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
10825                .await
10826                .unwrap();
10827            let old_binding = state.land_approval.clone().unwrap();
10828            let store = ask::Questions::open();
10829            let mut question = store.get(&old_binding.question).unwrap();
10830            question
10831                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10832                .unwrap();
10833            store.put(&mut question).unwrap();
10834            let mut views = Vec::new();
10835            if boundary != "initial" {
10836                views.push(seen(&old, Checks::Green, "CLEAN", false));
10837            }
10838            if boundary == "refusal" {
10839                views.push(seen(&old, Checks::Green, "CLEAN", false));
10840            }
10841            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
10842            behind.rollup_head = "old-ci-head".into();
10843            views.push(behind);
10844            // Publication checks the PR lease while verification has completed.
10845            views.push(seen(&old, Checks::Green, "CLEAN", false));
10846            views.push(seen("@published", Checks::Pending, "CLEAN", false));
10847            views.push(seen("@published", Checks::Green, "CLEAN", false));
10848            let merges = if boundary == "refusal" {
10849                vec![(false, REFUSED)]
10850            } else {
10851                vec![]
10852            };
10853            let mut forge = Scripted::new(views, merges);
10854            forge.public_repo = Some(state.repo.clone());
10855            let run = state.id.clone();
10856            land_with(&mut state, URL, &forge).await.unwrap();
10857            let head = state.pr_pushed_head.clone().unwrap();
10858            assert_ne!(head, old, "{boundary}");
10859            assert_eq!(state.id, run);
10860            assert_eq!(state.pr_branch(), Some("task-head"));
10861            assert_eq!(state.winner().unwrap().branch, "winner");
10862            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
10863            assert!(state.gate_allows_progress());
10864            let e2e = state.head_e2e.as_ref().unwrap();
10865            assert_eq!(e2e.head, head);
10866            assert!(e2e.passed);
10867            assert_eq!(state.land_sync_attempts, 1);
10868            assert!(!state.land_sync_pending);
10869            assert!(state.parked);
10870            let binding = state.land_approval.as_ref().unwrap();
10871            assert_eq!(binding.head, head);
10872            assert_ne!(binding.question, old_binding.question);
10873            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
10874            // The new question authorizes only the synchronized head on resume.
10875            let mut question = store.get(&binding.question).unwrap();
10876            question
10877                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10878                .unwrap();
10879            store.put(&mut question).unwrap();
10880            let forge = Scripted::new(
10881                vec![seen(&head, Checks::Green, "CLEAN", false)],
10882                vec![(true, "")],
10883            );
10884            land_with(&mut state, URL, &forge).await.unwrap();
10885            assert_eq!(state.status, RunStatus::Merged);
10886            assert_eq!(
10887                value_of(&forge.argvs()[0], "--match-head-commit"),
10888                Some(head.as_str())
10889            );
10890        }
10891    }
10892
10893    #[tokio::test]
10894    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
10895        let (_tmp, mut state, old) = landing_git_fixture().await;
10896        state.land_sync_pending = false;
10897        state.config.graph.land_approval = false;
10898        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
10899        advance_landing_base(&state).await;
10900        let mut forge = Scripted::new(
10901            vec![
10902                seen(&old, Checks::Green, "CLEAN", false),
10903                seen(&old, Checks::Green, "CLEAN", false),
10904                seen(&old, Checks::Green, "BEHIND", false),
10905                // The next observation is the publication lease check. The
10906                // refusal's evidence still applies to exactly this old head.
10907                seen(&old, Checks::Green, "CLEAN", false),
10908                seen("@published", Checks::Green, "CLEAN", false),
10909            ],
10910            vec![(false, REFUSED), (true, "")],
10911        );
10912        forge.public_repo = Some(state.repo.clone());
10913        land_with(&mut state, URL, &forge).await.unwrap();
10914        let head = state.pr_pushed_head.as_deref().unwrap();
10915        assert_ne!(head, old);
10916        assert_eq!(state.land_sync_attempts, 1);
10917        assert_eq!(state.gate_head.as_deref(), Some(head));
10918        assert_eq!(state.status, RunStatus::Merged);
10919        let requests = forge.argvs();
10920        assert_eq!(requests.len(), 2);
10921        assert_eq!(
10922            value_of(&requests[0], "--match-head-commit"),
10923            Some(old.as_str())
10924        );
10925        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
10926    }
10927
10928    #[tokio::test]
10929    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
10930        let (tmp, mut state, old) = landing_git_fixture().await;
10931        state.land_sync_pending = false;
10932        // A damaged history must not be interpreted as a missing base. Keep
10933        // the head's tree intact so worktree restoration itself can succeed.
10934        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
10935        let commit = tmp.path().join("broken-commit");
10936        std::fs::write(
10937            &commit,
10938            format!(
10939                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
10940                "f".repeat(40)
10941            ),
10942        )
10943        .unwrap();
10944        let replacement = git::git(
10945            &state.repo,
10946            &[
10947                "hash-object",
10948                "-t",
10949                "commit",
10950                "-w",
10951                commit.to_str().unwrap(),
10952            ],
10953        )
10954        .await
10955        .unwrap();
10956        git::git(&state.repo, &["replace", &old, replacement.trim()])
10957            .await
10958            .unwrap();
10959        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10960        land_with(&mut state, URL, &forge).await.unwrap();
10961        assert_eq!(state.land_sync_attempts, 0);
10962        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10963        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10964        assert!(forge.argvs().is_empty());
10965        assert!(
10966            state.events.iter().any(|e| e.message.contains(
10967                "could not determine whether the landing head contains the fetched base"
10968            ))
10969        );
10970    }
10971
10972    #[tokio::test]
10973    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
10974        let (_tmp, mut state, old) = landing_git_fixture().await;
10975        state.land_sync_pending = false;
10976        git::git(
10977            &state.repo,
10978            &["remote", "set-url", "origin", "missing-remote"],
10979        )
10980        .await
10981        .unwrap();
10982        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10983        land_with(&mut state, URL, &forge).await.unwrap();
10984        assert_eq!(state.land_sync_attempts, 0);
10985        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10986        assert!(
10987            state
10988                .events
10989                .iter()
10990                .any(|e| e.message.contains("cannot fetch landing base"))
10991        );
10992        assert!(forge.argvs().is_empty());
10993    }
10994
10995    #[tokio::test]
10996    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
10997        let (_tmp, mut state, old) = landing_git_fixture().await;
10998        state.land_sync_pending = false;
10999        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
11000        land_with(&mut state, URL, &forge).await.unwrap();
11001        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
11002        assert_eq!(state.land_sync_attempts, 0);
11003        assert!(
11004            state
11005                .events
11006                .iter()
11007                .any(|e| e.message.contains("already included"))
11008        );
11009        advance_landing_base(&state).await;
11010        state.land_sync_attempts = state.config.graph.land_rounds;
11011        state.land_sync_pending = true;
11012        state.save().unwrap();
11013        let mut restored = RunState::load(&state.id).unwrap();
11014        assert!(
11015            resume_observed_head(&mut restored, &old)
11016                .await
11017                .unwrap_err()
11018                .to_string()
11019                .contains("budget exhausted")
11020        );
11021        assert_eq!(
11022            git::remote_head(&state.repo, "origin", "task-head")
11023                .await
11024                .unwrap(),
11025            Some(old)
11026        );
11027    }
11028
11029    #[tokio::test]
11030    async fn a_normal_landing_merges_on_the_first_look() {
11031        let mut state = landing_state();
11032        let forge = Scripted::new(
11033            vec![seen("a", Checks::Green, "CLEAN", false)],
11034            vec![(true, "")],
11035        );
11036        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11037            .await
11038            .unwrap();
11039        // One fresh read, then the head-bound merge.
11040        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11041        assert_eq!(state.status, RunStatus::Merged);
11042    }
11043
11044    #[tokio::test]
11045    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
11046        let mut state = landing_state();
11047        let forge = Scripted::new(
11048            vec![seen("a", Checks::Green, "CLEAN", false)],
11049            std::iter::repeat_n((true, ""), 100).collect(),
11050        );
11051        *forge.queued.lock().unwrap() = true;
11052        let task = async {
11053            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11054                .await
11055                .unwrap();
11056        };
11057        // Still open after the command succeeded: it keeps watching and
11058        // never records a merge (it stops at the wait ceiling instead).
11059        task.await;
11060        assert_ne!(state.status, RunStatus::Merged);
11061    }
11062
11063    #[tokio::test]
11064    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
11065        let mut state = landing_state();
11066        let forge = Scripted::new(
11067            vec![seen("a", Checks::Green, "CLEAN", false)],
11068            std::iter::repeat_n((true, ""), 100).collect(),
11069        );
11070        *forge.unreadable_after_merge.lock().unwrap() = true;
11071        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11072            .await
11073            .ok();
11074        assert_ne!(state.status, RunStatus::Merged);
11075    }
11076
11077    #[tokio::test]
11078    async fn a_task_public_head_is_awaited_on_land_entry() {
11079        let mut state = landing_state();
11080        state.pr_head = Some("magi/task-abcd-1234".into());
11081        state.pr_pushed_head = Some("new".into());
11082        let forge = Scripted::new(
11083            vec![
11084                seen("old", Checks::Green, "CLEAN", false),
11085                seen("new", Checks::Green, "CLEAN", false),
11086            ],
11087            vec![(true, "")],
11088        );
11089        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11090            .await
11091            .unwrap();
11092        assert_eq!(
11093            forge.calls(),
11094            ["view", "poll", "view", "view", "merge", "view"]
11095        );
11096        assert_eq!(state.status, RunStatus::Merged);
11097    }
11098
11099    #[tokio::test]
11100    async fn a_superseded_public_head_owner_cannot_reenter_land() {
11101        let mut state = landing_state();
11102        state.pr_taken_over_by = Some("next".into());
11103        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
11104        assert!(
11105            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11106                .await
11107                .is_err()
11108        );
11109        assert!(forge.calls().is_empty());
11110    }
11111
11112    #[tokio::test]
11113    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
11114        let mut state = landing_state();
11115        let forge = Scripted::new(
11116            vec![
11117                seen("old", Checks::Green, "CLEAN", true),
11118                // The forge has not moved to the new head yet: still green.
11119                seen("old", Checks::Green, "CLEAN", true),
11120                seen("new", Checks::Pending, "BLOCKED", true),
11121                seen("new", Checks::Green, "CLEAN", true),
11122            ],
11123            vec![(true, "")],
11124        );
11125        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11126            head: "NEW".to_owned(),
11127        });
11128        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11129            .await
11130            .unwrap();
11131        assert_eq!(
11132            forge.calls(),
11133            [
11134                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
11135                "view"
11136            ]
11137        );
11138        assert_eq!(state.status, RunStatus::Merged);
11139    }
11140
11141    #[tokio::test]
11142    async fn a_head_that_never_arrives_stops_naming_both_commits() {
11143        let mut state = landing_state();
11144        let forge = Scripted::new(
11145            vec![
11146                seen("old", Checks::Green, "CLEAN", true),
11147                seen("someone-elses", Checks::Green, "CLEAN", true),
11148            ],
11149            vec![],
11150        );
11151        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11152            head: "mine".to_owned(),
11153        });
11154        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11155            .await
11156            .unwrap();
11157        assert!(!forge.calls().contains(&"merge"));
11158        let why = state.merge.as_ref().unwrap().detail.clone();
11159        assert!(
11160            why.contains("mine") && why.contains("someone-elses"),
11161            "{why}"
11162        );
11163        assert_eq!(state.status, RunStatus::Blocked);
11164    }
11165
11166    #[tokio::test]
11167    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
11168        let mut state = landing_state();
11169        let forge = Scripted::new(
11170            vec![
11171                seen("a", Checks::Green, "CLEAN", false),
11172                seen("a", Checks::Green, "CLEAN", false),
11173                seen("a", Checks::Pending, "BLOCKED", false),
11174                seen("a", Checks::Pending, "BLOCKED", false),
11175                seen("a", Checks::Green, "CLEAN", false),
11176            ],
11177            vec![(false, REFUSED), (true, "")],
11178        );
11179        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11180            .await
11181            .unwrap();
11182        assert_eq!(
11183            forge.calls(),
11184            [
11185                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
11186                "view"
11187            ]
11188        );
11189        assert_eq!(state.status, RunStatus::Merged);
11190    }
11191
11192    #[tokio::test]
11193    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
11194        let mut state = landing_state();
11195        let forge = Scripted::new(
11196            vec![
11197                seen("a", Checks::Green, "CLEAN", false),
11198                seen("a", Checks::Green, "BLOCKED", false),
11199            ],
11200            vec![(false, REFUSED), (false, REFUSED)],
11201        );
11202        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11203            .await
11204            .unwrap();
11205        // One re-look is allowed for the forge's own lag, then it is final.
11206        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
11207        let why = state.merge.as_ref().unwrap().detail.clone();
11208        assert!(
11209            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
11210            "{why}"
11211        );
11212        assert_eq!(state.status, RunStatus::Blocked);
11213    }
11214
11215    #[test]
11216    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
11217        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
11218        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
11219        // The pull request is still on the commit before the push.
11220        assert_eq!(bound_head("old", "old", Some("new")), None);
11221        // The checks are the previous commit's.
11222        assert_eq!(bound_head("new", "old", Some("new")), None);
11223        assert_eq!(bound_head("new", "old", None), None);
11224        // Nothing readable.
11225        assert_eq!(bound_head("", "", None), None);
11226        assert_eq!(bound_head("", "", Some("new")), None);
11227        assert_eq!(bound_head("abc", "", None), None);
11228    }
11229
11230    fn view_json(head: &str) -> String {
11231        format!(
11232            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
11233            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
11234            "reviews":[],"comments":[]}}"#
11235        )
11236    }
11237
11238    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
11239        format!(
11240            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
11241            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
11242            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
11243            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
11244        )
11245    }
11246
11247    #[test]
11248    fn rollup_is_bound_to_the_commit_in_the_same_node() {
11249        // The view already points at the new head, but the node still answers
11250        // for the old commit with its red check: the head stays unbound.
11251        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
11252        assert_eq!(s.rollup_head, "old");
11253        assert_eq!(s.pr.checks, Checks::Red);
11254        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
11255        assert_eq!(s.failing_urls.len(), 1);
11256    }
11257
11258    #[test]
11259    fn checks_come_from_the_node_not_the_view() {
11260        let view = view_json("new").replace(
11261            r#""reviews""#,
11262            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
11263        );
11264        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
11265        assert_eq!(s.pr.checks, Checks::Green);
11266        assert!(s.pr.failing.is_empty());
11267        assert_eq!(
11268            bound_head(&s.head, &s.rollup_head, Some("new")),
11269            Some("new")
11270        );
11271    }
11272
11273    #[test]
11274    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
11275        for node in [
11276            None,
11277            Some("not json".to_owned()),
11278            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
11279            Some(node_json("new", "SUCCESS", true)),
11280        ] {
11281            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
11282            assert!(s.rollup_head.is_empty());
11283            assert_eq!(s.pr.checks, Checks::Unknown);
11284            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
11285        }
11286    }
11287
11288    #[test]
11289    fn the_merge_command_is_pinned_to_the_observed_head() {
11290        let argv = merge_argv_at(7, "feat: x", "deadbeef");
11291        let at = argv
11292            .iter()
11293            .position(|a| a == "--match-head-commit")
11294            .unwrap();
11295        assert_eq!(argv[at + 1], "deadbeef");
11296    }
11297
11298    #[tokio::test]
11299    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
11300        let mut state = landing_state();
11301        // The pull request is on the pushed head but the rollup is still the
11302        // previous commit's red, non-required result.
11303        let mut stale = seen("new", Checks::Red, "CLEAN", false);
11304        stale.rollup_head = "old".to_owned();
11305        let forge = Scripted::new(
11306            vec![seen("old", Checks::Green, "CLEAN", true), stale],
11307            vec![],
11308        );
11309        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11310            head: "new".to_owned(),
11311        });
11312        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11313            .await
11314            .unwrap();
11315        assert!(!forge.calls().contains(&"merge"));
11316        assert_eq!(state.status, RunStatus::Blocked);
11317        let why = state.merge.as_ref().unwrap().detail.clone();
11318        assert!(why.contains("new") && why.contains("old"), "{why}");
11319    }
11320
11321    #[test]
11322    fn a_refusal_read_against_another_commits_checks_is_pending() {
11323        let mut after = seen("a", Checks::Green, "BLOCKED", false);
11324        after.rollup_head = "old".to_owned();
11325        assert_eq!(
11326            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
11327            Refused::Pending
11328        );
11329    }
11330
11331    #[tokio::test]
11332    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
11333        let mut state = landing_state();
11334        state.config.merge.ci = crate::config::MergeCi::None;
11335        state.config.graph.land_approval = true;
11336        let forge = Scripted::new(
11337            vec![seen("a", Checks::Unknown, "CLEAN", false)],
11338            vec![(true, "")],
11339        );
11340        land_with(&mut state, URL, &forge).await.unwrap();
11341        assert!(state.parked);
11342        assert_eq!(forge.calls(), ["view"]);
11343        let store = ask::Questions::open();
11344        let mut q = store
11345            .get(&state.land_approval.as_ref().unwrap().question)
11346            .unwrap();
11347        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11348        store.put(&mut q).unwrap();
11349
11350        land_with(&mut state, URL, &forge).await.unwrap();
11351        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
11352        assert_eq!(state.status, RunStatus::Merged);
11353        assert_eq!(
11354            value_of(&forge.argvs()[0], "--match-head-commit"),
11355            Some("a")
11356        );
11357    }
11358
11359    #[tokio::test]
11360    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
11361        let mut state = landing_state();
11362        state.config.merge.ci = crate::config::MergeCi::None;
11363        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
11364        land_with(&mut state, URL, &forge).await.unwrap();
11365        assert!(forge.reruns.lock().unwrap().is_empty());
11366        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11367        assert_eq!(state.status, RunStatus::Merged);
11368    }
11369
11370    #[test]
11371    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
11372        let shown = BTreeSet::new();
11373        let guard = |s: Option<&Seen>| {
11374            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11375        };
11376        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11377        assert!(guard(Some(&fresh)));
11378        assert!(!guard(None));
11379        fresh.rollup_head = "old".to_owned();
11380        assert!(!guard(Some(&fresh)));
11381        fresh.rollup_head = "a".to_owned();
11382        fresh.head = "b".to_owned();
11383        assert!(!guard(Some(&fresh)));
11384        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11385        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11386    }
11387
11388    #[test]
11389    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11390        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11391            let after = seen("a", checks, "BLOCKED", false);
11392            assert_eq!(
11393                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11394                Refused::Recheck
11395            );
11396            assert_eq!(
11397                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11398                Refused::Final
11399            );
11400        }
11401    }
11402
11403    #[tokio::test]
11404    async fn a_matching_head_with_red_non_required_checks_still_merges() {
11405        let mut state = landing_state();
11406        let forge = Scripted::new(
11407            vec![seen("a", Checks::Red, "CLEAN", false)],
11408            vec![(true, "")],
11409        );
11410        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11411            .await
11412            .unwrap();
11413        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11414        assert_eq!(state.status, RunStatus::Merged);
11415    }
11416
11417    #[tokio::test]
11418    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11419        let mut state = landing_state();
11420        let forge = Scripted::new(
11421            vec![
11422                seen("a", Checks::Green, "CLEAN", false),
11423                seen("a", Checks::Green, "CLEAN", false),
11424                // Re-viewed after the refusal: someone pushed.
11425                seen("b", Checks::Green, "BLOCKED", false),
11426                seen("b", Checks::Green, "CLEAN", false),
11427            ],
11428            vec![(false, REFUSED), (true, "")],
11429        );
11430        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11431            .await
11432            .unwrap();
11433        assert_eq!(
11434            forge.calls(),
11435            [
11436                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
11437            ]
11438        );
11439        assert_eq!(state.status, RunStatus::Merged);
11440    }
11441
11442    fn merged_view(head: &str) -> Seen {
11443        let mut m = seen(head, Checks::Green, "CLEAN", false);
11444        m.pr.state = PrLifecycle::Merged;
11445        m
11446    }
11447
11448    fn has(argv: &[String], flag: &str) -> bool {
11449        argv.iter().any(|a| a == flag)
11450    }
11451
11452    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11453        let at = argv.iter().position(|a| a == flag)?;
11454        argv.get(at + 1).map(String::as_str)
11455    }
11456
11457    const URL: &str = "https://github.com/o/r/pull/42";
11458
11459    #[tokio::test]
11460    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11461        let mut state = landing_state();
11462        let forge = Scripted::new(
11463            vec![
11464                seen("abc", Checks::Green, "CLEAN", false),
11465                seen("abc", Checks::Green, "CLEAN", false),
11466            ],
11467            vec![(true, "")],
11468        );
11469        land_with(&mut state, URL, &forge).await.unwrap();
11470        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11471        let argv = &forge.argvs()[0];
11472        assert!(has(argv, "--squash") && has(argv, "--subject"));
11473        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11474        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11475        assert_eq!(state.status, RunStatus::Merged);
11476        assert!(state.land_armed_head.is_none());
11477    }
11478
11479    #[tokio::test]
11480    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11481        let mut state = landing_state();
11482        state.land_armed_head = Some("a".to_owned());
11483        let forge = Scripted::new(
11484            vec![seen("a", Checks::Green, "CLEAN", false)],
11485            vec![(true, ""), (true, "")],
11486        );
11487        land_with(&mut state, URL, &forge).await.unwrap();
11488        let argvs = forge.argvs();
11489        assert!(has(&argvs[0], "--disable-auto"));
11490        assert!(!has(&argvs[1], "--auto"));
11491        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11492        assert_eq!(state.status, RunStatus::Merged);
11493        assert!(state.land_armed_head.is_none());
11494    }
11495
11496    #[tokio::test]
11497    async fn an_approval_never_carries_over_to_a_new_head() {
11498        crate::run::pin_test_home();
11499        let mut state = run_state();
11500        state.config.graph.land_approval = true;
11501        let pr = green_pr();
11502        let store = ask::Questions::open();
11503
11504        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11505            .await
11506            .unwrap();
11507        let mut q = store
11508            .list()
11509            .into_iter()
11510            .find(|q| q.run == state.id)
11511            .unwrap();
11512        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11513        store.put(&mut q).unwrap();
11514        assert_eq!(
11515            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
11516                .await
11517                .unwrap(),
11518            ApprovalGate::Approved,
11519            "the same head keeps its approval"
11520        );
11521
11522        // A new head is a new question, not the old word.
11523        assert_eq!(
11524            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11525                .await
11526                .unwrap(),
11527            ApprovalGate::Pending
11528        );
11529        let all: Vec<_> = store
11530            .list()
11531            .into_iter()
11532            .filter(|q| q.run == state.id)
11533            .collect();
11534        assert_eq!(all.len(), 2);
11535
11536        // A question recorded before heads were tracked is not reused either.
11537        state.land_approval = None;
11538        assert_eq!(
11539            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11540                .await
11541                .unwrap(),
11542            ApprovalGate::Pending
11543        );
11544        let open = store
11545            .list()
11546            .into_iter()
11547            .filter(|q| q.run == state.id && q.status.open())
11548            .count();
11549        assert_eq!(open, 1, "the superseded question was retired");
11550    }
11551
11552    #[tokio::test]
11553    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11554        let mut state = landing_state();
11555        let forge = Scripted::new(
11556            vec![
11557                seen("a", Checks::Green, "CLEAN", false),
11558                // The fresh read before the merge: someone pushed.
11559                seen("b", Checks::Green, "CLEAN", false),
11560            ],
11561            vec![(true, "")],
11562        );
11563        land_with(&mut state, URL, &forge).await.unwrap();
11564        let argvs = forge.argvs();
11565        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11566        assert!(!has(&argvs[0], "--auto"));
11567        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11568        assert_eq!(state.status, RunStatus::Merged);
11569    }
11570
11571    fn passing(label: &str) -> CheckInfo {
11572        CheckInfo {
11573            label: label.to_owned(),
11574            verdict: Verdict::Pass,
11575            required: Some(false),
11576            run: None,
11577        }
11578    }
11579
11580    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11581        (label.to_owned(), run.map(str::to_owned))
11582    }
11583
11584    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11585        LandReruns {
11586            head: head.to_owned(),
11587            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11588        }
11589    }
11590
11591    #[test]
11592    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11593        let f = [failing("test (macos)", Some("7"))];
11594        assert_eq!(
11595            rerun_step(&f, None, "h", 100),
11596            RerunStep::Rerun(vec!["7".to_owned()])
11597        );
11598        let rec = reran("h", &[("7", 100)]);
11599        let grace = crate::release_watch::RERUN_GRACE;
11600        assert_eq!(
11601            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11602            RerunStep::Grace
11603        );
11604        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11605    }
11606
11607    #[test]
11608    fn a_failure_without_a_run_id_goes_to_the_fixer() {
11609        let f = [failing("a", Some("7")), failing("ci/external", None)];
11610        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11611        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11612    }
11613
11614    #[test]
11615    fn a_moved_head_forgets_the_reruns() {
11616        let f = [failing("a", Some("7"))];
11617        let rec = reran("old", &[("7", 100)]);
11618        assert_eq!(
11619            rerun_step(&f, Some(&rec), "new", 101),
11620            RerunStep::Rerun(vec!["7".to_owned()])
11621        );
11622    }
11623
11624    #[test]
11625    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11626        let f = [
11627            failing("a", Some("7")),
11628            failing("b", Some("7")),
11629            failing("c", Some("8")),
11630        ];
11631        assert_eq!(
11632            rerun_step(&f, None, "h", 0),
11633            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11634        );
11635        let rec = reran("h", &[("7", 0)]);
11636        assert_eq!(
11637            rerun_step(&f, Some(&rec), "h", 1),
11638            RerunStep::Rerun(vec!["8".to_owned()])
11639        );
11640    }
11641
11642    #[test]
11643    fn only_blocking_failures_are_candidates_for_a_rerun() {
11644        let check = |label: &str, verdict, required, run: &str| CheckInfo {
11645            label: label.to_owned(),
11646            verdict,
11647            required,
11648            run: Some(run.to_owned()),
11649        };
11650        let got = rerunnable(&[
11651            check("passed", Verdict::Pass, Some(true), "1"),
11652            check("optional", Verdict::Fail, Some(false), "2"),
11653            check("required", Verdict::Fail, Some(true), "3"),
11654            check("unknown", Verdict::Fail, None, "4"),
11655        ]);
11656        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11657        assert_eq!(labels, ["required", "unknown"]);
11658    }
11659
11660    fn unrelated_ci_fixture() -> CiEvidence {
11661        let failure = CiFailure {
11662            path: "tests/web_render.rs".into(),
11663            start_line: 42,
11664            end_line: 42,
11665            title: "question_identity_disclosure_copy_and_live_updates".into(),
11666            message: "assertion failed".into(),
11667        };
11668        CiEvidence {
11669            head: "a".into(),
11670            base: "base-sha".into(),
11671            changed: vec![
11672                "AGENTS.md".into(),
11673                "src/talk.rs".into(),
11674                "tests/consult_investigation.rs".into(),
11675            ],
11676            checks: vec![CiCheckEvidence {
11677                label: "coverage".into(),
11678                head_check: 70,
11679                base_check: 60,
11680                app: 1,
11681                run: "7".into(),
11682                base_run: "6".into(),
11683                head_failures: vec![failure.clone()],
11684                base_failures: vec![failure],
11685                rerun_exhausted: true,
11686            }],
11687        }
11688    }
11689
11690    #[test]
11691    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11692        let good = unrelated_ci_fixture();
11693        let red = vec!["coverage".into()];
11694        assert!(good.unrelated("a", &red));
11695        assert!(!good.unrelated("another-head", &red));
11696        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11697        assert!(!good.unrelated("a", &[]));
11698        for mutation in 0..8 {
11699            let mut bad = good.clone();
11700            match mutation {
11701                0 => bad.checks[0].rerun_exhausted = false,
11702                1 => bad.checks[0].base_failures.clear(),
11703                2 => bad.checks[0].head_failures.clear(),
11704                3 => bad.changed.push("tests/web_render.rs".into()),
11705                4 => bad.changed.push(".github/workflows/ci.yml".into()),
11706                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11707                6 => bad.checks.push(bad.checks[0].clone()),
11708                _ => bad.base.clear(),
11709            }
11710            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11711        }
11712    }
11713
11714    #[test]
11715    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11716        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11717        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11718        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11719        assert!(matches!(
11720            decide(&pr, 2, 2, CHECKS_GRACE),
11721            Step::GiveUp { .. }
11722        ));
11723        let optional = CheckInfo {
11724            label: "coverage".into(),
11725            verdict: Verdict::Fail,
11726            required: Some(false),
11727            run: Some("7".into()),
11728        };
11729        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11730        assert_eq!(
11731            rerunnable_with(&[optional], true),
11732            vec![("coverage".into(), Some("7".into()))]
11733        );
11734    }
11735
11736    #[tokio::test]
11737    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11738        let mut state = landing_state();
11739        let mut red = coverage_unknown();
11740        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11741        red.pr.failing = vec!["coverage".into()];
11742        let forge = Scripted::new(vec![red], vec![]);
11743        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11744        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11745        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11746        assert!(forge.calls().contains(&"fix"));
11747        assert!(state.land_unrelated.is_some());
11748        assert!(state.parked);
11749        assert!(
11750            !state
11751                .events
11752                .iter()
11753                .any(|e| e.message.contains("fixer produced no commit"))
11754        );
11755    }
11756
11757    fn coverage_unknown() -> Seen {
11758        let mut s = red("a", Some("7"));
11759        s.pr.blocking = Blocking::Unsaid;
11760        s.merge_state = "UNKNOWN".into();
11761        s.pr.failing = vec!["coverage".into()];
11762        s.contexts[0].label = "coverage".into();
11763        s.contexts[0].required = Some(false);
11764        s
11765    }
11766
11767    #[tokio::test]
11768    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11769        let mut state = landing_state();
11770        let unknown = coverage_unknown();
11771        let mut unstable = unknown.clone();
11772        unstable.pr.blocking = Blocking::of("UNSTABLE");
11773        unstable.merge_state = "UNSTABLE".into();
11774        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11775        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11776        assert!(!forge.calls().contains(&"fix"));
11777        assert!(!forge.calls().contains(&"rerun"));
11778        assert_eq!(state.status, RunStatus::Merged);
11779        assert_eq!(state.pr.unwrap().round, 0);
11780    }
11781
11782    #[tokio::test]
11783    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11784        let mut state = landing_state();
11785        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
11786        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11787        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11788        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11789        assert!(!forge.calls().contains(&"fix"));
11790        assert!(state.parked);
11791        assert_eq!(state.status, RunStatus::Landing);
11792        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11793        let hold = state.land_unrelated.as_ref().unwrap();
11794        let q = ask::Questions::open().get(&hold.question).unwrap();
11795        assert!(
11796            q.actions
11797                .values()
11798                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
11799        );
11800        assert!(
11801            state
11802                .events
11803                .iter()
11804                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
11805        );
11806        let first = state.land_unsaid.clone();
11807        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
11808        state.parked = false;
11809        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11810        assert_eq!(state.land_unsaid, first);
11811        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11812    }
11813
11814    fn red(head: &str, run: Option<&str>) -> Seen {
11815        let mut s = seen(head, Checks::Red, "BLOCKED", false);
11816        s.pr.failing = vec!["test (macos)".to_owned()];
11817        s.contexts = vec![CheckInfo {
11818            label: "test (macos)".to_owned(),
11819            verdict: Verdict::Fail,
11820            required: Some(true),
11821            run: run.map(str::to_owned),
11822        }];
11823        s
11824    }
11825
11826    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
11827
11828    #[tokio::test]
11829    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
11830        let mut state = landing_state();
11831        let forge = Scripted::new(
11832            vec![
11833                red("a", Some("7")),
11834                seen("a", Checks::Pending, "BLOCKED", false),
11835                seen("a", Checks::Green, "CLEAN", false),
11836            ],
11837            vec![(true, "")],
11838        );
11839        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11840        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11841        assert!(!forge.calls().contains(&"fix"));
11842        assert_eq!(state.status, RunStatus::Merged);
11843        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11844        let argvs = forge.argvs();
11845        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
11846        assert!(
11847            state
11848                .events
11849                .iter()
11850                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
11851        );
11852    }
11853
11854    #[tokio::test]
11855    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
11856        let mut state = landing_state();
11857        let forge = Scripted::new(
11858            vec![
11859                red("a", Some("7")),
11860                seen("a", Checks::Green, "CLEAN", false),
11861            ],
11862            vec![(true, "")],
11863        );
11864        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11865        // The red view repeats for the grace, then the fixer is asked once.
11866        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11867        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
11868        let calls = forge.calls();
11869        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
11870        let fix_at = calls.iter().position(|c| *c == "fix");
11871        assert!(fix_at.is_none_or(|f| f > rerun_at));
11872    }
11873
11874    #[tokio::test]
11875    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
11876        let mut state = landing_state();
11877        let mut v = red("a", Some("7"));
11878        v.pr.checks = Checks::Pending;
11879        v.contexts.push(CheckInfo {
11880            label: "slow".to_owned(),
11881            verdict: Verdict::Pending,
11882            required: Some(true),
11883            run: Some("8".to_owned()),
11884        });
11885        let forge = Scripted::new(
11886            vec![v, seen("a", Checks::Green, "CLEAN", false)],
11887            vec![(true, "")],
11888        );
11889        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11890        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11891        assert_eq!(state.status, RunStatus::Merged);
11892    }
11893
11894    #[test]
11895    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
11896        let mut v = red("a", Some("7"));
11897        v.contexts.push(CheckInfo {
11898            label: "same run, still going".to_owned(),
11899            verdict: Verdict::Pending,
11900            required: Some(true),
11901            run: Some("7".to_owned()),
11902        });
11903        assert!(rerunnable(&v.contexts).is_empty());
11904    }
11905
11906    #[tokio::test]
11907    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
11908        let mut state = landing_state();
11909        state.config.graph.land_rounds = 0;
11910        let forge = Scripted::new(
11911            vec![
11912                red("a", Some("7")),
11913                seen("a", Checks::Green, "CLEAN", false),
11914            ],
11915            vec![(true, "")],
11916        );
11917        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11918        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11919        assert_eq!(state.status, RunStatus::Merged);
11920        assert!(!forge.calls().contains(&"fix"));
11921        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11922    }
11923
11924    #[tokio::test]
11925    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
11926        let mut state = landing_state();
11927        state.config.graph.land_rounds = 1;
11928        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
11929        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
11930        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11931        assert_eq!(pr.state, PrLifecycle::Open);
11932        assert_eq!(state.status, RunStatus::Blocked);
11933        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11934        assert!(
11935            state.merge_decision.is_none(),
11936            "no ordinary failure handoff"
11937        );
11938        assert!(forge.argvs().is_empty(), "no merge on outage");
11939
11940        let recovered = Scripted::new(
11941            vec![
11942                seen("a", Checks::Green, "CLEAN", true),
11943                seen("b", Checks::Green, "CLEAN", false),
11944            ],
11945            vec![(true, "")],
11946        );
11947        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
11948        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
11949        assert_eq!(state.status, RunStatus::Merged);
11950        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11951        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
11952    }
11953
11954    #[tokio::test]
11955    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
11956        let mut state = landing_state();
11957        state.config.graph.land_rounds = 1;
11958        let forge = Scripted::new(
11959            vec![
11960                seen("a", Checks::Green, "CLEAN", true),
11961                red("b", Some("7")),
11962                seen("b", Checks::Green, "CLEAN", false),
11963            ],
11964            vec![(true, "")],
11965        );
11966        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11967            head: "b".to_owned(),
11968        });
11969        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11970        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11971        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
11972        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11973        assert_eq!(state.status, RunStatus::Merged);
11974        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
11975        assert_eq!(
11976            value_of(&forge.argvs()[0], "--match-head-commit"),
11977            Some("b")
11978        );
11979    }
11980
11981    #[tokio::test]
11982    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
11983        let mut state = landing_state();
11984        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11985        *forge.rerun_fails.lock().unwrap() = true;
11986        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11987        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11988        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
11989        assert_eq!(
11990            forge.calls().iter().filter(|c| **c == "fix").count(),
11991            1,
11992            "{:?}",
11993            forge.calls()
11994        );
11995    }
11996
11997    #[tokio::test]
11998    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
11999        let mut state = landing_state();
12000        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12001        // The record was written just before the previous pass died.
12002        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
12003        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12004        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12005        assert!(forge.reruns.lock().unwrap().is_empty());
12006    }
12007
12008    #[tokio::test]
12009    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
12010        let mut state = landing_state();
12011        state.config.graph.rerun_flaky_checks = false;
12012        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
12013        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12014        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12015        assert!(forge.reruns.lock().unwrap().is_empty());
12016        assert!(forge.calls().contains(&"fix"));
12017
12018        let mut state = landing_state();
12019        let forge = Scripted::new(vec![red("a", None)], vec![]);
12020        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12021        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12022        assert!(forge.reruns.lock().unwrap().is_empty());
12023        assert!(forge.calls().contains(&"fix"));
12024    }
12025
12026    fn names(xs: &[&str]) -> BTreeSet<String> {
12027        xs.iter().map(|x| (*x).to_owned()).collect()
12028    }
12029
12030    #[test]
12031    fn a_required_check_the_rollup_never_listed_is_named() {
12032        let req = names(&["build"]);
12033        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
12034        assert!(why.contains("never reported: build"), "{why}");
12035        assert!(!why.contains("probably waiting for a review"), "{why}");
12036    }
12037
12038    #[test]
12039    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
12040        let why = waiting_on("BLOCKED", &[passing("review")], None);
12041        assert!(why.contains("could not be read"), "{why}");
12042        assert!(!why.contains("probably waiting for a review"), "{why}");
12043    }
12044
12045    #[test]
12046    fn all_required_reported_keeps_the_review_guess() {
12047        let req = names(&["build"]);
12048        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12049        assert!(why.contains("probably waiting for a review"), "{why}");
12050        assert!(!why.contains("never reported"), "{why}");
12051    }
12052
12053    #[test]
12054    fn required_names_match_the_rollup_ignoring_case_only() {
12055        let req = names(&["Build"]);
12056        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12057        assert!(!why.contains("never reported"), "{why}");
12058    }
12059
12060    #[test]
12061    fn required_contexts_are_read_from_protection_and_rulesets() {
12062        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
12063        assert_eq!(
12064            parse_classic_required(classic),
12065            Some(names(&["build", "lint"]))
12066        );
12067        let rules = r#"[{"type":"pull_request","parameters":{}},
12068            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
12069        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
12070        assert_eq!(parse_ruleset_required("nope"), None);
12071        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
12072    }
12073
12074    #[test]
12075    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
12076        let shown = BTreeSet::new();
12077        let ok = seen("a", Checks::Green, "CLEAN", false);
12078        let guard = |s: Option<&Seen>| {
12079            direct_merge_is_safe(
12080                s,
12081                "A",
12082                &shown,
12083                0,
12084                4,
12085                Duration::ZERO,
12086                CiExpectation::Expected,
12087            )
12088        };
12089        assert!(guard(Some(&ok)));
12090        assert!(!guard(None));
12091        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
12092        let mut stale = ok.clone();
12093        stale.rollup_head = "old".to_owned();
12094        assert!(!guard(Some(&stale)));
12095        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
12096        assert!(!guard(Some(&merged_view("a"))));
12097    }
12098
12099    #[test]
12100    fn the_rollup_node_carries_whether_each_check_is_required() {
12101        let node = node_json("new", "SUCCESS", false)
12102            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
12103        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
12104        assert_eq!(s.contexts.len(), 1);
12105        assert_eq!(s.contexts[0].required, Some(true));
12106        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
12107        assert_eq!(s.contexts[0].required, None);
12108    }
12109
12110    #[tokio::test]
12111    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
12112        let mut state = landing_state();
12113        state.land_armed_head = Some("a".to_owned());
12114        let forge = Scripted::new(
12115            vec![seen("a", Checks::Green, "CLEAN", true)],
12116            vec![(false, "disable exploded")],
12117        );
12118        land_with(&mut state, URL, &forge).await.unwrap();
12119        assert!(!forge.calls().contains(&"fix"));
12120        assert_eq!(state.status, RunStatus::Blocked);
12121        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
12122        let why = state.merge.as_ref().unwrap().detail.clone();
12123        assert!(why.contains("disable exploded"), "{why}");
12124    }
12125
12126    /// Create a cross-platform fake `gh` executable in `dir` backed by exact
12127    /// fixture files, avoiding shell quoting differences and global `PATH`
12128    /// mutation.
12129    pub(crate) fn fake_gh_script(
12130        dir: &Path,
12131        name: &str,
12132        stdout: &str,
12133        stderr: &str,
12134        exit_code: i32,
12135    ) -> PathBuf {
12136        let out_path = dir.join(format!("{name}.stdout"));
12137        let err_path = dir.join(format!("{name}.stderr"));
12138        std::fs::write(&out_path, stdout).unwrap();
12139        std::fs::write(&err_path, stderr).unwrap();
12140        #[cfg(windows)]
12141        {
12142            let script = dir.join(format!("{name}.cmd"));
12143            let mut body = String::from("@echo off\r\n");
12144            if !stdout.is_empty() {
12145                body.push_str(&format!("type \"{}\"\r\n", out_path.display()));
12146            }
12147            if !stderr.is_empty() {
12148                body.push_str(&format!("type \"{}\" 1>&2\r\n", err_path.display()));
12149            }
12150            body.push_str(&format!("exit /b {exit_code}\r\n"));
12151            std::fs::write(&script, body).unwrap();
12152            script
12153        }
12154        #[cfg(unix)]
12155        {
12156            use std::os::unix::fs::PermissionsExt as _;
12157            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
12158            let script = dir.join(name);
12159            let mut body = String::from("#!/bin/sh\n");
12160            if !stdout.is_empty() {
12161                body.push_str(&format!("cat {}\n", quote(&out_path)));
12162            }
12163            if !stderr.is_empty() {
12164                body.push_str(&format!("cat {} >&2\n", quote(&err_path)));
12165            }
12166            body.push_str(&format!("exit {exit_code}\n"));
12167            let status = std::process::Command::new("sh")
12168                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
12169                .arg(&script)
12170                .arg(&body)
12171                .status()
12172                .unwrap();
12173            assert!(status.success());
12174            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
12175            script
12176        }
12177    }
12178
12179    #[test]
12180    fn gh_output_combined_preserves_and_separates_both_streams() {
12181        let mk = |ok, stdout: &str, stderr: &str| GhOutput {
12182            ok,
12183            stdout: stdout.into(),
12184            stderr: stderr.into(),
12185        };
12186        assert_eq!(mk(true, "  ", "\n").combined(), "");
12187        assert_eq!(mk(true, "  only out \n", " \t ").combined(), "only out");
12188        assert_eq!(mk(false, "", "  only err\n").combined(), "only err");
12189        assert_eq!(
12190            mk(false, "{\"status\":\"404\"}", "gh: Not Found (HTTP 404)\n").combined(),
12191            "{\"status\":\"404\"}\ngh: Not Found (HTTP 404)"
12192        );
12193    }
12194
12195    #[tokio::test]
12196    async fn gh_separates_json_stdout_from_stderr_diagnostics() {
12197        let tmp = tempfile::tempdir().unwrap();
12198        let hint = "hint: to listen to pull request events, run `gh pr view --web`\n";
12199        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"}"#;
12200        let valid_list = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: test","baseRefName":"main","isCrossRepository":false}]"#;
12201
12202        // Valid JSON stdout + nonempty stderr hint on exit 0: structured reads
12203        // parse stdout cleanly while stderr remains available via `combined()`.
12204        let ok_view = fake_gh_script(tmp.path(), "ok-view", &format!("{valid_view}\n"), hint, 0);
12205        let out = gh_with(&ok_view, tmp.path(), &["pr".into(), "view".into()])
12206            .await
12207            .unwrap();
12208        assert!(out.ok);
12209        assert_eq!(parse_pr(&out.stdout).unwrap().state, PrLifecycle::Open);
12210        assert!(out.stderr.contains("listen to pull request events"));
12211        assert!(out.combined().contains("listen to pull request events"));
12212        assert!(out.combined().contains("feat: test"));
12213
12214        let ok_list = fake_gh_script(tmp.path(), "ok-list", &format!("{valid_list}\n"), hint, 0);
12215        assert_eq!(
12216            find_open_pr_with(&ok_list, tmp.path(), "magi/task-t", "main")
12217                .await
12218                .unwrap(),
12219            OpenPr::One {
12220                url: "https://github.com/example/repo/pull/1".into(),
12221                title: "feat: test".into(),
12222            }
12223        );
12224
12225        // Malformed stdout with trailing characters still fails strict JSON parsing.
12226        let malformed = fake_gh_script(
12227            tmp.path(),
12228            "malformed",
12229            &format!("{valid_view}\ntrailing garbage\n"),
12230            "",
12231            0,
12232        );
12233        let out = gh_with(&malformed, tmp.path(), &["pr".into(), "view".into()])
12234            .await
12235            .unwrap();
12236        assert!(out.ok);
12237        let err = parse_pr(&out.stdout).unwrap_err();
12238        assert!(
12239            format!("{err:#}").contains("trailing characters"),
12240            "{err:#}"
12241        );
12242
12243        // Empty stdout + nonempty stderr on exit 0 never substitutes stderr.
12244        let empty = fake_gh_script(tmp.path(), "empty", "", hint, 0);
12245        let out = gh_with(&empty, tmp.path(), &["pr".into(), "view".into()])
12246            .await
12247            .unwrap();
12248        assert!(out.ok);
12249        assert!(out.stdout.trim().is_empty());
12250        assert!(parse_pr(&out.stdout).is_err());
12251
12252        // Non-zero exit with valid JSON on stdout and error on stderr reports
12253        // failure and preserves both streams in `combined()`.
12254        let failed = fake_gh_script(
12255            tmp.path(),
12256            "failed",
12257            &format!("{valid_view}\n"),
12258            "gh: HTTP 404 Not Found\n",
12259            1,
12260        );
12261        let out = gh_with(&failed, tmp.path(), &["pr".into(), "view".into()])
12262            .await
12263            .unwrap();
12264        assert!(!out.ok);
12265        let diag = out.combined();
12266        assert!(diag.contains("HTTP 404 Not Found"), "{diag}");
12267        assert!(diag.contains("feat: test"), "{diag}");
12268        let list_err = find_open_pr_with(&failed, tmp.path(), "magi/task-t", "main")
12269            .await
12270            .unwrap_err()
12271            .to_string();
12272        assert!(list_err.contains("HTTP 404 Not Found"), "{list_err}");
12273    }
12274
12275    struct StaticPrObserver(crate::land_sync_recovery::ObservedPr);
12276
12277    impl crate::land_sync_recovery::PrObserver for StaticPrObserver {
12278        async fn observe_pr(
12279            &self,
12280            _repo: &Path,
12281            _pr_url: &str,
12282        ) -> Result<crate::land_sync_recovery::ObservedPr> {
12283            Ok(self.0.clone())
12284        }
12285    }
12286
12287    const FIXTURE_PR_PREFIX: &str = "https://github.com/example/landing-sync-";
12288
12289    /// Tests share a process-wide home, so each recovery fixture needs a unique
12290    /// PR URL to prevent another test's `write_pr_state_through` from settling it.
12291    fn fixture_pr_url(state: &RunState) -> String {
12292        format!("{FIXTURE_PR_PREFIX}{}/pull/42", state.id)
12293    }
12294
12295    /// Build a real-shaped legacy landing base-sync exhaustion fixture backed by
12296    /// an isolated temp Git repo, bare origin, queue task, and open PR metadata.
12297    async fn legacy_exhausted_landing_fixture() -> (
12298        tempfile::TempDir,
12299        PathBuf,
12300        crate::queue::Queue,
12301        crate::queue::Task,
12302        RunState,
12303        String,
12304    ) {
12305        let (tmp, mut state, old) = landing_git_fixture().await;
12306        crate::run::pin_test_home();
12307        let home = crate::run::home();
12308        // Move run state under this isolated home so load_under/save_under match.
12309        state.config.graph.land_rounds = 4;
12310        state.config.graph.land_approval = true;
12311        state.config.verify.gate = vec!["git rev-parse HEAD".into()];
12312        state.config.verify.e2e = vec!["git rev-parse HEAD".into()];
12313        state.status = RunStatus::Blocked;
12314        state.driver_exited = true;
12315        state.pr = Some(crate::run::PrRecord {
12316            url: fixture_pr_url(&state),
12317            number: 42,
12318            state: "open".to_owned(),
12319            checks: "green".to_owned(),
12320            round: 0,
12321            rounds: 4,
12322            red_at_merge: Vec::new(),
12323        });
12324        state.merge = Some(MergeOutcome {
12325            mode: MergeMode::Pr,
12326            ok: false,
12327            detail:
12328                "could not synchronize landing base: landing base synchronization budget exhausted"
12329                    .to_owned(),
12330            empty: false,
12331        });
12332        state.reviews = vec![serde_json::from_value(serde_json::json!({
12333            "round": 1,
12334            "head": old,
12335            "expected": 2,
12336            "answered": 2,
12337            "reviews": [],
12338            "clean": true,
12339            "e2e": [{"command": "git rev-parse HEAD", "code": 0, "output_tail": old, "duration_ms": 10}],
12340            "verified_head": old,
12341            "verified_at": jiff::Timestamp::now(),
12342            "e2e_deferred": false
12343        }))
12344        .unwrap()];
12345        let pass_cmd: crate::run::CommandOutcome = serde_json::from_value(serde_json::json!({
12346            "command": "git rev-parse HEAD",
12347            "code": 0,
12348            "output_tail": old,
12349            "duration_ms": 10
12350        }))
12351        .unwrap();
12352        state.head_e2e = Some(crate::run::GateRepairE2e::new(
12353            old.clone(),
12354            true,
12355            vec![pass_cmd.clone()],
12356        ));
12357        state.gate = vec![pass_cmd];
12358        state.gate_ran = true;
12359        state.gate_head = Some(old.clone());
12360        state.land_sync_attempts = 4;
12361        state.land_sync_target = None;
12362        state.land_sync_pending = true;
12363        state.event(
12364            "land",
12365            "stopped: could not synchronize landing base: landing base synchronization budget exhausted",
12366        );
12367
12368        let queue = crate::queue::Queue::at(home.join("queue"));
12369        let mut task = crate::queue::Task::new(
12370            "landing sync".into(),
12371            state.instruction.clone(),
12372            state.repo.clone(),
12373            crate::queue::Source::Human,
12374        );
12375        task.link_run(&state.id);
12376        task.hold_machine(Some("landing base synchronization budget exhausted".into()));
12377        queue.put(&mut task).unwrap();
12378        state.origin = Some(crate::run::Origin::queue(&task.id));
12379        state.save_under(&home).unwrap();
12380        (tmp, home, queue, task, state, old)
12381    }
12382
12383    #[tokio::test]
12384    async fn land_sync_recovery_isolated_from_unrelated_pr_settlement() {
12385        let (_tmp, _home, _queue, _task, mut state, _old) =
12386            legacy_exhausted_landing_fixture().await;
12387        let home = tempfile::tempdir().unwrap();
12388        state.save_under(home.path()).unwrap();
12389        let mut source = run_state();
12390        source.pr = state.pr.clone();
12391        source.pr.as_mut().unwrap().url = green_pr().url;
12392        assert_eq!(
12393            write_pr_state_through_in(home.path(), &source, PrLifecycle::Merged),
12394            0
12395        );
12396        // The unrelated record must not be locked even during selection.
12397        assert_eq!(
12398            rewrite_open_prs(home.path(), &mut |candidate| {
12399                assert_eq!(candidate.id, state.id);
12400                let _owner = crate::pr_head::owner_lock(home.path(), &candidate.id)
12401                    .expect("unrelated PR scan must not hold the recovery owner lock");
12402                names_same_pr(
12403                    candidate,
12404                    &source.pr.as_ref().unwrap().url,
12405                    42,
12406                    &source.repo,
12407                )
12408                .then_some(PrLifecycle::Merged)
12409            }),
12410            0
12411        );
12412        let saved = RunState::load_under(&state.id, home.path()).unwrap();
12413        assert_eq!(saved.pr.as_ref().unwrap().state, "open");
12414        assert!(saved.land_sync_exhausted());
12415    }
12416
12417    #[tokio::test]
12418    async fn land_sync_recovery_continues_legacy_real_shaped_stop_on_existing_pr() {
12419        let (_tmp, home, queue, task, mut state, old) = legacy_exhausted_landing_fixture().await;
12420        let home = home.as_path();
12421
12422        // Advance origin/main once so landing rebase has real work to replay.
12423        advance_landing_base(&state).await;
12424
12425        state.pre_gate = vec![
12426            serde_json::from_value(serde_json::json!({
12427                "command": "prepare sources",
12428                "code": 0,
12429                "output_tail": "prepared",
12430                "duration_ms": 15
12431            }))
12432            .unwrap(),
12433        ];
12434        let pre_gate_commit = git::rev_parse(&state.repo, "HEAD^").await.unwrap();
12435        assert_ne!(pre_gate_commit, old);
12436        state.pre_gate_commit = Some(pre_gate_commit.clone());
12437        let pre_gate = serde_json::to_value(&state.pre_gate).unwrap();
12438        state.save_under(home).unwrap();
12439
12440        // Pre-recovery: legacy shape recognized, recover-base refused, ordinary resume/release refused.
12441        assert!(state.land_sync_exhausted());
12442        assert!(!state.base_sync_blocked());
12443        assert!(crate::land_sync_recovery::held_task(&queue, &task));
12444        let base_err = crate::graph::Runner::authorize_base_recovery(home, &state.id, &task.id)
12445            .await
12446            .unwrap_err();
12447        assert!(
12448            base_err.to_string().contains("run has no base-sync stop"),
12449            "{base_err:#}"
12450        );
12451        assert!(crate::handover::resume_refusal_under(&state, Some(home)).is_none());
12452        assert!(crate::base_sync_recovery::ensure_generic_release(&queue, &task).is_err());
12453
12454        // Ordinary land_with without authorization refuses without refilling budget.
12455        let pr_url = state.pr.as_ref().unwrap().url.clone();
12456        let blocked_forge =
12457            Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
12458        let err = land_with(&mut state, &pr_url, &blocked_forge)
12459            .await
12460            .unwrap_err();
12461        assert!(err.to_string().contains("budget exhausted"), "{err:#}");
12462        assert_eq!(state.land_sync_attempts, 4);
12463        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12464
12465        // Attach a prior head-bound approval on `old` to prove fresh approval is required after recovery.
12466        let questions = ask::Questions::at(home.join("questions"));
12467        let mut old_q = ask::Question::new(
12468            state.id.clone(),
12469            APPROVAL_NODE.into(),
12470            "owner".into(),
12471            "old head approval".into(),
12472            String::new(),
12473            vec![APPROVE.into()],
12474        );
12475        old_q
12476            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12477            .unwrap();
12478        questions.put(&mut old_q).unwrap();
12479        state.land_approval = Some(LandApproval {
12480            question: old_q.id.clone(),
12481            head: old.clone(),
12482        });
12483        state.save_under(home).unwrap();
12484
12485        // Admit explicit recover-land-sync via two-phase control.
12486        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12487            url: pr_url.clone(),
12488            number: 42,
12489            open: true,
12490            head: old.clone(),
12491            base_branch: Some("main".to_owned()),
12492        });
12493        let outcome = crate::land_sync_recovery_control::recover_with(
12494            &queue,
12495            home,
12496            crate::land_sync_recovery_control::Request {
12497                run: state.id.clone(),
12498                head: old.clone(),
12499                actor: "cli".into(),
12500                request: "req-legacy-1".into(),
12501            },
12502            &observer,
12503        )
12504        .await
12505        .unwrap();
12506        assert!(!outcome.repeated);
12507        assert_eq!(
12508            outcome
12509                .task
12510                .resume_override
12511                .as_ref()
12512                .and_then(|pin| pin.pinned_run.as_deref()),
12513            Some(state.id.as_str())
12514        );
12515
12516        // Ordinary fast-forward of origin/main between admission and dispatch is allowed.
12517        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
12518        std::fs::write(state.repo.join("advance2"), "advance2").unwrap();
12519        git::git(&state.repo, &["add", "."]).await.unwrap();
12520        git::git(&state.repo, &["commit", "-m", "advance base again"])
12521            .await
12522            .unwrap();
12523        git::git(&state.repo, &["push", "origin", "main"])
12524            .await
12525            .unwrap();
12526        git::git(&state.repo, &["checkout", "winner"])
12527            .await
12528            .unwrap();
12529
12530        let reloaded_task = queue.get(&task.id).unwrap();
12531        assert!(matches!(
12532            crate::land_sync_recovery::dispatch_check_with(&queue, home, &reloaded_task, &observer)
12533                .await,
12534            crate::land_sync_recovery::DispatchDecision::Proceed
12535        ));
12536
12537        // Execute continuation on the existing PR using real rebase + fresh gate + fresh E2E.
12538        let mut run = RunState::load_under(&state.id, home).unwrap();
12539        assert!(run.land_sync_recovery_pending());
12540        let mut forge = Scripted::for_pr(
12541            &pr_url,
12542            vec![
12543                seen(&old, Checks::Green, "BEHIND", false),
12544                seen(&old, Checks::Green, "BEHIND", false),
12545                seen("@published", Checks::Green, "CLEAN", false),
12546            ],
12547        );
12548        forge.public_repo = Some(run.repo.clone());
12549        let pr = land_with(&mut run, &pr_url, &forge).await.unwrap();
12550        assert_eq!(pr.state, PrLifecycle::Open);
12551        assert!(run.parked, "must park awaiting fresh head-bound approval");
12552
12553        // Verify attempts preserved (4 -> 5), 1 grant consumed, fresh head published,
12554        // prior verification archived, fresh gate + E2E ran on new head, fresh approval asked.
12555        let new_head = git::rev_parse(&run.repo, "HEAD").await.unwrap();
12556        assert_ne!(new_head, old);
12557        assert_eq!(run.land_sync_attempts, 5);
12558        assert_eq!(run.land_sync_recovery.extra_attempts, 1);
12559        assert_eq!(run.land_sync_budget(), 5);
12560        assert!(!run.land_sync_pending);
12561        assert_eq!(run.pr_pushed_head.as_deref(), Some(new_head.as_str()));
12562        assert_eq!(
12563            git::remote_head(&run.repo, "origin", "task-head")
12564                .await
12565                .unwrap()
12566                .as_deref(),
12567            Some(new_head.as_str())
12568        );
12569        assert!(run.gate_ran);
12570        assert_eq!(run.gate_head.as_deref(), Some(new_head.as_str()));
12571        assert!(
12572            run.head_e2e
12573                .as_ref()
12574                .is_some_and(|e| e.head == new_head && e.passed)
12575        );
12576        assert_eq!(run.reviews.len(), 1);
12577        assert!(run.reviews[0].clean);
12578        assert_eq!(run.reviews[0].answered, 2);
12579        assert!(run.reviews[0].verified_head.is_none());
12580        assert!(!run.verification_history.is_empty());
12581        assert_eq!(run.land_sync_recovery.stops.len(), 1);
12582        assert_eq!(run.land_sync_recovery.authorizations.len(), 1);
12583        let auth = &run.land_sync_recovery.authorizations[0];
12584        assert!(auth.consumed);
12585        assert!(auth.invalidated.is_none());
12586        assert!(run.pre_gate.is_empty());
12587        assert!(run.pre_gate_commit.is_none());
12588        let saved = RunState::load_under(&run.id, home).unwrap();
12589        assert!(saved.pre_gate.is_empty());
12590        assert!(saved.pre_gate_commit.is_none());
12591        let archived = saved.land_sync_recovery.authorizations[0]
12592            .archived_verification
12593            .as_ref()
12594            .unwrap();
12595        assert_eq!(serde_json::to_value(&archived.pre_gate).unwrap(), pre_gate);
12596        assert_eq!(
12597            archived.pre_gate_commit.as_deref(),
12598            Some(pre_gate_commit.as_str())
12599        );
12600
12601        let mut legacy = serde_json::to_value(archived).unwrap();
12602        let fields = legacy.as_object_mut().unwrap();
12603        fields.remove("pre_gate");
12604        fields.remove("pre_gate_commit");
12605        let legacy: crate::land_sync_recovery::ArchivedVerification =
12606            serde_json::from_value(legacy).unwrap();
12607        assert!(legacy.pre_gate.is_empty());
12608        assert!(legacy.pre_gate_commit.is_none());
12609        let new_approval = run.land_approval.as_ref().unwrap();
12610        assert_ne!(new_approval.question, old_q.id);
12611        assert_eq!(new_approval.head, new_head);
12612    }
12613
12614    #[tokio::test]
12615    async fn land_sync_recovery_observes_external_merge_without_grant() {
12616        let (_tmp, home, queue, mut task, mut state, old) =
12617            legacy_exhausted_landing_fixture().await;
12618        let pr_url = state.pr.as_ref().unwrap().url.clone();
12619        task.resume_override = Some(crate::queue::OperatorResume {
12620            question_id: String::new(),
12621            at: jiff::Timestamp::now(),
12622            conductor_rehold: None,
12623            forced: true,
12624            pinned_run: Some(state.id.clone()),
12625        });
12626        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12627            url: pr_url.clone(),
12628            number: 42,
12629            open: false,
12630            head: old.clone(),
12631            base_branch: Some("main".into()),
12632        });
12633        assert!(matches!(
12634            crate::land_sync_recovery::dispatch_check_with(&queue, &home, &task, &observer).await,
12635            crate::land_sync_recovery::DispatchDecision::Proceed
12636        ));
12637        let forge = Scripted::for_pr(&pr_url, vec![merged_view(&old)]);
12638        land_with(&mut state, &pr_url, &forge).await.unwrap();
12639        assert_eq!(state.status, RunStatus::Merged);
12640        assert_eq!(state.land_sync_attempts, 4);
12641        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12642        assert_eq!(forge.calls(), ["view"]);
12643    }
12644
12645    #[tokio::test]
12646    async fn land_sync_recovery_forces_fresh_e2e_and_gate_even_when_head_unchanged() {
12647        let (tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
12648        let home = home.as_path();
12649
12650        // Create marker-writing commands for gate and e2e so we prove both execute freshly
12651        // even when HEAD does not change (origin/main is already an ancestor of winner).
12652        let gate_marker = tmp.path().join("fresh-gate-ran");
12653        let e2e_marker = tmp.path().join("fresh-e2e-ran");
12654        state.config.verify.gate = vec![format!(
12655            "git rev-parse HEAD > \"{}\"",
12656            gate_marker.display().to_string().replace('\\', "/")
12657        )];
12658        state.config.verify.e2e = vec![format!(
12659            "git rev-parse HEAD > \"{}\"",
12660            e2e_marker.display().to_string().replace('\\', "/")
12661        )];
12662        let questions = ask::Questions::at(home.join("questions"));
12663        let mut old_q = ask::Question::new(
12664            state.id.clone(),
12665            APPROVAL_NODE.into(),
12666            "owner".into(),
12667            "prior approval on same head".into(),
12668            String::new(),
12669            vec![APPROVE.into()],
12670        );
12671        old_q
12672            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12673            .unwrap();
12674        questions.put(&mut old_q).unwrap();
12675        state.land_approval = Some(LandApproval {
12676            question: old_q.id.clone(),
12677            head: old.clone(),
12678        });
12679        state.save_under(home).unwrap();
12680
12681        let pr_url = state.pr.as_ref().unwrap().url.clone();
12682        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12683            url: pr_url.clone(),
12684            number: 42,
12685            open: true,
12686            head: old.clone(),
12687            base_branch: Some("main".to_owned()),
12688        });
12689        crate::land_sync_recovery_control::recover_with(
12690            &queue,
12691            home,
12692            crate::land_sync_recovery_control::Request {
12693                run: state.id.clone(),
12694                head: old.clone(),
12695                actor: "cli".into(),
12696                request: "req-same-head".into(),
12697            },
12698            &observer,
12699        )
12700        .await
12701        .unwrap();
12702
12703        let mut run = RunState::load_under(&state.id, home).unwrap();
12704        let mut forge = Scripted::for_pr(
12705            &pr_url,
12706            vec![
12707                seen(&old, Checks::Green, "CLEAN", false),
12708                seen(&old, Checks::Green, "CLEAN", false),
12709                seen(&old, Checks::Green, "CLEAN", false),
12710            ],
12711        );
12712        forge.public_repo = Some(run.repo.clone());
12713        land_with(&mut run, &pr_url, &forge).await.unwrap();
12714
12715        assert!(
12716            gate_marker.exists(),
12717            "fresh gate must run even on unchanged HEAD"
12718        );
12719        assert!(
12720            e2e_marker.exists(),
12721            "fresh E2E must run even on unchanged HEAD"
12722        );
12723        assert!(
12724            run.parked,
12725            "old approval before recovery must not be reused"
12726        );
12727        assert_ne!(run.land_approval.as_ref().unwrap().question, old_q.id);
12728    }
12729
12730    #[tokio::test]
12731    async fn land_sync_recovery_resumes_after_gate_repair_before_push() {
12732        let (_tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
12733        landing_gate_fixer(
12734            &mut state,
12735            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
12736        );
12737        state.config.verify.gate =
12738            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
12739        state.save_under(&home).unwrap();
12740        let pr_url = state.pr.as_ref().unwrap().url.clone();
12741        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12742            url: pr_url.clone(),
12743            number: 42,
12744            open: true,
12745            head: old.clone(),
12746            base_branch: Some("main".into()),
12747        });
12748        crate::land_sync_recovery_control::recover_with(
12749            &queue,
12750            &home,
12751            crate::land_sync_recovery_control::Request {
12752                run: state.id.clone(),
12753                head: old.clone(),
12754                actor: "cli".into(),
12755                request: "req-interrupted-gate-repair".into(),
12756            },
12757            &observer,
12758        )
12759        .await
12760        .unwrap();
12761        let mut run = RunState::load_under(&state.id, &home).unwrap();
12762        let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "CLEAN", false)]);
12763        assert!(matches!(
12764            prepare_land_sync_recovery(&mut run, &pr_url, &forge)
12765                .await
12766                .unwrap(),
12767            LandSyncPrep::Continue(Some(_))
12768        ));
12769        // Interrupt at the publication check, after the real gate fixer commits.
12770        let changed = Scripted::for_pr(
12771            &pr_url,
12772            vec![seen("different", Checks::Green, "CLEAN", false)],
12773        );
12774        let error = resume_landing_head(&mut run, &old, &pr_url, &changed, None)
12775            .await
12776            .unwrap_err();
12777        assert!(
12778            error.to_string().contains("PR head changed while gating"),
12779            "{error}"
12780        );
12781        let repaired = git::rev_parse(&run.repo, "HEAD").await.unwrap();
12782        assert_ne!(repaired, old);
12783        assert_eq!(run.gate_fixes.len(), 1);
12784        assert!(run.gate_fixes[0].committed);
12785        assert_eq!(
12786            git::remote_head(&run.repo, "origin", "task-head")
12787                .await
12788                .unwrap(),
12789            Some(old.clone())
12790        );
12791
12792        run.status = RunStatus::Blocked;
12793        run.save().unwrap();
12794        let mut resumed = RunState::load_under(&run.id, &home).unwrap();
12795        assert_eq!(resumed.land_sync_attempts, 5);
12796        assert!(resumed.land_sync_pending);
12797        assert!(!resumed.land_sync_exhausted());
12798        assert!(!resumed.land_sync_unstarted_grant());
12799        assert!(matches!(
12800            prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
12801                .await
12802                .unwrap(),
12803            LandSyncPrep::Continue(None)
12804        ));
12805        assert_eq!(
12806            resume_landing_head(&mut resumed, &old, &pr_url, &forge, None)
12807                .await
12808                .unwrap(),
12809            repaired
12810        );
12811        assert_eq!(resumed.land_sync_attempts, 5);
12812        assert_eq!(resumed.gate_fixes.len(), 1);
12813        assert!(!resumed.land_sync_pending);
12814        assert!(
12815            resumed.land_sync_recovery.authorizations[0]
12816                .invalidated
12817                .is_none()
12818        );
12819        assert_eq!(
12820            git::remote_head(&resumed.repo, "origin", "task-head")
12821                .await
12822                .unwrap(),
12823            Some(repaired)
12824        );
12825    }
12826
12827    #[tokio::test]
12828    async fn land_sync_recovery_repeated_exhaustion_is_bounded_by_lifetime_cap() {
12829        let (_tmp, home, queue, task, mut state, mut head) =
12830            legacy_exhausted_landing_fixture().await;
12831        let home = home.as_path();
12832        state.config.graph.land_approval = false;
12833        state.save_under(home).unwrap();
12834
12835        let pr_url = state.pr.as_ref().unwrap().url.clone();
12836        let mut base_step = 0usize;
12837        let advance_step = |repo: PathBuf, step: usize| async move {
12838            git::git(&repo, &["checkout", "main"]).await.unwrap();
12839            std::fs::write(repo.join(format!("advance-{step}")), format!("step-{step}")).unwrap();
12840            git::git(&repo, &["add", "."]).await.unwrap();
12841            git::git(&repo, &["commit", "-m", &format!("advance base {step}")])
12842                .await
12843                .unwrap();
12844            git::git(&repo, &["push", "origin", "main"]).await.unwrap();
12845            git::git(&repo, &["checkout", "winner"]).await.unwrap();
12846        };
12847        for grant_num in 1..=crate::land_sync_recovery::MAX_GRANTS {
12848            base_step += 1;
12849            advance_step(state.repo.clone(), base_step).await;
12850            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12851                url: pr_url.clone(),
12852                number: 42,
12853                open: true,
12854                head: head.clone(),
12855                base_branch: Some("main".to_owned()),
12856            });
12857            crate::land_sync_recovery_control::recover_with(
12858                &queue,
12859                home,
12860                crate::land_sync_recovery_control::Request {
12861                    run: state.id.clone(),
12862                    head: head.clone(),
12863                    actor: "cli".into(),
12864                    request: format!("req-cap-{grant_num}"),
12865                },
12866                &observer,
12867            )
12868            .await
12869            .unwrap();
12870
12871            // Simulate execution consuming grant, spending the 1 attempt, and hitting exhaustion again.
12872            state = RunState::load_under(&state.id, home).unwrap();
12873            let mut forge = Scripted::for_pr(
12874                &pr_url,
12875                vec![
12876                    seen(&head, Checks::Green, "BEHIND", false),
12877                    seen(&head, Checks::Green, "BEHIND", false),
12878                    seen("@published", Checks::Green, "BEHIND", false),
12879                ],
12880            );
12881            forge.public_repo = Some(state.repo.clone());
12882            let prep = prepare_land_sync_recovery(&mut state, &pr_url, &forge)
12883                .await
12884                .unwrap();
12885            assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
12886            head = resume_landing_head(&mut state, &head, &pr_url, &forge, None)
12887                .await
12888                .unwrap();
12889            assert_eq!(state.land_sync_attempts, 4 + grant_num);
12890            assert_eq!(state.land_sync_recovery.extra_attempts, grant_num);
12891
12892            // Re-exhaust on another base advance.
12893            base_step += 1;
12894            advance_step(state.repo.clone(), base_step).await;
12895            let err = rebase_landing_worktree(&mut state, "origin/main")
12896                .await
12897                .unwrap_err();
12898            assert!(err.to_string().contains("budget exhausted"), "{err:#}");
12899            state.status = RunStatus::Blocked;
12900            state.save_under(home).unwrap();
12901            assert!(state.land_sync_exhausted());
12902
12903            // Put task back to Held so the next explicit authorization can queue it.
12904            let mut t = queue.get(&task.id).unwrap();
12905            t.hold_machine(Some("re-exhausted".into()));
12906            queue.put(&mut t).unwrap();
12907        }
12908
12909        assert_eq!(
12910            state.land_sync_attempts,
12911            4 + crate::land_sync_recovery::MAX_GRANTS
12912        );
12913        assert_eq!(state.land_sync_grants_remaining(), 0);
12914        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12915            url: pr_url,
12916            number: 42,
12917            open: true,
12918            head: head.clone(),
12919            base_branch: Some("main".to_owned()),
12920        });
12921        let err = crate::land_sync_recovery_control::recover_with(
12922            &queue,
12923            home,
12924            crate::land_sync_recovery_control::Request {
12925                run: state.id.clone(),
12926                head,
12927                actor: "cli".into(),
12928                request: "req-cap-overflow".into(),
12929            },
12930            &observer,
12931        )
12932        .await
12933        .unwrap_err();
12934        assert!(
12935            err.to_string()
12936                .contains("lifetime landing base-sync recovery limit reached"),
12937            "{err:#}"
12938        );
12939    }
12940
12941    #[tokio::test]
12942    async fn land_sync_recovery_execution_revalidation_refuses_stale_pr_head_and_rewritten_base() {
12943        // Case A: PR head moves externally between admission and execution.
12944        {
12945            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
12946            let pr_url = state.pr.as_ref().unwrap().url.clone();
12947            let home = home.as_path();
12948            advance_landing_base(&state).await;
12949            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12950                url: pr_url.clone(),
12951                number: 42,
12952                open: true,
12953                head: old.clone(),
12954                base_branch: Some("main".to_owned()),
12955            });
12956            crate::land_sync_recovery_control::recover_with(
12957                &queue,
12958                home,
12959                crate::land_sync_recovery_control::Request {
12960                    run: state.id.clone(),
12961                    head: old.clone(),
12962                    actor: "cli".into(),
12963                    request: "req-stale-pr".into(),
12964                },
12965                &observer,
12966            )
12967            .await
12968            .unwrap();
12969
12970            let mut run = RunState::load_under(&state.id, home).unwrap();
12971            let foreign_head = "f".repeat(40);
12972            let forge = Scripted::for_pr(
12973                &pr_url,
12974                vec![seen(&foreign_head, Checks::Green, "BEHIND", false)],
12975            );
12976            land_with(&mut run, &pr_url, &forge).await.unwrap();
12977            assert_eq!(run.status, RunStatus::Blocked);
12978            assert_eq!(run.land_sync_recovery.extra_attempts, 0);
12979            assert_eq!(run.land_sync_attempts, 4);
12980            let auth = run.land_sync_recovery.authorizations.last().unwrap();
12981            assert!(auth.consumed);
12982            assert!(
12983                auth.invalidated
12984                    .as_deref()
12985                    .is_some_and(|why| why.contains("published PR head changed")),
12986                "{:?}",
12987                auth.invalidated
12988            );
12989            assert_eq!(run.pr_pushed_head.as_deref(), Some(old.as_str()));
12990        }
12991
12992        // Case B: origin/main rewritten (non-fast-forward) between admission and execution.
12993        {
12994            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
12995            let pr_url = state.pr.as_ref().unwrap().url.clone();
12996            let home = home.as_path();
12997            advance_landing_base(&state).await;
12998            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12999                url: pr_url.clone(),
13000                number: 42,
13001                open: true,
13002                head: old.clone(),
13003                base_branch: Some("main".to_owned()),
13004            });
13005            crate::land_sync_recovery_control::recover_with(
13006                &queue,
13007                home,
13008                crate::land_sync_recovery_control::Request {
13009                    run: state.id.clone(),
13010                    head: old.clone(),
13011                    actor: "cli".into(),
13012                    request: "req-rewritten-base".into(),
13013                },
13014                &observer,
13015            )
13016            .await
13017            .unwrap();
13018
13019            // Persist consumption before the rewrite, as if the driver crashed
13020            // between granting the attempt and starting the rebase.
13021            let mut consumed = RunState::load_under(&state.id, home).unwrap();
13022            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13023            assert!(matches!(
13024                prepare_land_sync_recovery(&mut consumed, &pr_url, &forge)
13025                    .await
13026                    .unwrap(),
13027                LandSyncPrep::Continue(Some(_))
13028            ));
13029            assert_eq!(consumed.land_sync_attempts, 4);
13030
13031            // Rewrite origin/main by amending the latest base commit and force-pushing.
13032            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
13033            std::fs::write(state.repo.join("advance"), "rewritten").unwrap();
13034            git::git(&state.repo, &["add", "."]).await.unwrap();
13035            git::git(&state.repo, &["commit", "--amend", "-m", "rewritten base"])
13036                .await
13037                .unwrap();
13038            git::git(&state.repo, &["push", "--force", "origin", "main"])
13039                .await
13040                .unwrap();
13041            git::git(&state.repo, &["checkout", "winner"])
13042                .await
13043                .unwrap();
13044
13045            let mut run = RunState::load_under(&state.id, home).unwrap();
13046            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13047            land_with(&mut run, &pr_url, &forge).await.unwrap();
13048            assert_eq!(run.status, RunStatus::Blocked);
13049            assert_eq!(run.land_sync_recovery.extra_attempts, 1);
13050            assert_eq!(run.land_sync_attempts, 4);
13051            assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
13052            let auth = run.land_sync_recovery.authorizations.last().unwrap();
13053            assert!(auth.consumed);
13054            assert!(
13055                auth.invalidated
13056                    .as_deref()
13057                    .is_some_and(|why| why.contains("does not fast-forward")),
13058                "{:?}",
13059                auth.invalidated
13060            );
13061            assert!(run.land_sync_exhausted());
13062            assert_eq!(run.land_sync_budget(), 4);
13063            let mut held = queue
13064                .list()
13065                .into_iter()
13066                .find(|t| t.execution_runs().last() == Some(&run.id))
13067                .unwrap();
13068            held.hold_machine(Some("recovery scope changed".into()));
13069            queue.put(&mut held).unwrap();
13070            crate::land_sync_recovery_control::recover_with(
13071                &queue,
13072                home,
13073                crate::land_sync_recovery_control::Request {
13074                    run: run.id.clone(),
13075                    head: old.clone(),
13076                    actor: "cli".into(),
13077                    request: "req-rewritten-base-new-approval".into(),
13078                },
13079                &observer,
13080            )
13081            .await
13082            .unwrap();
13083            let mut resumed = RunState::load_under(&run.id, home).unwrap();
13084            let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13085            assert!(matches!(
13086                prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
13087                    .await
13088                    .unwrap(),
13089                LandSyncPrep::Continue(Some(_))
13090            ));
13091            assert_eq!(resumed.land_sync_recovery.extra_attempts, 2);
13092            assert_eq!(resumed.land_sync_budget(), 5);
13093            assert_eq!(resumed.land_sync_attempts, 4);
13094            assert!(
13095                resumed.land_sync_recovery.authorizations[0]
13096                    .invalidated
13097                    .is_some()
13098            );
13099        }
13100    }
13101
13102    #[tokio::test]
13103    async fn land_sync_recovery_restart_after_consume_continues_without_double_grant() {
13104        let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13105        let home = home.as_path();
13106        let pr_url = state.pr.as_ref().unwrap().url.clone();
13107        advance_landing_base(&state).await;
13108        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13109            url: pr_url.clone(),
13110            number: 42,
13111            open: true,
13112            head: old.clone(),
13113            base_branch: Some("main".to_owned()),
13114        });
13115        crate::land_sync_recovery_control::recover_with(
13116            &queue,
13117            home,
13118            crate::land_sync_recovery_control::Request {
13119                run: state.id.clone(),
13120                head: old.clone(),
13121                actor: "cli".into(),
13122                request: "req-crash-after-consume".into(),
13123            },
13124            &observer,
13125        )
13126        .await
13127        .unwrap();
13128
13129        // Simulate consuming the authorization and crashing right before rebase starts.
13130        let mut crashed = RunState::load_under(&state.id, home).unwrap();
13131        let initial_forge =
13132            Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13133        let prep = prepare_land_sync_recovery(&mut crashed, &pr_url, &initial_forge)
13134            .await
13135            .unwrap();
13136        assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
13137        assert_eq!(crashed.land_sync_recovery.extra_attempts, 1);
13138        assert_eq!(crashed.land_sync_attempts, 4);
13139        assert!(crashed.land_sync_recovery.authorizations[0].consumed);
13140
13141        // An unreadable base is not proof that the authorized lineage changed.
13142        let remote = git::git(&state.repo, &["remote", "get-url", "origin"])
13143            .await
13144            .unwrap();
13145        git::git(
13146            &state.repo,
13147            &["remote", "set-url", "origin", "missing-local-origin"],
13148        )
13149        .await
13150        .unwrap();
13151        let mut interrupted = RunState::load_under(&state.id, home).unwrap();
13152        let forge = Scripted::for_pr(&pr_url, vec![seen(&old, Checks::Green, "BEHIND", false)]);
13153        assert!(matches!(
13154            prepare_land_sync_recovery(&mut interrupted, &pr_url, &forge)
13155                .await
13156                .unwrap(),
13157            LandSyncPrep::Stop(_)
13158        ));
13159        assert!(
13160            interrupted.land_sync_recovery.authorizations[0]
13161                .invalidated
13162                .is_none()
13163        );
13164        assert_eq!(interrupted.land_sync_attempts, 4);
13165        git::git(&state.repo, &["remote", "set-url", "origin", remote.trim()])
13166            .await
13167            .unwrap();
13168        let mut held = queue
13169            .list()
13170            .into_iter()
13171            .find(|t| t.execution_runs().last() == Some(&state.id))
13172            .unwrap();
13173        held.hold_machine(Some("base observation failed".into()));
13174        queue.put(&mut held).unwrap();
13175        assert!(crate::resume::pin_queued(&queue, &state.id, None, None).unwrap());
13176        let queued = queue.get(&held.id).unwrap();
13177        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, .. } =
13178            crate::land_sync_recovery::dispatch_check_with(&queue, home, &queued, &observer).await
13179        {
13180            panic!("dispatch refused recovery: {reason}");
13181        }
13182
13183        // Reload after restart and run land_with: uses the 1 already-granted attempt, never double-grants.
13184        let mut restarted = RunState::load_under(&state.id, home).unwrap();
13185        let mut forge = Scripted::for_pr(
13186            &pr_url,
13187            vec![
13188                seen(&old, Checks::Green, "BEHIND", false),
13189                seen(&old, Checks::Green, "BEHIND", false),
13190                seen("@published", Checks::Green, "CLEAN", false),
13191            ],
13192        );
13193        forge.public_repo = Some(restarted.repo.clone());
13194        land_with(&mut restarted, &pr_url, &forge).await.unwrap();
13195        assert_eq!(restarted.land_sync_recovery.extra_attempts, 1);
13196        assert_eq!(restarted.land_sync_attempts, 5);
13197        assert_eq!(restarted.land_sync_recovery.authorizations.len(), 1);
13198        assert!(!restarted.land_sync_pending);
13199    }
13200
13201    #[tokio::test]
13202    async fn land_sync_recovery_dispatch_revalidation_refuses_stale_and_superseded_state() {
13203        // 1. Without authorization, dispatch holds without spending budget.
13204        let (_tmp, home, queue, task, state, old) = legacy_exhausted_landing_fixture().await;
13205        let home = home.as_path();
13206        let pr_url = state.pr.as_ref().unwrap().url.clone();
13207        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13208            url: pr_url,
13209            number: 42,
13210            open: true,
13211            head: old.clone(),
13212            base_branch: Some("main".to_owned()),
13213        });
13214        assert!(matches!(
13215            crate::land_sync_recovery::dispatch_check_with(&queue, home, &task, &observer).await,
13216            crate::land_sync_recovery::DispatchDecision::Hold { .. }
13217        ));
13218
13219        // 2. Admit authorization, then supersede with a newer owner decision before dispatch.
13220        crate::land_sync_recovery_control::recover_with(
13221            &queue,
13222            home,
13223            crate::land_sync_recovery_control::Request {
13224                run: state.id.clone(),
13225                head: old.clone(),
13226                actor: "cli".into(),
13227                request: "req-dispatch-superseded".into(),
13228            },
13229            &observer,
13230        )
13231        .await
13232        .unwrap();
13233        let mut t = queue.get(&task.id).unwrap();
13234        t.operator_decided_at = Some(
13235            t.operator_decided_at.unwrap_or_else(jiff::Timestamp::now)
13236                + jiff::SignedDuration::from_secs(10),
13237        );
13238        queue.put(&mut t).unwrap();
13239        let decision =
13240            crate::land_sync_recovery::dispatch_check_with(&queue, home, &t, &observer).await;
13241        match decision {
13242            crate::land_sync_recovery::DispatchDecision::Hold {
13243                reason,
13244                state: updated,
13245            } => {
13246                assert!(
13247                    reason.contains("newer owner decision superseded"),
13248                    "{reason}"
13249                );
13250                let auth = updated.land_sync_recovery.authorizations.last().unwrap();
13251                assert!(auth.consumed);
13252                assert!(auth.invalidated.is_some());
13253                assert_eq!(updated.land_sync_recovery.extra_attempts, 0);
13254            }
13255            crate::land_sync_recovery::DispatchDecision::Proceed => {
13256                panic!("superseded authorization must be refused at dispatch");
13257            }
13258        }
13259    }
13260}