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 Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2907            continue;
2908        };
2909        let path = home.join("runs").join(&id).join("run.json");
2910        let Ok(body) = std::fs::read_to_string(&path) else {
2911            continue;
2912        };
2913        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2914            continue;
2915        };
2916        if !state.status.done()
2917            || state.pr.as_ref().is_none_or(|p| p.state != "open")
2918            || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2919                != crate::run::Liveness::Dead
2920        {
2921            continue;
2922        }
2923        let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2924            continue;
2925        };
2926        if let Some(pr) = state.pr.as_mut() {
2927            pr.state = to.as_str().to_owned();
2928        }
2929        let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2930        state.event(
2931            "land",
2932            format!("recorded {url} as {}: another run settled it", to.as_str()),
2933        );
2934        match state.save_under(home) {
2935            Ok(()) => changed += 1,
2936            Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2937        }
2938    }
2939    changed
2940}
2941
2942/// A run reached a final state for its pull request: tell every other terminal
2943/// run in the same repository that names the same pull request (handed-over
2944/// predecessors, blocked attempts, anything), so their records stop saying
2945/// `open`. Best effort; `run`'s own record is the caller's.
2946pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2947    if to == PrLifecycle::Open {
2948        return;
2949    }
2950    let Some(home) = crate::run::try_home() else {
2951        return;
2952    };
2953    write_pr_state_through_in(&home, run, to);
2954}
2955
2956pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2957    let Some(pr) = run.pr.as_ref() else {
2958        return 0;
2959    };
2960    let (url, number) = (pr.url.clone(), pr.number);
2961    rewrite_open_prs(home, &mut |other| {
2962        (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2963    })
2964}
2965
2966/// Terminal runs whose record still says their pull request is open, as
2967/// `(run id, repo, url)`, for [`repair_stale_pr_states`].
2968pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
2969    let now = Timestamp::now();
2970    let mut out = Vec::new();
2971    for id in crate::run::list_ids_in(&home.join("runs")) {
2972        let path = home.join("runs").join(&id).join("run.json");
2973        let Ok(body) = std::fs::read_to_string(&path) else {
2974            continue;
2975        };
2976        let Ok(state) = serde_json::from_str::<RunState>(&body) else {
2977            continue;
2978        };
2979        if let Some(pr) = state.pr.as_ref()
2980            && state.status.done()
2981            && pr.state == "open"
2982            && !pr.url.is_empty()
2983            && !crate::daemon::is_working_on(home, &id, now)
2984        {
2985            out.push((id, state.repo.clone(), pr.url.clone()));
2986        }
2987    }
2988    out
2989}
2990
2991/// Apply forge answers (`pr url -> state`) to every stale terminal record.
2992/// A url with no answer (the forge was unreadable) changes nothing.
2993pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
2994    rewrite_open_prs(home, &mut |s| {
2995        s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
2996    })
2997}
2998
2999/// One-time (and idempotent) repair of records that froze an `open` pull
3000/// request: ask the forge about each distinct pull request that a terminal run
3001/// still calls open - at most `max_lookups` of them - and rewrite the merged
3002/// and closed ones. A genuinely open pull request is left alone, and a lookup
3003/// that fails is "unknown, change nothing". Returns `(records rewritten,
3004/// lookups that failed)`.
3005pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
3006    let mut known = BTreeMap::new();
3007    let mut failed = 0;
3008    let mut seen = BTreeSet::new();
3009    for (_, repo, url) in stale_open_prs(home) {
3010        if known.len() + failed >= max_lookups || !seen.insert(url.clone()) {
3011            continue;
3012        }
3013        match lifecycle(&repo, &url).await {
3014            Ok(state) => {
3015                known.insert(url, state);
3016            }
3017            Err(e) => {
3018                tracing::warn!("repair pr state of {url}: {e:#}");
3019                failed += 1;
3020            }
3021        }
3022    }
3023    (apply_pr_states(home, &known), failed)
3024}
3025
3026async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
3027    match lifecycle(&state.repo, url).await? {
3028        PrLifecycle::Merged => {}
3029        other => bail!(
3030            "{url} is {}, not merged; refusing to record {} as merged on a guess",
3031            other.as_str(),
3032            state.id
3033        ),
3034    }
3035    let before = state.status;
3036    if let Err(e) = land(state, url).await {
3037        // `land` sets `status` to `Landing` and saves before its first read
3038        // of the pull request — see its own doc — so a failure here (a
3039        // transient `gh` hiccup between the two forge reads this function
3040        // makes) can leave the run stuck on that in-between value with
3041        // nothing left driving it. Land it on the same terminal shape an
3042        // automated `land` failure lands on instead of leaving it stuck.
3043        state.status = RunStatus::Blocked;
3044        state.event("fold", format!("manual-merge correction failed: {e:#}"));
3045        state.save()?;
3046        return Err(e).context(format!("confirming the merge of {url}"));
3047    }
3048    state.event(
3049        "fold",
3050        "operator recorded this pull request as a manual merge; this run never \
3051         re-entered `land`, so `bump::after_merge` did not run for it - a release \
3052         bump this change might warrant has to be filed by hand",
3053    );
3054    // Unlike the bump, the findings the merge left open are filed on this
3055    // path too: nothing else would ever carry them forward.
3056    if state.status == RunStatus::Merged {
3057        crate::followup::after_merge(state, url).await;
3058    }
3059    state.save()?;
3060    Ok((before, state.status))
3061}
3062
3063/// Parse `gh api repos/{owner}/{repo}/pulls/<n>/comments` into inline review
3064/// comments. No I/O.
3065///
3066/// `gh pr view` does not surface inline comments, and inline is exactly where
3067/// both review bots put their findings - a landing loop that read only the
3068/// top-level thread would never see the thing it is supposed to fix.
3069pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3070    let raw: Vec<GhInline> =
3071        serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3072    let mut out = Vec::new();
3073    for c in raw {
3074        push_if_outstanding(
3075            &mut out,
3076            ReviewComment {
3077                author: c.user.login,
3078                path: c.path,
3079                line: c.line,
3080                body: c.body,
3081            },
3082        );
3083    }
3084    Ok(out)
3085}
3086
3087/// Keep a comment only when it asks for something.
3088///
3089/// An inline comment always does: it names a file and a line. A top-level
3090/// comment is dropped when it is empty, when it is magi's own, or when it is
3091/// [noise](is_noise).
3092fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3093    if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3094        return;
3095    }
3096    if comment.path.is_none() && is_noise(&comment.body) {
3097        return;
3098    }
3099    out.push(comment);
3100}
3101
3102/// Is this comment body machinery rather than a finding?
3103///
3104/// Two tests, both structural, because guessing from prose is how a "looks
3105/// good to me" turns into a fix round:
3106///
3107/// 1. The bot said so - the body carries one of the [`NOT_A_REVIEW`] markers
3108///    with which CodeRabbit labels its trigger notice, its walkthrough, and its
3109///    footer.
3110/// 2. It asks for nothing - once HTML comments, `<details>` blocks, headings,
3111///    horizontal rules, and the bot's own status banner are removed, every
3112///    remaining line is a task-list item. That is exactly the shape of the
3113///    comment the Claude review job posts while it is still working.
3114///
3115/// Anything else is input, including bot prose. A bot that writes a paragraph
3116/// has said something, and the fix prompt tells the fixer it may decline a
3117/// comment with an argument - a wasted sentence in a prompt is cheaper than a
3118/// missed finding.
3119pub fn is_noise(body: &str) -> bool {
3120    if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3121        return true;
3122    }
3123    let mut content = false;
3124    for line in strip_blocks(body).lines() {
3125        let line = unquote(line);
3126        if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3127            continue;
3128        }
3129        content = true;
3130        break;
3131    }
3132    !content
3133}
3134
3135/// Remove HTML comments and collapsed `<details>` blocks.
3136fn strip_blocks(body: &str) -> String {
3137    let mut out = String::with_capacity(body.len());
3138    let mut rest = body;
3139    loop {
3140        let open = ["<!--", "<details>"]
3141            .iter()
3142            .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3143            .min_by_key(|(i, _)| *i);
3144        let Some((at, tag)) = open else {
3145            out.push_str(rest);
3146            return out;
3147        };
3148        out.push_str(&rest[..at]);
3149        let after = &rest[at + tag.len()..];
3150        let close = if tag == "<!--" { "-->" } else { "</details>" };
3151        match after.find(close) {
3152            Some(end) => rest = &after[end + close.len()..],
3153            // Unterminated: the rest of the body is inside the block.
3154            None => return out,
3155        }
3156    }
3157}
3158
3159/// Strip blockquote markers, which both bots wrap their callouts in.
3160fn unquote(line: &str) -> &str {
3161    let mut s = line.trim();
3162    while let Some(rest) = s.strip_prefix('>') {
3163        s = rest.trim_start();
3164    }
3165    s.trim()
3166}
3167
3168/// `- [ ]` / `- [x]`, in any of the bullet styles GitHub renders.
3169fn is_checklist(line: &str) -> bool {
3170    let rest = line
3171        .strip_prefix("- ")
3172        .or_else(|| line.strip_prefix("* "))
3173        .unwrap_or("");
3174    let rest = rest.trim_start();
3175    matches!(
3176        rest.get(..3),
3177        Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3178    )
3179}
3180
3181/// A heading, a horizontal rule, or a callout tag - shape, never content.
3182fn is_decoration(line: &str) -> bool {
3183    line.starts_with('#')
3184        || line.starts_with("[!")
3185        || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3186}
3187
3188/// A line that is nothing but emphasis and links.
3189///
3190/// Both review jobs open with a status banner
3191/// (`**Claude finished ... in 4m 14s** —— [View job](url)`). It reads as prose
3192/// to a line-based test and asks for nothing, so it is measured the same way a
3193/// heading is: strip the markup, and if no word survives, it was decoration.
3194fn is_banner(line: &str) -> bool {
3195    let plain = drop_spans(line, "**", "**");
3196    let plain = if plain.contains("](") {
3197        drop_spans(&plain, "[", ")")
3198    } else {
3199        plain
3200    };
3201    !plain.chars().any(char::is_alphanumeric)
3202}
3203
3204/// Remove every `open` .. `close` span, including the delimiters. An
3205/// unterminated span swallows the rest of the input, which is what a reader
3206/// sees too.
3207fn drop_spans(s: &str, open: &str, close: &str) -> String {
3208    let mut out = String::with_capacity(s.len());
3209    let mut rest = s;
3210    while let Some(at) = rest.find(open) {
3211        out.push_str(&rest[..at]);
3212        let after = &rest[at + open.len()..];
3213        match after.find(close) {
3214            Some(end) => rest = &after[end + close.len()..],
3215            None => return out,
3216        }
3217    }
3218    out.push_str(rest);
3219    out
3220}
3221
3222/// The lock that keeps at most one run per repository actually moving the
3223/// base branch at a time: a rebase push, or `gh pr merge`.
3224///
3225/// Deliberately narrow. Everything else in [`land`]'s loop - watching CI,
3226/// running a fix round in the winner's own worktree, waiting on the owner's
3227/// approval - touches nothing a *different* run in the same repository could
3228/// collide with, and holding a lock across any of that would serialise one
3229/// run's CI wait (up to [`WAIT_CEILING`]) against another run's land-approval
3230/// resume, which is precisely the "must not wait on another task" property
3231/// the daemon's slot-freeing exists to give a resume. Only the two moments
3232/// that actually write to the shared base branch need mutual exclusion, and
3233/// both are brief.
3234///
3235/// One entry per repository, each its own `tokio::sync::Mutex`, so two
3236/// different repositories' runs never wait on each other. The outer
3237/// `std::sync::Mutex` guards only the map itself, held long enough to find or
3238/// insert an entry and clone its `Arc`, never across an `.await`.
3239fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3240    static LOCKS: std::sync::LazyLock<
3241        std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3242    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3243    LOCKS
3244        .lock()
3245        .unwrap_or_else(std::sync::PoisonError::into_inner)
3246        .entry(repo.to_path_buf())
3247        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3248        .clone()
3249}
3250
3251/// `owner/repo` out of a pull request url, falling back to the checkout's
3252/// directory name when the url is not the usual `host/owner/repo/pull/N`.
3253fn repo_label(repo: &Path, pr_url: &str) -> String {
3254    let parts: Vec<&str> = pr_url.split('/').collect();
3255    if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3256        && at >= 2
3257        && !parts[at - 1].is_empty()
3258        && !parts[at - 2].is_empty()
3259    {
3260        return format!("{}/{}", parts[at - 2], parts[at - 1]);
3261    }
3262    repo.file_name()
3263        .map(|n| n.to_string_lossy().into_owned())
3264        .unwrap_or_default()
3265}
3266
3267/// The operator-facing sentence for a merge that went ahead with red checks,
3268/// or `None` when the checks were not red. Judged on `checks`, not on
3269/// `failing`, which can be non-empty on a green observation.
3270fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3271    (pr.checks == Checks::Red).then(|| {
3272        let details = crate::notices::format_list(&pr.failing)
3273            .map(|names| format!(": {names}"))
3274            .unwrap_or_default();
3275        format!(
3276            "Merged {repo_name} PR #{} with red checks{details} ({})",
3277            pr.number, pr.url
3278        )
3279    })
3280}
3281
3282/// After a merge that succeeded: record which checks were red and tell the
3283/// operator. The decision to merge is already made; this only makes it audible.
3284/// Best-effort - a broken notifier never fails the run.
3285async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3286    let repo_name = repo_label(&state.repo, &pr.url);
3287    let Some(summary) = red_merge_summary(&repo_name, pr) else {
3288        return;
3289    };
3290    if let Some(rec) = state.pr.as_mut() {
3291        rec.red_at_merge = pr.failing.clone();
3292    }
3293    state.event("land", summary.clone());
3294    // The notice pages through `[notify]` itself, once, unless a question
3295    // already carries the cause.
3296    crate::notices::raise_with(
3297        crate::notices::merged_red(&state.id, &summary),
3298        &state.config.notify,
3299    );
3300}
3301
3302/// Run the loop against a real pull request until it merges or the budget runs
3303/// out.
3304///
3305/// The caller decides whether landing happens at all: this is only reached when
3306/// `graph.land` is on. Returns the last observation, so the caller can report
3307/// what magi was looking at when it stopped.
3308pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3309    land_with(state, pr_url, &GhForge).await
3310}
3311
3312/// The forge calls whose timing the loop's decisions depend on, behind a seam
3313/// so a test can script what the pull request looks like from one observation
3314/// to the next. Comments, logs and rebases stay on `gh` and `git` directly.
3315trait Forge {
3316    async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3317        let out = gh(
3318            repo,
3319            &[
3320                "pr".into(),
3321                "close".into(),
3322                pr_url.into(),
3323                "--comment".into(),
3324                comment.into(),
3325            ],
3326        )
3327        .await?;
3328        if !out.ok {
3329            bail!("PR closure failed: {}", out.combined());
3330        }
3331        Ok(())
3332    }
3333    async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3334        None
3335    }
3336    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3337    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3338    async fn poll(&self);
3339    /// Rerun the failed jobs of one workflow run.
3340    async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3341    /// Unix seconds, behind the seam so a test owns the clock.
3342    fn now(&self) -> i64;
3343    /// The check contexts the base branch requires, for a stop reason only.
3344    /// `None` when they could not be read, which is not the same as none.
3345    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3346    #[allow(clippy::too_many_arguments)]
3347    async fn fix(
3348        &self,
3349        state: &mut RunState,
3350        pr: &PrState,
3351        round: usize,
3352        budget: usize,
3353        reason: &str,
3354        logs: &str,
3355    ) -> Result<Fixed>;
3356}
3357
3358struct GhForge;
3359
3360impl Forge for GhForge {
3361    async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3362        collect_ci_evidence(state, seen).await
3363    }
3364    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3365        observe(repo, pr_url).await
3366    }
3367    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3368        let out = gh(repo, argv).await?;
3369        Ok((out.ok, out.combined()))
3370    }
3371    async fn poll(&self) {
3372        tokio::time::sleep(POLL).await;
3373    }
3374    async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3375        let args = [
3376            "run".to_owned(),
3377            "rerun".to_owned(),
3378            run.to_owned(),
3379            "--failed".to_owned(),
3380        ];
3381        let out = gh(repo, &args).await?;
3382        if !out.ok {
3383            bail!("gh run rerun {run}: {}", out.combined());
3384        }
3385        Ok(())
3386    }
3387    fn now(&self) -> i64 {
3388        jiff::Timestamp::now().as_second()
3389    }
3390    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3391        required_contexts_of(repo, base).await
3392    }
3393    async fn fix(
3394        &self,
3395        state: &mut RunState,
3396        pr: &PrState,
3397        round: usize,
3398        budget: usize,
3399        reason: &str,
3400        logs: &str,
3401    ) -> Result<Fixed> {
3402        fix_round(state, pr, round, budget, reason, logs).await
3403    }
3404}
3405
3406/// Percent-encode a branch name for a URL path segment (`/` included).
3407fn encode_path_segment(s: &str) -> String {
3408    let mut out = String::new();
3409    for b in s.bytes() {
3410        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3411            out.push(b as char);
3412        } else {
3413            let _ = write!(out, "%{b:02X}");
3414        }
3415    }
3416    out
3417}
3418
3419/// Read the required contexts of `base` from classic branch protection and
3420/// from rulesets, once, for a stop reason. Organisation-level rulesets that
3421/// these two endpoints do not list are missed. Any unreadable source makes the
3422/// whole answer `None`: a partial set would read as a complete one.
3423async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3424    let enc = encode_path_segment(base);
3425    let mut all = BTreeSet::new();
3426    // Classic protection answers 404 for an unprotected branch, which is
3427    // "nothing required here", not a failure to read.
3428    let classic = gh(
3429        repo,
3430        &[
3431            "api".to_owned(),
3432            format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3433        ],
3434    )
3435    .await
3436    .ok()?;
3437    if classic.ok {
3438        all.extend(parse_classic_required(&classic.stdout)?);
3439    } else if !classic.combined().contains("404") {
3440        return None;
3441    }
3442    let rules = gh(
3443        repo,
3444        &[
3445            "api".to_owned(),
3446            format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3447        ],
3448    )
3449    .await
3450    .ok()?;
3451    if !rules.ok {
3452        return None;
3453    }
3454    all.extend(parse_ruleset_required(&rules.stdout)?);
3455    Some(all)
3456}
3457
3458/// `required_status_checks` of classic protection: `contexts` plus the
3459/// `checks[].context` form.
3460fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3461    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3462    let mut out = BTreeSet::new();
3463    for c in v.get("contexts")?.as_array()? {
3464        out.insert(c.as_str()?.to_owned());
3465    }
3466    for c in v
3467        .get("checks")
3468        .and_then(|c| c.as_array())
3469        .into_iter()
3470        .flatten()
3471    {
3472        if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3473            out.insert(name.to_owned());
3474        }
3475    }
3476    Some(out)
3477}
3478
3479/// `rules/branches/<base>`: every `required_status_checks` rule's contexts.
3480fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3481    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3482    let mut out = BTreeSet::new();
3483    for rule in v.as_array()? {
3484        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3485            continue;
3486        }
3487        let checks = rule
3488            .pointer("/parameters/required_status_checks")?
3489            .as_array()?;
3490        for c in checks {
3491            out.insert(c.get("context")?.as_str()?.to_owned());
3492        }
3493    }
3494    Some(out)
3495}
3496
3497/// Is the observation older than the commit a fix round pushed?
3498///
3499/// The forge takes a few seconds to move the pull request to a new head and
3500/// attach that head's check runs, and until it has, the rollup is the previous
3501/// head's - all green, which is exactly what a merge decision must not read.
3502/// An absent or different head counts as not yet: guessing "close enough"
3503/// would reopen the hole.
3504fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3505    awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3506}
3507
3508/// The commit an observation may be decided on, or `None` while it cannot be
3509/// trusted to describe one.
3510///
3511/// `None` when a pushed commit is awaited and the pull request is not on it,
3512/// when the head is unreadable, or when the rollup (`statusCheckRollup` is the
3513/// last commit's) is not the head's: that is the previous commit's checks. The
3514/// caller re-polls on `None`. A rollup that cannot be read (including one
3515/// longer than a page) leaves `rollup_head` empty, so the wait runs to
3516/// [`WAIT_CEILING`] and stops - a safe failure, never a merge.
3517fn bound_head<'a>(
3518    seen_head: &'a str,
3519    rollup_head: &str,
3520    awaiting: Option<&str>,
3521) -> Option<&'a str> {
3522    if seen_head.is_empty()
3523        || awaiting_new_head(awaiting, seen_head)
3524        || !rollup_head.eq_ignore_ascii_case(seen_head)
3525    {
3526        return None;
3527    }
3528    Some(seen_head)
3529}
3530
3531/// What a refused `gh pr merge` means.
3532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3533enum Refused {
3534    /// An open PR on the observed head has a proven stale base.
3535    Behind,
3536    /// The branch policy is not satisfied *yet*: go back to waiting.
3537    Pending,
3538    /// Checks have settled and the merge state still says no, seen for the
3539    /// first time. The forge updates `mergeStateStatus` a moment after the last
3540    /// check finishes, so one more look is allowed before believing it.
3541    Recheck,
3542    /// Nothing is in flight and the policy still refuses: a person has to
3543    /// supply what it asks for (a review, say).
3544    Final,
3545}
3546
3547/// Judged from the pull request's state after the refusal, never from the
3548/// refusal's wording, which belongs to the forge and changes.
3549fn classify_refusal(
3550    after: Option<&Seen>,
3551    rechecked: bool,
3552    observed_head: &str,
3553    ci: CiExpectation,
3554) -> Refused {
3555    let Some(after) = after else {
3556        // Unreadable is not evidence of anything; the next loop reads again.
3557        return Refused::Pending;
3558    };
3559    if after.pr.state != PrLifecycle::Open {
3560        return Refused::Final;
3561    }
3562    // The branch moved after it was observed (the forge refuses a merge pinned
3563    // to the old commit): not a verdict on anything, look again.
3564    if !after.head.eq_ignore_ascii_case(observed_head) {
3565        return Refused::Pending;
3566    }
3567    if Blocking::of(&after.merge_state) == Blocking::Behind {
3568        return Refused::Behind;
3569    }
3570    // The same binding the loop applies: checks of another commit say nothing.
3571    if bound_head(&after.head, &after.rollup_head, None).is_none() {
3572        return Refused::Pending;
3573    }
3574    let state = after.merge_state.to_ascii_uppercase();
3575    if (ci == CiExpectation::Expected
3576        && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3577        || state.is_empty()
3578        || state == "UNKNOWN"
3579    {
3580        return Refused::Pending;
3581    }
3582    if rechecked {
3583        Refused::Final
3584    } else {
3585        Refused::Recheck
3586    }
3587}
3588
3589/// Take auto-merge back from the forge and forget that it was armed.
3590///
3591/// `Err` carries the forge's message: the caller must not push or move on, as
3592/// an armed merge left behind could still fire for a commit nobody approved.
3593async fn disarm<F: Forge>(
3594    forge: &F,
3595    state: &mut RunState,
3596    repo: &Path,
3597    number: u64,
3598) -> std::result::Result<(), String> {
3599    let argv = disable_automerge_argv(number);
3600    let out = {
3601        let merge_lock = repo_merge_lock(repo);
3602        let _merge_slot = merge_lock.lock().await;
3603        forge.merge(repo, &argv).await
3604    };
3605    match out {
3606        Ok((true, _)) => {
3607            state.land_armed_head = None;
3608            state.event("land", "auto-merge disabled");
3609            state.save().map_err(|e| format!("{e:#}"))?;
3610            Ok(())
3611        }
3612        Ok((false, msg)) => Err(msg),
3613        Err(e) => Err(format!("{e:#}")),
3614    }
3615}
3616
3617/// [`stop`], first taking back an armed auto-merge so a pull request magi
3618/// gave up on does not merge on its own later. A failure to disarm is added
3619/// to the reason rather than hiding it.
3620async fn stop_disarmed<F: Forge>(
3621    forge: &F,
3622    state: &mut RunState,
3623    repo: &Path,
3624    pr: &PrState,
3625    why: &str,
3626) -> Result<()> {
3627    if state.land_armed_head.is_none() {
3628        return stop(state, repo, pr, why).await;
3629    }
3630    match disarm(forge, state, repo, pr.number).await {
3631        Ok(()) => stop(state, repo, pr, why).await,
3632        Err(e) => {
3633            let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3634            stop(state, repo, pr, &why).await
3635        }
3636    }
3637}
3638
3639/// Check the persisted card again around awaits that can outlive an owner tap.
3640fn owner_requested_stop(state: &RunState) -> Result<bool> {
3641    let Some(binding) = &state.land_approval else {
3642        return Ok(false);
3643    };
3644    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3645    Ok(q.run == state.id
3646        && q.node == APPROVAL_NODE
3647        && q.resolution()
3648            .as_deref()
3649            .is_some_and(crate::merge_decision::stops))
3650}
3651
3652/// Read stop choices before checks, repair or rebase. These are about stopping
3653/// ownership, so a changed head never cancels them as it cancels merge consent.
3654async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3655    use crate::merge_decision as md;
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    let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3661        return Ok(false);
3662    };
3663    if q.run != state.id || q.node != APPROVAL_NODE {
3664        bail!("stop decision names another run");
3665    }
3666    let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3667        pr: pr.url.clone(),
3668        head: binding.head.clone(),
3669        language: state.config.graph.language.clone(),
3670    });
3671    if target.pr != pr.url {
3672        bail!("stop decision names another PR");
3673    }
3674    if state.merge_decision.is_none() {
3675        state.merge_decision = Some(md::Decision {
3676            question: q.id.clone(),
3677            target,
3678            choice: choice.clone(),
3679            closed: false,
3680            replacement_run: None,
3681            replacement_pr: None,
3682        });
3683        state.save()?;
3684    }
3685    let repo = state.repo.clone();
3686    // Always disable, including arms left by an older driver.
3687    if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3688        stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3689        return Ok(true);
3690    }
3691    if choice.eq_ignore_ascii_case(HOLD) {
3692        stop(
3693            state,
3694            &repo,
3695            pr,
3696            "owner held the decision: PR left open; no further repair or merge work",
3697        )
3698        .await?;
3699        return Ok(true);
3700    }
3701    if md::selected_agent(&choice).is_some()
3702        || state
3703            .origin
3704            .as_ref()
3705            .and_then(|o| o.task.as_ref())
3706            .is_some()
3707    {
3708        let owners: Vec<_> = crate::queue::Queue::open()
3709            .list()
3710            .into_iter()
3711            .filter(|task| task.execution_runs().last() == Some(&state.id))
3712            .collect();
3713        let owner = (owners.len() == 1).then(|| &owners[0]);
3714        if !owner.is_some_and(|task| {
3715            task.execution_runs().last() == Some(&state.id)
3716                && (!task
3717                    .operator_decided_at
3718                    .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3719                    || task.resumption.as_ref().is_some_and(|release| {
3720                        release.question_id.as_deref() == Some(q.id.as_str())
3721                            && task.operator_decided_at == Some(release.at)
3722                    }))
3723        }) {
3724            stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3725            return Ok(true);
3726        }
3727    }
3728    if pr.state == PrLifecycle::Merged {
3729        stop(
3730            state,
3731            &repo,
3732            pr,
3733            "PR already merged; withdrawal/replacement cannot be applied",
3734        )
3735        .await?;
3736        return Ok(true);
3737    }
3738    let comment = format!(
3739        "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3740        q.id, choice, state.id
3741    );
3742    if pr.state == PrLifecycle::Open {
3743        if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3744            stop(
3745                state,
3746                &repo,
3747                pr,
3748                &format!(
3749                    "owner requested closure but it failed: {e}; task held, no replacement started"
3750                ),
3751            )
3752            .await?;
3753            return Ok(true);
3754        }
3755    }
3756    let confirmed = forge.view(&repo, &pr.url).await?;
3757    if confirmed.pr.state != PrLifecycle::Closed {
3758        stop(
3759            state,
3760            &repo,
3761            pr,
3762            "PR closure was not confirmed; task held, no replacement started",
3763        )
3764        .await?;
3765        return Ok(true);
3766    }
3767    *pr = confirmed.pr;
3768    state.merge_decision.as_mut().unwrap().closed = true;
3769    if let Some(record) = &mut state.pr {
3770        record.state = "closed".into();
3771    }
3772    state.status = RunStatus::Superseded;
3773    state.merge = Some(MergeOutcome {
3774        mode: MergeMode::Pr,
3775        ok: false,
3776        detail: format!("owner decision: {choice}; PR closure confirmed"),
3777        empty: false,
3778    });
3779    state.event(
3780        "land",
3781        format!(
3782            "{} applied: PR closure confirmed; old execution retired",
3783            choice
3784        ),
3785    );
3786    state.save()?;
3787    Ok(true)
3788}
3789
3790/// Keep an unstarted verification resumable without charging a task attempt.
3791fn check_landing_resources(
3792    state: &mut RunState,
3793    node: &str,
3794    outcomes: &[crate::run::CommandOutcome],
3795) -> Result<()> {
3796    if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
3797        let detail = format!("{}: {}", blocked.command, blocked.output_tail);
3798        state
3799            .resource_block
3800            .get_or_insert_with(|| crate::run::ResourceBlock {
3801                cause: crate::run::ResourceBlockCause::Other,
3802                node: node.into(),
3803                kind: "shared build cache".into(),
3804                detail: detail.clone(),
3805                at: jiff::Timestamp::now(),
3806            });
3807        state.event("resource", &detail);
3808        state.save()?;
3809        bail!("landing verification could not start: {detail}");
3810    }
3811    Ok(())
3812}
3813
3814/// Gate the local winner and publish that exact SHA, retaining the saved lease.
3815/// A push completed before a crash is recoverable only when its SHA was gated.
3816async fn publish_landing_head<F: Forge>(
3817    state: &mut RunState,
3818    observed: &str,
3819    pr_url: &str,
3820    forge: &F,
3821) -> Result<String> {
3822    crate::pr_head::ensure_owner(state)?;
3823    let winner = state.winner().cloned().context("landing has no winner")?;
3824    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3825    let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
3826    anyhow::ensure!(
3827        observed == expected
3828            || (observed == head
3829                && state.gate_head.as_deref() == Some(&head)
3830                && state.gate_allows_progress()),
3831        "public head moved outside this run; refusing to overwrite it"
3832    );
3833    anyhow::ensure!(
3834        git::is_clean(&winner.worktree).await?,
3835        "landing worktree is dirty"
3836    );
3837    if state.gate_head.as_deref() != Some(&head)
3838        || !state.gate_ran
3839        || !state.gate_commands_allow_progress()
3840    {
3841        state.reconcile_verification_head(&head);
3842        state.gate.clear();
3843        state.gate_head = None;
3844        state.gate_ran = false;
3845        state.pre_gate.clear();
3846        state.pre_gate_commit = None;
3847        state.save()?;
3848        let inherited = crate::repo_lock::WaitPolicy::current();
3849        let wait = crate::repo_lock::WaitPolicy::new(
3850            Duration::from_secs(state.config.graph.timeout_resource_wait),
3851            move || inherited.cancelled(),
3852        );
3853        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3854        loop {
3855            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
3856                state.gate = outcomes.clone();
3857                check_landing_resources(state, "gate", &outcomes)?;
3858            }
3859            if outcomes.iter().all(|o| o.ok()) {
3860                break;
3861            }
3862            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
3863                crate::graph::GateFix::Retry => {
3864                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3865                }
3866                crate::graph::GateFix::Stop => break,
3867                crate::graph::GateFix::Defer => {
3868                    // The repair checks e2e immediately, before the next gate.
3869                    // Preserve a cache wait here as well as below; otherwise
3870                    // the daemon charges an attempt for unstarted verification.
3871                    if let Some(e2e) = &state.gate_repair_e2e {
3872                        let outcomes = e2e.outcomes.clone();
3873                        check_landing_resources(state, "e2e", &outcomes)?;
3874                    }
3875                    bail!("landing gate repair deferred");
3876                }
3877            }
3878        }
3879        state.gate = outcomes;
3880        state.gate_ran = true;
3881        state.save()?;
3882    }
3883    let inherited = crate::repo_lock::WaitPolicy::current();
3884    let wait = crate::repo_lock::WaitPolicy::new(
3885        Duration::from_secs(state.config.graph.timeout_resource_wait),
3886        move || inherited.cancelled(),
3887    );
3888    let checked = state
3889        .gate_head
3890        .clone()
3891        .context("landing gate has no checked SHA")?;
3892    anyhow::ensure!(
3893        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3894            && git::is_clean(&winner.worktree).await?,
3895        "landing tree changed after gate"
3896    );
3897    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
3898    if matches!(e2e, crate::graph::GateFix::Defer) {
3899        let outcomes = state
3900            .gate_repair_e2e
3901            .as_ref()
3902            .context("deferred landing e2e has no outcomes")?
3903            .outcomes
3904            .clone();
3905        check_landing_resources(state, "e2e", &outcomes)?;
3906    }
3907    anyhow::ensure!(
3908        matches!(e2e, crate::graph::GateFix::Retry),
3909        "post-repair e2e has not passed on the landing head; nothing published"
3910    );
3911    anyhow::ensure!(
3912        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3913            && git::is_clean(&winner.worktree).await?,
3914        "landing tree changed during post-repair e2e"
3915    );
3916    anyhow::ensure!(
3917        crate::graph::verify_current_head(state, &winner, &wait).await?,
3918        "current head e2e has not passed; nothing published"
3919    );
3920    anyhow::ensure!(
3921        state.gate_allows_progress(),
3922        "landing gate failed; nothing published"
3923    );
3924    crate::pr_head::ensure_owner(state)?;
3925    if owner_requested_stop(state)? {
3926        bail!("owner requested stop before publication");
3927    }
3928    let current = forge.view(&state.repo, pr_url).await?;
3929    anyhow::ensure!(
3930        current.pr.state == PrLifecycle::Open,
3931        "PR closed or merged while gating; nothing published"
3932    );
3933    anyhow::ensure!(
3934        current.head == observed || current.head == checked,
3935        "PR head changed while gating; nothing published"
3936    );
3937    anyhow::ensure!(
3938        crate::foreign_checkout::write_back(state, &checked).await?,
3939        "foreign checkout delivery is blocked; see the run events"
3940    );
3941    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
3942    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
3943    let refspec = format!("{checked}:refs/heads/{public}");
3944    let lock = repo_merge_lock(&state.repo);
3945    let _slot = lock.lock().await;
3946    let pushed = git::git_raw(
3947        &winner.worktree,
3948        &["push", &lease, &state.config.merge.remote, &refspec],
3949    )
3950    .await?;
3951    anyhow::ensure!(
3952        pushed.ok(),
3953        "publishing gated landing head failed: {}",
3954        pushed.stderr
3955    );
3956    state.pr_pushed_head = Some(checked.clone());
3957    // An already-current base still completes the authorized synchronization.
3958    // Do not leave its allowance available for a later, unrelated base move.
3959    if state.land_sync_unstarted_grant() {
3960        state.land_sync_attempts += 1;
3961    }
3962    state.land_sync_pending = false;
3963    state.save()?;
3964    Ok(checked)
3965}
3966
3967/// A scratch rebase moves the winner ref before its index and files. Recover
3968/// only a tree proven unchanged since the saved start; never discard edits.
3969async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
3970    let winner = state.winner().cloned().context("landing has no winner")?;
3971    let inherited = crate::repo_lock::WaitPolicy::current();
3972    let wait = crate::repo_lock::WaitPolicy::new(
3973        Duration::from_secs(state.config.graph.timeout_resource_wait),
3974        move || inherited.cancelled(),
3975    );
3976    let _coordination = crate::repo_lock::SeatLease::operation_with(
3977        &winner.worktree,
3978        state.config.coordination.as_ref(),
3979        &wait,
3980    )
3981    .await?;
3982    if !git::is_clean(&winner.worktree).await? {
3983        let from = state
3984            .land_rebase_from
3985            .as_deref()
3986            .context("landing worktree is dirty")?;
3987        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3988        anyhow::ensure!(head != from, "landing worktree is dirty");
3989        for args in [
3990            vec!["diff", "--cached", "--quiet", from],
3991            vec!["diff", "--quiet"],
3992        ] {
3993            anyhow::ensure!(
3994                git::git_raw(&winner.worktree, &args).await?.ok(),
3995                "landing worktree has edits beyond the interrupted rebase"
3996            );
3997        }
3998        // Preserve build artifacts and local files, including ignored ones.
3999        // read-tree can overwrite ignored paths, so reject collisions with
4000        // the new tree (including file/directory conflicts) before updating.
4001        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
4002        let tracked = git::git(
4003            &winner.worktree,
4004            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
4005        )
4006        .await?;
4007        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
4008            anyhow::ensure!(
4009                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
4010                    path == local
4011                        || path
4012                            .strip_prefix(local)
4013                            .is_some_and(|rest| rest.starts_with('/'))
4014                        || local
4015                            .strip_prefix(path)
4016                            .is_some_and(|rest| rest.starts_with('/'))
4017                }),
4018                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
4019            );
4020        }
4021        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
4022    }
4023    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
4024        anyhow::ensure!(
4025            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
4026            "landing synchronization started outside the foreign checkout history"
4027        );
4028        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
4029            // The rebase's tree already includes the base and the fixer's
4030            // resolutions. Retain that exact tree, but join the pre-sync
4031            // history so delivery remains fast-forward. Keep the checkpoint
4032            // until this succeeds: a crash after rebase (or after this merge)
4033            // must recover through this same idempotent path before gating.
4034            git::git(
4035                &winner.worktree,
4036                &[
4037                    "-c",
4038                    "core.hooksPath=/dev/null",
4039                    "merge",
4040                    "--strategy=ours",
4041                    "--no-ff",
4042                    "--no-autostash",
4043                    "--no-edit",
4044                    "-m",
4045                    "Merge pre-sync history into the repaired landing tree",
4046                    from,
4047                ],
4048            )
4049            .await?;
4050        }
4051    }
4052    crate::worktree_setup::prepare_with(
4053        &state.config,
4054        &state.repo,
4055        &winner.worktree,
4056        crate::build_target::Coordination::Held(_coordination.as_ref()),
4057    )
4058    .await?;
4059    state.land_rebase_from = None;
4060    state.save()?;
4061    Ok(())
4062}
4063
4064async fn rebase_landing_worktree(
4065    state: &mut RunState,
4066    onto: &str,
4067) -> Result<crate::rebase::Rebased> {
4068    restore_landing_worktree(state).await?;
4069    let winner = state.winner().cloned().context("landing has no winner")?;
4070    let scratch = state.dir().join("rebase");
4071    let target = match state.land_sync_target.clone() {
4072        Some(target) => {
4073            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4074            target
4075        }
4076        // Older records lack the target checkpoint, but Git retains the
4077        // exact target of an interrupted operation. It is a continuation too.
4078        None if crate::rebase::checked_progress(state, &scratch, "").await? => {
4079            crate::rebase::rebase_target(&scratch).await?
4080        }
4081        None => {
4082            if state.land_sync_attempts >= state.land_sync_budget() {
4083                let head = git::rev_parse(&winner.worktree, "HEAD")
4084                    .await
4085                    .unwrap_or_default();
4086                let tip = git::rev_parse(&state.repo, onto).await.unwrap_or_default();
4087                let pr_head = state.pr_pushed_head.clone().unwrap_or_else(|| head.clone());
4088                state.land_sync_pending = true;
4089                state.record_land_sync_exhausted_stop(&head, &pr_head, &tip);
4090                let _ = state.save();
4091                bail!("{}", crate::land_sync_recovery::EXHAUSTED_DETAIL);
4092            }
4093            let target = git::rev_parse(&state.repo, onto).await?;
4094            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4095            state.land_sync_attempts += 1;
4096            state.land_sync_target = Some(target.clone());
4097            target
4098        }
4099    };
4100    state.land_sync_target = Some(target.clone());
4101    state.land_sync_pending = true;
4102    state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4103    state.save()?;
4104    // A continuation owns the attempt already charged above, including a
4105    // crash before the scratch rebase started. Finish its pinned base first;
4106    // a newer base must use another attempt on the next observation.
4107    let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4108    state.land_sync_target = None;
4109    state.save()?;
4110    if result == crate::rebase::Rebased::Applied {
4111        restore_landing_worktree(state).await?;
4112    }
4113    Ok(result)
4114}
4115
4116/// Reconcile a stopped landing before changing its branch. This also handles
4117/// old records whose graph status or merge detail no longer identifies land.
4118async fn resume_landing_head<F: Forge>(
4119    state: &mut RunState,
4120    observed: &str,
4121    pr_url: &str,
4122    forge: &F,
4123    reason: Option<Blocking>,
4124) -> Result<String> {
4125    crate::pr_head::ensure_owner(state)?;
4126    let winner = state.winner().cloned().context("landing has no winner")?;
4127    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4128    let expected = state
4129        .pr_pushed_head
4130        .as_deref()
4131        .or(state.gate_head.as_deref())
4132        .context("missing public head lease")?;
4133    anyhow::ensure!(
4134        observed == expected
4135            || (observed == local
4136                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4137                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4138        "public head moved outside this run; refusing to sync"
4139    );
4140    // An operator may have extended and published the winner while approval
4141    // was pending. Matching local/public history can be adopted as the lease,
4142    // but publish_landing_head must gate its new SHA before proceeding. A
4143    // remote-only or divergent update still cannot be overwritten.
4144    // Save reconciliation before rebasing again; a prior push may have reached
4145    // the remote immediately before the previous driver's last save.
4146    state.pr_pushed_head = Some(observed.to_owned());
4147    state.save()?;
4148    restore_landing_worktree(state).await?;
4149    // Recover a rebase that finished before its completion checkpoint was
4150    // saved. Restoration above has already reconciled its files and ancestry.
4151    let scratch = state.dir().join("rebase");
4152    if let Some(target) = state.land_sync_target.clone()
4153        && !crate::rebase::checked_progress(state, &scratch, "").await?
4154        && git::ancestry(&winner.worktree, &target, &local).await?
4155    {
4156        state.land_sync_target = None;
4157        state.save()?;
4158    }
4159    let remote = state.config.merge.remote.clone();
4160    let base = state.base_branch.clone();
4161    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4162    anyhow::ensure!(
4163        fetched.ok(),
4164        "cannot fetch landing base: {}",
4165        fetched.stderr
4166    );
4167    anyhow::ensure!(
4168        !owner_requested_stop(state)?,
4169        "owner requested stop before base synchronization"
4170    );
4171    let onto = format!("{remote}/{base}");
4172    let tip = git::rev_parse(&state.repo, &onto).await?;
4173    if state.land_sync_unstarted_grant() {
4174        let auth = state
4175            .land_sync_recovery
4176            .authorizations
4177            .last()
4178            .context("missing recovery grant")?;
4179        anyhow::ensure!(
4180            auth.invalidated.is_none()
4181                && git::ancestry(&state.repo, &auth.scope.tip, &tip).await?
4182                && git::ancestry(&state.repo, &auth.stop.tip, &tip).await?,
4183            "fetched landing base is outside the authorized recovery lineage"
4184        );
4185    }
4186    let contains_base = git::ancestry(&state.repo, &tip, &local)
4187        .await
4188        .context("could not determine whether the landing head contains the fetched base")?;
4189    anyhow::ensure!(
4190        reason != Some(Blocking::Behind) || !contains_base,
4191        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4192    );
4193    if !contains_base || reason == Some(Blocking::Conflict) {
4194        match rebase_landing_worktree(state, &tip).await? {
4195            crate::rebase::Rebased::Applied => {}
4196            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4197        }
4198    }
4199    if reason == Some(Blocking::Behind) {
4200        anyhow::ensure!(
4201            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4202            "BEHIND synchronization left the head unchanged"
4203        );
4204    }
4205    publish_landing_head(state, observed, pr_url, forge).await
4206}
4207
4208/// Share the synchronization path with structured evidence retained after a refusal.
4209async fn synchronize_landing<F: Forge>(
4210    state: &mut RunState,
4211    pr: &mut PrState,
4212    observed: &str,
4213    pr_url: &str,
4214    forge: &F,
4215) -> Result<Option<String>> {
4216    if owner_stop(state, pr, forge).await? {
4217        return Ok(None);
4218    }
4219    state.event(
4220        "land",
4221        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4222    );
4223    state.save()?;
4224    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4225    if owner_stop(state, pr, forge).await? {
4226        return Ok(None);
4227    }
4228    match synced {
4229        Ok(head) => {
4230            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4231                crate::graph::refresh_reviewed_commits(state, &branch).await;
4232            }
4233            Ok(Some(head))
4234        }
4235        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4236        Err(e) => {
4237            let repo = state.repo.clone();
4238            stop(
4239                state,
4240                &repo,
4241                pr,
4242                &format!("could not synchronize landing base: {e:#}"),
4243            )
4244            .await?;
4245            Ok(None)
4246        }
4247    }
4248}
4249
4250enum LandSyncPrep {
4251    Continue(Option<Seen>),
4252    Stop(PrState),
4253}
4254
4255/// Revalidate and durably consume a pending landing base-sync recovery
4256/// authorization under the live execution lease before mutating landing status
4257/// or adopting any observed PR head.
4258async fn prepare_land_sync_recovery<F: Forge>(
4259    state: &mut RunState,
4260    pr_url: &str,
4261    forge: &F,
4262) -> Result<LandSyncPrep> {
4263    let has_unconsumed = state.has_unconsumed_land_sync_authorization();
4264    let unstarted = state.land_sync_unstarted_grant();
4265    let exhausted = state.land_sync_exhausted();
4266    if !has_unconsumed && !exhausted && !unstarted {
4267        return Ok(LandSyncPrep::Continue(None));
4268    }
4269    let repo = state.repo.clone();
4270    let seen = forge.view(&repo, pr_url).await?;
4271    if seen.pr.state != PrLifecycle::Open {
4272        anyhow::ensure!(
4273            state
4274                .pr
4275                .as_ref()
4276                .is_some_and(|pr| pr.url == seen.pr.url && pr.number == seen.pr.number),
4277            "terminal pull request does not match the retained run"
4278        );
4279        return Ok(LandSyncPrep::Continue(Some(seen)));
4280    }
4281    if !has_unconsumed && !unstarted {
4282        bail!(
4283            "{}; explicit recover-land-sync authorization required",
4284            crate::land_sync_recovery::EXHAUSTED_DETAIL
4285        );
4286    }
4287    let observed = crate::land_sync_recovery::ObservedPr {
4288        url: seen.pr.url.clone(),
4289        number: seen.pr.number,
4290        open: seen.pr.state == PrLifecycle::Open,
4291        head: seen.head.clone(),
4292        base_branch: (!seen.base.is_empty()).then(|| seen.base.clone()),
4293    };
4294    let home = crate::run::home();
4295    let validation = if owner_requested_stop(state)? {
4296        Err("owner requested stop before landing base-sync recovery".into())
4297    } else {
4298        crate::land_sync_recovery::validate_pending_authorization(
4299            &home,
4300            state,
4301            None,
4302            Some(&observed),
4303            &crate::land_sync_recovery::GhPrObserver,
4304        )
4305        .await
4306    };
4307    match validation {
4308        Ok((local_head, pr_head)) => {
4309            if unstarted {
4310                return Ok(LandSyncPrep::Continue(Some(seen)));
4311            }
4312            if let Err(reason) = state.consume_land_sync_recovery(&local_head, &pr_head) {
4313                state.status = RunStatus::Blocked;
4314                state.event("land-sync-recovery", format!("refused: {reason}"));
4315                state.save()?;
4316                return Ok(LandSyncPrep::Stop(seen.pr));
4317            }
4318            state.event(
4319                "land-sync-recovery",
4320                format!(
4321                    "consumed recovery grant {}/{}: authorized {} landing sync attempt ({}/{}); prior verification archived, fresh E2E and gate required",
4322                    state.land_sync_recovery.extra_attempts,
4323                    crate::land_sync_recovery::MAX_GRANTS,
4324                    crate::land_sync_recovery::GRANT_ATTEMPTS,
4325                    state.land_sync_attempts,
4326                    state.land_sync_budget()
4327                ),
4328            );
4329            state.save()?;
4330            Ok(LandSyncPrep::Continue(Some(seen)))
4331        }
4332        Err(failure) => {
4333            let reason = failure.reason;
4334            if !failure.observation_failed
4335                && let Some(auth) = state
4336                    .land_sync_recovery
4337                    .authorizations
4338                    .iter_mut()
4339                    .rev()
4340                    .find(|a| {
4341                        a.invalidated.is_none()
4342                            && (!a.consumed || unstarted && a.archived_verification.is_some())
4343                    })
4344            {
4345                auth.refuse(&reason);
4346            }
4347            state.status = RunStatus::Blocked;
4348            state.event("land-sync-recovery", format!("refused: {reason}"));
4349            state.save()?;
4350            Ok(LandSyncPrep::Stop(seen.pr))
4351        }
4352    }
4353}
4354
4355async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4356    crate::pr_head::ensure_owner(state)?;
4357    let mut initial_seen = match prepare_land_sync_recovery(state, pr_url, forge).await? {
4358        LandSyncPrep::Continue(seen) => seen,
4359        LandSyncPrep::Stop(pr) => return Ok(pr),
4360    };
4361    state.land_unrelated = None;
4362    let reopening_hold = crate::merge_decision::resumable_hold(state);
4363    let repo = state.repo.clone();
4364    let budget = state.config.graph.land_rounds;
4365    let mut round = 0usize;
4366    let ci = state.config.merge.ci.expectation();
4367    if ci == CiExpectation::Absent {
4368        state.event(
4369            "land",
4370            "CI not expected ([merge] ci = \"none\"); check status ignored",
4371        );
4372    }
4373    let mut waited = Duration::ZERO;
4374    // Comment bodies the fixer has already been shown. A comment is
4375    // outstanding until it has been handed over once; after that it is a
4376    // recorded decision, not an open question, and re-feeding it would loop the
4377    // budget away on a comment the fixer already declined with an argument.
4378    let mut shown: BTreeSet<String> = BTreeSet::new();
4379    // Await the last successfully published head, including across resumes.
4380    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4381    // Whether a settled-checks refusal has already been given its one re-look.
4382    let mut rechecked = false;
4383
4384    // Marks the run resumable through exactly this function, not through a
4385    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4386    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4387    // status specifically to know a resumed run belongs back in `land`
4388    // rather than at a second `gh pr create`. Set on every entry - fresh or
4389    // resumed - because a resume that parked here again must keep reading
4390    // `Landing`, not whatever a first pass through `merge` left behind.
4391    state.status = RunStatus::Landing;
4392    state.event("land", format!("watching {pr_url}"));
4393    state.save()?;
4394
4395    // An armed merge recorded by an earlier pass may or may not have reached
4396    // the forge (the record is written before the call). It is taken back on
4397    // the first observation, where a pull request is known to stop with.
4398    let mut resumed_armed = state.land_armed_head.is_some();
4399
4400    'landing: loop {
4401        let seen = match initial_seen.take() {
4402            Some(seen) => seen,
4403            None => forge.view(&repo, pr_url).await?,
4404        };
4405        let mut pr = seen.pr.clone();
4406        pr.review_comments.retain(|c| !shown.contains(&c.body));
4407        state.pr = Some(crate::run::PrRecord {
4408            url: pr.url.clone(),
4409            number: pr.number,
4410            state: pr.state.as_str().to_owned(),
4411            checks: pr.checks.as_str().to_owned(),
4412            round,
4413            rounds: budget,
4414            red_at_merge: Vec::new(),
4415        });
4416        state.save()?;
4417
4418        if pr.state == PrLifecycle::Open {
4419            state.observe_branch_owner_holds(&seen.head).await;
4420            state.save()?;
4421        }
4422        crate::pr_head::ensure_owner(state)?;
4423        if reopening_hold {
4424            anyhow::ensure!(
4425                pr.state == PrLifecycle::Open,
4426                "held PR is no longer open; cannot request a fresh decision"
4427            );
4428            // An explicit resume authorizes a fresh question only. Preserve the
4429            // answered card, and never enter repair/rebase/merge on this pass.
4430            disarm(forge, state, &repo, pr.number)
4431                .await
4432                .map_err(anyhow::Error::msg)?;
4433            let previous = state.merge_decision.take();
4434            let binding = state.land_approval.take();
4435            state.config.graph.land_approval = true;
4436            let subject = merge_subject(
4437                crate::graph::landing_title(state, &seen.title),
4438                &crate::graph::landing_subject_source(state),
4439            );
4440            let contested = contested_to_ask(state);
4441            if let Err(error) =
4442                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4443            {
4444                state.merge_decision = previous;
4445                state.land_approval = binding;
4446                return Err(error);
4447            }
4448            state.end_pass_parked(crate::run::ParkCause::Question);
4449            state.parked = true;
4450            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()));
4451            state.save()?;
4452            return Ok(pr);
4453        }
4454        if owner_stop(state, &mut pr, forge).await? {
4455            return Ok(pr);
4456        }
4457
4458        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4459            // An approval already given for the same head is reused, so
4460            // nothing is asked twice. A failed disable
4461            // stops the run with the record kept: pushing on could change the
4462            // head under an arm that is still live.
4463            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4464                let why = format!(
4465                    "a previous pass may have armed auto-merge and it could not be disabled \
4466                     on resume: {e}"
4467                );
4468                stop(state, &repo, &pr, &why).await?;
4469                return Ok(pr);
4470            }
4471        }
4472
4473        // The head moved away from the one auto-merge was armed on, by
4474        // someone other than this loop. The arm is pinned and would refuse to
4475        // merge the new commit, but the approval was for the old one: take it
4476        // back and go through the normal path again.
4477        if pr.state == PrLifecycle::Open
4478            && !seen.head.is_empty()
4479            && state
4480                .land_armed_head
4481                .as_deref()
4482                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4483        {
4484            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4485                let why = format!(
4486                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4487                );
4488                stop(state, &repo, &pr, &why).await?;
4489                return Ok(pr);
4490            }
4491        }
4492
4493        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4494            // Disarming can outlive an owner answer. Consume it before our
4495            // own rebase invalidates the head shown on the decision card.
4496            if owner_stop(state, &mut pr, forge).await? {
4497                return Ok(pr);
4498            }
4499            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4500                binding.head.eq_ignore_ascii_case(&seen.head)
4501                    && ask::Questions::open()
4502                        .get_for_effects(&binding.question)
4503                        .is_ok_and(|q| {
4504                            q.run == state.id
4505                                && q.node == APPROVAL_NODE
4506                                && q.status == ask::QuestionStatus::Answered
4507                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4508                        })
4509            });
4510            if repair_answer {
4511                let subject = merge_subject(
4512                    crate::graph::landing_title(state, &seen.title),
4513                    &crate::graph::landing_subject_source(state),
4514                );
4515                let contested = contested_to_ask(state);
4516                if matches!(
4517                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4518                    ApprovalGate::Repair
4519                ) {
4520                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4521                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4522                        state.save()?;
4523                    }
4524                    return Ok(pr);
4525                }
4526            }
4527            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4528            // A stop detected before publication must apply its durable
4529            // decision, even when verification returned an error meanwhile.
4530            if owner_stop(state, &mut pr, forge).await? {
4531                return Ok(pr);
4532            }
4533            let head = synced?;
4534            awaiting_head = Some(head);
4535            waited = Duration::ZERO;
4536            rechecked = false;
4537            // Read CI and approvals afresh, never from the pre-push observation.
4538            continue;
4539        }
4540
4541        // A stale base is independent of the CI rollup. Keep the public-head
4542        // lease, but synchronize before waiting for checks on the old tree.
4543        if pr.state == PrLifecycle::Open
4544            && pr.blocking == Blocking::Behind
4545            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4546        {
4547            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4548            let Some(head) = synced else {
4549                return Ok(pr);
4550            };
4551            awaiting_head = Some(head);
4552            rechecked = false;
4553            waited = Duration::ZERO;
4554            continue;
4555        }
4556
4557        if pr.state == PrLifecycle::Open {
4558            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4559                if waited >= WAIT_CEILING {
4560                    let want = awaiting_head.as_deref().unwrap_or_default();
4561                    let why = format!(
4562                        "the pull request's checks were still not about one readable head after \
4563                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4564                         someone may have pushed over it",
4565                        WAIT_CEILING.as_secs() / 60,
4566                        if want.is_empty() { "any" } else { want },
4567                        if seen.head.is_empty() {
4568                            "nothing readable"
4569                        } else {
4570                            &seen.head
4571                        },
4572                        if seen.rollup_head.is_empty() {
4573                            "nothing readable"
4574                        } else {
4575                            &seen.rollup_head
4576                        },
4577                    );
4578                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4579                    return Ok(pr);
4580                }
4581                waited += POLL;
4582                forge.poll().await;
4583                continue;
4584            }
4585            // Reset once, when the awaited head first shows up; resetting on
4586            // every re-observation would let a standing refusal wait forever.
4587            if awaiting_head.take().is_some() {
4588                // The checks now being read belong to the new head; give them
4589                // the same grace a fresh pull request gets.
4590                waited = Duration::ZERO;
4591            }
4592        }
4593
4594        // The merge-state grace is head-bound and durable. Reruns reset the
4595        // checks clock, but must not extend this deadline across resumes.
4596        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4597            let first = state
4598                .land_unsaid
4599                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4600            if !first.0.eq_ignore_ascii_case(&seen.head) {
4601                *first = (seen.head.clone(), forge.now());
4602            }
4603            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4604            state.save()?;
4605            elapsed
4606        } else {
4607            waited
4608        };
4609        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4610        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4611            if waited >= WAIT_CEILING {
4612                stop_disarmed(
4613                    forge,
4614                    state,
4615                    &repo,
4616                    &pr,
4617                    "merge state remained unreadable; refusing to merge on a guess",
4618                )
4619                .await?;
4620                return Ok(pr);
4621            }
4622            waited += POLL;
4623            forge.poll().await;
4624            continue;
4625        }
4626
4627        // A failed workflow run is rerun once, judged by its own run rather
4628        // than by the rollup's aggregate: another run still pending, or a fix
4629        // budget already spent, must not keep a flaky failure from its one
4630        // rerun. It spends no round and no attempt.
4631        if ci == CiExpectation::Expected
4632            && pr.state == PrLifecycle::Open
4633            && state.config.graph.rerun_flaky_checks
4634        {
4635            let include_optional = pr.checks == Checks::Red
4636                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4637            let failing = rerunnable_with(&seen.contexts, include_optional);
4638            let now = forge.now();
4639            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4640                RerunStep::Rerun(runs) => {
4641                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4642                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4643                        *rec = LandReruns {
4644                            head: seen.head.clone(),
4645                            runs: BTreeMap::new(),
4646                        };
4647                    }
4648                    for run in &runs {
4649                        rec.runs.insert(run.clone(), now);
4650                    }
4651                    // Durable before the call: a restart must not
4652                    // rerun the same run twice. A save that fails
4653                    // means no rerun.
4654                    state.save()?;
4655                    let mut any = false;
4656                    for run in &runs {
4657                        let names = failing
4658                            .iter()
4659                            .filter(|(_, r)| r.as_deref() == Some(run))
4660                            .map(|(l, _)| l.as_str())
4661                            .collect::<Vec<_>>()
4662                            .join(", ");
4663                        match forge.rerun(&repo, run).await {
4664                            Ok(()) => {
4665                                any = true;
4666                                state.event(
4667                                    "land",
4668                                    format!("reran failed check(s) {names} (run {run})"),
4669                                );
4670                            }
4671                            // Stays recorded: never a retry loop.
4672                            Err(e) => state.event(
4673                                "land",
4674                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4675                            ),
4676                        }
4677                    }
4678                    state.save()?;
4679                    if any {
4680                        waited = Duration::ZERO;
4681                        forge.poll().await;
4682                        continue;
4683                    }
4684                }
4685                RerunStep::Grace => {
4686                    if waited >= WAIT_CEILING {
4687                        let why = format!(
4688                            "checks were still failing after a rerun and {} minutes",
4689                            WAIT_CEILING.as_secs() / 60
4690                        );
4691                        stop(state, &repo, &pr, &why).await?;
4692                        return Ok(pr);
4693                    }
4694                    waited += POLL;
4695                    forge.poll().await;
4696                    continue;
4697                }
4698                RerunStep::Fix => {}
4699            }
4700        }
4701
4702        let step = proposed;
4703        // Armed on exactly this head: the forge is doing the waiting. A
4704        // decision to merge (or keep waiting) is only watched, never re-armed
4705        // and never re-approved; anything else - a red check, a comment, a
4706        // conflict - falls through to its own arm, which disarms first.
4707        let armed_here = state
4708            .land_armed_head
4709            .as_deref()
4710            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4711        if armed_here && matches!(step, Step::Merge | Step::Wait) {
4712            if waited >= WAIT_CEILING {
4713                let required = if seen.base.is_empty() {
4714                    None
4715                } else {
4716                    forge.required_contexts(&repo, &seen.base).await
4717                };
4718                let why = format!(
4719                    "auto-merge was armed on {} but the pull request did not merge within {} \
4720                     minutes ({})",
4721                    seen.head,
4722                    WAIT_CEILING.as_secs() / 60,
4723                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4724                );
4725                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4726                return Ok(pr);
4727            }
4728            waited += POLL;
4729            forge.poll().await;
4730            continue;
4731        }
4732        if armed_here && !matches!(step, Step::Done { .. }) {
4733            // Not merging or waiting any more: whatever is next may change the
4734            // head or give up, and neither may leave the arm standing.
4735            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4736                let why = format!("auto-merge could not be disabled: {e}");
4737                stop(state, &repo, &pr, &why).await?;
4738                return Ok(pr);
4739            }
4740        }
4741        if pr.checks == Checks::Red
4742            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4743            && pr.review_comments.is_empty()
4744            && let Some(evidence) = forge.attribution(state, &seen).await
4745            && evidence.unrelated(&seen.head, &pr.failing)
4746        {
4747            if owner_stop(state, &mut pr, forge).await? {
4748                return Ok(pr);
4749            }
4750            // Attribution does not authorize action against an unseen push.
4751            let fresh = forge.view(&repo, pr_url).await?;
4752            if fresh.head != seen.head
4753                || fresh.rollup_head != seen.rollup_head
4754                || fresh.pr.state != PrLifecycle::Open
4755                || fresh.pr.checks != Checks::Red
4756                || fresh.pr.failing != pr.failing
4757                || fresh
4758                    .pr
4759                    .review_comments
4760                    .iter()
4761                    .any(|c| !shown.contains(&c.body))
4762            {
4763                continue;
4764            }
4765            hold_unrelated(state, &pr, evidence).await?;
4766            return Ok(pr);
4767        }
4768        match step {
4769            Step::Wait => {
4770                if waited >= WAIT_CEILING {
4771                    let why = format!(
4772                        "checks were still running after {} minutes",
4773                        WAIT_CEILING.as_secs() / 60
4774                    );
4775                    stop(state, &repo, &pr, &why).await?;
4776                    return Ok(pr);
4777                }
4778                waited += POLL;
4779                forge.poll().await;
4780            }
4781            Step::Done { merged } => {
4782                if merged {
4783                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
4784                }
4785                // Auto-merge is pinned to the approved head, but the forge's
4786                // own handling of a later push is not something magi can
4787                // see: if the pull request merged on another commit, say so
4788                // loudly rather than record a clean landing.
4789                if let Some(armed) = state.land_armed_head.take() {
4790                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
4791                        let msg = format!(
4792                            "{} merged on {} but the owner approved {armed}; review what landed",
4793                            pr.url, seen.head
4794                        );
4795                        tracing::warn!("{msg}");
4796                        state.event("land", msg);
4797                        // Only an arm left by an older build can get here.
4798                        // The wording is fixed so a repeat does not relight
4799                        // the notice.
4800                        crate::notices::raise_with(
4801                            crate::notices::Notice::warn(
4802                                &format!("merged-unapproved-head:{}", state.id),
4803                                "A pull request merged on a commit the owner did not approve; \
4804                                 review what landed",
4805                            )
4806                            .link(crate::notices::Link::Run {
4807                                id: state.id.clone(),
4808                            }),
4809                            &state.config.notify,
4810                        );
4811                    }
4812                }
4813                state.status = if merged {
4814                    RunStatus::Merged
4815                } else {
4816                    RunStatus::Ready
4817                };
4818                let detail = if merged {
4819                    format!("{} was merged", pr.url)
4820                } else {
4821                    format!("{} was closed without merging", pr.url)
4822                };
4823                state.merge = Some(MergeOutcome {
4824                    mode: MergeMode::Pr,
4825                    ok: merged,
4826                    detail: detail.clone(),
4827                    empty: false,
4828                });
4829                state.event("land", detail);
4830                state.save()?;
4831                write_pr_state_through(state, pr.state);
4832                return Ok(pr);
4833            }
4834            Step::Merge => {
4835                state.check_delivery_evidence(&seen.head)?;
4836                let subject = merge_subject(
4837                    crate::graph::landing_title(state, &seen.title),
4838                    &crate::graph::landing_subject_source(state),
4839                );
4840                // The owner sees the panel before the one irreversible step,
4841                // and an unanswered question is a hold: silence never merges.
4842                //
4843                // The dedicated policy includes existing consent and post-repair
4844                // decisions; repair choice availability never grants merge authority.
4845                let contested = contested_to_ask(state);
4846                if !approval_reasons(state).is_empty() {
4847                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
4848                        .await?
4849                    {
4850                        ApprovalGate::Approved => {}
4851                        ApprovalGate::Repair => {
4852                            // The driver consumes the saved request under the existing
4853                            // run/task claim. No merge, no second run or task.
4854                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4855                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4856                                state.save()?;
4857                            }
4858                            return Ok(pr);
4859                        }
4860                        ApprovalGate::Held => {
4861                            // Another entry point may have saved a stop after
4862                            // the first read above. Apply its durable action.
4863                            if owner_stop(state, &mut pr, forge).await? {
4864                                return Ok(pr);
4865                            }
4866                            stop(
4867                                state,
4868                                &repo,
4869                                &pr,
4870                                "the owner did not approve the merge (held or unanswered)",
4871                            )
4872                            .await?;
4873                            return Ok(pr);
4874                        }
4875                        // Filed (or still standing from an earlier visit) and
4876                        // not yet answered. Park here rather than wait: the
4877                        // question survives on disk, the daemon hands this
4878                        // run's slot to something else, and a later resume
4879                        // re-enters `land`, finds the same question, and
4880                        // either merges or stops depending on what it says
4881                        // by then.
4882                        ApprovalGate::Pending => {
4883                            state.end_pass_parked(crate::run::ParkCause::Question);
4884                            state.parked = true;
4885                            state.event(
4886                                "land",
4887                                "parked awaiting merge approval - resumes once answered",
4888                            );
4889                            state.save()?;
4890                            return Ok(pr);
4891                        }
4892                    }
4893                }
4894                // Open and past the gate above, so `seen.head` is the commit
4895                // the checks were bound to and the owner approved.
4896                //
4897                // Merge directly, bound to that commit. Auto-merge is not
4898                // armed any more: the forge checks `--match-head-commit` only
4899                // when the request is made, so an arm outlives the head it
4900                // was made for, and a push of another commit whose
4901                // requirements are met first would merge without approval.
4902                // A direct merge is checked by the forge at the moment it
4903                // happens, so only the approved head can land.
4904                let observed_head = seen.head.clone();
4905                // Read the pull request again just before: the state seen
4906                // above can be a moment old.
4907                {
4908                    let fresh = forge.view(&repo, pr_url).await.ok();
4909                    if fresh.as_ref().is_some_and(|current| {
4910                        current.pr.state == PrLifecycle::Open
4911                            && current.head.eq_ignore_ascii_case(&observed_head)
4912                            && Blocking::of(&current.merge_state) == Blocking::Behind
4913                    }) {
4914                        pr.blocking = Blocking::Behind;
4915                        let synced =
4916                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4917                                .await?;
4918                        let Some(head) = synced else {
4919                            return Ok(pr);
4920                        };
4921                        awaiting_head = Some(head);
4922                        rechecked = false;
4923                        waited = Duration::ZERO;
4924                        continue 'landing;
4925                    }
4926                    if !direct_merge_is_safe(
4927                        fresh.as_ref(),
4928                        &observed_head,
4929                        &shown,
4930                        round,
4931                        budget,
4932                        waited,
4933                        ci,
4934                    ) {
4935                        if waited >= WAIT_CEILING {
4936                            let why = "the pull request did not settle on the approved head \
4937                                       before it could be merged";
4938                            stop(state, &repo, &pr, why).await?;
4939                            return Ok(pr);
4940                        }
4941                        state.event(
4942                            "land",
4943                            "the pull request changed before merging; looking again",
4944                        );
4945                        waited += POLL;
4946                        forge.poll().await;
4947                        continue;
4948                    }
4949                }
4950                let argv = merge_argv_at(pr.number, &subject, &observed_head);
4951                let out = {
4952                    let merge_lock = repo_merge_lock(&repo);
4953                    let _merge_slot = merge_lock.lock().await;
4954                    crate::pr_head::ensure_owner(state)?;
4955                    if let Some(task_id) = state
4956                        .origin
4957                        .as_ref()
4958                        .and_then(|origin| origin.task.as_ref())
4959                    {
4960                        let task = crate::queue::Queue::open()
4961                            .get(task_id)
4962                            .context("cannot verify the task owner immediately before merge")?;
4963                        if task.execution_runs().last() != Some(&state.id)
4964                            || task.operator_held()
4965                            || task.status == crate::queue::TaskStatus::Done
4966                        {
4967                            bail!(
4968                                "task ownership or an operator hold superseded this merge approval"
4969                            );
4970                        }
4971                    }
4972                    if let Some(binding) = &state.land_approval {
4973                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
4974                        if merge_consent_superseded(state, &current)?
4975                            || current.run != state.id
4976                            || !binding.head.eq_ignore_ascii_case(&observed_head)
4977                            || approval(current.resolution().as_deref()) != Approval::Merge
4978                            || current.merge_target.as_ref().is_some_and(|t| {
4979                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
4980                            })
4981                        {
4982                            bail!(
4983                                "merge decision is stale or no longer authorizes the reviewed head"
4984                            );
4985                        }
4986                    }
4987                    forge.merge(&repo, &argv).await?
4988                };
4989                if out.0 {
4990                    // Exit 0 is not proof of a merge: with a merge queue `gh`
4991                    // enqueues (or reports the pull request already queued)
4992                    // and succeeds while it is still open. Ask the forge; an
4993                    // unreadable answer is not a confirmation either, so it
4994                    // is looked at again rather than recorded as merged.
4995                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
4996                        if c.pr.state == PrLifecycle::Merged {
4997                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
4998                            true
4999                        } else {
5000                            false
5001                        }
5002                    });
5003                    if !confirmed {
5004                        if waited >= WAIT_CEILING {
5005                            let why = "the merge request succeeded but the pull request \
5006                                       could not be confirmed merged after waiting";
5007                            stop(state, &repo, &pr, why).await?;
5008                            return Ok(pr);
5009                        }
5010                        state.event(
5011                            "land",
5012                            "merge accepted but the pull request is not confirmed merged yet; waiting",
5013                        );
5014                        state.save()?;
5015                        waited += POLL;
5016                        forge.poll().await;
5017                        continue;
5018                    }
5019                    pr.state = PrLifecycle::Merged;
5020                    state.status = RunStatus::Merged;
5021                    state.merge = Some(MergeOutcome {
5022                        mode: MergeMode::Pr,
5023                        ok: true,
5024                        detail: format!("gh {}", argv.join(" ")),
5025                        empty: false,
5026                    });
5027                    // The last `state.pr` snapshot is whatever the poll before
5028                    // this merge observed - still `open` - and nothing below
5029                    // refreshes it from GitHub again, so the UI's round rail
5030                    // would otherwise keep animating a merged run forever.
5031                    if let Some(pr_record) = state.pr.as_mut() {
5032                        pr_record.state = pr.state.as_str().to_owned();
5033                    }
5034                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5035                    announce_red_merge(state, &pr).await;
5036                    state.save()?;
5037                    write_pr_state_through(state, pr.state);
5038                    return Ok(pr);
5039                }
5040                let after_seen = forge.view(&repo, pr_url).await.ok();
5041                let after = after_seen.as_ref().map(|s| s.pr.state);
5042                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
5043                    state.pr_merged_head = after_seen
5044                        .as_ref()
5045                        .map(|s| s.head.clone())
5046                        .filter(|h| !h.is_empty());
5047                    pr.state = PrLifecycle::Merged;
5048                    state.status = RunStatus::Merged;
5049                    state.merge = Some(outcome);
5050                    if let Some(pr_record) = state.pr.as_mut() {
5051                        pr_record.state = pr.state.as_str().to_owned();
5052                    }
5053                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5054                    announce_red_merge(state, &pr).await;
5055                    state.save()?;
5056                    write_pr_state_through(state, pr.state);
5057                    return Ok(pr);
5058                }
5059                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
5060                match verdict {
5061                    Refused::Behind => {
5062                        pr.blocking = Blocking::Behind;
5063                        let synced =
5064                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5065                                .await?;
5066                        let Some(head) = synced else {
5067                            return Ok(pr);
5068                        };
5069                        awaiting_head = Some(head);
5070                        rechecked = false;
5071                        waited = Duration::ZERO;
5072                        continue 'landing;
5073                    }
5074                    Refused::Final => {
5075                        let merge_state = after_seen
5076                            .as_ref()
5077                            .map(|s| s.merge_state.as_str())
5078                            .filter(|m| !m.is_empty())
5079                            .unwrap_or("unknown");
5080                        // Which refusal this was decides what a person has to
5081                        // do about it, so the two are worded apart; both carry
5082                        // the forge's own message.
5083                        let why = format!(
5084                            "the merge was refused: {} (merge state: {merge_state})",
5085                            out.1
5086                        );
5087                        stop(state, &repo, &pr, &why).await?;
5088                        return Ok(pr);
5089                    }
5090                    verdict => {
5091                        // Back to the top, which re-decides and passes the
5092                        // approval gate again, a poll later. `waited` is not
5093                        // reset here: only a pushed fix restarts it, or a
5094                        // standing refusal would wait forever.
5095                        if waited >= WAIT_CEILING {
5096                            let why = format!(
5097                                "the merge was still refused after {} minutes: {}",
5098                                WAIT_CEILING.as_secs() / 60,
5099                                out.1
5100                            );
5101                            stop(state, &repo, &pr, &why).await?;
5102                            return Ok(pr);
5103                        }
5104                        if verdict == Refused::Recheck {
5105                            rechecked = true;
5106                        }
5107                        state.event(
5108                            "land",
5109                            "merge refused while the branch policy is not satisfied yet; waiting",
5110                        );
5111                        state.save()?;
5112                        waited += POLL;
5113                        forge.poll().await;
5114                    }
5115                }
5116            }
5117            Step::Rebase => {
5118                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
5119                let Some(head) = synced else {
5120                    return Ok(pr);
5121                };
5122                awaiting_head = Some(head);
5123                rechecked = false;
5124                waited = Duration::ZERO;
5125                continue 'landing;
5126            }
5127            Step::GiveUp { reason } => {
5128                stop(state, &repo, &pr, &reason).await?;
5129                return Ok(pr);
5130            }
5131            Step::Fix { reason } => {
5132                round += 1;
5133                waited = Duration::ZERO;
5134                for c in &pr.review_comments {
5135                    shown.insert(c.body.clone());
5136                }
5137                state.event("land", format!("round {round}: {reason}"));
5138                state.save()?;
5139
5140                let logs = failing_logs(&repo, &seen.failing_urls).await;
5141                let was_red = pr.checks == Checks::Red;
5142                if owner_stop(state, &mut pr, forge).await? {
5143                    return Ok(pr);
5144                }
5145                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
5146                if owner_stop(state, &mut pr, forge).await? {
5147                    return Ok(pr);
5148                }
5149                match fixed {
5150                    Fixed::Committed { head } => {
5151                        // Whatever the next look shows may still be the
5152                        // previous head; see `awaiting_new_head`.
5153                        state.pr_pushed_head = Some(head.clone());
5154                        awaiting_head = Some(head);
5155                        rechecked = false;
5156                        waited = Duration::ZERO;
5157                        forge.poll().await;
5158                    }
5159                    Fixed::Declined if was_red => {
5160                        // Review comments may have required this round even
5161                        // when CI was unrelated. Once the fixer has read them,
5162                        // use the same structural attribution before charging
5163                        // a no-commit stop to the task.
5164                        if let Some(evidence) = forge.attribution(state, &seen).await
5165                            && evidence.unrelated(&seen.head, &pr.failing)
5166                        {
5167                            let fresh = forge.view(&repo, pr_url).await?;
5168                            if fresh.head != seen.head
5169                                || fresh.rollup_head != seen.rollup_head
5170                                || fresh.pr.state != PrLifecycle::Open
5171                                || fresh.pr.checks != Checks::Red
5172                                || fresh.pr.failing != pr.failing
5173                                || fresh
5174                                    .pr
5175                                    .review_comments
5176                                    .iter()
5177                                    .any(|c| !shown.contains(&c.body))
5178                            {
5179                                continue;
5180                            }
5181                            if owner_stop(state, &mut pr, forge).await? {
5182                                return Ok(pr);
5183                            }
5184                            hold_unrelated(state, &pr, evidence).await?;
5185                            return Ok(pr);
5186                        }
5187                        let why = format!(
5188                            "the fixer produced no commit while {} check(s) were failing \
5189                             ({}); stopping instead of looping on an unchanged tree",
5190                            pr.failing.len(),
5191                            pr.failing.join(", ")
5192                        );
5193                        stop(state, &repo, &pr, &why).await?;
5194                        return Ok(pr);
5195                    }
5196                    // Comment-driven round with no commit: the fixer read the
5197                    // comments and changed nothing, which is a decision it is
5198                    // allowed to make. The comments are recorded as shown, so
5199                    // the next observation sees a clean pull request.
5200                    Fixed::Declined => state.event(
5201                        "land",
5202                        format!("round {round}: fixer declined the comments, nothing committed"),
5203                    ),
5204                    Fixed::Deferred => {
5205                        // No fixer was available to judge these comments or
5206                        // checks. Keep the previous completed-round count and
5207                        // return without handing the PR off as a task failure.
5208                        state.status = RunStatus::Blocked;
5209                        state.save()?;
5210                        return Ok(pr);
5211                    }
5212                    Fixed::Failed(why) => {
5213                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5214                        return Ok(pr);
5215                    }
5216                }
5217                state.save()?;
5218            }
5219        }
5220    }
5221}
5222
5223/// Owner decision for a CI failure independently reproduced on the base.
5224pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5225
5226/// Durable machine-hold evidence, bound to one observed PR head.
5227#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5228pub struct CiHold {
5229    /// Head that exhibited the independently reproduced failures.
5230    pub head: String,
5231    /// Typed owner question controlling resumption.
5232    pub question: String,
5233    /// Complete structured facts used to attribute the failures.
5234    pub evidence: CiEvidence,
5235}
5236
5237/// Only structured forge annotations are compared, never log prose.
5238#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5239struct CiFailure {
5240    path: String,
5241    start_line: u64,
5242    end_line: u64,
5243    title: String,
5244    message: String,
5245}
5246
5247#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5248struct CiCheckEvidence {
5249    label: String,
5250    head_check: u64,
5251    base_check: u64,
5252    app: u64,
5253    run: String,
5254    base_run: String,
5255    head_failures: Vec<CiFailure>,
5256    base_failures: Vec<CiFailure>,
5257    rerun_exhausted: bool,
5258}
5259
5260/// Pinned Git diff and forge failure annotations used for CI attribution.
5261#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5262pub struct CiEvidence {
5263    head: String,
5264    base: String,
5265    changed: Vec<String>,
5266    checks: Vec<CiCheckEvidence>,
5267}
5268
5269impl CiEvidence {
5270    /// Every red check must have the same located failure on the base, outside
5271    /// the diff. Changes to CI/build configuration invalidate this inference.
5272    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5273        if self.head != head
5274            || self.base.is_empty()
5275            || failing.is_empty()
5276            || self.changed.iter().any(|p| {
5277                p.starts_with(".github/")
5278                    || p.starts_with(".config/")
5279                    || p.starts_with(".cargo/")
5280                    || matches!(
5281                        p.rsplit('/').next().unwrap_or(p),
5282                        "Cargo.toml"
5283                            | "Cargo.lock"
5284                            | "Makefile.toml"
5285                            | "build.rs"
5286                            | "rust-toolchain.toml"
5287                    )
5288            })
5289        {
5290            return false;
5291        }
5292        failing.iter().all(|label| {
5293            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5294            matches.len() == 1
5295                && matches[0].rerun_exhausted
5296                && !matches[0].head_failures.is_empty()
5297                && matches[0].head_failures.iter().all(|f| {
5298                    // Workflow-level exit-code annotations do not identify a
5299                    // failing test or source file, and prove nothing here.
5300                    !f.path.is_empty()
5301                        && !f.path.starts_with('.')
5302                        && !f.path.contains("..")
5303                        && !f.path.starts_with('/')
5304                        && !self.changed.contains(&f.path)
5305                        && matches[0].base_failures.contains(f)
5306                })
5307        })
5308    }
5309}
5310
5311async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5312    let out = gh(repo, &["api".into(), endpoint]).await.ok()?;
5313    if !out.ok {
5314        return None;
5315    }
5316    serde_json::from_str(&out.stdout).ok()
5317}
5318
5319async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5320    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5321    if count == 0 || count >= 100 {
5322        return None;
5323    }
5324    let id = check.get("id")?.as_u64()?;
5325    let value = ci_json(
5326        repo,
5327        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5328    )
5329    .await?;
5330    let annotations = value.as_array()?;
5331    if annotations.len() != count as usize {
5332        return None;
5333    }
5334    annotations
5335        .iter()
5336        .filter(|a| a["annotation_level"] == "failure")
5337        .map(|a| {
5338            Some(CiFailure {
5339                path: a["path"].as_str()?.into(),
5340                start_line: a["start_line"].as_u64()?,
5341                end_line: a["end_line"].as_u64()?,
5342                title: a["title"].as_str()?.into(),
5343                message: a["message"].as_str()?.into(),
5344            })
5345        })
5346        .collect()
5347}
5348
5349async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5350    let value = ci_json(
5351        repo,
5352        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5353    )
5354    .await?;
5355    let runs = value["check_runs"].as_array()?;
5356    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5357        return None;
5358    }
5359    Some(runs.clone())
5360}
5361
5362async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5363    let repo = &state.repo;
5364    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5365    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5366        .await
5367        .ok()?;
5368    if !base.ok() {
5369        return None;
5370    }
5371    let range = format!("{}...{}", base.stdout, seen.head);
5372    // No rename detection: both old and new paths must count as changed.
5373    let diff = git::git_raw(
5374        repo,
5375        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5376    )
5377    .await
5378    .ok()?;
5379    if !diff.ok() {
5380        return None;
5381    }
5382    let head_runs = ci_runs(repo, &seen.head).await?;
5383    let base_runs = ci_runs(repo, &base.stdout).await?;
5384    let mut checks = Vec::new();
5385    for label in &seen.pr.failing {
5386        let matching = |runs: &[serde_json::Value]| {
5387            runs.iter()
5388                .filter(|r| r["name"].as_str() == Some(label))
5389                .cloned()
5390                .collect::<Vec<_>>()
5391        };
5392        let heads = matching(&head_runs);
5393        let bases = matching(&base_runs);
5394        if heads.len() != 1 || bases.len() != 1 {
5395            return None;
5396        }
5397        let h = &heads[0];
5398        let b = &bases[0];
5399        if h["conclusion"] != "failure"
5400            || b["conclusion"] != "failure"
5401            || h["status"] != "completed"
5402            || b["status"] != "completed"
5403            || h["head_sha"].as_str()? != seen.head
5404            || b["head_sha"].as_str()? != base.stdout
5405            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5406        {
5407            return None;
5408        }
5409        let run = run_of(h["details_url"].as_str()?)?;
5410        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5411        if contexts.len() != 1
5412            || contexts[0].run.as_ref() != Some(&run)
5413            || contexts[0].verdict != Verdict::Fail
5414        {
5415            return None;
5416        }
5417        // A persisted request alone is not a completed rerun: require the
5418        // workflow's structured attempt number as well.
5419        let workflow =
5420            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5421        let base_run = run_of(b["details_url"].as_str()?)?;
5422        let base_workflow = ci_json(
5423            repo,
5424            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5425        )
5426        .await?;
5427        if base_workflow["head_sha"].as_str()? != base.stdout
5428            || base_workflow["head_branch"].as_str()? != seen.base
5429            || base_workflow["status"] != "completed"
5430            || base_workflow["conclusion"] != "failure"
5431            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5432        {
5433            return None;
5434        }
5435        let exhausted = state
5436            .land_reruns
5437            .as_ref()
5438            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5439            && workflow["head_sha"].as_str()? == seen.head
5440            && workflow["run_attempt"].as_u64()? > 1
5441            && workflow["status"] == "completed";
5442        checks.push(CiCheckEvidence {
5443            label: label.clone(),
5444            head_check: h["id"].as_u64()?,
5445            base_check: b["id"].as_u64()?,
5446            app: h.pointer("/app/id")?.as_u64()?,
5447            run,
5448            base_run,
5449            head_failures: ci_annotations(repo, h).await?,
5450            base_failures: ci_annotations(repo, b).await?,
5451            rerun_exhausted: exhausted,
5452        });
5453    }
5454    Some(CiEvidence {
5455        head: seen.head.clone(),
5456        base: base.stdout,
5457        changed: diff
5458            .stdout
5459            .split('\0')
5460            .filter(|p| !p.is_empty())
5461            .map(str::to_owned)
5462            .collect(),
5463        checks,
5464    })
5465}
5466
5467async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5468    let detail = serde_json::to_string(&evidence)?;
5469    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5470    let hold = "operator: 保留して後で判断する".to_owned();
5471    let mut q = ask::Question::new(
5472        state.id.clone(),
5473        CI_HOLD_NODE.into(),
5474        "land".into(),
5475        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5476        format!(
5477            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5478        ),
5479        vec![resume.clone(), hold.clone()],
5480    );
5481    q.actions.insert(
5482        resume,
5483        ask::ChoiceAction::Resume {
5484            run: state.id.clone(),
5485        },
5486    );
5487    q.actions.insert(hold, ask::ChoiceAction::Hold);
5488    ask::Questions::open().put_executable(&mut q)?;
5489    state.land_unrelated = Some(CiHold {
5490        head: evidence.head.clone(),
5491        question: q.id.clone(),
5492        evidence,
5493    });
5494    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5495    state.end_pass_parked(crate::run::ParkCause::Question);
5496    state.parked = true;
5497    state.save()?;
5498    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5499        tracing::warn!("could not notify about CI hold: {e:#}");
5500    }
5501    // A durable question and evidence are sufficient even if commenting fails.
5502    let body = stop_comment(
5503        &state.id,
5504        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5505    );
5506    let (_, body) = crate::github_text::prepare(state, "", &body);
5507    gh(
5508        &state.repo,
5509        &[
5510            "pr".into(),
5511            "comment".into(),
5512            pr.number.to_string(),
5513            "--body".into(),
5514            body,
5515        ],
5516    )
5517    .await
5518    .ok();
5519    Ok(())
5520}
5521
5522/// One observation, plus the two things [`PrState`] deliberately does not carry:
5523/// the title (needed for the squash subject) and where the failing checks'
5524/// logs live.
5525#[derive(Clone)]
5526struct Seen {
5527    pr: PrState,
5528    title: String,
5529    failing_urls: Vec<(String, String)>,
5530    /// `headRefOid`: the commit this observation, checks included, is about.
5531    head: String,
5532    /// The commit the checks belong to, read from the same GraphQL node as
5533    /// the checks themselves. Empty when unreadable.
5534    rollup_head: String,
5535    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5536    /// and DRAFT together, and a stop reason has to say which.
5537    merge_state: String,
5538    /// Every check of the rollup, for naming what an armed merge waits on.
5539    contexts: Vec<CheckInfo>,
5540    /// `baseRefName`, to look up which contexts the base requires.
5541    base: String,
5542}
5543
5544/// One check of the rollup as far as a stop reason needs it.
5545#[derive(Clone)]
5546struct CheckInfo {
5547    label: String,
5548    verdict: Verdict,
5549    required: Option<bool>,
5550    /// The workflow run the check belongs to; `None` for an external status.
5551    run: Option<String>,
5552}
5553
5554/// What to do with a red head before a fix round is spent on it.
5555#[derive(Debug, Clone, PartialEq, Eq)]
5556enum RerunStep {
5557    /// Rerun these workflow runs (each not yet rerun for this head).
5558    Rerun(Vec<String>),
5559    /// Reran already and the forge may still report the old failure: wait.
5560    Grace,
5561    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5562    Fix,
5563}
5564
5565/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5566/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5567/// pending checks in another run do not delay this run's rerun.
5568#[cfg(test)]
5569fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5570    rerunnable_with(contexts, false)
5571}
5572
5573fn rerunnable_with(
5574    contexts: &[CheckInfo],
5575    include_optional: bool,
5576) -> Vec<(String, Option<String>)> {
5577    contexts
5578        .iter()
5579        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5580        // `gh run rerun --failed` refuses a run with a job still going.
5581        .filter(|c| {
5582            c.run.as_ref().is_none_or(|r| {
5583                !contexts.iter().any(|o| {
5584                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5585                        && o.run.as_ref() == Some(r)
5586                })
5587            })
5588        })
5589        .map(|c| (c.label.clone(), c.run.clone()))
5590        .collect()
5591}
5592
5593/// Pure: rerun once per run id, wait out the grace, then hand over.
5594fn rerun_step(
5595    failing: &[(String, Option<String>)],
5596    record: Option<&LandReruns>,
5597    head: &str,
5598    now: i64,
5599) -> RerunStep {
5600    // A failure with no workflow run (an external status) cannot be rerun, and
5601    // the fixer's push re-runs everything anyway.
5602    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5603        return RerunStep::Fix;
5604    }
5605    // Reruns belong to the head they were made on.
5606    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5607    let mut fresh: Vec<String> = Vec::new();
5608    let mut recent = false;
5609    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5610        match record.and_then(|r| r.runs.get(run)) {
5611            None => {
5612                if !fresh.iter().any(|f| f == run) {
5613                    fresh.push(run.to_owned());
5614                }
5615            }
5616            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5617            Some(_) => {}
5618        }
5619    }
5620    if !fresh.is_empty() {
5621        RerunStep::Rerun(fresh)
5622    } else if recent {
5623        RerunStep::Grace
5624    } else {
5625        RerunStep::Fix
5626    }
5627}
5628
5629/// Read minimal live PR metadata (`url`, `number`, `state`, `headRefOid`,
5630/// `baseRefName`) for landing base-sync recovery admission and dispatch checks.
5631pub(crate) async fn observe_pr_summary(
5632    repo: &Path,
5633    pr_url: &str,
5634) -> Result<crate::land_sync_recovery::ObservedPr> {
5635    #[derive(serde::Deserialize)]
5636    struct Summary {
5637        #[serde(default)]
5638        url: String,
5639        #[serde(default)]
5640        number: u64,
5641        #[serde(default)]
5642        state: String,
5643        #[serde(default, rename = "headRefOid")]
5644        head_ref_oid: String,
5645        #[serde(default, rename = "baseRefName")]
5646        base_ref_name: String,
5647    }
5648    let view = gh(
5649        repo,
5650        &[
5651            "pr".to_owned(),
5652            "view".to_owned(),
5653            pr_url.to_owned(),
5654            "--json".to_owned(),
5655            "url,number,state,headRefOid,baseRefName".to_owned(),
5656        ],
5657    )
5658    .await?;
5659    if !view.ok {
5660        bail!("gh pr view {pr_url}: {}", view.combined());
5661    }
5662    let parsed: Summary = serde_json::from_str(&view.stdout).context("parse pull request json")?;
5663    Ok(crate::land_sync_recovery::ObservedPr {
5664        url: parsed.url,
5665        number: parsed.number,
5666        open: parsed.state.eq_ignore_ascii_case("OPEN"),
5667        head: parsed.head_ref_oid,
5668        base_branch: (!parsed.base_ref_name.is_empty()).then_some(parsed.base_ref_name),
5669    })
5670}
5671
5672/// Read the pull request: `gh pr view` for the top-level thread and merge
5673/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5674/// inline review comments `gh pr view` does not report.
5675async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5676    let view = gh(
5677        repo,
5678        &[
5679            "pr".to_owned(),
5680            "view".to_owned(),
5681            pr_url.to_owned(),
5682            "--json".to_owned(),
5683            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5684                .to_owned(),
5685        ],
5686    )
5687    .await?;
5688    if !view.ok {
5689        bail!("gh pr view {pr_url}: {}", view.combined());
5690    }
5691    let number = parse_pr(&view.stdout)?.number;
5692    let node = last_commit_node(repo, number).await;
5693    let mut seen = seen_from(&view.stdout, node.as_deref())?;
5694
5695    let inline = gh(
5696        repo,
5697        &[
5698            "api".to_owned(),
5699            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5700        ],
5701    )
5702    .await?;
5703    if inline.ok {
5704        match parse_inline_comments(&inline.stdout) {
5705            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5706            // An unreadable inline thread must not end a landing: the rollup
5707            // and the top-level thread are still real signal.
5708            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5709        }
5710    } else {
5711        tracing::warn!(
5712            "gh api pulls/{}/comments: {}",
5713            seen.pr.number,
5714            inline.combined()
5715        );
5716    }
5717    Ok(seen)
5718}
5719
5720/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
5721/// response. No I/O.
5722///
5723/// The commit oid and the checks are read from the *same* node, so the rollup
5724/// is bound to the commit it belongs to by construction; two reads that agree
5725/// before and after another response prove nothing about what that response
5726/// held. The view's own rollup is never used. A node that is missing,
5727/// unreadable, carries GraphQL errors, or whose checks run past the page
5728/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
5729/// as "look again" and never as a reason to merge.
5730fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5731    let mut pr = parse_pr(view_json)?;
5732    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5733
5734    let mut rollup_head = String::new();
5735    let mut failing_urls = Vec::new();
5736    let mut contexts = Vec::new();
5737    let mut checks = Checks::Unknown;
5738    let mut failing = Vec::new();
5739    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5740        (checks, failing) = rollup_verdict(&rollup);
5741        failing_urls = rollup
5742            .iter()
5743            .filter(|c| c.verdict() == Verdict::Fail)
5744            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5745            .collect();
5746        contexts = rollup
5747            .iter()
5748            .map(|c| CheckInfo {
5749                label: c.label(),
5750                verdict: c.verdict(),
5751                required: c.is_required,
5752                run: c.url().and_then(run_of),
5753            })
5754            .collect();
5755        rollup_head = oid;
5756    }
5757    pr.checks = checks;
5758    pr.failing = failing;
5759
5760    Ok(Seen {
5761        pr,
5762        title: raw.title,
5763        failing_urls,
5764        head: raw.head_ref_oid,
5765        rollup_head,
5766        merge_state: raw.merge_state_status,
5767        contexts,
5768        base: raw.base_ref_name,
5769    })
5770}
5771
5772/// The last commit's oid and its checks from one GraphQL response, `None`
5773/// when anything about it cannot be trusted.
5774fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
5775    let v: serde_json::Value = serde_json::from_str(json).ok()?;
5776    if v.get("errors").is_some_and(|e| !e.is_null()) {
5777        return None;
5778    }
5779    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
5780    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
5781    let contexts = commit.pointer("/statusCheckRollup/contexts");
5782    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
5783        // No rollup at all: the commit has no checks.
5784        return Some((oid.to_owned(), Vec::new()));
5785    };
5786    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
5787        return None;
5788    }
5789    let nodes = contexts.get("nodes")?.as_array()?;
5790    let rollup = nodes
5791        .iter()
5792        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
5793        .collect::<Result<Vec<_>, _>>()
5794        .ok()?;
5795    Some((oid.to_owned(), rollup))
5796}
5797
5798/// The pull request's last commit and its checks, in one response. `None`
5799/// when the forge could not be asked.
5800async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
5801    let out = gh(
5802        repo,
5803        &[
5804            "api".to_owned(),
5805            "graphql".to_owned(),
5806            "-F".to_owned(),
5807            "owner={owner}".to_owned(),
5808            "-F".to_owned(),
5809            "repo={repo}".to_owned(),
5810            "-F".to_owned(),
5811            format!("number={number}"),
5812            "-f".to_owned(),
5813            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
5814             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
5815             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
5816             ... on CheckRun{name status conclusion detailsUrl \
5817             isRequired(pullRequestNumber:$number)} \
5818             ... on StatusContext{context state targetUrl \
5819             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
5820                .to_owned(),
5821        ],
5822    )
5823    .await
5824    .ok()?;
5825    out.ok.then_some(out.stdout)
5826}
5827
5828/// What a fix round did.
5829#[doc(hidden)]
5830#[derive(Debug, PartialEq)]
5831pub enum Fixed {
5832    /// The fixer committed something, and this is the head that was pushed.
5833    Committed {
5834        /// The commit now at the tip of the pushed branch.
5835        head: String,
5836    },
5837    /// The fixer ran and chose to change nothing.
5838    Declined,
5839    /// Machine availability prevented a result; retry this round on resume.
5840    Deferred,
5841    /// The fixer could not run, or said nothing usable.
5842    Failed(String),
5843}
5844
5845/// Hand the failures and the comments to the fixer, then commit and push.
5846///
5847/// The fixer works in the winner's own worktree so its commits land on the
5848/// branch the pull request is built from, and it runs with `allow_write` for
5849/// the same reason.
5850#[doc(hidden)]
5851pub async fn fix_round(
5852    state: &mut RunState,
5853    pr: &PrState,
5854    round: usize,
5855    budget: usize,
5856    reason: &str,
5857    logs: &str,
5858) -> Result<Fixed> {
5859    let winner = state
5860        .winner()
5861        .cloned()
5862        .context("landing needs a winning candidate; none is recorded on this run")?;
5863    let roles = state
5864        .config
5865        .resolve_roles()
5866        .context("resolve the roster for the fix round")?;
5867    // Same chain as the review loop (see `crate::fixer`): the configured
5868    // fixers in order, otherwise the winner's own author continuing its own
5869    // conversation - the competition is over, so its context is pure benefit.
5870    let attempts = crate::fixer::attempts(state, &roles, &winner);
5871    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
5872
5873    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
5874    let mut artifacts = agent::artifacts_dir(&state.dir());
5875    if let Some(request) = state
5876        .merge_repairs
5877        .last()
5878        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
5879    {
5880        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
5881    }
5882    let prompt =
5883        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
5884            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
5885        } else {
5886            prompt
5887        };
5888    // Read before the fixer runs: it normally commits for itself, so HEAD has
5889    // already moved by the time it returns and a later read would see no
5890    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
5891    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5892    // Each id at most once, forward only: the next one is asked only when the
5893    // call advances, and only the last attempt's result is judged below, so an
5894    // exhausted chain ends as a single failed fixer does.
5895    let mut last = None;
5896    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
5897        if owner_requested_stop(state)? {
5898            return Ok(Fixed::Declined);
5899        }
5900        let mut seat = seat_of(state, &seat_key, &spec.id);
5901        let stem = if i == 0 {
5902            format!("land-{round}")
5903        } else {
5904            format!("land-{round}-{}", spec.id)
5905        };
5906        let out = agent::invoke(
5907            &spec,
5908            &mut seat,
5909            &Invocation {
5910                coordination: state.config.coordination.as_ref(),
5911                fetched_base: state.fetched_base.as_ref(),
5912                cwd: &winner.worktree,
5913                prompt: &prompt,
5914                timeout: Duration::from_secs(state.config.graph.timeout_fix),
5915                allow_write: true,
5916                sessions: state.config.graph.sessions,
5917                artifacts: &artifacts,
5918                stem: &stem,
5919                run: &state.id,
5920                node: "land",
5921                cache_dir: state.config.cache_dir().as_deref(),
5922                attachments: &[],
5923                writable: &[],
5924            },
5925        )
5926        .await;
5927        state.seats.insert(seat.key.clone(), seat);
5928        if let Some(next) = ids.get(i + 1)
5929            && agent::chain_advances(&out)
5930        {
5931            let (class, why) = crate::fixer::failure_of(&out);
5932            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
5933            continue;
5934        }
5935        last = Some((seat_key, out));
5936        break;
5937    }
5938    let (seat_key, out) = last.expect("the fixer chain always has an entry");
5939
5940    match out {
5941        Ok(o) if o.quota_exhausted() => {
5942            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
5943            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
5944            state.quota.push(loss);
5945            state.status = RunStatus::Blocked;
5946            state.save()?;
5947            // Keep partial edits reachable on the winner branch and leave a
5948            // clean tree for resume_landing_head. The resumed landing gates
5949            // this new commit before it can publish it; no push happens here.
5950            let inherited = crate::repo_lock::WaitPolicy::current();
5951            let wait = crate::repo_lock::WaitPolicy::new(
5952                Duration::from_secs(state.config.graph.timeout_resource_wait),
5953                move || inherited.cancelled(),
5954            );
5955            let _coordination = crate::repo_lock::SeatLease::operation_with(
5956                &winner.worktree,
5957                state.config.coordination.as_ref(),
5958                &wait,
5959            )
5960            .await?;
5961            let rescue = git::rescue_commit(
5962                &winner.worktree,
5963                &format!("magi: deferred land round {round} (uncommitted work)"),
5964            )
5965            .await?;
5966            state.note_withheld("land", &rescue.withheld);
5967            state.save()?;
5968            return Ok(Fixed::Deferred);
5969        }
5970        Ok(o) if !o.usable() => {
5971            return Ok(Fixed::Failed(format!(
5972                "the fixer produced nothing usable ({})",
5973                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
5974            )));
5975        }
5976        Ok(_) => {}
5977        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
5978        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
5979    }
5980
5981    if owner_requested_stop(state)? {
5982        return Ok(Fixed::Declined);
5983    }
5984
5985    // An agent that edited files but never committed would otherwise push
5986    // nothing and look like a refusal.
5987    let wait = crate::repo_lock::WaitPolicy::new(
5988        Duration::from_secs(state.config.graph.timeout_resource_wait),
5989        || false,
5990    );
5991    let coordination = crate::repo_lock::SeatLease::operation_with(
5992        &winner.worktree,
5993        state.config.coordination.as_ref(),
5994        &wait,
5995    )
5996    .await?;
5997    match git::rescue_commit(
5998        &winner.worktree,
5999        &format!("magi: land round {round} fixes (uncommitted work)"),
6000    )
6001    .await
6002    {
6003        Ok(r) => state.note_withheld("land", &r.withheld),
6004        Err(e)
6005            if state
6006                .merge_repairs
6007                .last()
6008                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
6009        {
6010            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
6011        }
6012        Err(_) => {}
6013    }
6014    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
6015    drop(coordination);
6016    if after == before {
6017        return Ok(Fixed::Declined);
6018    }
6019
6020    if owner_requested_stop(state)? {
6021        return Ok(Fixed::Declined);
6022    }
6023    crate::pr_head::ensure_owner(state)?;
6024    let remote = state.config.merge.remote.clone();
6025    anyhow::ensure!(
6026        crate::foreign_checkout::write_back(state, &after).await?,
6027        "foreign checkout delivery is blocked; see the run events"
6028    );
6029    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
6030    let push = if state.pr_head.is_some() {
6031        let expected = state
6032            .pr_pushed_head
6033            .as_deref()
6034            .context("missing public head lease")?;
6035        git::push_as(
6036            &winner.worktree,
6037            &remote,
6038            &winner.branch,
6039            &public_head,
6040            expected,
6041        )
6042        .await?
6043    } else {
6044        git::push(&winner.worktree, &remote, &winner.branch).await?
6045    };
6046    if !push.ok() {
6047        return Ok(Fixed::Failed(format!(
6048            "pushing {} to {remote} failed: {}",
6049            public_head, push.stderr
6050        )));
6051    }
6052    state.event(
6053        "land",
6054        format!("round {round}: pushed a fix to {public_head}"),
6055    );
6056    state.pr_pushed_head = Some(after.clone());
6057    state.save()?;
6058    Ok(Fixed::Committed { head: after })
6059}
6060
6061/// Fetch or create a seat, keeping its conversation across nodes.
6062pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
6063    crate::fixer::seat_for(state, key, agent)
6064}
6065
6066/// Recheck the live PR and local worktree before spending the requested fix.
6067/// A moved/closed PR is held, never repaired using obsolete evidence.
6068pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
6069    let seen = observe(&state.repo, url).await?;
6070    let winner = state.winner().context("no winning branch to repair")?;
6071    if seen.pr.state != PrLifecycle::Open || seen.head != head {
6072        anyhow::bail!(
6073            "PR is closed or its head changed; review the current head before requesting repair again"
6074        );
6075    }
6076    if git::rev_parse(&winner.worktree, "HEAD").await? != head
6077        || !git::is_clean(&winner.worktree).await?
6078    {
6079        anyhow::bail!(
6080            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
6081        );
6082    }
6083    // Always disable any forge-side reservation, including one not recorded
6084    // by this run. A repair request is never merge authorization.
6085    let view = gh(
6086        &state.repo,
6087        &[
6088            "pr".into(),
6089            "view".into(),
6090            url.into(),
6091            "--json".into(),
6092            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
6093        ],
6094    )
6095    .await?;
6096    if !view.ok {
6097        bail!("cannot check auto-merge: {}", view.combined());
6098    }
6099    let live: serde_json::Value = serde_json::from_str(&view.stdout)?;
6100    let public = state.pr_branch().unwrap_or(&winner.branch);
6101    if live["state"] != "OPEN"
6102        || live["headRefOid"] != head
6103        || live["headRefName"] != public
6104        || live["baseRefName"] != state.base_branch
6105        || live["isCrossRepository"] != false
6106    {
6107        bail!("PR changed during repair preflight; review its current head explicitly");
6108    }
6109    let auto_merge = live
6110        .get("autoMergeRequest")
6111        .context("cannot read the PR auto-merge reservation; repair held")?;
6112    if !auto_merge.is_null() {
6113        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
6114        if !out.ok {
6115            bail!("cannot disable auto-merge; repair held: {}", out.combined());
6116        }
6117    }
6118    Ok(seen.pr)
6119}
6120
6121/// What the fixer is told.
6122fn fix_prompt(
6123    state: &RunState,
6124    pr: &PrState,
6125    round: usize,
6126    budget: usize,
6127    reason: &str,
6128    logs: &str,
6129) -> String {
6130    let mut s = format!(
6131        "Your patch is open as a pull request and it is not landing. Land round \
6132         {round} of {budget}.\n\n\
6133         Pull request: {}\n\n\
6134         What is holding it: {reason}\n\n\
6135         # The task\n\n{}\n",
6136        pr.url, state.instruction
6137    );
6138
6139    if pr.failing.is_empty() {
6140        s.push_str("\n# Failing checks\n\n(none)\n");
6141    } else {
6142        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
6143        if logs.trim().is_empty() {
6144            s.push_str(
6145                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
6146            );
6147        } else {
6148            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
6149        }
6150    }
6151
6152    if pr.review_comments.is_empty() {
6153        s.push_str("\n# Review comments\n\n(none)\n");
6154    } else {
6155        s.push_str("\n# Review comments\n");
6156        for c in &pr.review_comments {
6157            let where_ = match (&c.path, c.line) {
6158                (Some(p), Some(l)) => format!(" ({p}:{l})"),
6159                (Some(p), None) => format!(" ({p})"),
6160                _ => String::new(),
6161            };
6162            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
6163        }
6164    }
6165
6166    s.push_str(
6167        "\n# Rules\n\n\
6168         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
6169            failing test; do not silence a lint with an allow attribute; do not \
6170            stretch a timeout to hide a race. If the check is right, the code is \
6171            wrong.\n\
6172         2. Change nothing the checks and the comments did not raise. A \
6173            drive-by refactor turns a one-line fix into a pull request that \
6174            needs reviewing again.\n\
6175         3. If a comment is wrong, say so with a checkable argument and change \
6176            nothing for it. A declined comment with a reason is a correct \
6177            outcome; a change made to appease a reviewer is not.\n\
6178         4. Commit in this worktree. magi pushes to the pull request's branch \
6179            for you; do not push, merge, or close anything yourself.\n\
6180         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
6181         # Output\n\n\
6182         Say what you changed and why, and what you declined and why.",
6183    );
6184
6185    let language = &state.config.graph.language;
6186    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
6187        let _ = write!(s, "\n\nWrite all prose in {language}.");
6188    }
6189    // After the language line, so the exception is the last word on it.
6190    s.push_str(&crate::prompt::github_rule(
6191        language,
6192        &state.config.graph.github_language,
6193    ));
6194    if let Some(overlay) = state.config.prompts.overlay("fix") {
6195        let _ = write!(s, "\n\n{overlay}");
6196    }
6197    s.push('\n');
6198    s.push_str(crate::prompt::child_run_ownership());
6199    s
6200}
6201
6202/// Failing log tails, the way the operator collects them by hand:
6203/// `gh run view --log-failed`.
6204async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6205    let mut out = String::new();
6206    for (name, url) in failing.iter().take(MAX_LOGS) {
6207        let args = match (job_of(url), run_of(url)) {
6208            (Some(job), _) => vec![
6209                "run".to_owned(),
6210                "view".to_owned(),
6211                "--log-failed".to_owned(),
6212                "--job".to_owned(),
6213                job,
6214            ],
6215            (None, Some(run)) => vec![
6216                "run".to_owned(),
6217                "view".to_owned(),
6218                run,
6219                "--log-failed".to_owned(),
6220            ],
6221            // Not a GitHub Actions check - an external status has no log here.
6222            (None, None) => continue,
6223        };
6224        let (ok, body) = match gh(repo, &args).await {
6225            Ok(v) => (v.ok, v.combined()),
6226            Err(e) => (false, format!("{e:#}")),
6227        };
6228        if !ok && body.trim().is_empty() {
6229            continue;
6230        }
6231        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6232    }
6233    out
6234}
6235
6236/// Job id out of a check's `detailsUrl`
6237/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
6238fn job_of(details_url: &str) -> Option<String> {
6239    let after = details_url.split("/job/").nth(1)?;
6240    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6241    (!id.is_empty()).then_some(id)
6242}
6243
6244/// Workflow run id out of a check's `detailsUrl`.
6245pub(crate) fn run_of(details_url: &str) -> Option<String> {
6246    let after = details_url.split("/actions/runs/").nth(1)?;
6247    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6248    (!id.is_empty()).then_some(id)
6249}
6250
6251/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6252/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6253/// it to that.
6254fn stop_comment(run_id: &str, why: &str) -> String {
6255    format!(
6256        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6257         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6258    )
6259}
6260
6261/// Leave the pull request open, say why on it, and mark the run blocked.
6262///
6263/// The comment is what makes an unattended stop actionable: the operator wakes
6264/// up to a pull request that explains itself rather than to a silent queue.
6265async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6266    let body = stop_comment(&state.id, why);
6267    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6268    if !body.contains(MARKER) {
6269        body = format!("{MARKER}\n{body}");
6270    }
6271    let posted = gh(
6272        repo,
6273        &[
6274            "pr".to_owned(),
6275            "comment".to_owned(),
6276            pr.number.to_string(),
6277            "--body".to_owned(),
6278            body,
6279        ],
6280    )
6281    .await;
6282    match posted {
6283        Ok(out) if out.ok => {}
6284        Ok(out) => tracing::warn!("could not comment on {}: {}", pr.url, out.combined()),
6285        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6286    }
6287    state.status = RunStatus::Blocked;
6288    state.merge = Some(MergeOutcome {
6289        mode: MergeMode::Pr,
6290        ok: false,
6291        detail: why.to_owned(),
6292        empty: false,
6293    });
6294    state.event("land", format!("stopped: {why}"));
6295    state.save()?;
6296    Ok(())
6297}
6298
6299/// Output of a `gh` subprocess, keeping machine-readable `stdout` separate from
6300/// diagnostic `stderr`.
6301///
6302/// Newer `gh` releases (for example `gh` 2.105.0) can emit advisory hints on
6303/// `stderr` even when a read-only `--json` or API command succeeds with exit
6304/// status 0. Appending `stderr` onto `stdout` before deserialization breaks
6305/// strict JSON parsing (for example `trailing characters at line 2 column 1`).
6306///
6307/// Output contract:
6308/// - **Successful structured reads** (`--json`, REST `gh api`, GraphQL, etc.):
6309///   check [`Self::ok`], then pass [`Self::stdout`] straight to a strict parser.
6310///   Never fall back to [`Self::stderr`] when `stdout` is empty, and never strip
6311///   specific hint text or heuristically extract JSON substrings.
6312/// - **Failed invocations (`!ok`)**: use [`Self::combined`] so both `stdout`
6313///   and `stderr` diagnostics stay actionable (for example `404` detection and
6314///   refused-merge details).
6315/// - **Human-facing or mutating commands** (`pr merge`, `pr close`, `pr edit`,
6316///   `pr comment`, `run rerun`, `run view --log-failed`): use
6317///   [`Self::combined`] for failure diagnostics or human-readable output.
6318#[derive(Debug, Clone, PartialEq, Eq)]
6319pub(crate) struct GhOutput {
6320    /// Whether `gh` exited with status 0.
6321    pub(crate) ok: bool,
6322    /// Process `stdout`, decoded lossily as UTF-8.
6323    pub(crate) stdout: String,
6324    /// Process `stderr`, decoded lossily as UTF-8.
6325    pub(crate) stderr: String,
6326}
6327
6328impl GhOutput {
6329    /// Build from a completed subprocess output and log non-empty `stderr`
6330    /// emitted on exit status 0 at debug level without logging command
6331    /// arguments.
6332    pub(crate) fn from_output(output: std::process::Output) -> Self {
6333        let parsed = Self {
6334            ok: output.status.success(),
6335            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
6336            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
6337        };
6338        if parsed.ok && !parsed.stderr.trim().is_empty() {
6339            tracing::debug!(
6340                stderr = parsed.stderr.trim(),
6341                "gh exited successfully with stderr diagnostics"
6342            );
6343        }
6344        parsed
6345    }
6346
6347    /// Combined trimmed `stdout` and `stderr` for failure diagnostics and
6348    /// human-facing commands.
6349    pub(crate) fn combined(&self) -> String {
6350        let out = self.stdout.trim();
6351        let err = self.stderr.trim();
6352        match (out.is_empty(), err.is_empty()) {
6353            (true, true) => String::new(),
6354            (false, true) => out.to_owned(),
6355            (true, false) => err.to_owned(),
6356            (false, false) => format!("{out}\n{err}"),
6357        }
6358    }
6359}
6360
6361/// Run `gh` in `cwd`, returning exit status with separated `stdout` and
6362/// `stderr` in [`GhOutput`].
6363///
6364/// Structured callers must check [`GhOutput::ok`] and parse [`GhOutput::stdout`]
6365/// strictly without substituting [`GhOutput::stderr`]. Failed invocations and
6366/// human-facing or mutating commands should use [`GhOutput::combined`] so both
6367/// streams remain available as diagnostics.
6368///
6369/// `GH_REPO` is stripped from the child's environment: every call site here
6370/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6371/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6372/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6373/// `GH_REPO` the operator happens to have exported for an unrelated script
6374/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6375/// below) to a different repository than the one actually on disk - which
6376/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6377/// could be made to agree with whatever repository a forged `--merged` URL
6378/// claims, defeating it entirely.
6379pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<GhOutput> {
6380    gh_with(Path::new("gh"), cwd, args).await
6381}
6382
6383pub(crate) async fn gh_with(program: &Path, cwd: &Path, args: &[String]) -> Result<GhOutput> {
6384    let out = tokio::process::Command::new(program)
6385        .args(args)
6386        .current_dir(cwd)
6387        .env_remove("GH_REPO")
6388        .quiet()
6389        .stdin(std::process::Stdio::null())
6390        .output()
6391        .await
6392        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6393    Ok(GhOutput::from_output(out))
6394}
6395
6396/// Verdict of one entry in the status rollup.
6397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6398pub(crate) enum Verdict {
6399    Pass,
6400    Fail,
6401    Pending,
6402    Unknown,
6403}
6404
6405impl Verdict {
6406    /// Short operator-facing check result.
6407    pub(crate) fn label(self) -> &'static str {
6408        match self {
6409            Self::Pass => "passed",
6410            Self::Fail => "failed",
6411            Self::Pending => "pending",
6412            Self::Unknown => "unknown",
6413        }
6414    }
6415}
6416
6417#[derive(Debug, Deserialize)]
6418#[serde(rename_all = "camelCase")]
6419struct GhPr {
6420    #[serde(default)]
6421    url: String,
6422    #[serde(default)]
6423    number: u64,
6424    #[serde(default)]
6425    state: String,
6426    #[serde(default)]
6427    title: String,
6428    #[serde(default)]
6429    status_check_rollup: Vec<GhCheck>,
6430    /// GitHub's own verdict on whether the pull request can be merged.
6431    ///
6432    /// Worth asking for because it is the only place the *required* check set
6433    /// is applied: the rollup lists every check equally, so a repository that
6434    /// deliberately does not require `coverage` still looks red here. See
6435    /// [`Blocking`].
6436    #[serde(default)]
6437    merge_state_status: String,
6438    /// The commit the pull request currently points at. Compared with the
6439    /// commit a fix round pushed, it is how the loop knows the forge has moved
6440    /// on and the rollup belongs to the new head.
6441    #[serde(default)]
6442    head_ref_oid: String,
6443    #[serde(default)]
6444    base_ref_name: String,
6445    #[serde(default)]
6446    reviews: Vec<GhReview>,
6447    #[serde(default)]
6448    comments: Vec<GhComment>,
6449}
6450
6451/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6452/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6453/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6454/// conclusion at all.
6455#[derive(Debug, Deserialize)]
6456#[serde(rename_all = "camelCase")]
6457struct GhCheck {
6458    #[serde(default)]
6459    name: Option<String>,
6460    #[serde(default)]
6461    context: Option<String>,
6462    #[serde(default)]
6463    status: Option<String>,
6464    #[serde(default)]
6465    conclusion: Option<String>,
6466    #[serde(default)]
6467    state: Option<String>,
6468    #[serde(default)]
6469    details_url: Option<String>,
6470    #[serde(default)]
6471    target_url: Option<String>,
6472    /// Whether the base branch requires this check. Only the GraphQL node
6473    /// carries it; `None` is "not read", never "not required".
6474    #[serde(default)]
6475    is_required: Option<bool>,
6476}
6477
6478impl GhCheck {
6479    /// Name to show a human and hand to the fixer.
6480    fn label(&self) -> String {
6481        self.name
6482            .clone()
6483            .or_else(|| self.context.clone())
6484            .unwrap_or_else(|| "(unnamed check)".to_owned())
6485    }
6486
6487    /// Where this check's logs live, when it has any.
6488    fn url(&self) -> Option<&str> {
6489        self.details_url
6490            .as_deref()
6491            .or(self.target_url.as_deref())
6492            .filter(|u| !u.is_empty())
6493    }
6494
6495    /// Did it pass?
6496    ///
6497    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6498    /// skips release and bot pull requests by design, and a skip that blocked
6499    /// landing would block exactly the pull requests that need no review.
6500    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6501    /// merging over one is merging over a check that never ran.
6502    fn verdict(&self) -> Verdict {
6503        if let Some(status) = self.status.as_deref() {
6504            if !status.eq_ignore_ascii_case("COMPLETED") {
6505                return Verdict::Pending;
6506            }
6507        }
6508        let outcome = self
6509            .conclusion
6510            .as_deref()
6511            .or(self.state.as_deref())
6512            .unwrap_or("");
6513        match outcome.to_ascii_uppercase().as_str() {
6514            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6515            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6516            | "ACTION_REQUIRED" => Verdict::Fail,
6517            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6518                Verdict::Pending
6519            }
6520            _ => Verdict::Unknown,
6521        }
6522    }
6523}
6524
6525#[derive(Debug, Deserialize)]
6526struct GhAuthor {
6527    #[serde(default)]
6528    login: String,
6529}
6530
6531#[derive(Debug, Deserialize)]
6532struct GhReview {
6533    #[serde(default)]
6534    author: GhAuthor,
6535    #[serde(default)]
6536    body: String,
6537}
6538
6539#[derive(Debug, Deserialize)]
6540struct GhComment {
6541    #[serde(default)]
6542    author: GhAuthor,
6543    #[serde(default)]
6544    body: String,
6545}
6546
6547#[derive(Debug, Deserialize)]
6548struct GhUser {
6549    #[serde(default)]
6550    login: String,
6551}
6552
6553#[derive(Debug, Deserialize)]
6554struct GhInline {
6555    #[serde(default)]
6556    user: GhUser,
6557    #[serde(default)]
6558    path: Option<String>,
6559    #[serde(default)]
6560    line: Option<u64>,
6561    #[serde(default)]
6562    body: String,
6563}
6564
6565impl Default for GhAuthor {
6566    fn default() -> Self {
6567        Self {
6568            login: "(unknown)".to_owned(),
6569        }
6570    }
6571}
6572
6573impl Default for GhUser {
6574    fn default() -> Self {
6575        Self {
6576            login: "(unknown)".to_owned(),
6577        }
6578    }
6579}
6580
6581#[cfg(test)]
6582pub(crate) mod tests {
6583    use super::*;
6584    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6585
6586    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6587        format!(
6588            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6589        )
6590    }
6591
6592    #[test]
6593    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6594        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6595        assert_eq!(
6596            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6597            Ok(())
6598        );
6599        for (json, why) in [
6600            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6601            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6602            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6603            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6604            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6605            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6606        ] {
6607            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6608                .unwrap_err()
6609                .why;
6610            assert!(err.contains(why), "{json}: {err}");
6611        }
6612        // A head that moved on past what was verified is left alone.
6613        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6614        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6615        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6616        assert!(
6617            !closable(
6618                &head_json("x", "main", "OPEN", false),
6619                "magi/27b2/A",
6620                "main",
6621                &[]
6622            )
6623            .unwrap_err()
6624            .retry
6625        );
6626        assert!(is_forge_url("https://github.com/o/r.git"));
6627        assert!(is_forge_url("git@github.com:o/r.git"));
6628        assert!(!is_forge_url("/tmp/origin.git"));
6629        assert!(!is_forge_url("C:\\work\\origin.git"));
6630        assert!(!is_forge_url("file:///tmp/origin.git"));
6631        assert!(forge_unavailable(
6632            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6633        ));
6634        assert!(!forge_unavailable(
6635            "gh pr list failed: error connecting to api.github.com"
6636        ));
6637        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6638        // A record that does not say whether it is a fork is not trusted.
6639        assert!(
6640            closable(
6641                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6642                "b",
6643                "main",
6644                &["aaa".to_owned()]
6645            )
6646            .is_err()
6647        );
6648    }
6649
6650    #[test]
6651    fn the_close_comment_names_the_commit_on_the_base() {
6652        let e = crate::already::Evidence {
6653            proof: crate::already::Proof::PatchId,
6654            tip: "1234567890".to_owned(),
6655            commits: vec!["0e368de0000".to_owned()],
6656        };
6657        let c = superseded_comment("main", &e);
6658        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6659    }
6660
6661    /// 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.
6662    const GREEN_OPEN: &str = r####"{
6663  "url": "https://github.com/yukimemi/magi/pull/10",
6664  "number": 10,
6665  "state": "OPEN",
6666  "mergeStateStatus": "CLEAN",
6667  "statusCheckRollup": [
6668    {
6669      "__typename": "CheckRun",
6670      "conclusion": "SKIPPED",
6671      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6672      "name": "review",
6673      "status": "COMPLETED",
6674      "workflowName": "claude-review"
6675    },
6676    {
6677      "__typename": "CheckRun",
6678      "conclusion": "SUCCESS",
6679      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6680      "name": "check (ubuntu-latest)",
6681      "status": "COMPLETED",
6682      "workflowName": "CI"
6683    },
6684    {
6685      "__typename": "CheckRun",
6686      "conclusion": "SUCCESS",
6687      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6688      "name": "rustfmt",
6689      "status": "COMPLETED",
6690      "workflowName": "CI"
6691    },
6692    {
6693      "__typename": "StatusContext",
6694      "context": "CodeRabbit",
6695      "state": "SUCCESS",
6696      "targetUrl": ""
6697    }
6698  ],
6699  "reviews": [],
6700  "comments": [
6701    {
6702      "author": {
6703        "login": "coderabbitai"
6704      },
6705      "authorAssociation": "NONE",
6706      "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"
6707    }
6708  ]
6709}"####;
6710
6711    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
6712    const RED_OPEN: &str = r####"{
6713  "url": "https://github.com/yukimemi/magi/pull/9",
6714  "number": 9,
6715  "state": "OPEN",
6716  "mergeStateStatus": "UNSTABLE",
6717  "statusCheckRollup": [
6718    {
6719      "__typename": "CheckRun",
6720      "conclusion": "SUCCESS",
6721      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6722      "name": "check (ubuntu-latest)",
6723      "status": "COMPLETED",
6724      "workflowName": "CI"
6725    },
6726    {
6727      "__typename": "CheckRun",
6728      "conclusion": "SUCCESS",
6729      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6730      "name": "rustfmt",
6731      "status": "COMPLETED",
6732      "workflowName": "CI"
6733    },
6734    {
6735      "__typename": "CheckRun",
6736      "conclusion": "FAILURE",
6737      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6738      "name": "editorconfig",
6739      "status": "COMPLETED",
6740      "workflowName": "CI"
6741    },
6742    {
6743      "__typename": "StatusContext",
6744      "context": "CodeRabbit",
6745      "state": "SUCCESS",
6746      "targetUrl": ""
6747    }
6748  ],
6749  "reviews": [],
6750  "comments": [
6751    {
6752      "author": {
6753        "login": "coderabbitai"
6754      },
6755      "authorAssociation": "NONE",
6756      "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"
6757    }
6758  ]
6759}"####;
6760
6761    /// 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.
6762    const PENDING_OPEN: &str = r####"{
6763  "url": "https://github.com/yukimemi/magi/pull/9",
6764  "number": 9,
6765  "state": "OPEN",
6766  "statusCheckRollup": [
6767    {
6768      "__typename": "CheckRun",
6769      "conclusion": "SUCCESS",
6770      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6771      "name": "check (ubuntu-latest)",
6772      "status": "COMPLETED",
6773      "workflowName": "CI"
6774    },
6775    {
6776      "__typename": "CheckRun",
6777      "conclusion": "SUCCESS",
6778      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6779      "name": "rustfmt",
6780      "status": "COMPLETED",
6781      "workflowName": "CI"
6782    },
6783    {
6784      "__typename": "CheckRun",
6785      "conclusion": null,
6786      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6787      "name": "editorconfig",
6788      "status": "IN_PROGRESS",
6789      "workflowName": "CI"
6790    },
6791    {
6792      "__typename": "StatusContext",
6793      "context": "CodeRabbit",
6794      "state": "SUCCESS",
6795      "targetUrl": ""
6796    }
6797  ],
6798  "reviews": [],
6799  "comments": []
6800}"####;
6801
6802    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
6803    const MERGED: &str = r####"{
6804  "url": "https://github.com/yukimemi/magi/pull/16",
6805  "number": 16,
6806  "state": "MERGED",
6807  "statusCheckRollup": [
6808    {
6809      "__typename": "CheckRun",
6810      "conclusion": "SUCCESS",
6811      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
6812      "name": "check (ubuntu-latest)",
6813      "status": "COMPLETED",
6814      "workflowName": "CI"
6815    },
6816    {
6817      "__typename": "CheckRun",
6818      "conclusion": "SUCCESS",
6819      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
6820      "name": "review",
6821      "status": "COMPLETED",
6822      "workflowName": "claude-review"
6823    }
6824  ],
6825  "reviews": [],
6826  "comments": []
6827}"####;
6828
6829    /// 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.
6830    const REVIEWED_OPEN: &str = r####"{
6831  "url": "https://github.com/yukimemi/magi/pull/12",
6832  "number": 12,
6833  "state": "OPEN",
6834  "statusCheckRollup": [
6835    {
6836      "__typename": "CheckRun",
6837      "conclusion": "SUCCESS",
6838      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
6839      "name": "check (ubuntu-latest)",
6840      "status": "COMPLETED",
6841      "workflowName": "CI"
6842    },
6843    {
6844      "__typename": "CheckRun",
6845      "conclusion": "SUCCESS",
6846      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
6847      "name": "review",
6848      "status": "COMPLETED",
6849      "workflowName": "claude-review"
6850    }
6851  ],
6852  "reviews": [
6853    {
6854      "author": {
6855        "login": "claude"
6856      },
6857      "state": "COMMENTED",
6858      "body": ""
6859    }
6860  ],
6861  "comments": [
6862    {
6863      "author": {
6864        "login": "coderabbitai"
6865      },
6866      "authorAssociation": "NONE",
6867      "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"
6868    },
6869    {
6870      "author": {
6871        "login": "claude"
6872      },
6873      "authorAssociation": "NONE",
6874      "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"
6875    }
6876  ]
6877}"####;
6878
6879    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
6880    const INLINE: &str = r####"[
6881  {
6882    "user": {
6883      "login": "claude[bot]"
6884    },
6885    "path": "src/graph.rs",
6886    "line": 231,
6887    "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"
6888  }
6889]"####;
6890
6891    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
6892    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
6893<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
6894
6895> [!IMPORTANT]
6896> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
6897> 
6898> This repository does not receive automatic reviews because it has fewer than 10 stars.
6899> 
6900> <details>
6901> <summary>⚙️ Run configuration</summary>
6902> 
6903> **Configuration used**: defaults
6904> 
6905> **Review profile**: CHILL
6906> 
6907> **Plan**: Team
6908> 
6909> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
6910> 
6911> </details>
6912
6913<!-- end of auto-generated comment: skip review by coderabbit.ai -->
6914
6915<!-- tips_start -->
6916
6917---
6918
6919Thanks 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.
6920
6921<details>
6922<summary>❤️ Share</summary>
6923
6924- [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"####;
6925
6926    /// 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.
6927    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
6928
6929---
6930### Reviewing PR #16
6931
6932- [x] Read AGENTS.md conventions
6933- [x] Review `src/daemon.rs` changes
6934- [x] Review `src/main.rs` changes (new `doctor` reporting)
6935- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
6936- [x] Check test coverage for new behavior
6937- [x] Run verification commands (blocked — see note)
6938- [x] Post findings"####;
6939
6940    /// The same job's real comment on pull request #12 once it had something to say.
6941    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
6942
6943---
6944### Review: `magi review <branch>` — cheap-half-only graph
6945
6946Read 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.
6947
6948**Correctness**
6949
6950- 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"####;
6951
6952    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
6953        PrState {
6954            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
6955            number: 16,
6956            state: PrLifecycle::Open,
6957            checks,
6958            // These tests are about red-means-fix, so a red here is one the
6959            // forge gates on. Without saying so they would assert the new
6960            // "merge past a check nobody requires" path by accident.
6961            blocking: if matches!(checks, Checks::Red) {
6962                Blocking::Yes
6963            } else {
6964                Blocking::No
6965            },
6966            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
6967            review_comments: (0..comments)
6968                .map(|i| ReviewComment {
6969                    author: "coderabbitai".to_owned(),
6970                    path: Some("src/graph.rs".to_owned()),
6971                    line: Some(231),
6972                    body: format!("finding {i}"),
6973                })
6974                .collect(),
6975        }
6976    }
6977
6978    #[test]
6979    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
6980        use CiExpectation::{Absent, Expected};
6981        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
6982            let p = pr(checks, &["x"], 0);
6983            for waited in [Duration::ZERO, CHECKS_GRACE] {
6984                assert_eq!(
6985                    decide_with(&p, 0, 4, waited, Expected),
6986                    decide(&p, 0, 4, waited)
6987                );
6988            }
6989        }
6990        // Nothing will ever report: no wait, no give-up, no fix round.
6991        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
6992            let p = pr(checks, &["x"], 0);
6993            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
6994            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
6995        }
6996        // Third-party statuses never change the review decision, even at budget.
6997        for comments in [0, 1] {
6998            for round in [0, 4] {
6999                let absent = decide_with(
7000                    &pr(Checks::Unknown, &[], comments),
7001                    round,
7002                    4,
7003                    CHECKS_GRACE,
7004                    Absent,
7005                );
7006                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
7007                    assert_eq!(
7008                        decide_with(
7009                            &pr(checks, &["third-party"], comments),
7010                            round,
7011                            4,
7012                            Duration::ZERO,
7013                            Absent
7014                        ),
7015                        absent
7016                    );
7017                }
7018                if comments != 0 {
7019                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
7020                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
7021                }
7022            }
7023        }
7024        let empty = pr(Checks::Unknown, &[], 0);
7025        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
7026            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
7027        }
7028        assert_eq!(
7029            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
7030            Step::Wait
7031        );
7032        assert_eq!(
7033            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
7034            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
7035        );
7036        // A conflict is not a check: it still wants the rebase.
7037        let mut p = pr(Checks::Unknown, &[], 0);
7038        p.blocking = Blocking::Conflict;
7039        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
7040        // And a pull request that left our hands is still done.
7041        p.state = PrLifecycle::Merged;
7042        assert_eq!(
7043            decide_with(&p, 0, 4, Duration::ZERO, Absent),
7044            Step::Done { merged: true }
7045        );
7046    }
7047
7048    #[test]
7049    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
7050        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
7051        assert_eq!(state.number, 10);
7052        assert_eq!(state.state, PrLifecycle::Open);
7053        assert_eq!(state.checks, Checks::Green);
7054        assert!(state.failing.is_empty());
7055        assert!(
7056            state.review_comments.is_empty(),
7057            "the only comment is CodeRabbit's trigger notice: {:?}",
7058            state.review_comments
7059        );
7060        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
7061    }
7062
7063    #[test]
7064    fn a_failing_check_parses_as_red_and_is_named() {
7065        let state = parse_pr(RED_OPEN).expect("red fixture parses");
7066        assert_eq!(state.checks, Checks::Red);
7067        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
7068        // The captured payload says `UNSTABLE` - mergeable, with a check
7069        // nobody requires red - which is exactly the shape that had to be
7070        // merged by hand. Asserted separately, in
7071        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
7072        // test is about is that a red check is *named*, so the reason a fixer
7073        // is handed says which one; so it asks the blocking question here.
7074        let mut blocking = state.clone();
7075        blocking.blocking = Blocking::Yes;
7076        match decide(&blocking, 0, 4, Duration::ZERO) {
7077            Step::Fix { reason } => {
7078                assert!(reason.contains("editorconfig"), "reason: {reason}");
7079                assert!(reason.contains("failing"), "reason: {reason}");
7080            }
7081            other => panic!("expected a fix round, got {other:?}"),
7082        }
7083    }
7084
7085    #[test]
7086    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
7087        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
7088        assert_eq!(state.checks, Checks::Pending);
7089        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
7090    }
7091
7092    #[test]
7093    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
7094        let state = parse_pr(MERGED).expect("merged fixture parses");
7095        assert_eq!(state.state, PrLifecycle::Merged);
7096        assert_eq!(
7097            decide(&state, 0, 4, Duration::ZERO),
7098            Step::Done { merged: true }
7099        );
7100    }
7101
7102    #[test]
7103    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
7104        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
7105        assert_eq!(state.checks, Checks::Green);
7106        let authors: Vec<&str> = state
7107            .review_comments
7108            .iter()
7109            .map(|c| c.author.as_str())
7110            .collect();
7111        assert_eq!(
7112            authors,
7113            vec!["claude"],
7114            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
7115        );
7116        match decide(&state, 0, 4, Duration::ZERO) {
7117            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
7118            other => panic!("expected a fix round, got {other:?}"),
7119        }
7120    }
7121
7122    #[test]
7123    fn inline_review_comments_keep_their_file_and_line() {
7124        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
7125        assert_eq!(comments.len(), 1);
7126        assert_eq!(comments[0].author, "claude[bot]");
7127        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
7128        assert_eq!(comments[0].line, Some(231));
7129        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
7130    }
7131
7132    #[test]
7133    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
7134        assert!(
7135            is_noise(CODERABBIT_TRIGGER),
7136            "CodeRabbit's trigger notice declares itself not a review"
7137        );
7138        assert!(
7139            is_noise(CLAUDE_CHECKLIST),
7140            "a progress checklist asks for nothing"
7141        );
7142        assert!(
7143            !is_noise(CLAUDE_FINDING),
7144            "a review that names a bug is input, not noise"
7145        );
7146
7147        let mut clean = pr(Checks::Green, &[], 0);
7148        clean.review_comments.push(ReviewComment {
7149            author: "coderabbitai".to_owned(),
7150            path: None,
7151            line: None,
7152            body: CODERABBIT_TRIGGER.to_owned(),
7153        });
7154        clean.review_comments.retain(|c| !is_noise(&c.body));
7155        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
7156
7157        let mut found = pr(Checks::Green, &[], 0);
7158        found.review_comments.push(ReviewComment {
7159            author: "claude".to_owned(),
7160            path: None,
7161            line: None,
7162            body: CLAUDE_FINDING.to_owned(),
7163        });
7164        found.review_comments.retain(|c| !is_noise(&c.body));
7165        assert!(matches!(
7166            decide(&found, 0, 4, Duration::ZERO),
7167            Step::Fix { .. }
7168        ));
7169    }
7170
7171    #[test]
7172    fn the_policy_table_holds_for_every_combination_that_matters() {
7173        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
7174            (
7175                "pending checks are waited for, even on the last round",
7176                pr(Checks::Pending, &[], 0),
7177                4,
7178                4,
7179                Duration::ZERO,
7180                Step::Wait,
7181            ),
7182            (
7183                "red checks are fixed",
7184                pr(Checks::Red, &["editorconfig"], 0),
7185                0,
7186                4,
7187                Duration::ZERO,
7188                Step::Fix {
7189                    reason: "1 check(s) failing: editorconfig".to_owned(),
7190                },
7191            ),
7192            (
7193                "green with comments is fixed, not merged",
7194                pr(Checks::Green, &[], 2),
7195                1,
7196                4,
7197                Duration::ZERO,
7198                Step::Fix {
7199                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
7200                        .to_owned(),
7201                },
7202            ),
7203            (
7204                "green and clean merges",
7205                pr(Checks::Green, &[], 0),
7206                3,
7207                4,
7208                Duration::ZERO,
7209                Step::Merge,
7210            ),
7211            (
7212                "an unreadable rollup is waited on while the grace lasts",
7213                pr(Checks::Unknown, &[], 0),
7214                0,
7215                4,
7216                Duration::ZERO,
7217                Step::Wait,
7218            ),
7219            (
7220                "an unreadable rollup is never merged once the grace is spent",
7221                pr(Checks::Unknown, &[], 0),
7222                0,
7223                4,
7224                CHECKS_GRACE,
7225                Step::GiveUp {
7226                    reason: "no check status is readable on the pull request after 3 minute(s); \
7227                             refusing to merge on a guess"
7228                        .to_owned(),
7229                },
7230            ),
7231        ];
7232        for (what, state, round, budget, waited, want) in cases {
7233            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
7234        }
7235    }
7236
7237    #[test]
7238    fn the_forge_verdict_survives_the_round_trip_from_gh() {
7239        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
7240        // requested but never parsed is the kind of thing that looks wired up
7241        // and answers `Unsaid` forever.
7242        let green = parse_pr(GREEN_OPEN).expect("parse");
7243        assert_eq!(green.blocking, Blocking::No);
7244        let red = parse_pr(RED_OPEN).expect("parse");
7245        assert_eq!(
7246            red.blocking,
7247            Blocking::No,
7248            "`UNSTABLE` is mergeable: the red check is one nobody requires"
7249        );
7250        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
7251        // A payload from an older `gh` has no such field at all.
7252        let quiet =
7253            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
7254        assert_eq!(quiet.blocking, Blocking::Unsaid);
7255    }
7256
7257    #[test]
7258    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
7259        // Pull request 37's only red check was `editorconfig`, failing
7260        // because the action could not fetch its own binary after
7261        // editorconfig-checker v4 renamed its release assets. The repository
7262        // does not require it. magi answered by asking a fixer to repair a
7263        // change that was fine, and the pull request had to be merged by hand.
7264        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7265        nonblocking.blocking = Blocking::No;
7266        assert_eq!(
7267            decide(&nonblocking, 0, 4, Duration::ZERO),
7268            Step::Merge,
7269            "the forge says nothing is in the way, so nothing is"
7270        );
7271
7272        // The same red, gated on: that is a fix round, as before.
7273        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7274        blocking.blocking = Blocking::Yes;
7275        assert!(matches!(
7276            decide(&blocking, 0, 4, Duration::ZERO),
7277            Step::Fix { .. }
7278        ));
7279
7280        // A review comment still outranks green-enough: a non-required red
7281        // must not become a way to merge past an unanswered reviewer.
7282        let mut commented = pr(Checks::Red, &["coverage"], 1);
7283        commented.blocking = Blocking::No;
7284        assert!(matches!(
7285            decide(&commented, 0, 4, Duration::ZERO),
7286            Step::Fix { .. }
7287        ));
7288
7289        // And silence from the forge is not consent.
7290        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7291        unsaid.blocking = Blocking::Unsaid;
7292        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7293        assert!(matches!(
7294            decide(&unsaid, 0, 4, CHECKS_GRACE),
7295            Step::Fix { .. }
7296        ));
7297    }
7298
7299    #[test]
7300    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7301        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7302        red.blocking = Blocking::No;
7303        assert_eq!(
7304            decide(&red, 0, 4, Duration::ZERO),
7305            Step::Merge,
7306            "announcing must not change the decision"
7307        );
7308        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7309        assert!(said.contains("yukimemi/magi"), "{said}");
7310        assert!(said.contains("#16"), "{said}");
7311        assert!(
7312            said.contains("https://github.com/yukimemi/magi/pull/16"),
7313            "{said}"
7314        );
7315        assert!(
7316            said.contains("test (windows-latest)") && said.contains("coverage"),
7317            "{said}"
7318        );
7319
7320        // `failing` can be left over on a green observation; only `checks` counts.
7321        let green = pr(Checks::Green, &["stale"], 0);
7322        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7323    }
7324
7325    #[test]
7326    fn red_merge_notices_omit_empty_check_details() {
7327        for checks in [vec![], vec!["", "  "]] {
7328            let red = pr(Checks::Red, &checks, 0);
7329            let summary = red_merge_summary("owner/repo", &red).unwrap();
7330            let notice = crate::notices::merged_red("run-1", &summary);
7331            assert_eq!(
7332                notice.message,
7333                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7334            );
7335            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7336        }
7337        let red = pr(Checks::Red, &["", " test ", " "], 0);
7338        let summary = red_merge_summary("owner/repo", &red).unwrap();
7339        assert!(summary.contains("with red checks: test ("), "{summary}");
7340    }
7341
7342    #[test]
7343    fn the_repo_label_comes_from_the_pull_request_url() {
7344        let p = Path::new("/tmp/checkout");
7345        assert_eq!(
7346            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7347            "yukimemi/magi"
7348        );
7349        assert_eq!(repo_label(p, "not a url"), "checkout");
7350    }
7351
7352    #[test]
7353    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7354        // Pull requests 35 and 37 were both rebased by hand: a competition
7355        // that runs for two hours against a repository merging pull requests
7356        // all day conflicts on the way in, and that is arithmetic rather
7357        // than a defect in the change.
7358        let mut conflicted = pr(Checks::Green, &[], 0);
7359        conflicted.blocking = Blocking::Conflict;
7360        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7361
7362        // Decided before the checks, and even with the rounds spent: every
7363        // check on a branch that cannot land is an answer about a state that
7364        // cannot land, and a conflict is not the change's fault.
7365        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7366        red.blocking = Blocking::Conflict;
7367        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7368
7369        // The lifecycle still wins over everything, conflict included.
7370        let mut merged = pr(Checks::Red, &[], 0);
7371        merged.blocking = Blocking::Conflict;
7372        merged.state = PrLifecycle::Merged;
7373        assert_eq!(
7374            decide(&merged, 0, 4, Duration::ZERO),
7375            Step::Done { merged: true }
7376        );
7377    }
7378
7379    #[test]
7380    fn the_forge_verdict_is_read_off_merge_state_status() {
7381        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7382        // matters: mergeable, with a non-required check red or still running.
7383        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7384            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7385            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7386        }
7387        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7388        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7389        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7390        // An older `gh`, or a token without the scope, says nothing - and
7391        // refusing to guess is the rule everywhere else in this module.
7392        for quiet in ["", "UNKNOWN"] {
7393            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7394            assert!(Blocking::of(quiet).stops_a_merge());
7395        }
7396    }
7397
7398    #[test]
7399    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7400        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7401        // The exact stderr from run ec12, in a jj-colocated repository.
7402        let jj = "could not determine current branch: failed to run git: not on any branch";
7403
7404        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7405            .expect("the forge says merged, so it merged");
7406        assert!(landed.ok);
7407        assert!(
7408            landed.detail.contains("but the pull request is merged"),
7409            "the record must not read as a clean success: {}",
7410            landed.detail
7411        );
7412        assert!(
7413            landed.detail.contains("not on any branch"),
7414            "and it must keep what the command actually said: {}",
7415            landed.detail
7416        );
7417
7418        // A pull request still open means the merge really failed.
7419        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7420        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7421        // And an unreadable answer is not evidence of success.
7422        assert!(merged_after_all(&argv, jj, None).is_none());
7423    }
7424
7425    #[test]
7426    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7427        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7428        state.state = PrLifecycle::Closed;
7429        assert_eq!(
7430            decide(&state, 0, 4, Duration::ZERO),
7431            Step::Done { merged: false },
7432            "a human closing the pull request ends the loop, whatever CI says"
7433        );
7434    }
7435
7436    #[test]
7437    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7438        let red = decide(
7439            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7440            4,
7441            4,
7442            Duration::ZERO,
7443        );
7444        match red {
7445            Step::GiveUp { reason } => {
7446                assert!(reason.contains("editorconfig"), "reason: {reason}");
7447                assert!(reason.contains("test (macos)"), "reason: {reason}");
7448                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7449            }
7450            other => panic!("expected a give-up, got {other:?}"),
7451        }
7452
7453        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7454        match commented {
7455            Step::GiveUp { reason } => {
7456                assert!(reason.contains("unresolved"), "reason: {reason}");
7457                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7458            }
7459            other => panic!("expected a give-up, got {other:?}"),
7460        }
7461    }
7462
7463    #[test]
7464    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7465        let candidate_commit = "magi: candidate A (uncommitted work)";
7466        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7467        let argv = merge_argv(16, &subject);
7468
7469        assert!(argv.contains(&"--squash".to_owned()));
7470        assert!(argv.contains(&"--delete-branch".to_owned()));
7471        assert!(argv.contains(&"--subject".to_owned()));
7472        assert_eq!(
7473            argv.last().map(String::as_str),
7474            Some("add retries to the uploader"),
7475            "the subject must not be the candidate commit message"
7476        );
7477        assert_ne!(subject, candidate_commit);
7478    }
7479
7480    #[test]
7481    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7482        assert_eq!(
7483            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7484            "feat: a queue, an unattended loop, and a phone UI"
7485        );
7486        assert_eq!(
7487            merge_subject("", "# port the retry logic\n\ndetails"),
7488            "port the retry logic",
7489            "an empty title falls back to the task's first line, heading marks stripped"
7490        );
7491    }
7492
7493    #[test]
7494    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7495        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7496        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7497        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7498        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7499        assert_eq!(run_of(""), None);
7500    }
7501
7502    #[test]
7503    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7504        let mut out = Vec::new();
7505        push_if_outstanding(
7506            &mut out,
7507            ReviewComment {
7508                author: "yukimemi".to_owned(),
7509                path: None,
7510                line: None,
7511                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7512            },
7513        );
7514        assert!(out.is_empty());
7515    }
7516
7517    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7518    /// falls back to the repository - which keeps these tests free of a
7519    /// worktree, a `git` invocation and a network.
7520    fn run_state() -> RunState {
7521        let mut state = RunState::new(
7522            std::path::PathBuf::from("/repo/magi"),
7523            "main".to_owned(),
7524            "abcdef1234".to_owned(),
7525            "add retries to the uploader".to_owned(),
7526            crate::config::Config::default(),
7527        );
7528        // These fixtures test execution flow, independent of host disk capacity.
7529        state.config.disk.min_free_bytes = 0;
7530        // Tests run in parallel against one persistent home and the ids
7531        // `RunState::new` draws from the clock can repeat, so two tests would
7532        // share a run's questions. The home also outlives the process, so the
7533        // counter alone would reuse an earlier run's ids.
7534        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7535        let nanos = std::time::SystemTime::now()
7536            .duration_since(std::time::UNIX_EPOCH)
7537            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7538        state.id = format!(
7539            "20261004-{nanos:06}-{:04x}",
7540            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7541        );
7542        state
7543    }
7544
7545    fn green_pr() -> PrState {
7546        PrState {
7547            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7548            number: 42,
7549            state: PrLifecycle::Open,
7550            checks: Checks::Green,
7551            // The forge sees nothing in the way unless a test says otherwise.
7552            blocking: Blocking::No,
7553            failing: Vec::new(),
7554            review_comments: vec![ReviewComment {
7555                author: "coderabbitai".to_owned(),
7556                path: Some("src/land.rs".to_owned()),
7557                line: Some(212),
7558                body: "this branch never checks the exit code".to_owned(),
7559            }],
7560        }
7561    }
7562
7563    #[test]
7564    fn land_fixer_defers_review_and_verification_without_a_cache() {
7565        let state = run_state();
7566        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7567        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7568        assert!(p.contains("Commit in this worktree"), "{p}");
7569    }
7570
7571    #[test]
7572    fn github_facing_land_text_is_english_whatever_the_language() {
7573        let mut state = run_state();
7574        state.config.graph.language = "ja".to_owned();
7575        let comment = stop_comment(&state.id, "checks are still red");
7576        assert!(crate::github_text::check("", &comment).is_empty());
7577        assert!(comment.is_ascii(), "{comment}");
7578        assert!(comment.starts_with(MARKER));
7579
7580        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7581        let ja_at = p.find("Write all prose in ja").unwrap();
7582        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7583        assert!(ja_at < rule_at, "{p}");
7584        assert!(p.contains("stays in Japanese"), "{p}");
7585
7586        state.config.graph.language = "en".to_owned();
7587        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7588        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7589        assert!(!p.contains("does not apply"), "{p}");
7590    }
7591
7592    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7593
7594    fn panel() -> String {
7595        approval_panel(
7596            &run_state(),
7597            &green_pr(),
7598            NUMSTAT,
7599            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7600            &[
7601                "land: ask before merging".to_owned(),
7602                "land: colour the diff".to_owned(),
7603            ],
7604            "feat: merge approval from the phone",
7605        )
7606    }
7607
7608    #[test]
7609    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7610        let html = panel();
7611        for needle in [
7612            "42",
7613            "main",
7614            "src/land.rs",
7615            "src/web.rs",
7616            "assets/logo.png",
7617            "feat: merge approval from the phone",
7618            "land: ask before merging",
7619            "land: colour the diff",
7620            "coderabbitai",
7621            "this branch never checks the exit code",
7622            "green",
7623        ] {
7624            assert!(html.contains(needle), "the panel must state `{needle}`");
7625        }
7626    }
7627
7628    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7629        crate::run::pin_test_home();
7630        let tmp = tempfile::tempdir().unwrap();
7631        let repo = tmp.path().join("repo");
7632        let remote = tmp.path().join("remote.git");
7633        std::fs::create_dir(&repo).unwrap();
7634        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7635            .await
7636            .unwrap();
7637        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7638        git::git(&repo, &["config", "user.name", "Test"])
7639            .await
7640            .unwrap();
7641        git::git(&repo, &["config", "user.email", "test@example.test"])
7642            .await
7643            .unwrap();
7644        std::fs::write(repo.join("base"), "base").unwrap();
7645        git::git(&repo, &["add", "."]).await.unwrap();
7646        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7647        git::git(
7648            &repo,
7649            &["remote", "add", "origin", remote.to_str().unwrap()],
7650        )
7651        .await
7652        .unwrap();
7653        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7654        git::git(&repo, &["checkout", "-b", "winner"])
7655            .await
7656            .unwrap();
7657        std::fs::write(repo.join("change"), "change").unwrap();
7658        git::git(&repo, &["add", "."]).await.unwrap();
7659        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7660        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7661        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7662            .await
7663            .unwrap();
7664        let mut state = run_state();
7665        state.repo = repo.clone();
7666        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7667        state.config.graph.land = true;
7668        state.config.graph.land_approval = true;
7669        state.pr_head = Some("task-head".into());
7670        state.pr_pushed_head = Some(head.clone());
7671        state.candidates = vec![winning_candidate("change")];
7672        state.candidates[0].worktree = repo;
7673        state.candidates[0].branch = "winner".into();
7674        state.tally = Some(uncontested_tally());
7675        state.gate_ran = true;
7676        state.gate_head = Some(head.clone());
7677        state.land_sync_pending = true;
7678        state.save().unwrap();
7679        (tmp, state, head)
7680    }
7681
7682    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7683        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7684        resume_landing_head(state, head, &green_pr().url, &forge, None).await
7685    }
7686
7687    async fn advance_landing_base(state: &RunState) {
7688        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7689        std::fs::write(state.repo.join("advance"), "advance").unwrap();
7690        git::git(&state.repo, &["add", "."]).await.unwrap();
7691        git::git(&state.repo, &["commit", "-m", "advance base"])
7692            .await
7693            .unwrap();
7694        git::git(&state.repo, &["push", "origin", "main"])
7695            .await
7696            .unwrap();
7697        git::git(&state.repo, &["checkout", "winner"])
7698            .await
7699            .unwrap();
7700    }
7701
7702    #[tokio::test]
7703    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
7704        let (_tmp, mut state, head) = landing_git_fixture().await;
7705        advance_landing_base(&state).await;
7706        let scratch = state.dir().join("rebase");
7707        std::fs::create_dir_all(&scratch).unwrap();
7708        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
7709        let attempts = state.land_sync_attempts;
7710        let error = rebase_landing_worktree(&mut state, "origin/main")
7711            .await
7712            .unwrap_err();
7713        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
7714        assert_eq!(state.land_sync_attempts, attempts);
7715        assert!(state.land_sync_target.is_none());
7716        assert!(state.rebase_fixes.is_empty());
7717        assert!(
7718            state
7719                .base_sync
7720                .as_ref()
7721                .is_none_or(|sync| sync.conflict.is_none())
7722        );
7723        let block = state.resource_block.as_ref().unwrap();
7724        assert_eq!(block.kind, crate::rebase::SEQUENCER_INFRASTRUCTURE);
7725        assert!(
7726            block.detail.contains("inspect scratch Git backlink"),
7727            "{}",
7728            block.detail
7729        );
7730        assert_eq!(
7731            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
7732            "keep"
7733        );
7734        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
7735        std::fs::remove_dir_all(&scratch).unwrap();
7736        state.resource_block = None;
7737        assert_eq!(
7738            rebase_landing_worktree(&mut state, "origin/main")
7739                .await
7740                .unwrap(),
7741            crate::rebase::Rebased::Applied
7742        );
7743        assert_eq!(state.land_sync_attempts, attempts + 1);
7744        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
7745        assert!(git::is_clean(&state.repo).await.unwrap());
7746        assert!(state.rebase_fixes.is_empty());
7747    }
7748
7749    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7750    {
7751        let (tmp, mut state, old) = landing_git_fixture().await;
7752        let path = tmp.path().join("foreign");
7753        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7754            .await
7755            .unwrap();
7756        state.foreign_checkout = Some(
7757            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7758                .await
7759                .unwrap(),
7760        );
7761        state.config.merge.mode = crate::config::MergeMode::Pr;
7762        state.save().unwrap();
7763        (tmp, state, old, path)
7764    }
7765
7766    #[tokio::test]
7767    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
7768        for phase in 0..4 {
7769            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7770            advance_landing_base(&state).await;
7771            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
7772            if phase == 0 {
7773                // The live Step::Rebase path uses this same synchronization
7774                // and publication pair, without going through resume.
7775                assert_eq!(
7776                    rebase_landing_worktree(&mut state, "origin/main")
7777                        .await
7778                        .unwrap(),
7779                    crate::rebase::Rebased::Applied
7780                );
7781            } else {
7782                interrupt_landing_rebase(&mut state).await;
7783                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
7784                if phase == 2 {
7785                    git::sync_to_head(&state.repo).await.unwrap();
7786                } else if phase == 3 {
7787                    // Crash after joining history, before clearing its saved
7788                    // start. Repeating restoration must not add another merge.
7789                    restore_landing_worktree(&mut state).await.unwrap();
7790                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7791                    state.land_rebase_from = Some(old.clone());
7792                    state.save().unwrap();
7793                    restore_landing_worktree(&mut state).await.unwrap();
7794                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
7795                }
7796                state.save().unwrap();
7797                state = RunState::load(&state.id).unwrap();
7798                restore_landing_worktree(&mut state).await.unwrap();
7799                assert_eq!(
7800                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
7801                    repaired_tree
7802                );
7803            }
7804            let head = if phase == 0 {
7805                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
7806                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
7807                    .await
7808                    .unwrap()
7809            } else {
7810                resume_observed_head(&mut state, &old).await.unwrap()
7811            };
7812            assert!(git::is_ancestor(&state.repo, &old, &head).await);
7813            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7814            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7815            assert_eq!(
7816                git::remote_head(&state.repo, "origin", "task-head")
7817                    .await
7818                    .unwrap(),
7819                Some(head.clone())
7820            );
7821            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7822            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
7823            assert!(state.gate_allows_progress());
7824            assert!(state.land_rebase_from.is_none());
7825            assert!(!state.land_sync_pending);
7826            assert!(git::is_clean(&path).await.unwrap());
7827        }
7828    }
7829
7830    #[tokio::test]
7831    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
7832        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7833        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7834        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7835        git::commit_all(&state.repo, "conflicting base")
7836            .await
7837            .unwrap();
7838        git::git(&state.repo, &["push", "origin", "main"])
7839            .await
7840            .unwrap();
7841        git::git(&state.repo, &["checkout", "winner"])
7842            .await
7843            .unwrap();
7844        landing_gate_fixer(
7845            &mut state,
7846            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7847        );
7848        state.config.graph.gate_fix_rounds = 0;
7849        state.config.verify.gate = vec!["exit 1".into()];
7850        assert!(resume_observed_head(&mut state, &old).await.is_err());
7851        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
7852        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7853        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
7854        assert_eq!(
7855            std::fs::read_to_string(state.repo.join("change")).unwrap(),
7856            "resolved"
7857        );
7858        // A red gate must neither deliver nor publish the repaired tree.
7859        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
7860        assert_eq!(
7861            git::remote_head(&state.repo, "origin", "task-head")
7862                .await
7863                .unwrap(),
7864            Some(old.clone())
7865        );
7866        state = RunState::load(&state.id).unwrap();
7867        state.config.verify.gate = vec!["grep -q resolved change".into()];
7868        let head = resume_observed_head(&mut state, &old).await.unwrap();
7869        assert_eq!(head, repaired);
7870        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7871        assert_eq!(
7872            std::fs::read_to_string(path.join("change")).unwrap(),
7873            "resolved"
7874        );
7875        assert_eq!(
7876            git::remote_head(&state.repo, "origin", "task-head")
7877                .await
7878                .unwrap(),
7879            Some(head.clone())
7880        );
7881        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7882        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7883        assert!(git::is_clean(&path).await.unwrap());
7884    }
7885
7886    #[tokio::test]
7887    async fn landing_resume_completes_the_last_charged_sync_attempt() {
7888        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
7889            let (_tmp, mut state, old) = landing_git_fixture().await;
7890            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7891            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7892            git::commit_all(&state.repo, "conflicting base")
7893                .await
7894                .unwrap();
7895            git::git(&state.repo, &["push", "origin", "main"])
7896                .await
7897                .unwrap();
7898            git::git(&state.repo, &["checkout", "winner"])
7899                .await
7900                .unwrap();
7901            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
7902            state.config.graph.land_rounds = 1;
7903            state.land_sync_attempts = 1;
7904            state.land_sync_target = saved_target.then(|| target.clone());
7905            state.land_rebase_from = Some(old.clone());
7906            landing_gate_fixer(
7907                &mut state,
7908                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7909            );
7910            state.config.verify.gate = vec!["grep -q resolved change".into()];
7911            state.save().unwrap();
7912            // Simulate interruption before the scratch start and at a conflict.
7913            if scratch_started {
7914                assert!(matches!(
7915                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
7916                        .await
7917                        .unwrap(),
7918                    git::RebaseStart::Conflicted(_)
7919                ));
7920            }
7921            state = RunState::load(&state.id).unwrap();
7922            let head = resume_observed_head(&mut state, &old).await.unwrap();
7923            assert_ne!(head, old);
7924            assert_eq!(state.land_sync_attempts, 1);
7925            assert!(state.land_sync_target.is_none());
7926            assert!(state.land_rebase_from.is_none());
7927            assert!(!state.land_sync_pending);
7928            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7929            assert!(state.gate_allows_progress());
7930            assert_eq!(
7931                git::remote_head(&state.repo, "origin", "task-head")
7932                    .await
7933                    .unwrap(),
7934                Some(head)
7935            );
7936            assert!(
7937                rebase_landing_worktree(&mut state, "origin/main")
7938                    .await
7939                    .unwrap_err()
7940                    .to_string()
7941                    .contains("budget exhausted")
7942            );
7943        }
7944    }
7945
7946    #[tokio::test]
7947    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
7948        let (_tmp, mut state, old) = landing_git_fixture().await;
7949        advance_landing_base(&state).await;
7950        state.config.verify.gate = vec!["test -f advance".into()];
7951        let head = resume_observed_head(&mut state, &old).await.unwrap();
7952        assert_ne!(head, old);
7953        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7954        assert!(state.gate_allows_progress());
7955        assert_eq!(
7956            git::remote_head(&state.repo, "origin", "task-head")
7957                .await
7958                .unwrap(),
7959            Some(head.clone())
7960        );
7961        assert_eq!(state.pr_pushed_head, Some(head));
7962        assert!(!state.land_sync_pending);
7963        assert!(state.config.graph.land_approval);
7964    }
7965
7966    fn landing_gate_fixer(state: &mut RunState, script: &str) {
7967        state.config.disk.min_free_bytes = 0;
7968        state.config.graph.gate_fix_rounds = 1;
7969        state.config.agents = vec![crate::config::AgentSpec {
7970            id: "mock".into(),
7971            kind: crate::config::AgentKind::Command,
7972            model: None,
7973            command: vec!["sh".into(), "-c".into(), script.into()],
7974            extra_args: Vec::new(),
7975            env: Default::default(),
7976            prompt_delivery: None,
7977            max_turn_secs: None,
7978        }];
7979        state.candidates[0].agent = "mock".into();
7980    }
7981
7982    #[tokio::test]
7983    async fn rebase_fixer_invocation_cap_survives_fallback_and_reload() {
7984        let (tmp, mut state, original) = landing_git_fixture().await;
7985        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7986        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7987        git::commit_all(&state.repo, "conflicting base")
7988            .await
7989            .unwrap();
7990        let target = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7991        git::git(&state.repo, &["checkout", "winner"])
7992            .await
7993            .unwrap();
7994        let scratch = state.dir().join("rebase");
7995        let counter = tmp.path().join("calls");
7996        landing_gate_fixer(
7997            &mut state,
7998            "echo \"$REBASE_AGENT\" >> \"$REBASE_COUNTER\"; exit 1",
7999        );
8000        let template = state.config.agents[0].clone();
8001        let ids = ["mock", "fallback1", "fallback2", "fallback3"].map(str::to_owned);
8002        state.config.agents = ids
8003            .iter()
8004            .map(|id| {
8005                let mut spec = template.clone();
8006                spec.id.clone_from(id);
8007                spec.env.insert("REBASE_AGENT".into(), id.clone());
8008                spec.env
8009                    .insert("REBASE_COUNTER".into(), git::path_arg(&counter));
8010                spec
8011            })
8012            .collect();
8013        state.config.roles.fixer = Some(crate::config::AgentChoice::Chain(ids.to_vec()));
8014        state.config.graph.review_rounds = 3;
8015        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8016        state.config.graph.timeout_resource_wait = 0;
8017        let started = git::rebase_start(&state.repo, &scratch, "winner", &target)
8018            .await
8019            .unwrap();
8020        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
8021        let home = crate::run::home();
8022        let cache = crate::build_target::resolve(&home, &scratch).unwrap();
8023        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", &scratch, &original);
8024        let crate::cache::AcquireOutcome::Acquired(lease) =
8025            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
8026        else {
8027            panic!("test target was already leased");
8028        };
8029        let error = crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8030            .await
8031            .unwrap_err();
8032        assert!(error.is::<crate::agent::IsolatedSeatWait>(), "{error:#}");
8033        assert!(!counter.exists());
8034        assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), ["change"]);
8035        drop(lease);
8036        state = RunState::load(&state.id).unwrap();
8037        for _ in 0..2 {
8038            let crate::rebase::Rebased::Stopped(why) =
8039                crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8040                    .await
8041                    .unwrap()
8042            else {
8043                panic!("the unresolved conflict must stop");
8044            };
8045            assert!(why.contains("after 3 of 3 fixer round(s)"), "{why}");
8046            assert_eq!(
8047                std::fs::read_to_string(&counter)
8048                    .unwrap()
8049                    .lines()
8050                    .collect::<Vec<_>>(),
8051                ["mock", "fallback1", "fallback2"]
8052            );
8053            assert_eq!(
8054                git::rev_parse(&state.repo, "winner").await.unwrap(),
8055                original
8056            );
8057            state = RunState::load(&state.id).unwrap();
8058        }
8059    }
8060
8061    #[tokio::test]
8062    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
8063        let (_tmp, mut state, old) = landing_git_fixture().await;
8064        std::fs::write(state.repo.join("change"), "operator update").unwrap();
8065        git::commit_all(&state.repo, "extend winner").await.unwrap();
8066        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8067        git::git(
8068            &state.repo,
8069            &["push", "origin", "HEAD:refs/heads/task-head"],
8070        )
8071        .await
8072        .unwrap();
8073        state.config.verify.gate = vec!["exit 1".into()];
8074        state.config.graph.gate_fix_rounds = 0;
8075        assert!(resume_observed_head(&mut state, &updated).await.is_err());
8076        assert_ne!(old, updated);
8077        assert_eq!(state.gate_head.as_ref(), Some(&updated));
8078        assert!(!state.gate_allows_progress());
8079        assert!(state.land_sync_pending);
8080        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
8081        let head = resume_observed_head(&mut state, &updated).await.unwrap();
8082        assert_eq!(head, updated);
8083        assert!(state.gate_allows_progress());
8084        assert!(!state.land_sync_pending);
8085        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8086        land_with(&mut state, &green_pr().url, &forge)
8087            .await
8088            .unwrap();
8089        assert!(state.parked);
8090        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8091        assert!(forge.argvs().is_empty());
8092    }
8093
8094    #[tokio::test]
8095    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
8096        for divergent in [false, true] {
8097            let (_tmp, mut state, old) = landing_git_fixture().await;
8098            if divergent {
8099                git::git(&state.repo, &["reset", "--hard", "origin/main"])
8100                    .await
8101                    .unwrap();
8102            }
8103            std::fs::write(state.repo.join("external"), "external").unwrap();
8104            git::commit_all(&state.repo, "external update")
8105                .await
8106                .unwrap();
8107            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8108            git::git(
8109                &state.repo,
8110                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
8111            )
8112            .await
8113            .unwrap();
8114            if !divergent {
8115                git::git(&state.repo, &["reset", "--hard", &old])
8116                    .await
8117                    .unwrap();
8118            }
8119            let error = resume_observed_head(&mut state, &external)
8120                .await
8121                .unwrap_err();
8122            assert!(
8123                error
8124                    .to_string()
8125                    .contains("public head moved outside this run")
8126            );
8127            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
8128            assert_eq!(
8129                git::remote_head(&state.repo, "origin", "task-head")
8130                    .await
8131                    .unwrap(),
8132                Some(external)
8133            );
8134        }
8135    }
8136
8137    #[tokio::test]
8138    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
8139        let (_tmp, mut state, old) = landing_git_fixture().await;
8140        advance_landing_base(&state).await;
8141        landing_gate_fixer(
8142            &mut state,
8143            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8144        );
8145        state.config.verify.gate =
8146            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8147        state.config.verify.e2e = vec!["test -f advance".into()];
8148        // First save a red gate without spending a fixer round. Resume must
8149        // still offer the remaining budget for this exact same failed head.
8150        state.config.graph.gate_fix_rounds = 0;
8151        assert!(resume_observed_head(&mut state, &old).await.is_err());
8152        assert_eq!(
8153            git::remote_head(&state.repo, "origin", "task-head")
8154                .await
8155                .unwrap(),
8156            Some(old.clone())
8157        );
8158        state.config.graph.gate_fix_rounds = 1;
8159        let head = resume_observed_head(&mut state, &old).await.unwrap();
8160        assert_eq!(state.gate_fixes.len(), 1);
8161        assert!(state.gate_fixes[0].committed);
8162        assert!(state.gate_allows_progress());
8163        assert_eq!(state.gate_head.as_ref(), Some(&head));
8164        assert_eq!(
8165            git::remote_head(&state.repo, "origin", "task-head")
8166                .await
8167                .unwrap(),
8168            Some(head.clone())
8169        );
8170        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8171        land_with(&mut state, &green_pr().url, &forge)
8172            .await
8173            .unwrap();
8174        assert!(state.parked);
8175        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8176        assert!(forge.argvs().is_empty());
8177    }
8178
8179    #[tokio::test]
8180    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
8181        let (_tmp, mut state, old) = landing_git_fixture().await;
8182        advance_landing_base(&state).await;
8183        landing_gate_fixer(
8184            &mut state,
8185            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8186        );
8187        state.config.verify.gate = vec!["echo still red; exit 1".into()];
8188        for _ in 0..2 {
8189            assert!(resume_observed_head(&mut state, &old).await.is_err());
8190            assert_eq!(state.gate_fixes.len(), 1);
8191            assert_eq!(
8192                git::remote_head(&state.repo, "origin", "task-head")
8193                    .await
8194                    .unwrap(),
8195                Some(old.clone())
8196            );
8197        }
8198    }
8199
8200    #[tokio::test]
8201    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
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 =
8209            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8210        // The repair makes the gate green while breaking an e2e invariant.
8211        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
8212        let mut saved_comparison = None;
8213        for resume in 0..3 {
8214            assert!(resume_observed_head(&mut state, &old).await.is_err());
8215            state = RunState::load(&state.id).unwrap();
8216            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8217            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8218            assert_eq!(evidence.head, head);
8219            assert!(!evidence.passed);
8220            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
8221            let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
8222            if let Some(saved) = &saved_comparison {
8223                assert_eq!(comparison, saved);
8224            } else {
8225                saved_comparison = Some(comparison.clone());
8226            }
8227            assert_eq!(state.gate_fixes.len(), 1);
8228            assert_eq!(
8229                git::remote_head(&state.repo, "origin", "task-head")
8230                    .await
8231                    .unwrap(),
8232                Some(old.clone())
8233            );
8234            if resume > 0 {
8235                assert!(
8236                    state.gate_allows_progress(),
8237                    "a green gate must not bypass red e2e"
8238                );
8239            }
8240        }
8241        // A changed command is not new evidence about the already checked SHA.
8242        state.config.verify.e2e = vec!["grep -q fixed change".into()];
8243        assert!(resume_observed_head(&mut state, &old).await.is_err());
8244        assert_eq!(
8245            state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
8246            saved_comparison
8247        );
8248    }
8249
8250    #[tokio::test]
8251    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
8252        for phase in 0..3 {
8253            let (_tmp, mut state, old) = landing_git_fixture().await;
8254            advance_landing_base(&state).await;
8255            let head = resume_observed_head(&mut state, &old).await.unwrap();
8256            // Persist the shapes left by interruption, resource deferral,
8257            // and a successful check for a different (older) SHA.
8258            state.land_sync_pending = true;
8259            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
8260            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8261                if phase == 2 {
8262                    old.clone()
8263                } else {
8264                    head.clone()
8265                },
8266                phase == 2,
8267                if phase == 1 {
8268                    vec![crate::run::CommandOutcome {
8269                        command: state.config.verify.e2e[0].clone(),
8270                        code: None,
8271                        output_tail: "verification resource unavailable".into(),
8272                        duration_ms: 0,
8273                        resource_blocked: true,
8274                        ..Default::default()
8275                    }]
8276                } else {
8277                    Vec::new()
8278                },
8279            ));
8280            state.save().unwrap();
8281            for _ in 0..2 {
8282                state = RunState::load(&state.id).unwrap();
8283                assert!(resume_observed_head(&mut state, &head).await.is_err());
8284                let evidence = state.gate_repair_e2e.as_ref().unwrap();
8285                assert_eq!(evidence.head, head);
8286                assert!(!evidence.passed);
8287                assert!(!evidence.outcomes.is_empty());
8288                assert_eq!(
8289                    git::remote_head(&state.repo, "origin", "task-head")
8290                        .await
8291                        .unwrap(),
8292                    Some(head.clone())
8293                );
8294                assert!(state.land_sync_pending);
8295            }
8296        }
8297    }
8298
8299    #[tokio::test]
8300    async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
8301        for code in [None, Some(126), Some(127)] {
8302            let (_tmp, mut state, old) = landing_git_fixture().await;
8303            advance_landing_base(&state).await;
8304            let head = resume_observed_head(&mut state, &old).await.unwrap();
8305            state.land_sync_pending = true;
8306            state.config.verify.e2e = vec!["true".into()];
8307            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8308                head.clone(),
8309                false,
8310                vec![crate::run::CommandOutcome {
8311                    command: state.config.verify.e2e[0].clone(),
8312                    code,
8313                    output_tail: "verification command did not complete".into(),
8314                    ..Default::default()
8315                }],
8316            ));
8317            state.save().unwrap();
8318            state = RunState::load(&state.id).unwrap();
8319            assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
8320            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8321            assert_eq!(evidence.head, head);
8322            assert!(evidence.passed);
8323            assert_eq!(evidence.outcomes[0].code, Some(0));
8324        }
8325    }
8326
8327    async fn interrupt_landing_rebase(state: &mut RunState) {
8328        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
8329        state.save().unwrap();
8330        let scratch = state.dir().join("rebase");
8331        assert_eq!(
8332            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
8333                .await
8334                .unwrap(),
8335            crate::rebase::Rebased::Applied
8336        );
8337        assert!(!git::is_clean(&state.repo).await.unwrap());
8338    }
8339
8340    async fn landing_setup(state: &mut RunState) {
8341        git::git(
8342            &state.repo,
8343            &["config", "extensions.worktreeConfig", "true"],
8344        )
8345        .await
8346        .unwrap();
8347        state.config.worktree.setup =
8348            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8349        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8350            .await
8351            .unwrap();
8352        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8353    }
8354
8355    #[tokio::test]
8356    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8357        let (tmp, mut state, head) = landing_git_fixture().await;
8358        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8359        git::acquire_worktree_config(&state.repo).await.unwrap();
8360        let winner = tmp.path().join("landing");
8361        git::worktree_add_existing(&state.repo, &winner, "winner", false)
8362            .await
8363            .unwrap();
8364        state.candidates[0].worktree = winner.clone();
8365        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8366        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8367        state.config.disk.min_free_bytes = 0;
8368        state.config.worktree.setup = vec![crate::config::SetupStep {
8369            run: Some("touch setup-completed".into()),
8370            ..Default::default()
8371        }];
8372        #[cfg(unix)]
8373        {
8374            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8375            state.config.coordination = Some(crate::config::Coordination {
8376                contract_file: "fixture-contract".into(),
8377                contract_token: "fixture-v1".into(),
8378                lock_file: "fixture-lock".into(),
8379            });
8380        }
8381        state.land_rebase_from = Some(head);
8382        let restore = restore_landing_worktree(&mut state);
8383        // Only the registered Unix fixture can deadlock by reacquiring its
8384        // own operation lease. Don't time the whole Git/setup path elsewhere.
8385        #[cfg(unix)]
8386        let restore = async {
8387            tokio::time::timeout(Duration::from_secs(15), restore)
8388                .await
8389                .expect("landing setup must not wait for its own repository operation")
8390        };
8391        restore.await.unwrap();
8392        assert!(winner.join("setup-completed").is_file());
8393        assert!(git::is_clean(&winner).await.unwrap());
8394        assert!(state.land_rebase_from.is_none());
8395    }
8396
8397    #[tokio::test]
8398    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8399        for phase in 0..3 {
8400            let (_tmp, mut state, old) = landing_git_fixture().await;
8401            advance_landing_base(&state).await;
8402            landing_setup(&mut state).await;
8403            if phase > 0 {
8404                interrupt_landing_rebase(&mut state).await;
8405                if phase == 2 {
8406                    // Crash after clean removed setup products, before setup.
8407                    git::sync_to_head(&state.repo).await.unwrap();
8408                    assert!(!state.repo.join(".env").exists());
8409                }
8410                state = RunState::load(&state.id).unwrap();
8411            }
8412            let head = resume_observed_head(&mut state, &old).await.unwrap();
8413            assert_ne!(head, old);
8414            assert!(state.gate_allows_progress());
8415            assert!(state.land_rebase_from.is_none());
8416            assert_eq!(
8417                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8418                "secret"
8419            );
8420            assert!(git::is_clean(&state.repo).await.unwrap());
8421            assert!(
8422                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8423                    .await
8424                    .unwrap()
8425                    .contains(".env")
8426            );
8427        }
8428    }
8429
8430    #[tokio::test]
8431    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8432        let (_tmp, mut state, _) = landing_git_fixture().await;
8433        advance_landing_base(&state).await;
8434        landing_setup(&mut state).await;
8435        interrupt_landing_rebase(&mut state).await;
8436        // Exercise unusual names without asking Windows to create an invalid
8437        // control-character filename. Unix also covers embedded newlines.
8438        let locals = [
8439            "local notes",
8440            #[cfg(unix)]
8441            "local\nnotes",
8442        ];
8443        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8444            .await
8445            .unwrap();
8446        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8447        for local in locals {
8448            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8449            assert!(
8450                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8451                    .await
8452                    .unwrap()
8453                    .ok()
8454            );
8455        }
8456        restore_landing_worktree(&mut state).await.unwrap();
8457        for local in locals {
8458            assert_eq!(
8459                std::fs::read_to_string(state.repo.join(local)).unwrap(),
8460                "keep these notes"
8461            );
8462        }
8463        assert_eq!(
8464            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8465            "secret"
8466        );
8467        assert!(git::is_clean(&state.repo).await.unwrap());
8468        assert!(state.land_rebase_from.is_none());
8469    }
8470
8471    #[tokio::test]
8472    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8473        for local in ["advance", "advance/notes", "new-directory"] {
8474            let (_tmp, mut state, _) = landing_git_fixture().await;
8475            advance_landing_base(&state).await;
8476            // Also cover a local file blocking a new tracked directory.
8477            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8478            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8479            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8480            git::git(&state.repo, &["add", "."]).await.unwrap();
8481            git::git(&state.repo, &["commit", "-m", "add directory"])
8482                .await
8483                .unwrap();
8484            git::git(&state.repo, &["push", "origin", "main"])
8485                .await
8486                .unwrap();
8487            git::git(&state.repo, &["checkout", "winner"])
8488                .await
8489                .unwrap();
8490            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8491                .await
8492                .unwrap();
8493            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8494            let path = state.repo.join(local);
8495            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8496            std::fs::write(&path, "local notes").unwrap();
8497            interrupt_landing_rebase(&mut state).await;
8498            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8499            let checkpoint = state.land_rebase_from.clone();
8500            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8501            assert!(
8502                error.to_string().contains("conflicting with HEAD"),
8503                "{error:#}"
8504            );
8505            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8506            assert_eq!(
8507                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8508                before
8509            );
8510            assert_eq!(state.land_rebase_from, checkpoint);
8511        }
8512    }
8513
8514    #[tokio::test]
8515    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8516        for interrupted in [false, true] {
8517            let (_tmp, mut state, old) = landing_git_fixture().await;
8518            assert!(state.config.worktree.setup.is_empty());
8519            // A gate product exists before the base moves, without setup metadata.
8520            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8521                .await
8522                .unwrap();
8523            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8524            state.config.verify.gate =
8525                vec!["mkdir -p target && printf artifact > target/probe".into()];
8526            state.gate_ran = false;
8527            resume_observed_head(&mut state, &old).await.unwrap();
8528            assert_eq!(
8529                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8530                "artifact"
8531            );
8532            advance_landing_base(&state).await;
8533            if interrupted {
8534                interrupt_landing_rebase(&mut state).await;
8535                state = RunState::load(&state.id).unwrap();
8536            }
8537            state.config.verify.gate =
8538                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8539            let head = resume_observed_head(&mut state, &old).await.unwrap();
8540            assert_ne!(head, old);
8541            assert!(state.gate_allows_progress());
8542            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8543            assert_eq!(
8544                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8545                "artifact"
8546            );
8547            assert!(state.land_rebase_from.is_none());
8548            assert_eq!(
8549                git::remote_head(&state.repo, "origin", "task-head")
8550                    .await
8551                    .unwrap(),
8552                Some(head.clone())
8553            );
8554            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8555            land_with(&mut state, &green_pr().url, &forge)
8556                .await
8557                .unwrap();
8558            assert!(state.parked);
8559            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8560            assert!(forge.argvs().is_empty());
8561        }
8562    }
8563
8564    #[tokio::test]
8565    #[cfg(unix)]
8566    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8567        use std::os::fd::AsRawFd as _;
8568
8569        for interrupted in [false, true] {
8570            let (_tmp, mut state, _) = landing_git_fixture().await;
8571            advance_landing_base(&state).await;
8572            landing_setup(&mut state).await;
8573            if interrupted {
8574                interrupt_landing_rebase(&mut state).await;
8575            }
8576            state.config.worktree.setup =
8577                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8578            let common = crate::repo_lock::common_dir(&state.repo)
8579                .await
8580                .unwrap()
8581                .unwrap();
8582            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8583            state.config.coordination = crate::config::test_coordination();
8584            state.config.graph.timeout_resource_wait = 0;
8585            let external = std::fs::OpenOptions::new()
8586                .read(true)
8587                .write(true)
8588                .create(true)
8589                .truncate(false)
8590                .open(common.join("updater.lock"))
8591                .unwrap();
8592            // SAFETY: the descriptor belongs to `external` and remains open.
8593            let locked =
8594                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8595            assert_eq!(locked, 0);
8596            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8597            let checkpoint = state.land_rebase_from.clone();
8598            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8599            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8600            assert_eq!(
8601                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8602                before
8603            );
8604            assert_eq!(state.land_rebase_from, checkpoint);
8605            assert_eq!(
8606                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8607                "secret"
8608            );
8609
8610            drop(external);
8611            state.config.graph.timeout_resource_wait = 2;
8612            restore_landing_worktree(&mut state).await.unwrap();
8613            assert!(git::is_clean(&state.repo).await.unwrap());
8614            assert!(state.land_rebase_from.is_none());
8615            assert_eq!(
8616                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8617                "restored"
8618            );
8619        }
8620    }
8621
8622    #[tokio::test]
8623    #[cfg(unix)]
8624    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8625        use std::sync::atomic::{AtomicBool, Ordering};
8626
8627        let (_tmp, mut state, _) = landing_git_fixture().await;
8628        advance_landing_base(&state).await;
8629        landing_setup(&mut state).await;
8630        interrupt_landing_rebase(&mut state).await;
8631        let common = crate::repo_lock::common_dir(&state.repo)
8632            .await
8633            .unwrap()
8634            .unwrap();
8635        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8636        state.config.coordination = crate::config::test_coordination();
8637        let holder = crate::repo_lock::SeatLease::for_checkout(
8638            &state.repo,
8639            true,
8640            state.config.coordination.as_ref(),
8641        )
8642        .await
8643        .unwrap();
8644        assert!(holder.is_some());
8645        let cancelled = Arc::new(AtomicBool::new(false));
8646        let signal = cancelled.clone();
8647        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8648            signal.load(Ordering::SeqCst)
8649        });
8650        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8651        let checkpoint = state.land_rebase_from.clone();
8652        let (result, ()) = tokio::join!(
8653            tokio::time::timeout(
8654                Duration::from_secs(2),
8655                wait.scope(restore_landing_worktree(&mut state)),
8656            ),
8657            async {
8658                tokio::time::sleep(Duration::from_millis(100)).await;
8659                cancelled.store(true, Ordering::SeqCst);
8660            }
8661        );
8662        let error = result
8663            .expect("cancellation must release the waiting driver")
8664            .unwrap_err();
8665        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8666        assert_eq!(
8667            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8668            before
8669        );
8670        assert_eq!(state.land_rebase_from, checkpoint);
8671        assert_eq!(
8672            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8673            "secret"
8674        );
8675        drop(holder);
8676        restore_landing_worktree(&mut state).await.unwrap();
8677        assert!(state.land_rebase_from.is_none());
8678        assert!(git::is_clean(&state.repo).await.unwrap());
8679    }
8680
8681    #[tokio::test]
8682    #[cfg(unix)]
8683    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8684        use std::sync::atomic::{AtomicBool, Ordering};
8685
8686        for e2e in [false, true] {
8687            let (_tmp, mut state, head) = landing_git_fixture().await;
8688            let common = crate::repo_lock::common_dir(&state.repo)
8689                .await
8690                .unwrap()
8691                .unwrap();
8692            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8693            state.config.coordination = crate::config::test_coordination();
8694            if e2e {
8695                state.config.verify.e2e = vec!["true".into()];
8696                state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8697                    head.clone(),
8698                    false,
8699                    Vec::new(),
8700                ));
8701            } else {
8702                state.config.verify.gate = vec!["true".into()];
8703                state.gate_ran = false;
8704            }
8705            let holder = crate::repo_lock::SeatLease::for_checkout(
8706                &state.repo,
8707                true,
8708                state.config.coordination.as_ref(),
8709            )
8710            .await
8711            .unwrap();
8712            assert!(holder.is_some());
8713            let cancelled = Arc::new(AtomicBool::new(false));
8714            let signal = cancelled.clone();
8715            let waiting = Arc::new(tokio::sync::Notify::new());
8716            let observed = waiting.clone();
8717            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8718                observed.notify_one();
8719                signal.load(Ordering::SeqCst)
8720            });
8721            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8722            let url = green_pr().url;
8723            let result = {
8724                let mut publishing =
8725                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8726                // Git and fixture I/O precede local coordination. Start the
8727                // cancellation deadline only once the inherited wait policy
8728                // is polled, rather than timing those unrelated subprocesses.
8729                tokio::time::timeout(Duration::from_secs(30), async {
8730                    tokio::select! {
8731                        result = &mut publishing => panic!(
8732                            "verification must wait behind the held seat: {result:?}"
8733                        ),
8734                        () = waiting.notified() => {}
8735                    }
8736                })
8737                .await
8738                .expect("verification must reach the inherited coordination wait");
8739                cancelled.store(true, Ordering::SeqCst);
8740                tokio::time::timeout(Duration::from_secs(2), publishing).await
8741            };
8742            let error = result
8743                .expect("cancellation must release the verification waiter")
8744                .unwrap_err();
8745            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8746            assert!(error.to_string().contains("cancelled"), "{error:#}");
8747            assert!(forge.argvs().is_empty());
8748            assert_eq!(
8749                git::remote_head(&state.repo, "origin", "task-head")
8750                    .await
8751                    .unwrap(),
8752                Some(head.clone())
8753            );
8754            drop(holder);
8755            // Cancellation must release its reservation so another attempt can verify.
8756            assert_eq!(
8757                publish_landing_head(&mut state, &head, &url, &forge)
8758                    .await
8759                    .unwrap(),
8760                head
8761            );
8762        }
8763    }
8764
8765    #[tokio::test]
8766    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
8767        for staged in [false, true] {
8768            let (_tmp, mut state, old) = landing_git_fixture().await;
8769            advance_landing_base(&state).await;
8770            interrupt_landing_rebase(&mut state).await;
8771            std::fs::write(state.repo.join("change"), "user edit").unwrap();
8772            if staged {
8773                git::git(&state.repo, &["add", "change"]).await.unwrap();
8774            }
8775            assert!(resume_observed_head(&mut state, &old).await.is_err());
8776            assert_eq!(
8777                std::fs::read_to_string(state.repo.join("change")).unwrap(),
8778                "user edit"
8779            );
8780            assert_eq!(
8781                git::remote_head(&state.repo, "origin", "task-head")
8782                    .await
8783                    .unwrap(),
8784                Some(old)
8785            );
8786        }
8787    }
8788
8789    #[tokio::test]
8790    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
8791        let (_tmp, mut state, head) = landing_git_fixture().await;
8792        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8793        let id = state.id.clone();
8794        let pr = land_with(&mut state, &green_pr().url, &forge)
8795            .await
8796            .unwrap();
8797        assert_eq!(pr.state, PrLifecycle::Open);
8798        assert_eq!(state.id, id);
8799        assert!(state.parked);
8800        assert_eq!(state.status, RunStatus::Landing);
8801        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8802        assert!(forge.argvs().is_empty());
8803
8804        state.land_sync_pending = true;
8805        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
8806        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
8807        closed.pr.state = PrLifecycle::Closed;
8808        let forge = Scripted::new(vec![closed], vec![]);
8809        assert_eq!(
8810            land_with(&mut state, &green_pr().url, &forge)
8811                .await
8812                .unwrap()
8813                .state,
8814            PrLifecycle::Closed
8815        );
8816        assert_eq!(
8817            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
8818            "do not touch"
8819        );
8820        assert!(forge.argvs().is_empty());
8821    }
8822
8823    #[tokio::test]
8824    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
8825        let (_tmp, mut state, old) = landing_git_fixture().await;
8826        advance_landing_base(&state).await;
8827        state.config.verify.gate = vec!["exit 1".into()];
8828        assert!(resume_observed_head(&mut state, &old).await.is_err());
8829        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
8830        assert!(!state.gate_allows_progress());
8831        assert_eq!(
8832            git::remote_head(&state.repo, "origin", "task-head")
8833                .await
8834                .unwrap(),
8835            Some(old)
8836        );
8837        assert!(state.land_sync_pending);
8838    }
8839
8840    #[tokio::test]
8841    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
8842        let (_tmp, mut state, old) = landing_git_fixture().await;
8843        advance_landing_base(&state).await;
8844        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
8845        // Model a crash after the push but before saving its published SHA.
8846        state.pr_pushed_head = Some(old.clone());
8847        state.land_sync_pending = true;
8848        assert_eq!(
8849            resume_observed_head(&mut state, &pushed).await.unwrap(),
8850            pushed
8851        );
8852        // A writer races the observed PR snapshot: the explicit remote lease
8853        // must reject the push even though preflight saw our expected head.
8854        git::git(
8855            &state.repo,
8856            &["push", "--force", "origin", "main:refs/heads/task-head"],
8857        )
8858        .await
8859        .unwrap();
8860        assert!(
8861            publish_landing_head(
8862                &mut state,
8863                &pushed,
8864                &green_pr().url,
8865                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
8866            )
8867            .await
8868            .unwrap_err()
8869            .to_string()
8870            .contains("publishing gated")
8871        );
8872        assert!(
8873            resume_observed_head(&mut state, "foreign-head")
8874                .await
8875                .is_err()
8876        );
8877    }
8878    #[tokio::test]
8879    async fn landing_publication_refuses_a_pr_closed_during_gate() {
8880        let (_tmp, mut state, head) = landing_git_fixture().await;
8881        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
8882        closed.pr.state = PrLifecycle::Closed;
8883        let forge = Scripted::new(vec![closed], vec![]);
8884        assert!(
8885            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
8886                .await
8887                .unwrap_err()
8888                .to_string()
8889                .contains("PR closed or merged")
8890        );
8891    }
8892
8893    /// A candidate selected by the uncontested tally.
8894    fn winning_candidate(summary: &str) -> Candidate {
8895        Candidate {
8896            index: 0,
8897            label: 'A',
8898            agent: "opus".to_owned(),
8899            branch: "magi/x/A".to_owned(),
8900            worktree: PathBuf::from("/wt/A"),
8901            summary: summary.to_owned(),
8902            stat: String::new(),
8903            files: 1,
8904            commits: 1,
8905            empty: false,
8906            failed: None,
8907            verified_noop: None,
8908            duration_ms: 0,
8909            folded: false,
8910        }
8911    }
8912
8913    fn uncontested_tally() -> Tally {
8914        Tally {
8915            first_choice: BTreeMap::from([('A', 1)]),
8916            borda: BTreeMap::new(),
8917            winner: 'A',
8918            rankings: 1,
8919            unanimous_initial: true,
8920            deliberated: false,
8921            changed_votes: 0,
8922            unanimous_final: true,
8923            tie_break: None,
8924            judges: 1,
8925            present: 1,
8926            quorum: 1,
8927            met_quorum: true,
8928            uncontested: None,
8929        }
8930    }
8931
8932    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
8933        ReviewRecord {
8934            attempts: 0,
8935            reviewer,
8936            agent: agent.to_owned(),
8937            summary: summary.to_owned(),
8938            findings: Vec::new(),
8939            vote: None,
8940            failed: None,
8941            duration_ms: 0,
8942        }
8943    }
8944
8945    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
8946        let answered = reviews.len();
8947        ReviewRound {
8948            round,
8949            head: "abc1234".to_owned(),
8950            verified_head: None,
8951            verified_at: None,
8952            reviews,
8953            e2e: Vec::new(),
8954            verify_retried: false,
8955            e2e_deferred: false,
8956            e2e_defer_reason: None,
8957            fix: None,
8958            blocking: 0,
8959            answered,
8960            expected: answered,
8961            clean: true,
8962            progressed: false,
8963            vote_split: false,
8964            reconsideration: Vec::new(),
8965            verdict: None,
8966        }
8967    }
8968
8969    #[test]
8970    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
8971        let en = panel();
8972        assert!(en.contains("Task"), "{en}");
8973        assert!(en.contains("add retries to the uploader"), "{en}");
8974
8975        let mut state = run_state();
8976        state.config.graph.language = "ja".to_owned();
8977        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8978        assert!(ja.contains("タスク"), "{ja}");
8979        assert!(
8980            ja.contains("add retries to the uploader"),
8981            "the task itself is not translated: {ja}"
8982        );
8983    }
8984
8985    #[test]
8986    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
8987        // `run_state()` has no candidates, no tally and no reviews - exactly
8988        // the shape a run has before anything has judged or reviewed it, and
8989        // the panel must not print an empty box for either.
8990        let html = panel();
8991        assert!(!html.contains("What changed"), "{html}");
8992        assert!(!html.contains("Review verdict"), "{html}");
8993    }
8994
8995    #[test]
8996    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
8997        let mut state = run_state();
8998        state.candidates = vec![winning_candidate("")];
8999        state.tally = Some(uncontested_tally());
9000        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9001        assert!(
9002            !html.contains("What changed"),
9003            "an empty summary must not render an empty box: {html}"
9004        );
9005    }
9006
9007    #[test]
9008    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
9009        let mut state = run_state();
9010        state.candidates = vec![winning_candidate(
9011            "Added a retry loop around the uploader PUT call.",
9012        )];
9013        state.tally = Some(uncontested_tally());
9014        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9015        assert!(en.contains("What changed"), "{en}");
9016        assert!(
9017            en.contains("Added a retry loop around the uploader PUT call."),
9018            "{en}"
9019        );
9020
9021        state.config.graph.language = "ja".to_owned();
9022        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9023        assert!(ja.contains("変更内容"), "{ja}");
9024        assert!(
9025            ja.contains("Added a retry loop around the uploader PUT call."),
9026            "{ja}"
9027        );
9028    }
9029
9030    #[test]
9031    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
9032        let mut state = run_state();
9033        state.reviews = vec![
9034            review_round(
9035                1,
9036                vec![review_record(1, "alpha", "found a race, sent back")],
9037            ),
9038            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
9039        ];
9040        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9041        assert!(en.contains("Review verdict"), "{en}");
9042        assert!(en.contains("race is fixed, clean"), "{en}");
9043        assert!(
9044            !en.contains("found a race, sent back"),
9045            "only the round that actually cleared the merge should show: {en}"
9046        );
9047
9048        state.config.graph.language = "ja".to_owned();
9049        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9050        assert!(ja.contains("レビューの結論"), "{ja}");
9051        assert!(ja.contains("レビュアー"), "{ja}");
9052        assert!(ja.contains("race is fixed, clean"), "{ja}");
9053    }
9054
9055    /// The `incomplete_review = "warn"` policy (see
9056    /// `graph::Runner::review_loop`) can push a `clean` round to
9057    /// `state.reviews` while one seat's own record still has `failed: Some`
9058    /// and an empty `summary` - a seat that never answered, not one that
9059    /// answered with nothing to say.
9060    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
9061        ReviewRecord {
9062            attempts: 0,
9063            reviewer,
9064            agent: agent.to_owned(),
9065            summary: String::new(),
9066            findings: Vec::new(),
9067            vote: None,
9068            failed: Some(reason.to_owned()),
9069            duration_ms: 0,
9070        }
9071    }
9072
9073    #[test]
9074    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
9075        let mut state = run_state();
9076        state.reviews = vec![review_round(
9077            1,
9078            vec![
9079                review_record(1, "alpha", "clean, nothing to add"),
9080                unanswered_review_record(2, "beta", "timed out"),
9081            ],
9082        )];
9083        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9084        assert!(en.contains("clean, nothing to add"), "{en}");
9085        assert!(
9086            en.contains("produced no answer: timed out"),
9087            "a seat that never answered must say so, not render a blank box: {en}"
9088        );
9089        assert!(
9090            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
9091            "no reviewer box may be left empty: {en}"
9092        );
9093
9094        state.config.graph.language = "ja".to_owned();
9095        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9096        assert!(ja.contains("回答なし: timed out"), "{ja}");
9097    }
9098
9099    #[test]
9100    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
9101        let html = panel();
9102        assert!(!html.contains("<script"), "no script survives the csp");
9103        assert!(!html.contains("<form"), "form-action is 'none'");
9104        let pr = green_pr();
9105        assert_eq!(
9106            html.matches("http").count(),
9107            html.matches(pr.url.as_str()).count(),
9108            "the only http url in the panel is the pull request's own link"
9109        );
9110        assert!(
9111            html.contains("target=\"_blank\""),
9112            "the PR link must open in a new tab so it escapes the iframe"
9113        );
9114        assert!(
9115            html.contains("rel=\"noopener noreferrer\""),
9116            "external links opening in new tabs must carry noopener noreferrer"
9117        );
9118    }
9119
9120    #[test]
9121    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
9122        let html = panel();
9123        assert!(
9124            html.contains(">+</span>"),
9125            "an added line carries a `+` in the gutter, not only a background"
9126        );
9127        assert!(
9128            html.contains(">-</span>"),
9129            "a removed line carries a `-` in the gutter, not only a background"
9130        );
9131        assert!(
9132            html.contains(">new line</span>"),
9133            "the marker is moved to the gutter, so the body is printed once without it"
9134        );
9135    }
9136
9137    #[test]
9138    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
9139        let total = DIFF_MAX_LINES + 100;
9140        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
9141        let html = approval_panel(
9142            &run_state(),
9143            &green_pr(),
9144            NUMSTAT,
9145            &diff,
9146            &[],
9147            "feat: something long",
9148        );
9149        assert!(
9150            html.contains(&format!("100 of {total} diff lines omitted")),
9151            "the note must say exactly how much was cut"
9152        );
9153        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
9154        assert!(
9155            !html.contains(&format!("line {DIFF_MAX_LINES}")),
9156            "nothing past the threshold is rendered"
9157        );
9158        assert!(
9159            html.contains("/repo/magi"),
9160            "the note says where the rest is"
9161        );
9162    }
9163
9164    #[test]
9165    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
9166        let html = approval_panel(
9167            &run_state(),
9168            &green_pr(),
9169            "1\t2\tsrc/<b>&\"x\"'.rs",
9170            "",
9171            &[],
9172            "subject",
9173        );
9174        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
9175        assert!(
9176            !html.contains("<b>"),
9177            "an agent-influenced path must never become markup"
9178        );
9179    }
9180
9181    #[tokio::test]
9182    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
9183        let a = std::path::PathBuf::from("/repo/a");
9184        let b = std::path::PathBuf::from("/repo/b");
9185
9186        let held = repo_merge_lock(&a).lock_owned().await;
9187
9188        // A second, concurrent land run against the *same* repository must
9189        // wait - `try_lock` fails while `held` is alive.
9190        assert!(
9191            repo_merge_lock(&a).try_lock().is_err(),
9192            "a second merge into the same repository must not proceed concurrently"
9193        );
9194
9195        // A run against a *different* repository must not be blocked by it -
9196        // this is what keeps a slow rebase or `gh pr merge` in one
9197        // repository from also stalling a land-approval resume in another.
9198        assert!(
9199            repo_merge_lock(&b).try_lock().is_ok(),
9200            "a different repository's merge lock must be independent"
9201        );
9202
9203        drop(held);
9204        assert!(
9205            repo_merge_lock(&a).try_lock().is_ok(),
9206            "the lock is released once the holder is done"
9207        );
9208    }
9209
9210    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
9211        let mut state = landing_state();
9212        let mut rec = review_record(1, "alpha", "precise rejection reason");
9213        rec.vote = Some(if reject {
9214            crate::verdict::ReviewVote::Reject
9215        } else {
9216            crate::verdict::ReviewVote::Approve
9217        });
9218        if major {
9219            rec.findings = contested().findings;
9220        }
9221        let mut round = review_round(1, vec![rec]);
9222        round.clean = false;
9223        round.blocking = usize::from(major);
9224        state.reviews.push(round);
9225        state.config.graph.review_rounds = 1;
9226        state
9227    }
9228
9229    #[test]
9230    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
9231        for every in [false, true] {
9232            for contested in [false, true] {
9233                for major in [false, true] {
9234                    for reject in [false, true] {
9235                        let mut state = repair_state(major, reject);
9236                        state.config.graph.land_approval = every;
9237                        state.config.graph.hold_contested_merge = contested;
9238                        let reasons = approval_reasons(&state);
9239                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
9240                        assert_eq!(
9241                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
9242                            contested && major
9243                        );
9244                        assert_eq!(
9245                            reasons.contains(&ApprovalReason::FinalReject),
9246                            contested && reject
9247                        );
9248                        assert_eq!(
9249                            reasons.len(),
9250                            usize::from(every)
9251                                + usize::from(contested && major)
9252                                + usize::from(contested && reject)
9253                        );
9254                    }
9255                }
9256            }
9257        }
9258    }
9259
9260    #[test]
9261    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
9262        use crate::verdict::ReviewVote::{Approve, Reject};
9263        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
9264            let mut state = repair_state(false, initial_reject);
9265            state.reviews[0]
9266                .reconsideration
9267                .push(crate::run::ReviewRevoteRecord {
9268                    reviewer: 1,
9269                    agent: "alpha".into(),
9270                    vote: Some(final_vote),
9271                    reason: "changed after reading the panel <evidence>".into(),
9272                    failed: None,
9273                });
9274            assert_eq!(
9275                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9276                final_vote == Reject
9277            );
9278            for language in ["en", "ja"] {
9279                state.config.graph.language = language.into();
9280                let evidence = approval_evidence(&state);
9281                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
9282                assert!(evidence.contains("changed after reading the panel <evidence>"));
9283                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9284                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
9285                assert!(!html.contains("<evidence>"));
9286            }
9287            state.reviews[0].reconsideration[0].vote = None;
9288            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
9289            assert_eq!(
9290                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9291                initial_reject
9292            );
9293            assert!(approval_evidence(&state).contains("timed out"));
9294        }
9295    }
9296
9297    #[tokio::test]
9298    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
9299        for every in [false, true] {
9300            for contested in [false, true] {
9301                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
9302                {
9303                    let mut state = repair_state(major, reject);
9304                    state.config.graph.land_approval = every;
9305                    state.config.graph.hold_contested_merge = contested;
9306                    let forge = Scripted::new(
9307                        vec![seen("abc", Checks::Green, "CLEAN", false)],
9308                        vec![(true, "")],
9309                    );
9310                    land_with(&mut state, URL, &forge).await.unwrap();
9311                    let expected = every || (contested && (major || reject));
9312                    assert_eq!(state.land_approval.is_some(), expected);
9313                    assert_eq!(forge.calls().contains(&"merge"), !expected);
9314                    if expected {
9315                        assert!(state.parked);
9316                    }
9317                }
9318            }
9319        }
9320    }
9321
9322    #[tokio::test]
9323    async fn reviewed_branch_hold_is_read_before_landing_decision() {
9324        for (base, control) in [
9325            (false, "land_approval"),
9326            (true, "land_approval"),
9327            (false, "hold_contested_merge"),
9328        ] {
9329            let (_tmp, mut state, _) = landing_git_fixture().await;
9330            state.config.graph.land_approval = base;
9331            state.config.graph.hold_contested_merge = false;
9332            state.reviewed_commits = Some(Vec::new());
9333            if control == "hold_contested_merge" {
9334                state.reviews = repair_state(false, true).reviews;
9335            }
9336            std::fs::write(
9337                state.repo.join("magi.toml"),
9338                format!("[graph]\n{control} = {}\n", !base),
9339            )
9340            .unwrap();
9341            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
9342            git::git(&state.repo, &["commit", "-m", "approval policy"])
9343                .await
9344                .unwrap();
9345            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9346            state.land_sync_pending = false;
9347            state.pr_pushed_head = Some(head.clone());
9348            state.gate_head = Some(head.clone());
9349            let forge = Scripted::new(
9350                vec![seen(&head, Checks::Green, "CLEAN", false)],
9351                vec![(true, "")],
9352            );
9353            land_with(&mut state, URL, &forge).await.unwrap();
9354            assert!(
9355                state.land_approval.is_some(),
9356                "base={base}, control={control}"
9357            );
9358            assert!(!forge.calls().contains(&"merge"));
9359            if !base {
9360                let question = ask::Questions::open()
9361                    .get(&state.land_approval.as_ref().unwrap().question)
9362                    .unwrap();
9363                assert!(question.detail.contains(&format!(
9364                    "{control}=true from the reviewed branch's magi.toml"
9365                )));
9366            }
9367        }
9368    }
9369
9370    #[tokio::test]
9371    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9372        for file in ["magi.toml", ".magi/config.toml"] {
9373            for control in crate::config::OwnerHold::ALL {
9374                let (_tmp, mut state, _) = landing_git_fixture().await;
9375                state.config.graph.land_approval = false;
9376                state.config.graph.hold_contested_merge = false;
9377                state.reviewed_commits = Some(Vec::new());
9378                if control == crate::config::OwnerHold::HoldContestedMerge {
9379                    state.reviews = repair_state(false, true).reviews;
9380                }
9381                let config = state.repo.join(file);
9382                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9383                std::fs::write(
9384                    &config,
9385                    format!(
9386                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9387                        control.key()
9388                    ),
9389                )
9390                .unwrap();
9391                git::git(&state.repo, &["add", file]).await.unwrap();
9392                git::git(&state.repo, &["commit", "-m", "require approval"])
9393                    .await
9394                    .unwrap();
9395                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9396                let gate = state.config.verify.gate.clone();
9397                state.observe_branch_owner_holds(&head).await;
9398                assert_eq!(state.config.verify.gate, gate);
9399                assert!(state.owner_hold(control));
9400                let holds = state.branch_owner_holds.clone();
9401                git::git(&state.repo, &["rm", file]).await.unwrap();
9402                git::git(&state.repo, &["commit", "-m", "remove config"])
9403                    .await
9404                    .unwrap();
9405                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9406                state.save().unwrap();
9407                state = RunState::load(&state.id).unwrap();
9408                state.observe_branch_owner_holds(&later).await;
9409                assert_eq!(state.branch_owner_holds, holds);
9410                assert_eq!(state.branch_owner_holds[0].head, head);
9411                state.land_sync_pending = false;
9412                state.pr_pushed_head = Some(later.clone());
9413                state.gate_head = Some(later.clone());
9414                let forge = Scripted::new(
9415                    vec![seen(&later, Checks::Green, "CLEAN", false)],
9416                    vec![(true, "")],
9417                );
9418                land_with(&mut state, URL, &forge).await.unwrap();
9419                assert!(!forge.calls().contains(&"merge"));
9420                assert!(state.parked);
9421                let question = ask::Questions::open()
9422                    .get(&state.land_approval.as_ref().unwrap().question)
9423                    .unwrap();
9424                assert!(question.detail.contains("Approval required because:"));
9425                assert!(question.detail.contains(&format!(
9426                    "{}=true from the reviewed branch's {file}",
9427                    control.key()
9428                )));
9429                assert_eq!(state.branch_owner_holds, holds);
9430                state.save().unwrap();
9431                let resumed = RunState::load(&state.id).unwrap();
9432                assert!(resumed.owner_hold(control));
9433                assert_eq!(resumed.branch_owner_holds, holds);
9434                assert_eq!(
9435                    resumed.land_approval.unwrap().question,
9436                    state.land_approval.unwrap().question
9437                );
9438            }
9439        }
9440    }
9441
9442    #[tokio::test]
9443    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9444        let mut state = repair_state(false, true);
9445        state.reviews[0].clean = true;
9446        let mut finding = contested().findings.remove(0);
9447        finding.severity = crate::verdict::Severity::Minor;
9448        state.reviews[0].reviews[0].findings.push(finding);
9449        assert!(state.open_findings().is_empty());
9450        let mut pr = green_pr();
9451        pr.review_comments.clear();
9452        for language in ["en", "ja"] {
9453            state.config.graph.language = language.into();
9454            let html = approval_panel(&state, &pr, "", "", &[], "subject");
9455            assert!(html.contains("[R3-1-1] minor"));
9456            assert!(html.contains(if language == "ja" {
9457                "内部指摘の解決を意味するものではありません"
9458            } else {
9459                "This does not mean internal findings are resolved"
9460            }));
9461            assert!(
9462                html.find(if language == "ja" {
9463                    "承認が必要な理由:"
9464                } else {
9465                    "Approval required because:"
9466                })
9467                .unwrap()
9468                    < html.find("[R3-1-1]").unwrap()
9469            );
9470        }
9471        state.config.graph.language = "en".into();
9472        let observed = seen("abc", Checks::Green, "CLEAN", false);
9473        assert_eq!(
9474            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9475                .await
9476                .unwrap(),
9477            ApprovalGate::Pending
9478        );
9479        let id = state.land_approval.as_ref().unwrap().question.clone();
9480        let q = ask::Questions::open().get(&id).unwrap();
9481        assert!(q.detail.starts_with("Approval required because:"));
9482        assert!(q.detail.contains("final reviewer reject"));
9483        assert!(q.detail.contains("[R3-1-1] minor"));
9484        assert!(
9485            q.detail
9486                .contains("No adoption or resolution evidence recorded")
9487        );
9488        state.config.graph.land_approval = false;
9489        state.config.graph.hold_contested_merge = false;
9490        state.reviews.clear();
9491        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9492        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9493        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9494        let forge = Scripted::new(vec![observed], vec![]);
9495        land_with(&mut state, URL, &forge).await.unwrap();
9496        assert!(!forge.calls().contains(&"merge"));
9497        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9498        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9499    }
9500
9501    #[tokio::test]
9502    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9503        let mut state = repair_state(false, true);
9504        state.config.graph.land_approval = false;
9505        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9506        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9507        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9508        state.reviews[0].reviews[0].summary = long_reason.clone();
9509        for i in 1..=10 {
9510            let mut finding = contested().findings.remove(0);
9511            finding.id = format!("R1-1-{i}");
9512            finding.severity = if i == 9 {
9513                crate::verdict::Severity::Major
9514            } else {
9515                crate::verdict::Severity::Minor
9516            };
9517            finding.title = long_title.clone();
9518            finding.detail = long_detail.clone();
9519            state.reviews[0].reviews[0].findings.push(finding);
9520        }
9521        state.reviews[0].fix = Some(crate::run::FixRecord {
9522            agent: "fixer".into(),
9523            addressed: vec!["R1-1-9".into()],
9524            rejected: vec![crate::verdict::Rejection {
9525                id: "R1-1-10".into(),
9526                why: long_reason.clone(),
9527            }],
9528            notes: long_detail.clone(),
9529            committed: false,
9530            failed: None,
9531            duration_ms: 0,
9532            continuation: None,
9533        });
9534        assert_eq!(
9535            approval_reasons(&state),
9536            [
9537                ApprovalReason::OpenBlockingFindings,
9538                ApprovalReason::FinalReject
9539            ]
9540        );
9541        let excerpt = approval_excerpt(&long_reason, 300);
9542        assert_eq!(excerpt.chars().count(), 300);
9543        assert!(excerpt.ends_with('…'));
9544        let boundary = "拒".repeat(300);
9545        assert_eq!(approval_excerpt(&boundary, 300), boundary);
9546        for language in ["en", "ja"] {
9547            state.config.graph.language = language.into();
9548            for revote in [
9549                None,
9550                Some(crate::verdict::ReviewVote::Reject),
9551                Some(crate::verdict::ReviewVote::Approve),
9552            ] {
9553                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9554                state.reviews[0].reconsideration.clear();
9555                if let Some(vote) = revote {
9556                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9557                    state.reviews[0]
9558                        .reconsideration
9559                        .push(crate::run::ReviewRevoteRecord {
9560                            reviewer: 1,
9561                            agent: "alpha".into(),
9562                            vote: Some(vote),
9563                            reason: long_reason.clone(),
9564                            failed: None,
9565                        });
9566                }
9567                let evidence = approval_evidence(&state);
9568                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9569                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9570                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9571                assert_eq!(
9572                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9573                    final_vote == crate::verdict::ReviewVote::Reject
9574                );
9575                assert!(evidence.contains(&excerpt));
9576                assert!(evidence.contains("[R1-1-8] minor"));
9577                assert!(evidence.contains("[R1-1-9] major"));
9578                assert!(evidence.contains("[R1-1-10] minor"));
9579                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9580                    assert!(!evidence.contains(tail));
9581                }
9582                assert!(evidence.contains(if language == "ja" {
9583                    "採用申告(解決未確認)"
9584                } else {
9585                    "claimed addressed (resolution unconfirmed)"
9586                }));
9587                assert!(evidence.contains(if language == "ja" {
9588                    "不採用理由"
9589                } else {
9590                    "declined"
9591                }));
9592                let major_evidence = evidence
9593                    .split("[R1-1-9] major")
9594                    .nth(1)
9595                    .unwrap()
9596                    .split("[R1-1-10]")
9597                    .next()
9598                    .unwrap();
9599                assert!(major_evidence.contains(if language == "ja" {
9600                    "採用申告(解決未確認)"
9601                } else {
9602                    "claimed addressed (resolution unconfirmed)"
9603                }));
9604                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9605                assert!(last_evidence.contains(if language == "ja" {
9606                    "不採用理由"
9607                } else {
9608                    "declined"
9609                }));
9610                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9611                assert!(html.contains(&esc(&evidence)));
9612                assert_eq!(
9613                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9614                        .await
9615                        .unwrap(),
9616                    ApprovalGate::Pending
9617                );
9618                let id = &state.land_approval.take().unwrap().question;
9619                let q = ask::Questions::open().get(id).unwrap();
9620                assert!(q.detail.starts_with(&evidence));
9621            }
9622            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9623        }
9624    }
9625
9626    #[test]
9627    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9628        for (major, reject) in [(true, false), (false, true), (true, true)] {
9629            let state = repair_state(major, reject);
9630            assert!(repair_available(&state));
9631            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9632        }
9633        assert!(!repair_available(&repair_state(false, false)));
9634        let mut clean = repair_state(true, false);
9635        clean.reviews[0].clean = true;
9636        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9637        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9638    }
9639
9640    #[tokio::test]
9641    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9642        let mut state = repair_state(true, false);
9643        let pr = green_pr();
9644        approval_gate(&mut state, &pr, "feat: x", None, "abc")
9645            .await
9646            .unwrap();
9647        let store = ask::Questions::open();
9648        let id = state.land_approval.as_ref().unwrap().question.clone();
9649        // Simulate an unanswered two-choice question created by an older build.
9650        store
9651            .update(&id, |q| {
9652                q.choices = vec![APPROVE.into(), HOLD.into()];
9653                Ok(())
9654            })
9655            .unwrap();
9656        let upgraded = store.get(&id).unwrap();
9657        assert_eq!(upgraded.choices, approval_choices(&state));
9658        assert!(!upgraded.actions.contains_key(HOLD));
9659        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9660        assert!(
9661            store
9662                .list()
9663                .iter()
9664                .any(|q| q.id == id && q.choices == upgraded.choices)
9665        );
9666        assert!(
9667            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9668        );
9669        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9670        store
9671            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9672            .unwrap();
9673        // An earlier build may have recorded the repair answer and stopped
9674        // before any driver consumed it. Reconcile that durable decision too.
9675        store
9676            .update(&id, |q| {
9677                q.actions.clear();
9678                Ok(())
9679            })
9680            .unwrap();
9681        assert_eq!(
9682            store.get(&id).unwrap().chosen_action(),
9683            Some(&ask::ChoiceAction::Resume {
9684                run: state.id.clone()
9685            })
9686        );
9687        let binding = state.land_approval.clone();
9688        assert_eq!(
9689            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9690                .await
9691                .unwrap(),
9692            ApprovalGate::Repair
9693        );
9694        assert!(state.land_approval.is_none());
9695        assert_eq!(state.merge_repairs.len(), 1);
9696        let request = &state.merge_repairs[0];
9697        assert_eq!(request.question, id);
9698        assert_eq!(request.head, "abc");
9699        assert_eq!(request.pr, pr.url);
9700        assert_eq!(
9701            request.reviews[0].reviews[0].summary,
9702            "precise rejection reason"
9703        );
9704        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9705        assert_eq!(
9706            request.reviews[0].reviews[0].findings[0].detail,
9707            state.reviews[0].reviews[0].findings[0].detail
9708        );
9709        // A repeated consumption of the same answer never dispatches another repair.
9710        state.land_approval = binding;
9711        assert_eq!(
9712            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9713                .await
9714                .unwrap(),
9715            ApprovalGate::Repair
9716        );
9717        assert_eq!(state.merge_repairs.len(), 1);
9718        state.land_approval = None;
9719        state.config.graph.land_approval = false;
9720        state.config.graph.hold_contested_merge = false;
9721        state.reviews.clear();
9722        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9723        assert_eq!(
9724            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9725                .await
9726                .unwrap(),
9727            ApprovalGate::Pending
9728        );
9729        let fresh_id = &state.land_approval.as_ref().unwrap().question;
9730        assert_ne!(fresh_id, &id);
9731        let fresh = store.get(fresh_id).unwrap();
9732        assert!(
9733            fresh
9734                .detail
9735                .contains("fresh owner approval after merge repair")
9736        );
9737        assert!(fresh.detail.contains("No review recorded"));
9738        assert!(!fresh.detail.contains("precise rejection reason"));
9739    }
9740
9741    #[tokio::test]
9742    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9743        for choice in [REPAIR, HOLD] {
9744            let mut state = repair_state(false, true);
9745            let observed = seen("abc", Checks::Green, "CLEAN", false);
9746            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9747                .await
9748                .unwrap();
9749            let id = state.land_approval.as_ref().unwrap().question.clone();
9750            ask::Questions::open()
9751                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9752                .unwrap();
9753            let forge = Scripted::new(vec![observed], vec![(true, "")]);
9754            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9755                .await
9756                .unwrap();
9757            assert!(
9758                forge
9759                    .argvs()
9760                    .iter()
9761                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
9762            );
9763            assert!(!forge.calls().contains(&"fix"));
9764            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
9765            assert_ne!(state.status, RunStatus::Merged);
9766        }
9767    }
9768
9769    #[test]
9770    fn only_the_merge_choice_merges_and_silence_holds() {
9771        let table = [
9772            (None, Approval::Hold),
9773            (Some("merge"), Approval::Merge),
9774            (Some(" merge\n"), Approval::Merge),
9775            (Some("hold"), Approval::Hold),
9776            (Some(""), Approval::Hold),
9777            (Some("yes"), Approval::Hold),
9778        ];
9779        for (answer, want) in table {
9780            assert_eq!(
9781                approval(answer),
9782                want,
9783                "answer {answer:?} must resolve to {want:?}"
9784            );
9785        }
9786    }
9787
9788    #[tokio::test]
9789    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
9790        let mut state = landing_state();
9791        state.config.graph.land_approval = true;
9792        let pr = green_pr();
9793
9794        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9795            .await
9796            .unwrap();
9797        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
9798        assert!(
9799            !state.parked,
9800            "approval_gate itself never sets `parked`; only its caller does"
9801        );
9802
9803        let store = ask::Questions::open();
9804        let filed: Vec<_> = store
9805            .list()
9806            .into_iter()
9807            .filter(|q| q.run == state.id)
9808            .collect();
9809        assert_eq!(filed.len(), 1, "exactly one question is filed");
9810        assert_eq!(filed[0].node, APPROVAL_NODE);
9811        assert_eq!(filed[0].choices, approval_choices(&state));
9812        assert!(filed[0].status.open());
9813
9814        // A second visit - standing in for a resumed run whose slot the
9815        // daemon handed to something else while nobody had answered - must
9816        // find the same question rather than filing a second one.
9817        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9818            .await
9819            .unwrap();
9820        assert_eq!(again, ApprovalGate::Pending);
9821        let still_one = store
9822            .list()
9823            .into_iter()
9824            .filter(|q| q.run == state.id)
9825            .count();
9826        assert_eq!(
9827            still_one, 1,
9828            "asking twice must not double-file the question"
9829        );
9830    }
9831
9832    #[tokio::test]
9833    async fn approving_the_existing_question_is_read_back_as_approved() {
9834        crate::run::pin_test_home();
9835        let mut state = run_state();
9836        state.config.graph.land_approval = true;
9837        let pr = green_pr();
9838        assert_eq!(
9839            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9840                .await
9841                .unwrap(),
9842            ApprovalGate::Pending
9843        );
9844
9845        let store = ask::Questions::open();
9846        let mut q = store
9847            .list()
9848            .into_iter()
9849            .find(|q| q.run == state.id)
9850            .expect("filed above");
9851        let talks = crate::talk::Talks::open();
9852        let cfg = crate::config::Config {
9853            agents: vec![crate::config::AgentSpec {
9854                id: "mock".into(),
9855                kind: crate::config::AgentKind::Command,
9856                model: None,
9857                command: vec!["true".into()],
9858                extra_args: Vec::new(),
9859                env: Default::default(),
9860                prompt_delivery: None,
9861                max_turn_secs: None,
9862            }],
9863            ..crate::config::Config::default()
9864        };
9865        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
9866        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
9867        crate::talk::drain(&mut talk, &talks).unwrap();
9868        assert_eq!(
9869            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9870                .await
9871                .unwrap(),
9872            ApprovalGate::Pending,
9873            "consultation cannot approve or hold the merge"
9874        );
9875        q = store.get(&q.id).unwrap();
9876        assert!(q.answer.is_none());
9877        // The owner's merge answer (from the chat or the card) is the approval.
9878        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9879        store.put(&mut q).unwrap();
9880
9881        assert_eq!(
9882            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9883                .await
9884                .unwrap(),
9885            ApprovalGate::Approved
9886        );
9887    }
9888
9889    #[tokio::test]
9890    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
9891        crate::run::pin_test_home();
9892        let store = ask::Questions::open();
9893        for via_list in [false, true] {
9894            let mut state = repair_state(false, true);
9895            let pr = green_pr();
9896            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9897                .await
9898                .unwrap();
9899            let id = state.land_approval.as_ref().unwrap().question.clone();
9900            store
9901                .update(&id, |q| {
9902                    q.actions.insert(
9903                        HOLD.to_owned(),
9904                        ask::ChoiceAction::Resume {
9905                            run: state.id.clone(),
9906                        },
9907                    );
9908                    Ok(())
9909                })
9910                .unwrap();
9911            let q = if via_list {
9912                store.list().into_iter().find(|q| q.id == id).unwrap()
9913            } else {
9914                store.get(&id).unwrap()
9915            };
9916            assert!(!q.actions.contains_key(HOLD));
9917            store
9918                .update(&id, |q| {
9919                    // Check the persisted migration, without another read upgrade.
9920                    assert!(!q.actions.contains_key(HOLD));
9921                    assert!(!upgrade_repair_choice(q, &state));
9922                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
9923                })
9924                .unwrap();
9925            assert!(store.get(&id).unwrap().chosen_action().is_none());
9926            assert_eq!(
9927                approval_gate(&mut state, &pr, "feat: x", None, "abc")
9928                    .await
9929                    .unwrap(),
9930                ApprovalGate::Held
9931            );
9932        }
9933    }
9934
9935    #[tokio::test]
9936    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
9937        crate::run::pin_test_home();
9938        let store = ask::Questions::open();
9939
9940        let mut held_state = run_state();
9941        held_state.config.graph.land_approval = true;
9942        let pr = green_pr();
9943        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9944            .await
9945            .unwrap();
9946        let mut q = store
9947            .list()
9948            .into_iter()
9949            .find(|q| q.run == held_state.id)
9950            .expect("filed above");
9951        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
9952        store.put(&mut q).unwrap();
9953        assert_eq!(
9954            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9955                .await
9956                .unwrap(),
9957            ApprovalGate::Held
9958        );
9959
9960        let mut abandoned_state = run_state();
9961        abandoned_state.config.graph.land_approval = true;
9962        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9963            .await
9964            .unwrap();
9965        let mut q = store
9966            .list()
9967            .into_iter()
9968            .find(|q| q.run == abandoned_state.id)
9969            .expect("filed above");
9970        q.abandon("no answer within the timeout");
9971        store.put(&mut q).unwrap();
9972        assert_eq!(
9973            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9974                .await
9975                .unwrap(),
9976            ApprovalGate::Pending,
9977            "an expired approval must ask again without merging"
9978        );
9979        assert_eq!(
9980            store.get(&q.id).unwrap().status,
9981            ask::QuestionStatus::Abandoned
9982        );
9983        assert_ne!(
9984            abandoned_state.land_approval.as_ref().unwrap().question,
9985            q.id
9986        );
9987    }
9988
9989    fn contested() -> ContestedHandoff {
9990        let finding = |id: &str, n: u32| crate::verdict::Finding {
9991            id: id.to_owned(),
9992            severity: crate::verdict::Severity::Major,
9993            file: Some("src/a.rs".to_owned()),
9994            line: Some(n),
9995            title: format!("problem {id}"),
9996            detail: String::new(),
9997        };
9998        ContestedHandoff {
9999            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
10000            rejecters: vec![(1, "alpha".to_owned())],
10001        }
10002    }
10003
10004    #[test]
10005    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
10006        let mut state = run_state();
10007        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
10008        state.contested_handoff = Some(contested());
10009        assert!(contested_to_ask(&state).is_some());
10010        state.config.graph.hold_contested_merge = false;
10011        assert!(
10012            contested_to_ask(&state).is_none(),
10013            "the switch restores today"
10014        );
10015    }
10016
10017    #[test]
10018    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
10019        let q = ask::Question::new(
10020            "run-1".to_owned(),
10021            APPROVAL_NODE.to_owned(),
10022            "land".to_owned(),
10023            "Merge?".to_owned(),
10024            String::new(),
10025            vec![APPROVE.to_owned(), HOLD.to_owned()],
10026        );
10027        let none = deputy_brief(&q, None);
10028        assert!(none.contains("could not be read"), "{none}");
10029        assert!(none.contains("Silence is a hold"), "{none}");
10030
10031        let mut state = run_state();
10032        state.pr = Some(crate::run::PrRecord {
10033            url: "https://example.test/pull/7".to_owned(),
10034            number: 7,
10035            state: "open".to_owned(),
10036            checks: "green".to_owned(),
10037            round: 0,
10038            rounds: 3,
10039            red_at_merge: Vec::new(),
10040        });
10041        state.contested_handoff = Some(contested());
10042        let b = deputy_brief(&q, Some(&state));
10043        assert!(b.contains("https://example.test/pull/7"), "{b}");
10044        assert!(b.contains("not recorded in this legacy question"), "{b}");
10045        assert!(!b.contains("This question was filed although"));
10046        state.contested_handoff = None;
10047        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
10048    }
10049
10050    #[test]
10051    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
10052        for lang in ["en", "ja"] {
10053            let mut cfg = crate::config::Config::default();
10054            cfg.graph.language = lang.to_owned();
10055            let w = words(&cfg.graph.language);
10056            let text = w.approval_detail(
10057                "https://github.com/yukimemi/magi/pull/42",
10058                "main",
10059                "feat: x",
10060                Some(&contested()),
10061            );
10062            assert!(text.contains("pull/42"), "{text}");
10063            assert!(
10064                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
10065                "{text}"
10066            );
10067            assert!(text.contains("R3-1-5"), "{text}");
10068            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
10069            assert!(text.contains("2"), "the rest are counted: {text}");
10070            assert!(text.contains("#1 (alpha)"), "{text}");
10071        }
10072        let plain = words("en").approval_detail("u", "main", "s", None);
10073        assert!(!plain.contains("reject"), "{plain}");
10074    }
10075
10076    #[tokio::test]
10077    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
10078        crate::run::pin_test_home();
10079        let mut state = run_state();
10080        state.config.graph.land_approval = false;
10081        state.contested_handoff = Some(contested());
10082        let pr = green_pr();
10083        let c = contested_to_ask(&state);
10084        assert_eq!(
10085            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10086                .await
10087                .unwrap(),
10088            ApprovalGate::Pending,
10089            "silence is a hold"
10090        );
10091        let store = ask::Questions::open();
10092        let filed: Vec<_> = store
10093            .list()
10094            .into_iter()
10095            .filter(|q| q.run == state.id)
10096            .collect();
10097        assert_eq!(filed.len(), 1);
10098        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
10099
10100        assert_eq!(
10101            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10102                .await
10103                .unwrap(),
10104            ApprovalGate::Pending
10105        );
10106        let mut q = store
10107            .list()
10108            .into_iter()
10109            .find(|q| q.run == state.id)
10110            .unwrap();
10111        assert_eq!(q.id, filed[0].id, "the same question after a resume");
10112        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10113        store.put(&mut q).unwrap();
10114        assert_eq!(
10115            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10116                .await
10117                .unwrap(),
10118            ApprovalGate::Approved
10119        );
10120    }
10121
10122    #[test]
10123    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
10124        let rows = parse_numstat(NUMSTAT);
10125        assert_eq!(
10126            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
10127            ["src/web.rs", "src/land.rs", "assets/logo.png"]
10128        );
10129        assert_eq!(rows[2].added, None, "a binary file has no line counts");
10130    }
10131    #[test]
10132    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
10133        // Reported from a real run: the merge question arrived in English on a
10134        // repository with `language = "ja"`. magi's own strings have to follow
10135        // that setting too - "it is a literal in Rust" is not an answer.
10136        let mut state = run_state();
10137        state.config.graph.language = "ja".to_owned();
10138        let pr = green_pr();
10139        let commits = ["c1".to_owned()];
10140
10141        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10142        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
10143        assert!(ja.contains("squash されるコミット"), "{ja}");
10144        assert!(ja.contains("レビューコメント"), "{ja}");
10145        assert!(ja.contains("差分"), "{ja}");
10146        assert!(
10147            !ja.contains("Commits being squashed"),
10148            "no English left over"
10149        );
10150
10151        let w = words("ja");
10152        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
10153        assert!(
10154            w.approval_detail("http://x/1", "main", "feat: x", None)
10155                .contains("パネル")
10156        );
10157
10158        // The evidence itself is language-neutral and must survive either way.
10159        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
10160        assert!(ja.contains("feat: x"), "nor is the merge subject");
10161
10162        // English stays the default, and a language magi cannot check falls
10163        // back to it rather than shipping a guess.
10164        state.config.graph.language = "en".to_owned();
10165        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10166        assert!(en.contains("Commits being squashed"), "{en}");
10167        assert_eq!(words("Klingon").html_lang, "en");
10168    }
10169
10170    /// A `gh pr list` result naming exactly one pull request whose base and
10171    /// merge time both fit the run is exactly the case
10172    /// [`find_external_merge`] exists to act on.
10173    #[test]
10174    fn pick_open_pr_classifies_by_count_and_base() {
10175        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
10176        assert_eq!(
10177            pick_open_pr(one, "main").unwrap(),
10178            OpenPr::One {
10179                url: "https://x/pull/58".into(),
10180                title: "t".into()
10181            }
10182        );
10183        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
10184        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
10185        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
10186                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
10187        assert_eq!(
10188            pick_open_pr(two, "main").unwrap(),
10189            OpenPr::Many(vec!["u1".into(), "u2".into()])
10190        );
10191        // A fork's same-named branch is not a pull request for this head.
10192        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
10193        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
10194        assert!(pick_open_pr("not json", "main").is_err());
10195        // An incomplete record is an error, never "nothing open".
10196        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
10197        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
10198    }
10199
10200    #[test]
10201    fn pick_merged_pr_picks_the_unique_match() {
10202        let json = r#"[
10203            {"url": "https://github.com/o/r/pull/42", "number": 42,
10204             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
10205        ]"#;
10206        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10207        let found = pick_merged_pr(json, "main", created_at)
10208            .expect("valid json")
10209            .expect("one unambiguous match");
10210        assert_eq!(found.url, "https://github.com/o/r/pull/42");
10211        assert_eq!(found.number, 42);
10212    }
10213
10214    /// Two candidates surviving the filter is exactly as uninformative as
10215    /// zero — a branch name can be reused across runs — so neither is
10216    /// preferred over the other and nothing is recorded automatically.
10217    #[test]
10218    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
10219        let json = r#"[
10220            {"url": "https://github.com/o/r/pull/42", "number": 42,
10221             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
10222            {"url": "https://github.com/o/r/pull/43", "number": 43,
10223             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
10224        ]"#;
10225        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10226        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10227        let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
10228        assert!(error.to_string().contains("ambiguous"), "{error:#}");
10229    }
10230
10231    /// A pull request that targets a different base branch cannot be this
10232    /// run's, whatever its head branch is named — a reused branch name from
10233    /// an unrelated task must not be recorded as this run's merge.
10234    #[test]
10235    fn pick_merged_pr_ignores_a_different_base_branch() {
10236        let json = r#"[
10237            {"url": "https://github.com/o/r/pull/42", "number": 42,
10238             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
10239        ]"#;
10240        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10241        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10242    }
10243
10244    /// A pull request merged before this run was even created cannot be this
10245    /// run's winner, no matter how its head branch is spelled.
10246    #[test]
10247    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
10248        let json = r#"[
10249            {"url": "https://github.com/o/r/pull/42", "number": 42,
10250             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
10251        ]"#;
10252        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10253        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10254    }
10255
10256    #[test]
10257    fn slug_of_pr_url_reads_host_owner_and_repo() {
10258        assert_eq!(
10259            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
10260            Some("github.com/yukimemi/shun")
10261        );
10262    }
10263
10264    #[test]
10265    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
10266        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
10267        assert_eq!(slug_of_pr_url("not a url at all"), None);
10268        assert_eq!(slug_of_pr_url("https://github.com"), None);
10269    }
10270
10271    #[test]
10272    fn slug_of_repo_url_reads_host_owner_and_repo() {
10273        assert_eq!(
10274            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
10275            Some("github.com/yukimemi/magi")
10276        );
10277        assert_eq!(slug_of_repo_url("https://github.com"), None);
10278    }
10279
10280    #[test]
10281    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
10282        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
10283            .expect("same repo, different case");
10284    }
10285
10286    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
10287    /// own in-progress run and rewrote its status from a pull request in a
10288    /// completely different repository. This is the guard that must catch
10289    /// that even when an explicit (but wrong) id is given.
10290    #[test]
10291    fn ensure_same_repo_refuses_a_different_repo() {
10292        let err =
10293            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
10294        let msg = format!("{err:#}");
10295        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10296        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
10297    }
10298
10299    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
10300    /// instance mirroring a `github.com` repository's name, say) must not be
10301    /// treated as the same repository just because the trailing path
10302    /// matches.
10303    #[test]
10304    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
10305        let err = ensure_same_repo(
10306            "github.com/yukimemi/magi",
10307            "github.example.com/yukimemi/magi",
10308        )
10309        .unwrap_err();
10310        let msg = format!("{err:#}");
10311        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10312        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
10313    }
10314
10315    /// No winner decided yet means there is no branch to ask GitHub about at
10316    /// all — `find_external_merge` must return `None` without ever spawning
10317    /// `gh`, which this proves by never providing a real repository to spawn
10318    /// it in.
10319    #[tokio::test]
10320    async fn find_external_merge_returns_none_without_a_winner() {
10321        let state = RunState::new(
10322            PathBuf::from("/no/such/repo"),
10323            "main".to_owned(),
10324            "0000000000000000000000000000000000000000".to_owned(),
10325            "irrelevant".to_owned(),
10326            crate::config::Config::default(),
10327        );
10328        assert_eq!(find_external_merge(&state).await.unwrap(), None);
10329    }
10330
10331    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
10332        let mut run = RunState::new(
10333            PathBuf::from(repo),
10334            "main".to_owned(),
10335            "abcdef1234".to_owned(),
10336            "x".to_owned(),
10337            crate::config::Config::default(),
10338        );
10339        run.id = id.to_owned();
10340        run.status = status;
10341        run.driver_exited = true;
10342        run.pr = Some(crate::run::PrRecord {
10343            number: url.rsplit('/').next().unwrap().parse().unwrap(),
10344            url: url.to_owned(),
10345            state: state.to_owned(),
10346            checks: "red".to_owned(),
10347            round: 0,
10348            rounds: 2,
10349            red_at_merge: Vec::new(),
10350        });
10351        run.save_under(home).unwrap();
10352    }
10353
10354    fn recorded(home: &Path, id: &str) -> String {
10355        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10356        serde_json::from_str::<RunState>(&body)
10357            .unwrap()
10358            .pr
10359            .unwrap()
10360            .state
10361    }
10362
10363    const PR: &str = "https://github.com/o/r/pull/7";
10364
10365    #[test]
10366    fn write_through_updates_predecessors_and_siblings_only() {
10367        let tmp = tempfile::tempdir().unwrap();
10368        let h = tmp.path();
10369        pr_run(
10370            h,
10371            "20261004-100000-aaaa",
10372            "/repo/r",
10373            RunStatus::Superseded,
10374            PR,
10375            "open",
10376        );
10377        pr_run(
10378            h,
10379            "20261004-100100-bbbb",
10380            "/repo/r",
10381            RunStatus::Blocked,
10382            PR,
10383            "open",
10384        );
10385        // Not terminal: a driver may be writing it.
10386        pr_run(
10387            h,
10388            "20261004-100200-cccc",
10389            "/repo/r",
10390            RunStatus::Landing,
10391            PR,
10392            "open",
10393        );
10394        // Another repository's pull request with the same number.
10395        pr_run(
10396            h,
10397            "20261004-100300-dddd",
10398            "/repo/other",
10399            RunStatus::Blocked,
10400            "https://github.com/o/other/pull/7",
10401            "open",
10402        );
10403        // A different pull request of the same repository.
10404        pr_run(
10405            h,
10406            "20261004-100400-eeee",
10407            "/repo/r",
10408            RunStatus::Blocked,
10409            "https://github.com/o/r/pull/8",
10410            "open",
10411        );
10412        pr_run(
10413            h,
10414            "20261004-100500-ffff",
10415            "/repo/r",
10416            RunStatus::Merged,
10417            PR,
10418            "open",
10419        );
10420        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10421
10422        assert_eq!(
10423            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10424            2
10425        );
10426        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10427        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10428        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10429        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10430        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10431        // The source's own record is the caller's to write.
10432        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10433        // Idempotent.
10434        assert_eq!(
10435            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10436            0
10437        );
10438        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10439        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10440    }
10441
10442    #[test]
10443    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10444        let home = tempfile::tempdir().unwrap();
10445        let live_id = "20261004-100000-aaaa";
10446        let unknown_id = "20261004-100100-bbbb";
10447        for id in [live_id, unknown_id] {
10448            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10449            let mut s = RunState::load_under(id, home.path()).unwrap();
10450            s.driver_exited = false;
10451            // Model legacy driver evidence, not a newly reserved unstarted run.
10452            s.driver_claimed = None;
10453            if id == live_id {
10454                s.driver_pid = Some(std::process::id());
10455                s.driver_started_at = crate::proc::process_started_at(std::process::id());
10456            }
10457            s.save_under(home.path()).unwrap();
10458            if id == unknown_id {
10459                assert_eq!(
10460                    s.liveness_under(home.path(), false),
10461                    crate::run::Liveness::Unknown
10462                );
10463            }
10464        }
10465        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10466        assert_eq!(apply_pr_states(home.path(), &known), 0);
10467        for id in [live_id, unknown_id] {
10468            assert_eq!(recorded(home.path(), id), "open");
10469        }
10470    }
10471
10472    #[test]
10473    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10474        let tmp = tempfile::tempdir().unwrap();
10475        let h = tmp.path();
10476        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10477        pr_run(
10478            h,
10479            "20261004-100000-aaaa",
10480            "/repo/r",
10481            RunStatus::Superseded,
10482            &url(1),
10483            "open",
10484        );
10485        pr_run(
10486            h,
10487            "20261004-100100-bbbb",
10488            "/repo/r",
10489            RunStatus::Blocked,
10490            &url(2),
10491            "open",
10492        );
10493        pr_run(
10494            h,
10495            "20261004-100200-cccc",
10496            "/repo/r",
10497            RunStatus::Ready,
10498            &url(3),
10499            "open",
10500        );
10501        pr_run(
10502            h,
10503            "20261004-100300-dddd",
10504            "/repo/r",
10505            RunStatus::Ready,
10506            &url(4),
10507            "open",
10508        );
10509        pr_run(
10510            h,
10511            "20261004-100400-eeee",
10512            "/repo/r",
10513            RunStatus::Implementing,
10514            &url(1),
10515            "open",
10516        );
10517        assert_eq!(stale_open_prs(h).len(), 4);
10518
10519        let mut known = BTreeMap::new();
10520        known.insert(url(1), PrLifecycle::Merged);
10521        known.insert(url(2), PrLifecycle::Closed);
10522        known.insert(url(3), PrLifecycle::Open);
10523        // #4: the forge could not be read, so it has no answer.
10524        assert_eq!(apply_pr_states(h, &known), 2);
10525        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10526        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10527        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10528        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10529        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10530        assert_eq!(apply_pr_states(h, &known), 0);
10531    }
10532
10533    // --- the land loop against a scripted forge -------------------------
10534
10535    use std::collections::VecDeque;
10536    use std::sync::Mutex;
10537
10538    /// Answers views from a script (the last one repeats), merges from a
10539    /// queue, and records every call so a test can assert the order.
10540    struct Scripted {
10541        public_repo: Option<PathBuf>,
10542        evidence: Mutex<Option<CiEvidence>>,
10543        views: Mutex<VecDeque<Seen>>,
10544        merges: Mutex<VecDeque<(bool, String)>>,
10545        fix: Mutex<Option<Fixed>>,
10546        log: Mutex<Vec<&'static str>>,
10547        argvs: Mutex<Vec<Vec<String>>>,
10548        required: Mutex<Option<BTreeSet<String>>>,
10549        /// Set once a merge answered ok: the forge then reports `merged`,
10550        /// unless `queued` says the merge only entered a queue.
10551        merged: Mutex<bool>,
10552        queued: Mutex<bool>,
10553        /// Views fail once a merge answered ok.
10554        unreadable_after_merge: Mutex<bool>,
10555        /// Workflow runs asked to rerun, and whether that call fails.
10556        reruns: Mutex<Vec<String>>,
10557        rerun_fails: Mutex<bool>,
10558        /// Unix seconds; every poll moves it on by `POLL`.
10559        clock: Mutex<i64>,
10560    }
10561
10562    impl Scripted {
10563        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10564            Self {
10565                public_repo: None,
10566                evidence: Mutex::new(None),
10567                views: Mutex::new(views.into()),
10568                merges: Mutex::new(
10569                    merges
10570                        .into_iter()
10571                        .map(|(ok, m)| (ok, m.to_owned()))
10572                        .collect(),
10573                ),
10574                fix: Mutex::new(None),
10575                log: Mutex::new(Vec::new()),
10576                argvs: Mutex::new(Vec::new()),
10577                required: Mutex::new(None),
10578                merged: Mutex::new(false),
10579                queued: Mutex::new(false),
10580                unreadable_after_merge: Mutex::new(false),
10581                reruns: Mutex::new(Vec::new()),
10582                rerun_fails: Mutex::new(false),
10583                clock: Mutex::new(1_000),
10584            }
10585        }
10586        fn argvs(&self) -> Vec<Vec<String>> {
10587            self.argvs.lock().unwrap().clone()
10588        }
10589        fn calls(&self) -> Vec<&'static str> {
10590            self.log.lock().unwrap().clone()
10591        }
10592    }
10593
10594    impl Forge for Scripted {
10595        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10596            self.evidence.lock().unwrap().clone()
10597        }
10598        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10599            self.log.lock().unwrap().push("view");
10600            if *self.unreadable_after_merge.lock().unwrap()
10601                && !self.argvs.lock().unwrap().is_empty()
10602            {
10603                anyhow::bail!("forge unreachable");
10604            }
10605            let mut seen = {
10606                let mut v = self.views.lock().unwrap();
10607                if v.len() > 1 {
10608                    v.pop_front().unwrap()
10609                } else {
10610                    v[0].clone()
10611                }
10612            };
10613            if seen.head == "@published" {
10614                let head =
10615                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10616                        .await?
10617                        .context("missing published head")?;
10618                seen.head.clone_from(&head);
10619                seen.rollup_head = head;
10620            }
10621            if *self.merged.lock().unwrap() {
10622                seen.pr.state = PrLifecycle::Merged;
10623            }
10624            Ok(seen)
10625        }
10626        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10627            self.log.lock().unwrap().push("merge");
10628            self.argvs.lock().unwrap().push(argv.to_vec());
10629            let out = self
10630                .merges
10631                .lock()
10632                .unwrap()
10633                .pop_front()
10634                .expect("unscripted merge");
10635            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10636            {
10637                *self.merged.lock().unwrap() = true;
10638            }
10639            Ok(out)
10640        }
10641        async fn poll(&self) {
10642            self.log.lock().unwrap().push("poll");
10643            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10644        }
10645        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10646            self.log.lock().unwrap().push("rerun");
10647            self.reruns.lock().unwrap().push(run.to_owned());
10648            if *self.rerun_fails.lock().unwrap() {
10649                anyhow::bail!("gh run rerun: no");
10650            }
10651            Ok(())
10652        }
10653        fn now(&self) -> i64 {
10654            *self.clock.lock().unwrap()
10655        }
10656        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10657            self.required.lock().unwrap().clone()
10658        }
10659        async fn fix(
10660            &self,
10661            _state: &mut RunState,
10662            _pr: &PrState,
10663            _round: usize,
10664            _budget: usize,
10665            _reason: &str,
10666            _logs: &str,
10667        ) -> Result<Fixed> {
10668            self.log.lock().unwrap().push("fix");
10669            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10670        }
10671    }
10672
10673    const REFUSED: &str =
10674        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10675
10676    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10677        let mut pr = green_pr();
10678        pr.checks = checks;
10679        pr.blocking = Blocking::of(merge_state);
10680        if !comments {
10681            pr.review_comments.clear();
10682        }
10683        Seen {
10684            pr,
10685            title: "feat: x".to_owned(),
10686            failing_urls: Vec::new(),
10687            head: head.to_owned(),
10688            rollup_head: head.to_owned(),
10689            merge_state: merge_state.to_owned(),
10690            contexts: Vec::new(),
10691            base: "main".to_owned(),
10692        }
10693    }
10694
10695    fn landing_state() -> RunState {
10696        crate::run::pin_test_home();
10697        let mut state = run_state();
10698        state.config.graph.land_approval = false;
10699        state
10700    }
10701
10702    #[test]
10703    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10704        assert!(!awaiting_new_head(None, "aaa"));
10705        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10706        assert!(awaiting_new_head(Some("abc123"), "def456"));
10707        assert!(awaiting_new_head(Some("abc123"), ""));
10708    }
10709
10710    #[test]
10711    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10712        let open = |c, m: &str| seen("a", c, m, false);
10713        let table = [
10714            (None, false, Refused::Pending),
10715            (
10716                Some(open(Checks::Pending, "BLOCKED")),
10717                false,
10718                Refused::Pending,
10719            ),
10720            (
10721                Some(open(Checks::Unknown, "BLOCKED")),
10722                false,
10723                Refused::Pending,
10724            ),
10725            (
10726                Some(open(Checks::Green, "UNKNOWN")),
10727                false,
10728                Refused::Pending,
10729            ),
10730            (Some(open(Checks::Green, "")), false, Refused::Pending),
10731            (
10732                Some(open(Checks::Green, "BLOCKED")),
10733                false,
10734                Refused::Recheck,
10735            ),
10736            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10737        ];
10738        for (after, rechecked, want) in table {
10739            assert_eq!(
10740                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10741                want
10742            );
10743        }
10744        let mut closed = open(Checks::Green, "CLEAN");
10745        closed.pr.state = PrLifecycle::Closed;
10746        assert_eq!(
10747            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10748            Refused::Final
10749        );
10750    }
10751
10752    #[test]
10753    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10754        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10755            let pr = seen("a", checks, "BEHIND", false).pr;
10756            assert_eq!(
10757                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10758                Step::Rebase
10759            );
10760        }
10761        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
10762            let current = seen("a", Checks::Green, status, false);
10763            assert_ne!(
10764                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10765                Step::Rebase
10766            );
10767            assert_ne!(
10768                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
10769                Refused::Behind
10770            );
10771        }
10772        let mut current = seen("a", Checks::Pending, "BEHIND", false);
10773        current.rollup_head = "old".into();
10774        assert_eq!(
10775            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10776            Refused::Behind
10777        );
10778        assert_eq!(
10779            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
10780            Refused::Pending
10781        );
10782        current.pr.state = PrLifecycle::Closed;
10783        assert_eq!(
10784            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10785            Refused::Final
10786        );
10787    }
10788
10789    #[tokio::test]
10790    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
10791        for boundary in ["initial", "premerge", "refusal"] {
10792            let (_tmp, mut state, old) = landing_git_fixture().await;
10793            state.land_sync_pending = false;
10794            advance_landing_base(&state).await;
10795            state.config.verify.gate = vec!["test -f advance".into()];
10796            state.config.verify.e2e = vec!["test -f advance".into()];
10797            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
10798                .await
10799                .unwrap();
10800            let old_binding = state.land_approval.clone().unwrap();
10801            let store = ask::Questions::open();
10802            let mut question = store.get(&old_binding.question).unwrap();
10803            question
10804                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10805                .unwrap();
10806            store.put(&mut question).unwrap();
10807            let mut views = Vec::new();
10808            if boundary != "initial" {
10809                views.push(seen(&old, Checks::Green, "CLEAN", false));
10810            }
10811            if boundary == "refusal" {
10812                views.push(seen(&old, Checks::Green, "CLEAN", false));
10813            }
10814            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
10815            behind.rollup_head = "old-ci-head".into();
10816            views.push(behind);
10817            // Publication checks the PR lease while verification has completed.
10818            views.push(seen(&old, Checks::Green, "CLEAN", false));
10819            views.push(seen("@published", Checks::Pending, "CLEAN", false));
10820            views.push(seen("@published", Checks::Green, "CLEAN", false));
10821            let merges = if boundary == "refusal" {
10822                vec![(false, REFUSED)]
10823            } else {
10824                vec![]
10825            };
10826            let mut forge = Scripted::new(views, merges);
10827            forge.public_repo = Some(state.repo.clone());
10828            let run = state.id.clone();
10829            land_with(&mut state, URL, &forge).await.unwrap();
10830            let head = state.pr_pushed_head.clone().unwrap();
10831            assert_ne!(head, old, "{boundary}");
10832            assert_eq!(state.id, run);
10833            assert_eq!(state.pr_branch(), Some("task-head"));
10834            assert_eq!(state.winner().unwrap().branch, "winner");
10835            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
10836            assert!(state.gate_allows_progress());
10837            let e2e = state.head_e2e.as_ref().unwrap();
10838            assert_eq!(e2e.head, head);
10839            assert!(e2e.passed);
10840            assert_eq!(state.land_sync_attempts, 1);
10841            assert!(!state.land_sync_pending);
10842            assert!(state.parked);
10843            let binding = state.land_approval.as_ref().unwrap();
10844            assert_eq!(binding.head, head);
10845            assert_ne!(binding.question, old_binding.question);
10846            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
10847            // The new question authorizes only the synchronized head on resume.
10848            let mut question = store.get(&binding.question).unwrap();
10849            question
10850                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10851                .unwrap();
10852            store.put(&mut question).unwrap();
10853            let forge = Scripted::new(
10854                vec![seen(&head, Checks::Green, "CLEAN", false)],
10855                vec![(true, "")],
10856            );
10857            land_with(&mut state, URL, &forge).await.unwrap();
10858            assert_eq!(state.status, RunStatus::Merged);
10859            assert_eq!(
10860                value_of(&forge.argvs()[0], "--match-head-commit"),
10861                Some(head.as_str())
10862            );
10863        }
10864    }
10865
10866    #[tokio::test]
10867    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
10868        let (_tmp, mut state, old) = landing_git_fixture().await;
10869        state.land_sync_pending = false;
10870        state.config.graph.land_approval = false;
10871        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
10872        advance_landing_base(&state).await;
10873        let mut forge = Scripted::new(
10874            vec![
10875                seen(&old, Checks::Green, "CLEAN", false),
10876                seen(&old, Checks::Green, "CLEAN", false),
10877                seen(&old, Checks::Green, "BEHIND", false),
10878                // The next observation is the publication lease check. The
10879                // refusal's evidence still applies to exactly this old head.
10880                seen(&old, Checks::Green, "CLEAN", false),
10881                seen("@published", Checks::Green, "CLEAN", false),
10882            ],
10883            vec![(false, REFUSED), (true, "")],
10884        );
10885        forge.public_repo = Some(state.repo.clone());
10886        land_with(&mut state, URL, &forge).await.unwrap();
10887        let head = state.pr_pushed_head.as_deref().unwrap();
10888        assert_ne!(head, old);
10889        assert_eq!(state.land_sync_attempts, 1);
10890        assert_eq!(state.gate_head.as_deref(), Some(head));
10891        assert_eq!(state.status, RunStatus::Merged);
10892        let requests = forge.argvs();
10893        assert_eq!(requests.len(), 2);
10894        assert_eq!(
10895            value_of(&requests[0], "--match-head-commit"),
10896            Some(old.as_str())
10897        );
10898        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
10899    }
10900
10901    #[tokio::test]
10902    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
10903        let (tmp, mut state, old) = landing_git_fixture().await;
10904        state.land_sync_pending = false;
10905        // A damaged history must not be interpreted as a missing base. Keep
10906        // the head's tree intact so worktree restoration itself can succeed.
10907        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
10908        let commit = tmp.path().join("broken-commit");
10909        std::fs::write(
10910            &commit,
10911            format!(
10912                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
10913                "f".repeat(40)
10914            ),
10915        )
10916        .unwrap();
10917        let replacement = git::git(
10918            &state.repo,
10919            &[
10920                "hash-object",
10921                "-t",
10922                "commit",
10923                "-w",
10924                commit.to_str().unwrap(),
10925            ],
10926        )
10927        .await
10928        .unwrap();
10929        git::git(&state.repo, &["replace", &old, replacement.trim()])
10930            .await
10931            .unwrap();
10932        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10933        land_with(&mut state, URL, &forge).await.unwrap();
10934        assert_eq!(state.land_sync_attempts, 0);
10935        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10936        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10937        assert!(forge.argvs().is_empty());
10938        assert!(
10939            state.events.iter().any(|e| e.message.contains(
10940                "could not determine whether the landing head contains the fetched base"
10941            ))
10942        );
10943    }
10944
10945    #[tokio::test]
10946    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
10947        let (_tmp, mut state, old) = landing_git_fixture().await;
10948        state.land_sync_pending = false;
10949        git::git(
10950            &state.repo,
10951            &["remote", "set-url", "origin", "missing-remote"],
10952        )
10953        .await
10954        .unwrap();
10955        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10956        land_with(&mut state, URL, &forge).await.unwrap();
10957        assert_eq!(state.land_sync_attempts, 0);
10958        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10959        assert!(
10960            state
10961                .events
10962                .iter()
10963                .any(|e| e.message.contains("cannot fetch landing base"))
10964        );
10965        assert!(forge.argvs().is_empty());
10966    }
10967
10968    #[tokio::test]
10969    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
10970        let (_tmp, mut state, old) = landing_git_fixture().await;
10971        state.land_sync_pending = false;
10972        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10973        land_with(&mut state, URL, &forge).await.unwrap();
10974        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10975        assert_eq!(state.land_sync_attempts, 0);
10976        assert!(
10977            state
10978                .events
10979                .iter()
10980                .any(|e| e.message.contains("already included"))
10981        );
10982        advance_landing_base(&state).await;
10983        state.land_sync_attempts = state.config.graph.land_rounds;
10984        state.land_sync_pending = true;
10985        state.save().unwrap();
10986        let mut restored = RunState::load(&state.id).unwrap();
10987        assert!(
10988            resume_observed_head(&mut restored, &old)
10989                .await
10990                .unwrap_err()
10991                .to_string()
10992                .contains("budget exhausted")
10993        );
10994        assert_eq!(
10995            git::remote_head(&state.repo, "origin", "task-head")
10996                .await
10997                .unwrap(),
10998            Some(old)
10999        );
11000    }
11001
11002    #[tokio::test]
11003    async fn a_normal_landing_merges_on_the_first_look() {
11004        let mut state = landing_state();
11005        let forge = Scripted::new(
11006            vec![seen("a", Checks::Green, "CLEAN", false)],
11007            vec![(true, "")],
11008        );
11009        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11010            .await
11011            .unwrap();
11012        // One fresh read, then the head-bound merge.
11013        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11014        assert_eq!(state.status, RunStatus::Merged);
11015    }
11016
11017    #[tokio::test]
11018    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
11019        let mut state = landing_state();
11020        let forge = Scripted::new(
11021            vec![seen("a", Checks::Green, "CLEAN", false)],
11022            std::iter::repeat_n((true, ""), 100).collect(),
11023        );
11024        *forge.queued.lock().unwrap() = true;
11025        let task = async {
11026            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11027                .await
11028                .unwrap();
11029        };
11030        // Still open after the command succeeded: it keeps watching and
11031        // never records a merge (it stops at the wait ceiling instead).
11032        task.await;
11033        assert_ne!(state.status, RunStatus::Merged);
11034    }
11035
11036    #[tokio::test]
11037    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
11038        let mut state = landing_state();
11039        let forge = Scripted::new(
11040            vec![seen("a", Checks::Green, "CLEAN", false)],
11041            std::iter::repeat_n((true, ""), 100).collect(),
11042        );
11043        *forge.unreadable_after_merge.lock().unwrap() = true;
11044        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11045            .await
11046            .ok();
11047        assert_ne!(state.status, RunStatus::Merged);
11048    }
11049
11050    #[tokio::test]
11051    async fn a_task_public_head_is_awaited_on_land_entry() {
11052        let mut state = landing_state();
11053        state.pr_head = Some("magi/task-abcd-1234".into());
11054        state.pr_pushed_head = Some("new".into());
11055        let forge = Scripted::new(
11056            vec![
11057                seen("old", Checks::Green, "CLEAN", false),
11058                seen("new", Checks::Green, "CLEAN", false),
11059            ],
11060            vec![(true, "")],
11061        );
11062        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11063            .await
11064            .unwrap();
11065        assert_eq!(
11066            forge.calls(),
11067            ["view", "poll", "view", "view", "merge", "view"]
11068        );
11069        assert_eq!(state.status, RunStatus::Merged);
11070    }
11071
11072    #[tokio::test]
11073    async fn a_superseded_public_head_owner_cannot_reenter_land() {
11074        let mut state = landing_state();
11075        state.pr_taken_over_by = Some("next".into());
11076        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
11077        assert!(
11078            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11079                .await
11080                .is_err()
11081        );
11082        assert!(forge.calls().is_empty());
11083    }
11084
11085    #[tokio::test]
11086    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
11087        let mut state = landing_state();
11088        let forge = Scripted::new(
11089            vec![
11090                seen("old", Checks::Green, "CLEAN", true),
11091                // The forge has not moved to the new head yet: still green.
11092                seen("old", Checks::Green, "CLEAN", true),
11093                seen("new", Checks::Pending, "BLOCKED", true),
11094                seen("new", Checks::Green, "CLEAN", true),
11095            ],
11096            vec![(true, "")],
11097        );
11098        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11099            head: "NEW".to_owned(),
11100        });
11101        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11102            .await
11103            .unwrap();
11104        assert_eq!(
11105            forge.calls(),
11106            [
11107                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
11108                "view"
11109            ]
11110        );
11111        assert_eq!(state.status, RunStatus::Merged);
11112    }
11113
11114    #[tokio::test]
11115    async fn a_head_that_never_arrives_stops_naming_both_commits() {
11116        let mut state = landing_state();
11117        let forge = Scripted::new(
11118            vec![
11119                seen("old", Checks::Green, "CLEAN", true),
11120                seen("someone-elses", Checks::Green, "CLEAN", true),
11121            ],
11122            vec![],
11123        );
11124        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11125            head: "mine".to_owned(),
11126        });
11127        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11128            .await
11129            .unwrap();
11130        assert!(!forge.calls().contains(&"merge"));
11131        let why = state.merge.as_ref().unwrap().detail.clone();
11132        assert!(
11133            why.contains("mine") && why.contains("someone-elses"),
11134            "{why}"
11135        );
11136        assert_eq!(state.status, RunStatus::Blocked);
11137    }
11138
11139    #[tokio::test]
11140    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
11141        let mut state = landing_state();
11142        let forge = Scripted::new(
11143            vec![
11144                seen("a", Checks::Green, "CLEAN", false),
11145                seen("a", Checks::Green, "CLEAN", false),
11146                seen("a", Checks::Pending, "BLOCKED", false),
11147                seen("a", Checks::Pending, "BLOCKED", false),
11148                seen("a", Checks::Green, "CLEAN", false),
11149            ],
11150            vec![(false, REFUSED), (true, "")],
11151        );
11152        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11153            .await
11154            .unwrap();
11155        assert_eq!(
11156            forge.calls(),
11157            [
11158                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
11159                "view"
11160            ]
11161        );
11162        assert_eq!(state.status, RunStatus::Merged);
11163    }
11164
11165    #[tokio::test]
11166    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
11167        let mut state = landing_state();
11168        let forge = Scripted::new(
11169            vec![
11170                seen("a", Checks::Green, "CLEAN", false),
11171                seen("a", Checks::Green, "BLOCKED", false),
11172            ],
11173            vec![(false, REFUSED), (false, REFUSED)],
11174        );
11175        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11176            .await
11177            .unwrap();
11178        // One re-look is allowed for the forge's own lag, then it is final.
11179        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
11180        let why = state.merge.as_ref().unwrap().detail.clone();
11181        assert!(
11182            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
11183            "{why}"
11184        );
11185        assert_eq!(state.status, RunStatus::Blocked);
11186    }
11187
11188    #[test]
11189    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
11190        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
11191        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
11192        // The pull request is still on the commit before the push.
11193        assert_eq!(bound_head("old", "old", Some("new")), None);
11194        // The checks are the previous commit's.
11195        assert_eq!(bound_head("new", "old", Some("new")), None);
11196        assert_eq!(bound_head("new", "old", None), None);
11197        // Nothing readable.
11198        assert_eq!(bound_head("", "", None), None);
11199        assert_eq!(bound_head("", "", Some("new")), None);
11200        assert_eq!(bound_head("abc", "", None), None);
11201    }
11202
11203    fn view_json(head: &str) -> String {
11204        format!(
11205            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
11206            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
11207            "reviews":[],"comments":[]}}"#
11208        )
11209    }
11210
11211    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
11212        format!(
11213            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
11214            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
11215            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
11216            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
11217        )
11218    }
11219
11220    #[test]
11221    fn rollup_is_bound_to_the_commit_in_the_same_node() {
11222        // The view already points at the new head, but the node still answers
11223        // for the old commit with its red check: the head stays unbound.
11224        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
11225        assert_eq!(s.rollup_head, "old");
11226        assert_eq!(s.pr.checks, Checks::Red);
11227        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
11228        assert_eq!(s.failing_urls.len(), 1);
11229    }
11230
11231    #[test]
11232    fn checks_come_from_the_node_not_the_view() {
11233        let view = view_json("new").replace(
11234            r#""reviews""#,
11235            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
11236        );
11237        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
11238        assert_eq!(s.pr.checks, Checks::Green);
11239        assert!(s.pr.failing.is_empty());
11240        assert_eq!(
11241            bound_head(&s.head, &s.rollup_head, Some("new")),
11242            Some("new")
11243        );
11244    }
11245
11246    #[test]
11247    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
11248        for node in [
11249            None,
11250            Some("not json".to_owned()),
11251            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
11252            Some(node_json("new", "SUCCESS", true)),
11253        ] {
11254            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
11255            assert!(s.rollup_head.is_empty());
11256            assert_eq!(s.pr.checks, Checks::Unknown);
11257            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
11258        }
11259    }
11260
11261    #[test]
11262    fn the_merge_command_is_pinned_to_the_observed_head() {
11263        let argv = merge_argv_at(7, "feat: x", "deadbeef");
11264        let at = argv
11265            .iter()
11266            .position(|a| a == "--match-head-commit")
11267            .unwrap();
11268        assert_eq!(argv[at + 1], "deadbeef");
11269    }
11270
11271    #[tokio::test]
11272    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
11273        let mut state = landing_state();
11274        // The pull request is on the pushed head but the rollup is still the
11275        // previous commit's red, non-required result.
11276        let mut stale = seen("new", Checks::Red, "CLEAN", false);
11277        stale.rollup_head = "old".to_owned();
11278        let forge = Scripted::new(
11279            vec![seen("old", Checks::Green, "CLEAN", true), stale],
11280            vec![],
11281        );
11282        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11283            head: "new".to_owned(),
11284        });
11285        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11286            .await
11287            .unwrap();
11288        assert!(!forge.calls().contains(&"merge"));
11289        assert_eq!(state.status, RunStatus::Blocked);
11290        let why = state.merge.as_ref().unwrap().detail.clone();
11291        assert!(why.contains("new") && why.contains("old"), "{why}");
11292    }
11293
11294    #[test]
11295    fn a_refusal_read_against_another_commits_checks_is_pending() {
11296        let mut after = seen("a", Checks::Green, "BLOCKED", false);
11297        after.rollup_head = "old".to_owned();
11298        assert_eq!(
11299            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
11300            Refused::Pending
11301        );
11302    }
11303
11304    #[tokio::test]
11305    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
11306        let mut state = landing_state();
11307        state.config.merge.ci = crate::config::MergeCi::None;
11308        state.config.graph.land_approval = true;
11309        let forge = Scripted::new(
11310            vec![seen("a", Checks::Unknown, "CLEAN", false)],
11311            vec![(true, "")],
11312        );
11313        land_with(&mut state, URL, &forge).await.unwrap();
11314        assert!(state.parked);
11315        assert_eq!(forge.calls(), ["view"]);
11316        let store = ask::Questions::open();
11317        let mut q = store
11318            .get(&state.land_approval.as_ref().unwrap().question)
11319            .unwrap();
11320        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11321        store.put(&mut q).unwrap();
11322
11323        land_with(&mut state, URL, &forge).await.unwrap();
11324        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
11325        assert_eq!(state.status, RunStatus::Merged);
11326        assert_eq!(
11327            value_of(&forge.argvs()[0], "--match-head-commit"),
11328            Some("a")
11329        );
11330    }
11331
11332    #[tokio::test]
11333    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
11334        let mut state = landing_state();
11335        state.config.merge.ci = crate::config::MergeCi::None;
11336        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
11337        land_with(&mut state, URL, &forge).await.unwrap();
11338        assert!(forge.reruns.lock().unwrap().is_empty());
11339        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11340        assert_eq!(state.status, RunStatus::Merged);
11341    }
11342
11343    #[test]
11344    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
11345        let shown = BTreeSet::new();
11346        let guard = |s: Option<&Seen>| {
11347            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11348        };
11349        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11350        assert!(guard(Some(&fresh)));
11351        assert!(!guard(None));
11352        fresh.rollup_head = "old".to_owned();
11353        assert!(!guard(Some(&fresh)));
11354        fresh.rollup_head = "a".to_owned();
11355        fresh.head = "b".to_owned();
11356        assert!(!guard(Some(&fresh)));
11357        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11358        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11359    }
11360
11361    #[test]
11362    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11363        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11364            let after = seen("a", checks, "BLOCKED", false);
11365            assert_eq!(
11366                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11367                Refused::Recheck
11368            );
11369            assert_eq!(
11370                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11371                Refused::Final
11372            );
11373        }
11374    }
11375
11376    #[tokio::test]
11377    async fn a_matching_head_with_red_non_required_checks_still_merges() {
11378        let mut state = landing_state();
11379        let forge = Scripted::new(
11380            vec![seen("a", Checks::Red, "CLEAN", false)],
11381            vec![(true, "")],
11382        );
11383        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11384            .await
11385            .unwrap();
11386        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11387        assert_eq!(state.status, RunStatus::Merged);
11388    }
11389
11390    #[tokio::test]
11391    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11392        let mut state = landing_state();
11393        let forge = Scripted::new(
11394            vec![
11395                seen("a", Checks::Green, "CLEAN", false),
11396                seen("a", Checks::Green, "CLEAN", false),
11397                // Re-viewed after the refusal: someone pushed.
11398                seen("b", Checks::Green, "BLOCKED", false),
11399                seen("b", Checks::Green, "CLEAN", false),
11400            ],
11401            vec![(false, REFUSED), (true, "")],
11402        );
11403        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11404            .await
11405            .unwrap();
11406        assert_eq!(
11407            forge.calls(),
11408            [
11409                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
11410            ]
11411        );
11412        assert_eq!(state.status, RunStatus::Merged);
11413    }
11414
11415    fn merged_view(head: &str) -> Seen {
11416        let mut m = seen(head, Checks::Green, "CLEAN", false);
11417        m.pr.state = PrLifecycle::Merged;
11418        m
11419    }
11420
11421    fn has(argv: &[String], flag: &str) -> bool {
11422        argv.iter().any(|a| a == flag)
11423    }
11424
11425    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11426        let at = argv.iter().position(|a| a == flag)?;
11427        argv.get(at + 1).map(String::as_str)
11428    }
11429
11430    const URL: &str = "https://github.com/o/r/pull/42";
11431
11432    #[tokio::test]
11433    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11434        let mut state = landing_state();
11435        let forge = Scripted::new(
11436            vec![
11437                seen("abc", Checks::Green, "CLEAN", false),
11438                seen("abc", Checks::Green, "CLEAN", false),
11439            ],
11440            vec![(true, "")],
11441        );
11442        land_with(&mut state, URL, &forge).await.unwrap();
11443        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11444        let argv = &forge.argvs()[0];
11445        assert!(has(argv, "--squash") && has(argv, "--subject"));
11446        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11447        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11448        assert_eq!(state.status, RunStatus::Merged);
11449        assert!(state.land_armed_head.is_none());
11450    }
11451
11452    #[tokio::test]
11453    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11454        let mut state = landing_state();
11455        state.land_armed_head = Some("a".to_owned());
11456        let forge = Scripted::new(
11457            vec![seen("a", Checks::Green, "CLEAN", false)],
11458            vec![(true, ""), (true, "")],
11459        );
11460        land_with(&mut state, URL, &forge).await.unwrap();
11461        let argvs = forge.argvs();
11462        assert!(has(&argvs[0], "--disable-auto"));
11463        assert!(!has(&argvs[1], "--auto"));
11464        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11465        assert_eq!(state.status, RunStatus::Merged);
11466        assert!(state.land_armed_head.is_none());
11467    }
11468
11469    #[tokio::test]
11470    async fn an_approval_never_carries_over_to_a_new_head() {
11471        crate::run::pin_test_home();
11472        let mut state = run_state();
11473        state.config.graph.land_approval = true;
11474        let pr = green_pr();
11475        let store = ask::Questions::open();
11476
11477        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11478            .await
11479            .unwrap();
11480        let mut q = store
11481            .list()
11482            .into_iter()
11483            .find(|q| q.run == state.id)
11484            .unwrap();
11485        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11486        store.put(&mut q).unwrap();
11487        assert_eq!(
11488            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
11489                .await
11490                .unwrap(),
11491            ApprovalGate::Approved,
11492            "the same head keeps its approval"
11493        );
11494
11495        // A new head is a new question, not the old word.
11496        assert_eq!(
11497            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11498                .await
11499                .unwrap(),
11500            ApprovalGate::Pending
11501        );
11502        let all: Vec<_> = store
11503            .list()
11504            .into_iter()
11505            .filter(|q| q.run == state.id)
11506            .collect();
11507        assert_eq!(all.len(), 2);
11508
11509        // A question recorded before heads were tracked is not reused either.
11510        state.land_approval = None;
11511        assert_eq!(
11512            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11513                .await
11514                .unwrap(),
11515            ApprovalGate::Pending
11516        );
11517        let open = store
11518            .list()
11519            .into_iter()
11520            .filter(|q| q.run == state.id && q.status.open())
11521            .count();
11522        assert_eq!(open, 1, "the superseded question was retired");
11523    }
11524
11525    #[tokio::test]
11526    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11527        let mut state = landing_state();
11528        let forge = Scripted::new(
11529            vec![
11530                seen("a", Checks::Green, "CLEAN", false),
11531                // The fresh read before the merge: someone pushed.
11532                seen("b", Checks::Green, "CLEAN", false),
11533            ],
11534            vec![(true, "")],
11535        );
11536        land_with(&mut state, URL, &forge).await.unwrap();
11537        let argvs = forge.argvs();
11538        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11539        assert!(!has(&argvs[0], "--auto"));
11540        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11541        assert_eq!(state.status, RunStatus::Merged);
11542    }
11543
11544    fn passing(label: &str) -> CheckInfo {
11545        CheckInfo {
11546            label: label.to_owned(),
11547            verdict: Verdict::Pass,
11548            required: Some(false),
11549            run: None,
11550        }
11551    }
11552
11553    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11554        (label.to_owned(), run.map(str::to_owned))
11555    }
11556
11557    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11558        LandReruns {
11559            head: head.to_owned(),
11560            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11561        }
11562    }
11563
11564    #[test]
11565    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11566        let f = [failing("test (macos)", Some("7"))];
11567        assert_eq!(
11568            rerun_step(&f, None, "h", 100),
11569            RerunStep::Rerun(vec!["7".to_owned()])
11570        );
11571        let rec = reran("h", &[("7", 100)]);
11572        let grace = crate::release_watch::RERUN_GRACE;
11573        assert_eq!(
11574            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11575            RerunStep::Grace
11576        );
11577        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11578    }
11579
11580    #[test]
11581    fn a_failure_without_a_run_id_goes_to_the_fixer() {
11582        let f = [failing("a", Some("7")), failing("ci/external", None)];
11583        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11584        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11585    }
11586
11587    #[test]
11588    fn a_moved_head_forgets_the_reruns() {
11589        let f = [failing("a", Some("7"))];
11590        let rec = reran("old", &[("7", 100)]);
11591        assert_eq!(
11592            rerun_step(&f, Some(&rec), "new", 101),
11593            RerunStep::Rerun(vec!["7".to_owned()])
11594        );
11595    }
11596
11597    #[test]
11598    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11599        let f = [
11600            failing("a", Some("7")),
11601            failing("b", Some("7")),
11602            failing("c", Some("8")),
11603        ];
11604        assert_eq!(
11605            rerun_step(&f, None, "h", 0),
11606            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11607        );
11608        let rec = reran("h", &[("7", 0)]);
11609        assert_eq!(
11610            rerun_step(&f, Some(&rec), "h", 1),
11611            RerunStep::Rerun(vec!["8".to_owned()])
11612        );
11613    }
11614
11615    #[test]
11616    fn only_blocking_failures_are_candidates_for_a_rerun() {
11617        let check = |label: &str, verdict, required, run: &str| CheckInfo {
11618            label: label.to_owned(),
11619            verdict,
11620            required,
11621            run: Some(run.to_owned()),
11622        };
11623        let got = rerunnable(&[
11624            check("passed", Verdict::Pass, Some(true), "1"),
11625            check("optional", Verdict::Fail, Some(false), "2"),
11626            check("required", Verdict::Fail, Some(true), "3"),
11627            check("unknown", Verdict::Fail, None, "4"),
11628        ]);
11629        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11630        assert_eq!(labels, ["required", "unknown"]);
11631    }
11632
11633    fn unrelated_ci_fixture() -> CiEvidence {
11634        let failure = CiFailure {
11635            path: "tests/web_render.rs".into(),
11636            start_line: 42,
11637            end_line: 42,
11638            title: "question_identity_disclosure_copy_and_live_updates".into(),
11639            message: "assertion failed".into(),
11640        };
11641        CiEvidence {
11642            head: "a".into(),
11643            base: "base-sha".into(),
11644            changed: vec![
11645                "AGENTS.md".into(),
11646                "src/talk.rs".into(),
11647                "tests/consult_investigation.rs".into(),
11648            ],
11649            checks: vec![CiCheckEvidence {
11650                label: "coverage".into(),
11651                head_check: 70,
11652                base_check: 60,
11653                app: 1,
11654                run: "7".into(),
11655                base_run: "6".into(),
11656                head_failures: vec![failure.clone()],
11657                base_failures: vec![failure],
11658                rerun_exhausted: true,
11659            }],
11660        }
11661    }
11662
11663    #[test]
11664    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11665        let good = unrelated_ci_fixture();
11666        let red = vec!["coverage".into()];
11667        assert!(good.unrelated("a", &red));
11668        assert!(!good.unrelated("another-head", &red));
11669        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11670        assert!(!good.unrelated("a", &[]));
11671        for mutation in 0..8 {
11672            let mut bad = good.clone();
11673            match mutation {
11674                0 => bad.checks[0].rerun_exhausted = false,
11675                1 => bad.checks[0].base_failures.clear(),
11676                2 => bad.checks[0].head_failures.clear(),
11677                3 => bad.changed.push("tests/web_render.rs".into()),
11678                4 => bad.changed.push(".github/workflows/ci.yml".into()),
11679                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11680                6 => bad.checks.push(bad.checks[0].clone()),
11681                _ => bad.base.clear(),
11682            }
11683            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11684        }
11685    }
11686
11687    #[test]
11688    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11689        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11690        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11691        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11692        assert!(matches!(
11693            decide(&pr, 2, 2, CHECKS_GRACE),
11694            Step::GiveUp { .. }
11695        ));
11696        let optional = CheckInfo {
11697            label: "coverage".into(),
11698            verdict: Verdict::Fail,
11699            required: Some(false),
11700            run: Some("7".into()),
11701        };
11702        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11703        assert_eq!(
11704            rerunnable_with(&[optional], true),
11705            vec![("coverage".into(), Some("7".into()))]
11706        );
11707    }
11708
11709    #[tokio::test]
11710    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11711        let mut state = landing_state();
11712        let mut red = coverage_unknown();
11713        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11714        red.pr.failing = vec!["coverage".into()];
11715        let forge = Scripted::new(vec![red], vec![]);
11716        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11717        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11718        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11719        assert!(forge.calls().contains(&"fix"));
11720        assert!(state.land_unrelated.is_some());
11721        assert!(state.parked);
11722        assert!(
11723            !state
11724                .events
11725                .iter()
11726                .any(|e| e.message.contains("fixer produced no commit"))
11727        );
11728    }
11729
11730    fn coverage_unknown() -> Seen {
11731        let mut s = red("a", Some("7"));
11732        s.pr.blocking = Blocking::Unsaid;
11733        s.merge_state = "UNKNOWN".into();
11734        s.pr.failing = vec!["coverage".into()];
11735        s.contexts[0].label = "coverage".into();
11736        s.contexts[0].required = Some(false);
11737        s
11738    }
11739
11740    #[tokio::test]
11741    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11742        let mut state = landing_state();
11743        let unknown = coverage_unknown();
11744        let mut unstable = unknown.clone();
11745        unstable.pr.blocking = Blocking::of("UNSTABLE");
11746        unstable.merge_state = "UNSTABLE".into();
11747        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11748        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11749        assert!(!forge.calls().contains(&"fix"));
11750        assert!(!forge.calls().contains(&"rerun"));
11751        assert_eq!(state.status, RunStatus::Merged);
11752        assert_eq!(state.pr.unwrap().round, 0);
11753    }
11754
11755    #[tokio::test]
11756    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11757        let mut state = landing_state();
11758        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
11759        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11760        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11761        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11762        assert!(!forge.calls().contains(&"fix"));
11763        assert!(state.parked);
11764        assert_eq!(state.status, RunStatus::Landing);
11765        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11766        let hold = state.land_unrelated.as_ref().unwrap();
11767        let q = ask::Questions::open().get(&hold.question).unwrap();
11768        assert!(
11769            q.actions
11770                .values()
11771                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
11772        );
11773        assert!(
11774            state
11775                .events
11776                .iter()
11777                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
11778        );
11779        let first = state.land_unsaid.clone();
11780        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
11781        state.parked = false;
11782        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11783        assert_eq!(state.land_unsaid, first);
11784        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11785    }
11786
11787    fn red(head: &str, run: Option<&str>) -> Seen {
11788        let mut s = seen(head, Checks::Red, "BLOCKED", false);
11789        s.pr.failing = vec!["test (macos)".to_owned()];
11790        s.contexts = vec![CheckInfo {
11791            label: "test (macos)".to_owned(),
11792            verdict: Verdict::Fail,
11793            required: Some(true),
11794            run: run.map(str::to_owned),
11795        }];
11796        s
11797    }
11798
11799    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
11800
11801    #[tokio::test]
11802    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
11803        let mut state = landing_state();
11804        let forge = Scripted::new(
11805            vec![
11806                red("a", Some("7")),
11807                seen("a", Checks::Pending, "BLOCKED", false),
11808                seen("a", Checks::Green, "CLEAN", false),
11809            ],
11810            vec![(true, "")],
11811        );
11812        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11813        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11814        assert!(!forge.calls().contains(&"fix"));
11815        assert_eq!(state.status, RunStatus::Merged);
11816        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11817        let argvs = forge.argvs();
11818        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
11819        assert!(
11820            state
11821                .events
11822                .iter()
11823                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
11824        );
11825    }
11826
11827    #[tokio::test]
11828    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
11829        let mut state = landing_state();
11830        let forge = Scripted::new(
11831            vec![
11832                red("a", Some("7")),
11833                seen("a", Checks::Green, "CLEAN", false),
11834            ],
11835            vec![(true, "")],
11836        );
11837        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11838        // The red view repeats for the grace, then the fixer is asked once.
11839        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11840        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
11841        let calls = forge.calls();
11842        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
11843        let fix_at = calls.iter().position(|c| *c == "fix");
11844        assert!(fix_at.is_none_or(|f| f > rerun_at));
11845    }
11846
11847    #[tokio::test]
11848    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
11849        let mut state = landing_state();
11850        let mut v = red("a", Some("7"));
11851        v.pr.checks = Checks::Pending;
11852        v.contexts.push(CheckInfo {
11853            label: "slow".to_owned(),
11854            verdict: Verdict::Pending,
11855            required: Some(true),
11856            run: Some("8".to_owned()),
11857        });
11858        let forge = Scripted::new(
11859            vec![v, seen("a", Checks::Green, "CLEAN", false)],
11860            vec![(true, "")],
11861        );
11862        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11863        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11864        assert_eq!(state.status, RunStatus::Merged);
11865    }
11866
11867    #[test]
11868    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
11869        let mut v = red("a", Some("7"));
11870        v.contexts.push(CheckInfo {
11871            label: "same run, still going".to_owned(),
11872            verdict: Verdict::Pending,
11873            required: Some(true),
11874            run: Some("7".to_owned()),
11875        });
11876        assert!(rerunnable(&v.contexts).is_empty());
11877    }
11878
11879    #[tokio::test]
11880    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
11881        let mut state = landing_state();
11882        state.config.graph.land_rounds = 0;
11883        let forge = Scripted::new(
11884            vec![
11885                red("a", Some("7")),
11886                seen("a", Checks::Green, "CLEAN", false),
11887            ],
11888            vec![(true, "")],
11889        );
11890        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11891        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11892        assert_eq!(state.status, RunStatus::Merged);
11893        assert!(!forge.calls().contains(&"fix"));
11894        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11895    }
11896
11897    #[tokio::test]
11898    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
11899        let mut state = landing_state();
11900        state.config.graph.land_rounds = 1;
11901        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
11902        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
11903        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11904        assert_eq!(pr.state, PrLifecycle::Open);
11905        assert_eq!(state.status, RunStatus::Blocked);
11906        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11907        assert!(
11908            state.merge_decision.is_none(),
11909            "no ordinary failure handoff"
11910        );
11911        assert!(forge.argvs().is_empty(), "no merge on outage");
11912
11913        let recovered = Scripted::new(
11914            vec![
11915                seen("a", Checks::Green, "CLEAN", true),
11916                seen("b", Checks::Green, "CLEAN", false),
11917            ],
11918            vec![(true, "")],
11919        );
11920        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
11921        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
11922        assert_eq!(state.status, RunStatus::Merged);
11923        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11924        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
11925    }
11926
11927    #[tokio::test]
11928    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
11929        let mut state = landing_state();
11930        state.config.graph.land_rounds = 1;
11931        let forge = Scripted::new(
11932            vec![
11933                seen("a", Checks::Green, "CLEAN", true),
11934                red("b", Some("7")),
11935                seen("b", Checks::Green, "CLEAN", false),
11936            ],
11937            vec![(true, "")],
11938        );
11939        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11940            head: "b".to_owned(),
11941        });
11942        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11943        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11944        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
11945        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11946        assert_eq!(state.status, RunStatus::Merged);
11947        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
11948        assert_eq!(
11949            value_of(&forge.argvs()[0], "--match-head-commit"),
11950            Some("b")
11951        );
11952    }
11953
11954    #[tokio::test]
11955    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
11956        let mut state = landing_state();
11957        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11958        *forge.rerun_fails.lock().unwrap() = true;
11959        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11960        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11961        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
11962        assert_eq!(
11963            forge.calls().iter().filter(|c| **c == "fix").count(),
11964            1,
11965            "{:?}",
11966            forge.calls()
11967        );
11968    }
11969
11970    #[tokio::test]
11971    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
11972        let mut state = landing_state();
11973        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11974        // The record was written just before the previous pass died.
11975        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
11976        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11977        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11978        assert!(forge.reruns.lock().unwrap().is_empty());
11979    }
11980
11981    #[tokio::test]
11982    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
11983        let mut state = landing_state();
11984        state.config.graph.rerun_flaky_checks = false;
11985        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11986        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11987        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11988        assert!(forge.reruns.lock().unwrap().is_empty());
11989        assert!(forge.calls().contains(&"fix"));
11990
11991        let mut state = landing_state();
11992        let forge = Scripted::new(vec![red("a", None)], vec![]);
11993        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11994        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11995        assert!(forge.reruns.lock().unwrap().is_empty());
11996        assert!(forge.calls().contains(&"fix"));
11997    }
11998
11999    fn names(xs: &[&str]) -> BTreeSet<String> {
12000        xs.iter().map(|x| (*x).to_owned()).collect()
12001    }
12002
12003    #[test]
12004    fn a_required_check_the_rollup_never_listed_is_named() {
12005        let req = names(&["build"]);
12006        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
12007        assert!(why.contains("never reported: build"), "{why}");
12008        assert!(!why.contains("probably waiting for a review"), "{why}");
12009    }
12010
12011    #[test]
12012    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
12013        let why = waiting_on("BLOCKED", &[passing("review")], None);
12014        assert!(why.contains("could not be read"), "{why}");
12015        assert!(!why.contains("probably waiting for a review"), "{why}");
12016    }
12017
12018    #[test]
12019    fn all_required_reported_keeps_the_review_guess() {
12020        let req = names(&["build"]);
12021        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12022        assert!(why.contains("probably waiting for a review"), "{why}");
12023        assert!(!why.contains("never reported"), "{why}");
12024    }
12025
12026    #[test]
12027    fn required_names_match_the_rollup_ignoring_case_only() {
12028        let req = names(&["Build"]);
12029        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12030        assert!(!why.contains("never reported"), "{why}");
12031    }
12032
12033    #[test]
12034    fn required_contexts_are_read_from_protection_and_rulesets() {
12035        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
12036        assert_eq!(
12037            parse_classic_required(classic),
12038            Some(names(&["build", "lint"]))
12039        );
12040        let rules = r#"[{"type":"pull_request","parameters":{}},
12041            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
12042        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
12043        assert_eq!(parse_ruleset_required("nope"), None);
12044        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
12045    }
12046
12047    #[test]
12048    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
12049        let shown = BTreeSet::new();
12050        let ok = seen("a", Checks::Green, "CLEAN", false);
12051        let guard = |s: Option<&Seen>| {
12052            direct_merge_is_safe(
12053                s,
12054                "A",
12055                &shown,
12056                0,
12057                4,
12058                Duration::ZERO,
12059                CiExpectation::Expected,
12060            )
12061        };
12062        assert!(guard(Some(&ok)));
12063        assert!(!guard(None));
12064        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
12065        let mut stale = ok.clone();
12066        stale.rollup_head = "old".to_owned();
12067        assert!(!guard(Some(&stale)));
12068        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
12069        assert!(!guard(Some(&merged_view("a"))));
12070    }
12071
12072    #[test]
12073    fn the_rollup_node_carries_whether_each_check_is_required() {
12074        let node = node_json("new", "SUCCESS", false)
12075            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
12076        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
12077        assert_eq!(s.contexts.len(), 1);
12078        assert_eq!(s.contexts[0].required, Some(true));
12079        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
12080        assert_eq!(s.contexts[0].required, None);
12081    }
12082
12083    #[tokio::test]
12084    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
12085        let mut state = landing_state();
12086        state.land_armed_head = Some("a".to_owned());
12087        let forge = Scripted::new(
12088            vec![seen("a", Checks::Green, "CLEAN", true)],
12089            vec![(false, "disable exploded")],
12090        );
12091        land_with(&mut state, URL, &forge).await.unwrap();
12092        assert!(!forge.calls().contains(&"fix"));
12093        assert_eq!(state.status, RunStatus::Blocked);
12094        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
12095        let why = state.merge.as_ref().unwrap().detail.clone();
12096        assert!(why.contains("disable exploded"), "{why}");
12097    }
12098
12099    /// Create a cross-platform fake `gh` executable in `dir` backed by exact
12100    /// fixture files, avoiding shell quoting differences and global `PATH`
12101    /// mutation.
12102    pub(crate) fn fake_gh_script(
12103        dir: &Path,
12104        name: &str,
12105        stdout: &str,
12106        stderr: &str,
12107        exit_code: i32,
12108    ) -> PathBuf {
12109        let out_path = dir.join(format!("{name}.stdout"));
12110        let err_path = dir.join(format!("{name}.stderr"));
12111        std::fs::write(&out_path, stdout).unwrap();
12112        std::fs::write(&err_path, stderr).unwrap();
12113        #[cfg(windows)]
12114        {
12115            let script = dir.join(format!("{name}.cmd"));
12116            let mut body = String::from("@echo off\r\n");
12117            if !stdout.is_empty() {
12118                body.push_str(&format!("type \"{}\"\r\n", out_path.display()));
12119            }
12120            if !stderr.is_empty() {
12121                body.push_str(&format!("type \"{}\" 1>&2\r\n", err_path.display()));
12122            }
12123            body.push_str(&format!("exit /b {exit_code}\r\n"));
12124            std::fs::write(&script, body).unwrap();
12125            script
12126        }
12127        #[cfg(unix)]
12128        {
12129            use std::os::unix::fs::PermissionsExt as _;
12130            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
12131            let script = dir.join(name);
12132            let mut body = String::from("#!/bin/sh\n");
12133            if !stdout.is_empty() {
12134                body.push_str(&format!("cat {}\n", quote(&out_path)));
12135            }
12136            if !stderr.is_empty() {
12137                body.push_str(&format!("cat {} >&2\n", quote(&err_path)));
12138            }
12139            body.push_str(&format!("exit {exit_code}\n"));
12140            let status = std::process::Command::new("sh")
12141                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
12142                .arg(&script)
12143                .arg(&body)
12144                .status()
12145                .unwrap();
12146            assert!(status.success());
12147            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
12148            script
12149        }
12150    }
12151
12152    #[test]
12153    fn gh_output_combined_preserves_and_separates_both_streams() {
12154        let mk = |ok, stdout: &str, stderr: &str| GhOutput {
12155            ok,
12156            stdout: stdout.into(),
12157            stderr: stderr.into(),
12158        };
12159        assert_eq!(mk(true, "  ", "\n").combined(), "");
12160        assert_eq!(mk(true, "  only out \n", " \t ").combined(), "only out");
12161        assert_eq!(mk(false, "", "  only err\n").combined(), "only err");
12162        assert_eq!(
12163            mk(false, "{\"status\":\"404\"}", "gh: Not Found (HTTP 404)\n").combined(),
12164            "{\"status\":\"404\"}\ngh: Not Found (HTTP 404)"
12165        );
12166    }
12167
12168    #[tokio::test]
12169    async fn gh_separates_json_stdout_from_stderr_diagnostics() {
12170        let tmp = tempfile::tempdir().unwrap();
12171        let hint = "hint: to listen to pull request events, run `gh pr view --web`\n";
12172        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"}"#;
12173        let valid_list = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: test","baseRefName":"main","isCrossRepository":false}]"#;
12174
12175        // Valid JSON stdout + nonempty stderr hint on exit 0: structured reads
12176        // parse stdout cleanly while stderr remains available via `combined()`.
12177        let ok_view = fake_gh_script(tmp.path(), "ok-view", &format!("{valid_view}\n"), hint, 0);
12178        let out = gh_with(&ok_view, tmp.path(), &["pr".into(), "view".into()])
12179            .await
12180            .unwrap();
12181        assert!(out.ok);
12182        assert_eq!(parse_pr(&out.stdout).unwrap().state, PrLifecycle::Open);
12183        assert!(out.stderr.contains("listen to pull request events"));
12184        assert!(out.combined().contains("listen to pull request events"));
12185        assert!(out.combined().contains("feat: test"));
12186
12187        let ok_list = fake_gh_script(tmp.path(), "ok-list", &format!("{valid_list}\n"), hint, 0);
12188        assert_eq!(
12189            find_open_pr_with(&ok_list, tmp.path(), "magi/task-t", "main")
12190                .await
12191                .unwrap(),
12192            OpenPr::One {
12193                url: "https://github.com/example/repo/pull/1".into(),
12194                title: "feat: test".into(),
12195            }
12196        );
12197
12198        // Malformed stdout with trailing characters still fails strict JSON parsing.
12199        let malformed = fake_gh_script(
12200            tmp.path(),
12201            "malformed",
12202            &format!("{valid_view}\ntrailing garbage\n"),
12203            "",
12204            0,
12205        );
12206        let out = gh_with(&malformed, tmp.path(), &["pr".into(), "view".into()])
12207            .await
12208            .unwrap();
12209        assert!(out.ok);
12210        let err = parse_pr(&out.stdout).unwrap_err();
12211        assert!(
12212            format!("{err:#}").contains("trailing characters"),
12213            "{err:#}"
12214        );
12215
12216        // Empty stdout + nonempty stderr on exit 0 never substitutes stderr.
12217        let empty = fake_gh_script(tmp.path(), "empty", "", hint, 0);
12218        let out = gh_with(&empty, tmp.path(), &["pr".into(), "view".into()])
12219            .await
12220            .unwrap();
12221        assert!(out.ok);
12222        assert!(out.stdout.trim().is_empty());
12223        assert!(parse_pr(&out.stdout).is_err());
12224
12225        // Non-zero exit with valid JSON on stdout and error on stderr reports
12226        // failure and preserves both streams in `combined()`.
12227        let failed = fake_gh_script(
12228            tmp.path(),
12229            "failed",
12230            &format!("{valid_view}\n"),
12231            "gh: HTTP 404 Not Found\n",
12232            1,
12233        );
12234        let out = gh_with(&failed, tmp.path(), &["pr".into(), "view".into()])
12235            .await
12236            .unwrap();
12237        assert!(!out.ok);
12238        let diag = out.combined();
12239        assert!(diag.contains("HTTP 404 Not Found"), "{diag}");
12240        assert!(diag.contains("feat: test"), "{diag}");
12241        let list_err = find_open_pr_with(&failed, tmp.path(), "magi/task-t", "main")
12242            .await
12243            .unwrap_err()
12244            .to_string();
12245        assert!(list_err.contains("HTTP 404 Not Found"), "{list_err}");
12246    }
12247
12248    struct StaticPrObserver(crate::land_sync_recovery::ObservedPr);
12249
12250    impl crate::land_sync_recovery::PrObserver for StaticPrObserver {
12251        async fn observe_pr(
12252            &self,
12253            _repo: &Path,
12254            _pr_url: &str,
12255        ) -> Result<crate::land_sync_recovery::ObservedPr> {
12256            Ok(self.0.clone())
12257        }
12258    }
12259
12260    /// Build a real-shaped legacy landing base-sync exhaustion fixture backed by
12261    /// an isolated temp Git repo, bare origin, queue task, and open PR metadata.
12262    async fn legacy_exhausted_landing_fixture() -> (
12263        tempfile::TempDir,
12264        PathBuf,
12265        crate::queue::Queue,
12266        crate::queue::Task,
12267        RunState,
12268        String,
12269    ) {
12270        let (tmp, mut state, old) = landing_git_fixture().await;
12271        crate::run::pin_test_home();
12272        let home = crate::run::home();
12273        // Move run state under this isolated home so load_under/save_under match.
12274        state.config.graph.land_rounds = 4;
12275        state.config.graph.land_approval = true;
12276        state.config.verify.gate = vec!["git rev-parse HEAD".into()];
12277        state.config.verify.e2e = vec!["git rev-parse HEAD".into()];
12278        state.status = RunStatus::Blocked;
12279        state.driver_exited = true;
12280        state.pr = Some(crate::run::PrRecord {
12281            url: green_pr().url,
12282            number: 42,
12283            state: "open".to_owned(),
12284            checks: "green".to_owned(),
12285            round: 0,
12286            rounds: 4,
12287            red_at_merge: Vec::new(),
12288        });
12289        state.merge = Some(MergeOutcome {
12290            mode: MergeMode::Pr,
12291            ok: false,
12292            detail:
12293                "could not synchronize landing base: landing base synchronization budget exhausted"
12294                    .to_owned(),
12295            empty: false,
12296        });
12297        state.reviews = vec![serde_json::from_value(serde_json::json!({
12298            "round": 1,
12299            "head": old,
12300            "expected": 2,
12301            "answered": 2,
12302            "reviews": [],
12303            "clean": true,
12304            "e2e": [{"command": "git rev-parse HEAD", "code": 0, "output_tail": old, "duration_ms": 10}],
12305            "verified_head": old,
12306            "verified_at": jiff::Timestamp::now(),
12307            "e2e_deferred": false
12308        }))
12309        .unwrap()];
12310        let pass_cmd: crate::run::CommandOutcome = serde_json::from_value(serde_json::json!({
12311            "command": "git rev-parse HEAD",
12312            "code": 0,
12313            "output_tail": old,
12314            "duration_ms": 10
12315        }))
12316        .unwrap();
12317        state.head_e2e = Some(crate::run::GateRepairE2e::new(
12318            old.clone(),
12319            true,
12320            vec![pass_cmd.clone()],
12321        ));
12322        state.gate = vec![pass_cmd];
12323        state.gate_ran = true;
12324        state.gate_head = Some(old.clone());
12325        state.land_sync_attempts = 4;
12326        state.land_sync_target = None;
12327        state.land_sync_pending = true;
12328        state.event(
12329            "land",
12330            "stopped: could not synchronize landing base: landing base synchronization budget exhausted",
12331        );
12332
12333        let queue = crate::queue::Queue::at(home.join("queue"));
12334        let mut task = crate::queue::Task::new(
12335            "landing sync".into(),
12336            state.instruction.clone(),
12337            state.repo.clone(),
12338            crate::queue::Source::Human,
12339        );
12340        task.link_run(&state.id);
12341        task.hold_machine(Some("landing base synchronization budget exhausted".into()));
12342        queue.put(&mut task).unwrap();
12343        state.origin = Some(crate::run::Origin::queue(&task.id));
12344        state.save_under(&home).unwrap();
12345        (tmp, home, queue, task, state, old)
12346    }
12347
12348    #[tokio::test]
12349    async fn land_sync_recovery_continues_legacy_real_shaped_stop_on_existing_pr() {
12350        let (_tmp, home, queue, task, mut state, old) = legacy_exhausted_landing_fixture().await;
12351        let home = home.as_path();
12352
12353        // Advance origin/main once so landing rebase has real work to replay.
12354        advance_landing_base(&state).await;
12355
12356        // Pre-recovery: legacy shape recognized, recover-base refused, ordinary resume/release refused.
12357        assert!(state.land_sync_exhausted());
12358        assert!(!state.base_sync_blocked());
12359        assert!(crate::land_sync_recovery::held_task(&queue, &task));
12360        let base_err = crate::graph::Runner::authorize_base_recovery(home, &state.id, &task.id)
12361            .await
12362            .unwrap_err();
12363        assert!(
12364            base_err.to_string().contains("run has no base-sync stop"),
12365            "{base_err:#}"
12366        );
12367        assert!(crate::handover::resume_refusal_under(&state, Some(home)).is_none());
12368        assert!(crate::base_sync_recovery::ensure_generic_release(&queue, &task).is_err());
12369
12370        // Ordinary land_with without authorization refuses without refilling budget.
12371        let pr_url = green_pr().url;
12372        let blocked_forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12373        let err = land_with(&mut state, &pr_url, &blocked_forge)
12374            .await
12375            .unwrap_err();
12376        assert!(err.to_string().contains("budget exhausted"), "{err:#}");
12377        assert_eq!(state.land_sync_attempts, 4);
12378        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12379
12380        // Attach a prior head-bound approval on `old` to prove fresh approval is required after recovery.
12381        let questions = ask::Questions::at(home.join("questions"));
12382        let mut old_q = ask::Question::new(
12383            state.id.clone(),
12384            APPROVAL_NODE.into(),
12385            "owner".into(),
12386            "old head approval".into(),
12387            String::new(),
12388            vec![APPROVE.into()],
12389        );
12390        old_q
12391            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12392            .unwrap();
12393        questions.put(&mut old_q).unwrap();
12394        state.land_approval = Some(LandApproval {
12395            question: old_q.id.clone(),
12396            head: old.clone(),
12397        });
12398        state.save_under(home).unwrap();
12399
12400        // Admit explicit recover-land-sync via two-phase control.
12401        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12402            url: pr_url.clone(),
12403            number: 42,
12404            open: true,
12405            head: old.clone(),
12406            base_branch: Some("main".to_owned()),
12407        });
12408        let outcome = crate::land_sync_recovery_control::recover_with(
12409            &queue,
12410            home,
12411            crate::land_sync_recovery_control::Request {
12412                run: state.id.clone(),
12413                head: old.clone(),
12414                actor: "cli".into(),
12415                request: "req-legacy-1".into(),
12416            },
12417            &observer,
12418        )
12419        .await
12420        .unwrap();
12421        assert!(!outcome.repeated);
12422        assert_eq!(
12423            outcome
12424                .task
12425                .resume_override
12426                .as_ref()
12427                .and_then(|pin| pin.pinned_run.as_deref()),
12428            Some(state.id.as_str())
12429        );
12430
12431        // Ordinary fast-forward of origin/main between admission and dispatch is allowed.
12432        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
12433        std::fs::write(state.repo.join("advance2"), "advance2").unwrap();
12434        git::git(&state.repo, &["add", "."]).await.unwrap();
12435        git::git(&state.repo, &["commit", "-m", "advance base again"])
12436            .await
12437            .unwrap();
12438        git::git(&state.repo, &["push", "origin", "main"])
12439            .await
12440            .unwrap();
12441        git::git(&state.repo, &["checkout", "winner"])
12442            .await
12443            .unwrap();
12444
12445        let reloaded_task = queue.get(&task.id).unwrap();
12446        assert!(matches!(
12447            crate::land_sync_recovery::dispatch_check_with(&queue, home, &reloaded_task, &observer)
12448                .await,
12449            crate::land_sync_recovery::DispatchDecision::Proceed
12450        ));
12451
12452        // Execute continuation on the existing PR using real rebase + fresh gate + fresh E2E.
12453        let mut run = RunState::load_under(&state.id, home).unwrap();
12454        assert!(run.land_sync_recovery_pending());
12455        let mut forge = Scripted::new(
12456            vec![
12457                seen(&old, Checks::Green, "BEHIND", false),
12458                seen(&old, Checks::Green, "BEHIND", false),
12459                seen("@published", Checks::Green, "CLEAN", false),
12460            ],
12461            vec![],
12462        );
12463        forge.public_repo = Some(run.repo.clone());
12464        let pr = land_with(&mut run, &pr_url, &forge).await.unwrap();
12465        assert_eq!(pr.state, PrLifecycle::Open);
12466        assert!(run.parked, "must park awaiting fresh head-bound approval");
12467
12468        // Verify attempts preserved (4 -> 5), 1 grant consumed, fresh head published,
12469        // prior verification archived, fresh gate + E2E ran on new head, fresh approval asked.
12470        let new_head = git::rev_parse(&run.repo, "HEAD").await.unwrap();
12471        assert_ne!(new_head, old);
12472        assert_eq!(run.land_sync_attempts, 5);
12473        assert_eq!(run.land_sync_recovery.extra_attempts, 1);
12474        assert_eq!(run.land_sync_budget(), 5);
12475        assert!(!run.land_sync_pending);
12476        assert_eq!(run.pr_pushed_head.as_deref(), Some(new_head.as_str()));
12477        assert_eq!(
12478            git::remote_head(&run.repo, "origin", "task-head")
12479                .await
12480                .unwrap()
12481                .as_deref(),
12482            Some(new_head.as_str())
12483        );
12484        assert!(run.gate_ran);
12485        assert_eq!(run.gate_head.as_deref(), Some(new_head.as_str()));
12486        assert!(
12487            run.head_e2e
12488                .as_ref()
12489                .is_some_and(|e| e.head == new_head && e.passed)
12490        );
12491        assert_eq!(run.reviews.len(), 1);
12492        assert!(run.reviews[0].clean);
12493        assert_eq!(run.reviews[0].answered, 2);
12494        assert!(run.reviews[0].verified_head.is_none());
12495        assert!(!run.verification_history.is_empty());
12496        assert_eq!(run.land_sync_recovery.stops.len(), 1);
12497        assert_eq!(run.land_sync_recovery.authorizations.len(), 1);
12498        let auth = &run.land_sync_recovery.authorizations[0];
12499        assert!(auth.consumed);
12500        assert!(auth.invalidated.is_none());
12501        assert!(auth.archived_verification.is_some());
12502        let new_approval = run.land_approval.as_ref().unwrap();
12503        assert_ne!(new_approval.question, old_q.id);
12504        assert_eq!(new_approval.head, new_head);
12505    }
12506
12507    #[tokio::test]
12508    async fn land_sync_recovery_observes_external_merge_without_grant() {
12509        let (_tmp, home, queue, mut task, mut state, old) =
12510            legacy_exhausted_landing_fixture().await;
12511        let pr_url = format!(
12512            "https://github.com/example/landing-merge-{}/pull/42",
12513            state.id
12514        );
12515        state.pr.as_mut().unwrap().url.clone_from(&pr_url);
12516        state.save_under(&home).unwrap();
12517        task.resume_override = Some(crate::queue::OperatorResume {
12518            question_id: String::new(),
12519            at: jiff::Timestamp::now(),
12520            conductor_rehold: None,
12521            forced: true,
12522            pinned_run: Some(state.id.clone()),
12523        });
12524        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12525            url: pr_url.clone(),
12526            number: 42,
12527            open: false,
12528            head: old.clone(),
12529            base_branch: Some("main".into()),
12530        });
12531        assert!(matches!(
12532            crate::land_sync_recovery::dispatch_check_with(&queue, &home, &task, &observer).await,
12533            crate::land_sync_recovery::DispatchDecision::Proceed
12534        ));
12535        let mut merged = merged_view(&old);
12536        merged.pr.url = pr_url.clone();
12537        let forge = Scripted::new(vec![merged], vec![]);
12538        land_with(&mut state, &pr_url, &forge).await.unwrap();
12539        assert_eq!(state.status, RunStatus::Merged);
12540        assert_eq!(state.land_sync_attempts, 4);
12541        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12542        assert_eq!(forge.calls(), ["view"]);
12543    }
12544
12545    #[tokio::test]
12546    async fn land_sync_recovery_forces_fresh_e2e_and_gate_even_when_head_unchanged() {
12547        let (tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
12548        let home = home.as_path();
12549
12550        // Create marker-writing commands for gate and e2e so we prove both execute freshly
12551        // even when HEAD does not change (origin/main is already an ancestor of winner).
12552        let gate_marker = tmp.path().join("fresh-gate-ran");
12553        let e2e_marker = tmp.path().join("fresh-e2e-ran");
12554        state.config.verify.gate = vec![format!(
12555            "git rev-parse HEAD > \"{}\"",
12556            gate_marker.display().to_string().replace('\\', "/")
12557        )];
12558        state.config.verify.e2e = vec![format!(
12559            "git rev-parse HEAD > \"{}\"",
12560            e2e_marker.display().to_string().replace('\\', "/")
12561        )];
12562        let questions = ask::Questions::at(home.join("questions"));
12563        let mut old_q = ask::Question::new(
12564            state.id.clone(),
12565            APPROVAL_NODE.into(),
12566            "owner".into(),
12567            "prior approval on same head".into(),
12568            String::new(),
12569            vec![APPROVE.into()],
12570        );
12571        old_q
12572            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12573            .unwrap();
12574        questions.put(&mut old_q).unwrap();
12575        state.land_approval = Some(LandApproval {
12576            question: old_q.id.clone(),
12577            head: old.clone(),
12578        });
12579        state.save_under(home).unwrap();
12580
12581        let pr_url = green_pr().url;
12582        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12583            url: pr_url.clone(),
12584            number: 42,
12585            open: true,
12586            head: old.clone(),
12587            base_branch: Some("main".to_owned()),
12588        });
12589        crate::land_sync_recovery_control::recover_with(
12590            &queue,
12591            home,
12592            crate::land_sync_recovery_control::Request {
12593                run: state.id.clone(),
12594                head: old.clone(),
12595                actor: "cli".into(),
12596                request: "req-same-head".into(),
12597            },
12598            &observer,
12599        )
12600        .await
12601        .unwrap();
12602
12603        let mut run = RunState::load_under(&state.id, home).unwrap();
12604        let mut forge = Scripted::new(
12605            vec![
12606                seen(&old, Checks::Green, "CLEAN", false),
12607                seen(&old, Checks::Green, "CLEAN", false),
12608                seen(&old, Checks::Green, "CLEAN", false),
12609            ],
12610            vec![],
12611        );
12612        forge.public_repo = Some(run.repo.clone());
12613        land_with(&mut run, &pr_url, &forge).await.unwrap();
12614
12615        assert!(
12616            gate_marker.exists(),
12617            "fresh gate must run even on unchanged HEAD"
12618        );
12619        assert!(
12620            e2e_marker.exists(),
12621            "fresh E2E must run even on unchanged HEAD"
12622        );
12623        assert!(
12624            run.parked,
12625            "old approval before recovery must not be reused"
12626        );
12627        assert_ne!(run.land_approval.as_ref().unwrap().question, old_q.id);
12628    }
12629
12630    #[tokio::test]
12631    async fn land_sync_recovery_repeated_exhaustion_is_bounded_by_lifetime_cap() {
12632        let (_tmp, home, queue, task, mut state, mut head) =
12633            legacy_exhausted_landing_fixture().await;
12634        let home = home.as_path();
12635        state.config.graph.land_approval = false;
12636        state.save_under(home).unwrap();
12637
12638        let pr_url = green_pr().url;
12639        let mut base_step = 0usize;
12640        let advance_step = |repo: PathBuf, step: usize| async move {
12641            git::git(&repo, &["checkout", "main"]).await.unwrap();
12642            std::fs::write(repo.join(format!("advance-{step}")), format!("step-{step}")).unwrap();
12643            git::git(&repo, &["add", "."]).await.unwrap();
12644            git::git(&repo, &["commit", "-m", &format!("advance base {step}")])
12645                .await
12646                .unwrap();
12647            git::git(&repo, &["push", "origin", "main"]).await.unwrap();
12648            git::git(&repo, &["checkout", "winner"]).await.unwrap();
12649        };
12650        for grant_num in 1..=crate::land_sync_recovery::MAX_GRANTS {
12651            base_step += 1;
12652            advance_step(state.repo.clone(), base_step).await;
12653            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12654                url: pr_url.clone(),
12655                number: 42,
12656                open: true,
12657                head: head.clone(),
12658                base_branch: Some("main".to_owned()),
12659            });
12660            crate::land_sync_recovery_control::recover_with(
12661                &queue,
12662                home,
12663                crate::land_sync_recovery_control::Request {
12664                    run: state.id.clone(),
12665                    head: head.clone(),
12666                    actor: "cli".into(),
12667                    request: format!("req-cap-{grant_num}"),
12668                },
12669                &observer,
12670            )
12671            .await
12672            .unwrap();
12673
12674            // Simulate execution consuming grant, spending the 1 attempt, and hitting exhaustion again.
12675            state = RunState::load_under(&state.id, home).unwrap();
12676            let mut forge = Scripted::new(
12677                vec![
12678                    seen(&head, Checks::Green, "BEHIND", false),
12679                    seen(&head, Checks::Green, "BEHIND", false),
12680                    seen("@published", Checks::Green, "BEHIND", false),
12681                ],
12682                vec![],
12683            );
12684            forge.public_repo = Some(state.repo.clone());
12685            let prep = prepare_land_sync_recovery(&mut state, &pr_url, &forge)
12686                .await
12687                .unwrap();
12688            assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
12689            head = resume_landing_head(&mut state, &head, &pr_url, &forge, None)
12690                .await
12691                .unwrap();
12692            assert_eq!(state.land_sync_attempts, 4 + grant_num);
12693            assert_eq!(state.land_sync_recovery.extra_attempts, grant_num);
12694
12695            // Re-exhaust on another base advance.
12696            base_step += 1;
12697            advance_step(state.repo.clone(), base_step).await;
12698            let err = rebase_landing_worktree(&mut state, "origin/main")
12699                .await
12700                .unwrap_err();
12701            assert!(err.to_string().contains("budget exhausted"), "{err:#}");
12702            state.status = RunStatus::Blocked;
12703            state.save_under(home).unwrap();
12704            assert!(state.land_sync_exhausted());
12705
12706            // Put task back to Held so the next explicit authorization can queue it.
12707            let mut t = queue.get(&task.id).unwrap();
12708            t.hold_machine(Some("re-exhausted".into()));
12709            queue.put(&mut t).unwrap();
12710        }
12711
12712        assert_eq!(
12713            state.land_sync_attempts,
12714            4 + crate::land_sync_recovery::MAX_GRANTS
12715        );
12716        assert_eq!(state.land_sync_grants_remaining(), 0);
12717        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12718            url: pr_url,
12719            number: 42,
12720            open: true,
12721            head: head.clone(),
12722            base_branch: Some("main".to_owned()),
12723        });
12724        let err = crate::land_sync_recovery_control::recover_with(
12725            &queue,
12726            home,
12727            crate::land_sync_recovery_control::Request {
12728                run: state.id.clone(),
12729                head,
12730                actor: "cli".into(),
12731                request: "req-cap-overflow".into(),
12732            },
12733            &observer,
12734        )
12735        .await
12736        .unwrap_err();
12737        assert!(
12738            err.to_string()
12739                .contains("lifetime landing base-sync recovery limit reached"),
12740            "{err:#}"
12741        );
12742    }
12743
12744    #[tokio::test]
12745    async fn land_sync_recovery_execution_revalidation_refuses_stale_pr_head_and_rewritten_base() {
12746        let pr_url = green_pr().url;
12747        // Case A: PR head moves externally between admission and execution.
12748        {
12749            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
12750            let home = home.as_path();
12751            advance_landing_base(&state).await;
12752            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12753                url: pr_url.clone(),
12754                number: 42,
12755                open: true,
12756                head: old.clone(),
12757                base_branch: Some("main".to_owned()),
12758            });
12759            crate::land_sync_recovery_control::recover_with(
12760                &queue,
12761                home,
12762                crate::land_sync_recovery_control::Request {
12763                    run: state.id.clone(),
12764                    head: old.clone(),
12765                    actor: "cli".into(),
12766                    request: "req-stale-pr".into(),
12767                },
12768                &observer,
12769            )
12770            .await
12771            .unwrap();
12772
12773            let mut run = RunState::load_under(&state.id, home).unwrap();
12774            let foreign_head = "f".repeat(40);
12775            let forge = Scripted::new(
12776                vec![seen(&foreign_head, Checks::Green, "BEHIND", false)],
12777                vec![],
12778            );
12779            land_with(&mut run, &pr_url, &forge).await.unwrap();
12780            assert_eq!(run.status, RunStatus::Blocked);
12781            assert_eq!(run.land_sync_recovery.extra_attempts, 0);
12782            assert_eq!(run.land_sync_attempts, 4);
12783            let auth = run.land_sync_recovery.authorizations.last().unwrap();
12784            assert!(auth.consumed);
12785            assert!(
12786                auth.invalidated
12787                    .as_deref()
12788                    .is_some_and(|why| why.contains("published PR head changed")),
12789                "{:?}",
12790                auth.invalidated
12791            );
12792            assert_eq!(run.pr_pushed_head.as_deref(), Some(old.as_str()));
12793        }
12794
12795        // Case B: origin/main rewritten (non-fast-forward) between admission and execution.
12796        {
12797            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
12798            let home = home.as_path();
12799            advance_landing_base(&state).await;
12800            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12801                url: pr_url.clone(),
12802                number: 42,
12803                open: true,
12804                head: old.clone(),
12805                base_branch: Some("main".to_owned()),
12806            });
12807            crate::land_sync_recovery_control::recover_with(
12808                &queue,
12809                home,
12810                crate::land_sync_recovery_control::Request {
12811                    run: state.id.clone(),
12812                    head: old.clone(),
12813                    actor: "cli".into(),
12814                    request: "req-rewritten-base".into(),
12815                },
12816                &observer,
12817            )
12818            .await
12819            .unwrap();
12820
12821            // Persist consumption before the rewrite, as if the driver crashed
12822            // between granting the attempt and starting the rebase.
12823            let mut consumed = RunState::load_under(&state.id, home).unwrap();
12824            let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12825            assert!(matches!(
12826                prepare_land_sync_recovery(&mut consumed, &pr_url, &forge)
12827                    .await
12828                    .unwrap(),
12829                LandSyncPrep::Continue(Some(_))
12830            ));
12831            assert_eq!(consumed.land_sync_attempts, 4);
12832
12833            // Rewrite origin/main by amending the latest base commit and force-pushing.
12834            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
12835            std::fs::write(state.repo.join("advance"), "rewritten").unwrap();
12836            git::git(&state.repo, &["add", "."]).await.unwrap();
12837            git::git(&state.repo, &["commit", "--amend", "-m", "rewritten base"])
12838                .await
12839                .unwrap();
12840            git::git(&state.repo, &["push", "--force", "origin", "main"])
12841                .await
12842                .unwrap();
12843            git::git(&state.repo, &["checkout", "winner"])
12844                .await
12845                .unwrap();
12846
12847            let mut run = RunState::load_under(&state.id, home).unwrap();
12848            let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12849            land_with(&mut run, &pr_url, &forge).await.unwrap();
12850            assert_eq!(run.status, RunStatus::Blocked);
12851            assert_eq!(run.land_sync_recovery.extra_attempts, 1);
12852            assert_eq!(run.land_sync_attempts, 4);
12853            assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
12854            let auth = run.land_sync_recovery.authorizations.last().unwrap();
12855            assert!(auth.consumed);
12856            assert!(
12857                auth.invalidated
12858                    .as_deref()
12859                    .is_some_and(|why| why.contains("does not fast-forward")),
12860                "{:?}",
12861                auth.invalidated
12862            );
12863            assert!(run.land_sync_exhausted());
12864            assert_eq!(run.land_sync_budget(), 4);
12865            let mut held = queue
12866                .list()
12867                .into_iter()
12868                .find(|t| t.execution_runs().last() == Some(&run.id))
12869                .unwrap();
12870            held.hold_machine(Some("recovery scope changed".into()));
12871            queue.put(&mut held).unwrap();
12872            crate::land_sync_recovery_control::recover_with(
12873                &queue,
12874                home,
12875                crate::land_sync_recovery_control::Request {
12876                    run: run.id.clone(),
12877                    head: old.clone(),
12878                    actor: "cli".into(),
12879                    request: "req-rewritten-base-new-approval".into(),
12880                },
12881                &observer,
12882            )
12883            .await
12884            .unwrap();
12885            let mut resumed = RunState::load_under(&run.id, home).unwrap();
12886            let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12887            assert!(matches!(
12888                prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
12889                    .await
12890                    .unwrap(),
12891                LandSyncPrep::Continue(Some(_))
12892            ));
12893            assert_eq!(resumed.land_sync_recovery.extra_attempts, 2);
12894            assert_eq!(resumed.land_sync_budget(), 5);
12895            assert_eq!(resumed.land_sync_attempts, 4);
12896            assert!(
12897                resumed.land_sync_recovery.authorizations[0]
12898                    .invalidated
12899                    .is_some()
12900            );
12901        }
12902    }
12903
12904    #[tokio::test]
12905    async fn land_sync_recovery_restart_after_consume_continues_without_double_grant() {
12906        let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
12907        let home = home.as_path();
12908        let pr_url = green_pr().url;
12909        advance_landing_base(&state).await;
12910        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12911            url: pr_url.clone(),
12912            number: 42,
12913            open: true,
12914            head: old.clone(),
12915            base_branch: Some("main".to_owned()),
12916        });
12917        crate::land_sync_recovery_control::recover_with(
12918            &queue,
12919            home,
12920            crate::land_sync_recovery_control::Request {
12921                run: state.id.clone(),
12922                head: old.clone(),
12923                actor: "cli".into(),
12924                request: "req-crash-after-consume".into(),
12925            },
12926            &observer,
12927        )
12928        .await
12929        .unwrap();
12930
12931        // Simulate consuming the authorization and crashing right before rebase starts.
12932        let mut crashed = RunState::load_under(&state.id, home).unwrap();
12933        let initial_forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12934        let prep = prepare_land_sync_recovery(&mut crashed, &pr_url, &initial_forge)
12935            .await
12936            .unwrap();
12937        assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
12938        assert_eq!(crashed.land_sync_recovery.extra_attempts, 1);
12939        assert_eq!(crashed.land_sync_attempts, 4);
12940        assert!(crashed.land_sync_recovery.authorizations[0].consumed);
12941
12942        // An unreadable base is not proof that the authorized lineage changed.
12943        let remote = git::git(&state.repo, &["remote", "get-url", "origin"])
12944            .await
12945            .unwrap();
12946        git::git(
12947            &state.repo,
12948            &["remote", "set-url", "origin", "missing-local-origin"],
12949        )
12950        .await
12951        .unwrap();
12952        let mut interrupted = RunState::load_under(&state.id, home).unwrap();
12953        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12954        assert!(matches!(
12955            prepare_land_sync_recovery(&mut interrupted, &pr_url, &forge)
12956                .await
12957                .unwrap(),
12958            LandSyncPrep::Stop(_)
12959        ));
12960        assert!(
12961            interrupted.land_sync_recovery.authorizations[0]
12962                .invalidated
12963                .is_none()
12964        );
12965        assert_eq!(interrupted.land_sync_attempts, 4);
12966        git::git(&state.repo, &["remote", "set-url", "origin", remote.trim()])
12967            .await
12968            .unwrap();
12969        let mut held = queue
12970            .list()
12971            .into_iter()
12972            .find(|t| t.execution_runs().last() == Some(&state.id))
12973            .unwrap();
12974        held.hold_machine(Some("base observation failed".into()));
12975        queue.put(&mut held).unwrap();
12976        assert!(crate::resume::pin_queued(&queue, &state.id, None, None).unwrap());
12977        let queued = queue.get(&held.id).unwrap();
12978        assert!(matches!(
12979            crate::land_sync_recovery::dispatch_check_with(&queue, home, &queued, &observer).await,
12980            crate::land_sync_recovery::DispatchDecision::Proceed
12981        ));
12982
12983        // Reload after restart and run land_with: uses the 1 already-granted attempt, never double-grants.
12984        let mut restarted = RunState::load_under(&state.id, home).unwrap();
12985        let mut forge = Scripted::new(
12986            vec![
12987                seen(&old, Checks::Green, "BEHIND", false),
12988                seen(&old, Checks::Green, "BEHIND", false),
12989                seen("@published", Checks::Green, "CLEAN", false),
12990            ],
12991            vec![],
12992        );
12993        forge.public_repo = Some(restarted.repo.clone());
12994        land_with(&mut restarted, &pr_url, &forge).await.unwrap();
12995        assert_eq!(restarted.land_sync_recovery.extra_attempts, 1);
12996        assert_eq!(restarted.land_sync_attempts, 5);
12997        assert_eq!(restarted.land_sync_recovery.authorizations.len(), 1);
12998        assert!(!restarted.land_sync_pending);
12999    }
13000
13001    #[tokio::test]
13002    async fn land_sync_recovery_dispatch_revalidation_refuses_stale_and_superseded_state() {
13003        // 1. Without authorization, dispatch holds without spending budget.
13004        let (_tmp, home, queue, task, state, old) = legacy_exhausted_landing_fixture().await;
13005        let home = home.as_path();
13006        let pr_url = green_pr().url;
13007        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13008            url: pr_url,
13009            number: 42,
13010            open: true,
13011            head: old.clone(),
13012            base_branch: Some("main".to_owned()),
13013        });
13014        assert!(matches!(
13015            crate::land_sync_recovery::dispatch_check_with(&queue, home, &task, &observer).await,
13016            crate::land_sync_recovery::DispatchDecision::Hold { .. }
13017        ));
13018
13019        // 2. Admit authorization, then supersede with a newer owner decision before dispatch.
13020        crate::land_sync_recovery_control::recover_with(
13021            &queue,
13022            home,
13023            crate::land_sync_recovery_control::Request {
13024                run: state.id.clone(),
13025                head: old.clone(),
13026                actor: "cli".into(),
13027                request: "req-dispatch-superseded".into(),
13028            },
13029            &observer,
13030        )
13031        .await
13032        .unwrap();
13033        let mut t = queue.get(&task.id).unwrap();
13034        t.operator_decided_at = Some(
13035            t.operator_decided_at.unwrap_or_else(jiff::Timestamp::now)
13036                + jiff::SignedDuration::from_secs(10),
13037        );
13038        queue.put(&mut t).unwrap();
13039        let decision =
13040            crate::land_sync_recovery::dispatch_check_with(&queue, home, &t, &observer).await;
13041        match decision {
13042            crate::land_sync_recovery::DispatchDecision::Hold {
13043                reason,
13044                state: updated,
13045            } => {
13046                assert!(
13047                    reason.contains("newer owner decision superseded"),
13048                    "{reason}"
13049                );
13050                let auth = updated.land_sync_recovery.authorizations.last().unwrap();
13051                assert!(auth.consumed);
13052                assert!(auth.invalidated.is_some());
13053                assert_eq!(updated.land_sync_recovery.extra_attempts, 0);
13054            }
13055            crate::land_sync_recovery::DispatchDecision::Proceed => {
13056                panic!("superseded authorization must be refused at dispatch");
13057            }
13058        }
13059    }
13060}