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    // Even without a rebase, verification can change HEAD through gate repair.
3838    // Persist the start before either verification or repair can run.
3839    if state.land_sync_unstarted_grant() {
3840        state.land_sync_attempts += 1;
3841        state.land_sync_pending = true;
3842        state.event(
3843            "land-sync-recovery",
3844            "started recovery attempt without rebase",
3845        );
3846        state.save()?;
3847    }
3848    if state.gate_head.as_deref() != Some(&head)
3849        || !state.gate_ran
3850        || !state.gate_commands_allow_progress()
3851    {
3852        state.reconcile_verification_head(&head);
3853        state.gate.clear();
3854        state.gate_head = None;
3855        state.gate_ran = false;
3856        state.pre_gate.clear();
3857        state.pre_gate_commit = None;
3858        state.save()?;
3859        let inherited = crate::repo_lock::WaitPolicy::current();
3860        let wait = crate::repo_lock::WaitPolicy::new(
3861            Duration::from_secs(state.config.graph.timeout_resource_wait),
3862            move || inherited.cancelled(),
3863        );
3864        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3865        loop {
3866            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
3867                state.gate = outcomes.clone();
3868                check_landing_resources(state, "gate", &outcomes)?;
3869            }
3870            if outcomes.iter().all(|o| o.ok()) {
3871                break;
3872            }
3873            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
3874                crate::graph::GateFix::Retry => {
3875                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3876                }
3877                crate::graph::GateFix::Stop => break,
3878                crate::graph::GateFix::Defer => {
3879                    // The repair checks e2e immediately, before the next gate.
3880                    // Preserve a cache wait here as well as below; otherwise
3881                    // the daemon charges an attempt for unstarted verification.
3882                    if let Some(e2e) = &state.gate_repair_e2e {
3883                        let outcomes = e2e.outcomes.clone();
3884                        check_landing_resources(state, "e2e", &outcomes)?;
3885                    }
3886                    bail!("landing gate repair deferred");
3887                }
3888            }
3889        }
3890        state.gate = outcomes;
3891        state.gate_ran = true;
3892        state.save()?;
3893    }
3894    let inherited = crate::repo_lock::WaitPolicy::current();
3895    let wait = crate::repo_lock::WaitPolicy::new(
3896        Duration::from_secs(state.config.graph.timeout_resource_wait),
3897        move || inherited.cancelled(),
3898    );
3899    let checked = state
3900        .gate_head
3901        .clone()
3902        .context("landing gate has no checked SHA")?;
3903    anyhow::ensure!(
3904        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3905            && git::is_clean(&winner.worktree).await?,
3906        "landing tree changed after gate"
3907    );
3908    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
3909    if matches!(e2e, crate::graph::GateFix::Defer) {
3910        let outcomes = state
3911            .gate_repair_e2e
3912            .as_ref()
3913            .context("deferred landing e2e has no outcomes")?
3914            .outcomes
3915            .clone();
3916        check_landing_resources(state, "e2e", &outcomes)?;
3917    }
3918    anyhow::ensure!(
3919        matches!(e2e, crate::graph::GateFix::Retry),
3920        "post-repair e2e has not passed on the landing head; nothing published"
3921    );
3922    anyhow::ensure!(
3923        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3924            && git::is_clean(&winner.worktree).await?,
3925        "landing tree changed during post-repair e2e"
3926    );
3927    anyhow::ensure!(
3928        crate::graph::verify_current_head(state, &winner, &wait).await?,
3929        "current head e2e has not passed; nothing published"
3930    );
3931    anyhow::ensure!(
3932        state.gate_allows_progress(),
3933        "landing gate failed; nothing published"
3934    );
3935    crate::pr_head::ensure_owner(state)?;
3936    if owner_requested_stop(state)? {
3937        bail!("owner requested stop before publication");
3938    }
3939    let current = forge.view(&state.repo, pr_url).await?;
3940    anyhow::ensure!(
3941        current.pr.state == PrLifecycle::Open,
3942        "PR closed or merged while gating; nothing published"
3943    );
3944    anyhow::ensure!(
3945        current.head == observed || current.head == checked,
3946        "PR head changed while gating; nothing published"
3947    );
3948    anyhow::ensure!(
3949        crate::foreign_checkout::write_back(state, &checked).await?,
3950        "foreign checkout delivery is blocked; see the run events"
3951    );
3952    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
3953    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
3954    let refspec = format!("{checked}:refs/heads/{public}");
3955    let lock = repo_merge_lock(&state.repo);
3956    let _slot = lock.lock().await;
3957    let pushed = git::git_raw(
3958        &winner.worktree,
3959        &["push", &lease, &state.config.merge.remote, &refspec],
3960    )
3961    .await?;
3962    anyhow::ensure!(
3963        pushed.ok(),
3964        "publishing gated landing head failed: {}",
3965        pushed.stderr
3966    );
3967    state.pr_pushed_head = Some(checked.clone());
3968    state.land_sync_pending = false;
3969    state.save()?;
3970    Ok(checked)
3971}
3972
3973/// A scratch rebase moves the winner ref before its index and files. Recover
3974/// only a tree proven unchanged since the saved start; never discard edits.
3975async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
3976    let winner = state.winner().cloned().context("landing has no winner")?;
3977    let inherited = crate::repo_lock::WaitPolicy::current();
3978    let wait = crate::repo_lock::WaitPolicy::new(
3979        Duration::from_secs(state.config.graph.timeout_resource_wait),
3980        move || inherited.cancelled(),
3981    );
3982    let _coordination = crate::repo_lock::SeatLease::operation_with(
3983        &winner.worktree,
3984        state.config.coordination.as_ref(),
3985        &wait,
3986    )
3987    .await?;
3988    if !git::is_clean(&winner.worktree).await? {
3989        let from = state
3990            .land_rebase_from
3991            .as_deref()
3992            .context("landing worktree is dirty")?;
3993        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3994        anyhow::ensure!(head != from, "landing worktree is dirty");
3995        for args in [
3996            vec!["diff", "--cached", "--quiet", from],
3997            vec!["diff", "--quiet"],
3998        ] {
3999            anyhow::ensure!(
4000                git::git_raw(&winner.worktree, &args).await?.ok(),
4001                "landing worktree has edits beyond the interrupted rebase"
4002            );
4003        }
4004        // Preserve build artifacts and local files, including ignored ones.
4005        // read-tree can overwrite ignored paths, so reject collisions with
4006        // the new tree (including file/directory conflicts) before updating.
4007        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
4008        let tracked = git::git(
4009            &winner.worktree,
4010            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
4011        )
4012        .await?;
4013        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
4014            anyhow::ensure!(
4015                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
4016                    path == local
4017                        || path
4018                            .strip_prefix(local)
4019                            .is_some_and(|rest| rest.starts_with('/'))
4020                        || local
4021                            .strip_prefix(path)
4022                            .is_some_and(|rest| rest.starts_with('/'))
4023                }),
4024                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
4025            );
4026        }
4027        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
4028    }
4029    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
4030        anyhow::ensure!(
4031            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
4032            "landing synchronization started outside the foreign checkout history"
4033        );
4034        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
4035            // The rebase's tree already includes the base and the fixer's
4036            // resolutions. Retain that exact tree, but join the pre-sync
4037            // history so delivery remains fast-forward. Keep the checkpoint
4038            // until this succeeds: a crash after rebase (or after this merge)
4039            // must recover through this same idempotent path before gating.
4040            git::git(
4041                &winner.worktree,
4042                &[
4043                    "-c",
4044                    "core.hooksPath=/dev/null",
4045                    "merge",
4046                    "--strategy=ours",
4047                    "--no-ff",
4048                    "--no-autostash",
4049                    "--no-edit",
4050                    "-m",
4051                    "Merge pre-sync history into the repaired landing tree",
4052                    from,
4053                ],
4054            )
4055            .await?;
4056        }
4057    }
4058    crate::worktree_setup::prepare_with(
4059        &state.config,
4060        &state.repo,
4061        &winner.worktree,
4062        crate::build_target::Coordination::Held(_coordination.as_ref()),
4063    )
4064    .await?;
4065    state.land_rebase_from = None;
4066    state.save()?;
4067    Ok(())
4068}
4069
4070async fn rebase_landing_worktree(
4071    state: &mut RunState,
4072    onto: &str,
4073) -> Result<crate::rebase::Rebased> {
4074    restore_landing_worktree(state).await?;
4075    let winner = state.winner().cloned().context("landing has no winner")?;
4076    let scratch = state.dir().join("rebase");
4077    let target = match state.land_sync_target.clone() {
4078        Some(target) => {
4079            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4080            target
4081        }
4082        // Older records lack the target checkpoint, but Git retains the
4083        // exact target of an interrupted operation. It is a continuation too.
4084        None if crate::rebase::checked_progress(state, &scratch, "").await? => {
4085            crate::rebase::rebase_target(&scratch).await?
4086        }
4087        None => {
4088            if state.land_sync_attempts >= state.land_sync_budget() {
4089                let head = git::rev_parse(&winner.worktree, "HEAD")
4090                    .await
4091                    .unwrap_or_default();
4092                let tip = git::rev_parse(&state.repo, onto).await.unwrap_or_default();
4093                let pr_head = state.pr_pushed_head.clone().unwrap_or_else(|| head.clone());
4094                state.land_sync_pending = true;
4095                state.record_land_sync_exhausted_stop(&head, &pr_head, &tip);
4096                let _ = state.save();
4097                bail!("{}", crate::land_sync_recovery::EXHAUSTED_DETAIL);
4098            }
4099            let target = git::rev_parse(&state.repo, onto).await?;
4100            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4101            state.land_sync_attempts += 1;
4102            state.land_sync_target = Some(target.clone());
4103            target
4104        }
4105    };
4106    state.land_sync_target = Some(target.clone());
4107    state.land_sync_pending = true;
4108    state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4109    state.save()?;
4110    // A continuation owns the attempt already charged above, including a
4111    // crash before the scratch rebase started. Finish its pinned base first;
4112    // a newer base must use another attempt on the next observation.
4113    let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4114    state.land_sync_target = None;
4115    state.save()?;
4116    if result == crate::rebase::Rebased::Applied {
4117        restore_landing_worktree(state).await?;
4118    }
4119    Ok(result)
4120}
4121
4122/// Reconcile a stopped landing before changing its branch. This also handles
4123/// old records whose graph status or merge detail no longer identifies land.
4124async fn resume_landing_head<F: Forge>(
4125    state: &mut RunState,
4126    observed: &str,
4127    pr_url: &str,
4128    forge: &F,
4129    reason: Option<Blocking>,
4130) -> Result<String> {
4131    crate::pr_head::ensure_owner(state)?;
4132    let winner = state.winner().cloned().context("landing has no winner")?;
4133    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4134    let expected = state
4135        .pr_pushed_head
4136        .as_deref()
4137        .or(state.gate_head.as_deref())
4138        .context("missing public head lease")?;
4139    anyhow::ensure!(
4140        observed == expected
4141            || (observed == local
4142                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4143                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4144        "public head moved outside this run; refusing to sync"
4145    );
4146    // An operator may have extended and published the winner while approval
4147    // was pending. Matching local/public history can be adopted as the lease,
4148    // but publish_landing_head must gate its new SHA before proceeding. A
4149    // remote-only or divergent update still cannot be overwritten.
4150    // Save reconciliation before rebasing again; a prior push may have reached
4151    // the remote immediately before the previous driver's last save.
4152    state.pr_pushed_head = Some(observed.to_owned());
4153    state.save()?;
4154    restore_landing_worktree(state).await?;
4155    // Recover a rebase that finished before its completion checkpoint was
4156    // saved. Restoration above has already reconciled its files and ancestry.
4157    let scratch = state.dir().join("rebase");
4158    if let Some(target) = state.land_sync_target.clone()
4159        && !crate::rebase::checked_progress(state, &scratch, "").await?
4160        && git::ancestry(&winner.worktree, &target, &local).await?
4161    {
4162        state.land_sync_target = None;
4163        state.save()?;
4164    }
4165    let remote = state.config.merge.remote.clone();
4166    let base = state.base_branch.clone();
4167    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4168    anyhow::ensure!(
4169        fetched.ok(),
4170        "cannot fetch landing base: {}",
4171        fetched.stderr
4172    );
4173    anyhow::ensure!(
4174        !owner_requested_stop(state)?,
4175        "owner requested stop before base synchronization"
4176    );
4177    let onto = format!("{remote}/{base}");
4178    let tip = git::rev_parse(&state.repo, &onto).await?;
4179    if state.land_sync_unstarted_grant() {
4180        let auth = state
4181            .land_sync_recovery
4182            .authorizations
4183            .last()
4184            .context("missing recovery grant")?;
4185        anyhow::ensure!(
4186            auth.invalidated.is_none()
4187                && git::ancestry(&state.repo, &auth.scope.tip, &tip).await?
4188                && git::ancestry(&state.repo, &auth.stop.tip, &tip).await?,
4189            "fetched landing base is outside the authorized recovery lineage"
4190        );
4191    }
4192    let contains_base = git::ancestry(&state.repo, &tip, &local)
4193        .await
4194        .context("could not determine whether the landing head contains the fetched base")?;
4195    anyhow::ensure!(
4196        reason != Some(Blocking::Behind) || !contains_base,
4197        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4198    );
4199    if !contains_base || reason == Some(Blocking::Conflict) {
4200        match rebase_landing_worktree(state, &tip).await? {
4201            crate::rebase::Rebased::Applied => {}
4202            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4203        }
4204    }
4205    if reason == Some(Blocking::Behind) {
4206        anyhow::ensure!(
4207            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4208            "BEHIND synchronization left the head unchanged"
4209        );
4210    }
4211    publish_landing_head(state, observed, pr_url, forge).await
4212}
4213
4214/// Share the synchronization path with structured evidence retained after a refusal.
4215async fn synchronize_landing<F: Forge>(
4216    state: &mut RunState,
4217    pr: &mut PrState,
4218    observed: &str,
4219    pr_url: &str,
4220    forge: &F,
4221) -> Result<Option<String>> {
4222    if owner_stop(state, pr, forge).await? {
4223        return Ok(None);
4224    }
4225    state.event(
4226        "land",
4227        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4228    );
4229    state.save()?;
4230    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4231    if owner_stop(state, pr, forge).await? {
4232        return Ok(None);
4233    }
4234    match synced {
4235        Ok(head) => {
4236            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4237                crate::graph::refresh_reviewed_commits(state, &branch).await;
4238            }
4239            Ok(Some(head))
4240        }
4241        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4242        Err(e) => {
4243            let repo = state.repo.clone();
4244            stop(
4245                state,
4246                &repo,
4247                pr,
4248                &format!("could not synchronize landing base: {e:#}"),
4249            )
4250            .await?;
4251            Ok(None)
4252        }
4253    }
4254}
4255
4256enum LandSyncPrep {
4257    Continue(Option<Seen>),
4258    Stop(PrState),
4259}
4260
4261/// Revalidate and durably consume a pending landing base-sync recovery
4262/// authorization under the live execution lease before mutating landing status
4263/// or adopting any observed PR head.
4264async fn prepare_land_sync_recovery<F: Forge>(
4265    state: &mut RunState,
4266    pr_url: &str,
4267    forge: &F,
4268) -> Result<LandSyncPrep> {
4269    let has_unconsumed = state.has_unconsumed_land_sync_authorization();
4270    let unstarted = state.land_sync_unstarted_grant();
4271    let exhausted = state.land_sync_exhausted();
4272    if !has_unconsumed && !exhausted && !unstarted {
4273        return Ok(LandSyncPrep::Continue(None));
4274    }
4275    let repo = state.repo.clone();
4276    let seen = forge.view(&repo, pr_url).await?;
4277    if seen.pr.state != PrLifecycle::Open {
4278        anyhow::ensure!(
4279            state
4280                .pr
4281                .as_ref()
4282                .is_some_and(|pr| pr.url == seen.pr.url && pr.number == seen.pr.number),
4283            "terminal pull request does not match the retained run"
4284        );
4285        return Ok(LandSyncPrep::Continue(Some(seen)));
4286    }
4287    if !has_unconsumed && !unstarted {
4288        bail!(
4289            "{}; explicit recover-land-sync authorization required",
4290            crate::land_sync_recovery::EXHAUSTED_DETAIL
4291        );
4292    }
4293    let observed = crate::land_sync_recovery::ObservedPr {
4294        url: seen.pr.url.clone(),
4295        number: seen.pr.number,
4296        open: seen.pr.state == PrLifecycle::Open,
4297        head: seen.head.clone(),
4298        base_branch: (!seen.base.is_empty()).then(|| seen.base.clone()),
4299    };
4300    let home = crate::run::home();
4301    let validation = if owner_requested_stop(state)? {
4302        Err("owner requested stop before landing base-sync recovery".into())
4303    } else {
4304        crate::land_sync_recovery::validate_pending_authorization(
4305            &home,
4306            state,
4307            None,
4308            Some(&observed),
4309            &crate::land_sync_recovery::GhPrObserver,
4310        )
4311        .await
4312    };
4313    match validation {
4314        Ok((local_head, pr_head)) => {
4315            if unstarted {
4316                return Ok(LandSyncPrep::Continue(Some(seen)));
4317            }
4318            if let Err(reason) = state.consume_land_sync_recovery(&local_head, &pr_head) {
4319                state.status = RunStatus::Blocked;
4320                state.event("land-sync-recovery", format!("refused: {reason}"));
4321                state.save()?;
4322                return Ok(LandSyncPrep::Stop(seen.pr));
4323            }
4324            state.event(
4325                "land-sync-recovery",
4326                format!(
4327                    "consumed recovery grant {}/{}: authorized {} landing sync attempt ({}/{}); prior verification archived, fresh E2E and gate required",
4328                    state.land_sync_recovery.extra_attempts,
4329                    crate::land_sync_recovery::MAX_GRANTS,
4330                    crate::land_sync_recovery::GRANT_ATTEMPTS,
4331                    state.land_sync_attempts,
4332                    state.land_sync_budget()
4333                ),
4334            );
4335            state.save()?;
4336            Ok(LandSyncPrep::Continue(Some(seen)))
4337        }
4338        Err(failure) => {
4339            let reason = failure.reason;
4340            if !failure.observation_failed
4341                && let Some(auth) = state
4342                    .land_sync_recovery
4343                    .authorizations
4344                    .iter_mut()
4345                    .rev()
4346                    .find(|a| {
4347                        a.invalidated.is_none()
4348                            && (!a.consumed || unstarted && a.archived_verification.is_some())
4349                    })
4350            {
4351                auth.refuse(&reason);
4352            }
4353            state.status = RunStatus::Blocked;
4354            state.event("land-sync-recovery", format!("refused: {reason}"));
4355            state.save()?;
4356            Ok(LandSyncPrep::Stop(seen.pr))
4357        }
4358    }
4359}
4360
4361async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4362    crate::pr_head::ensure_owner(state)?;
4363    let mut initial_seen = match prepare_land_sync_recovery(state, pr_url, forge).await? {
4364        LandSyncPrep::Continue(seen) => seen,
4365        LandSyncPrep::Stop(pr) => return Ok(pr),
4366    };
4367    state.land_unrelated = None;
4368    let reopening_hold = crate::merge_decision::resumable_hold(state);
4369    let repo = state.repo.clone();
4370    let budget = state.config.graph.land_rounds;
4371    let mut round = 0usize;
4372    let ci = state.config.merge.ci.expectation();
4373    if ci == CiExpectation::Absent {
4374        state.event(
4375            "land",
4376            "CI not expected ([merge] ci = \"none\"); check status ignored",
4377        );
4378    }
4379    let mut waited = Duration::ZERO;
4380    // Comment bodies the fixer has already been shown. A comment is
4381    // outstanding until it has been handed over once; after that it is a
4382    // recorded decision, not an open question, and re-feeding it would loop the
4383    // budget away on a comment the fixer already declined with an argument.
4384    let mut shown: BTreeSet<String> = BTreeSet::new();
4385    // Await the last successfully published head, including across resumes.
4386    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4387    // Whether a settled-checks refusal has already been given its one re-look.
4388    let mut rechecked = false;
4389
4390    // Marks the run resumable through exactly this function, not through a
4391    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4392    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4393    // status specifically to know a resumed run belongs back in `land`
4394    // rather than at a second `gh pr create`. Set on every entry - fresh or
4395    // resumed - because a resume that parked here again must keep reading
4396    // `Landing`, not whatever a first pass through `merge` left behind.
4397    state.status = RunStatus::Landing;
4398    state.event("land", format!("watching {pr_url}"));
4399    state.save()?;
4400
4401    // An armed merge recorded by an earlier pass may or may not have reached
4402    // the forge (the record is written before the call). It is taken back on
4403    // the first observation, where a pull request is known to stop with.
4404    let mut resumed_armed = state.land_armed_head.is_some();
4405
4406    'landing: loop {
4407        let seen = match initial_seen.take() {
4408            Some(seen) => seen,
4409            None => forge.view(&repo, pr_url).await?,
4410        };
4411        let mut pr = seen.pr.clone();
4412        pr.review_comments.retain(|c| !shown.contains(&c.body));
4413        state.pr = Some(crate::run::PrRecord {
4414            url: pr.url.clone(),
4415            number: pr.number,
4416            state: pr.state.as_str().to_owned(),
4417            checks: pr.checks.as_str().to_owned(),
4418            round,
4419            rounds: budget,
4420            red_at_merge: Vec::new(),
4421        });
4422        state.save()?;
4423
4424        if pr.state == PrLifecycle::Open {
4425            state.observe_branch_owner_holds(&seen.head).await;
4426            state.save()?;
4427        }
4428        crate::pr_head::ensure_owner(state)?;
4429        if reopening_hold {
4430            anyhow::ensure!(
4431                pr.state == PrLifecycle::Open,
4432                "held PR is no longer open; cannot request a fresh decision"
4433            );
4434            // An explicit resume authorizes a fresh question only. Preserve the
4435            // answered card, and never enter repair/rebase/merge on this pass.
4436            disarm(forge, state, &repo, pr.number)
4437                .await
4438                .map_err(anyhow::Error::msg)?;
4439            let previous = state.merge_decision.take();
4440            let binding = state.land_approval.take();
4441            state.config.graph.land_approval = true;
4442            let subject = merge_subject(
4443                crate::graph::landing_title(state, &seen.title),
4444                &crate::graph::landing_subject_source(state),
4445            );
4446            let contested = contested_to_ask(state);
4447            if let Err(error) =
4448                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4449            {
4450                state.merge_decision = previous;
4451                state.land_approval = binding;
4452                return Err(error);
4453            }
4454            state.end_pass_parked(crate::run::ParkCause::Question);
4455            state.parked = true;
4456            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()));
4457            state.save()?;
4458            return Ok(pr);
4459        }
4460        if owner_stop(state, &mut pr, forge).await? {
4461            return Ok(pr);
4462        }
4463
4464        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4465            // An approval already given for the same head is reused, so
4466            // nothing is asked twice. A failed disable
4467            // stops the run with the record kept: pushing on could change the
4468            // head under an arm that is still live.
4469            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4470                let why = format!(
4471                    "a previous pass may have armed auto-merge and it could not be disabled \
4472                     on resume: {e}"
4473                );
4474                stop(state, &repo, &pr, &why).await?;
4475                return Ok(pr);
4476            }
4477        }
4478
4479        // The head moved away from the one auto-merge was armed on, by
4480        // someone other than this loop. The arm is pinned and would refuse to
4481        // merge the new commit, but the approval was for the old one: take it
4482        // back and go through the normal path again.
4483        if pr.state == PrLifecycle::Open
4484            && !seen.head.is_empty()
4485            && state
4486                .land_armed_head
4487                .as_deref()
4488                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4489        {
4490            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4491                let why = format!(
4492                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4493                );
4494                stop(state, &repo, &pr, &why).await?;
4495                return Ok(pr);
4496            }
4497        }
4498
4499        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4500            // Disarming can outlive an owner answer. Consume it before our
4501            // own rebase invalidates the head shown on the decision card.
4502            if owner_stop(state, &mut pr, forge).await? {
4503                return Ok(pr);
4504            }
4505            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4506                binding.head.eq_ignore_ascii_case(&seen.head)
4507                    && ask::Questions::open()
4508                        .get_for_effects(&binding.question)
4509                        .is_ok_and(|q| {
4510                            q.run == state.id
4511                                && q.node == APPROVAL_NODE
4512                                && q.status == ask::QuestionStatus::Answered
4513                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4514                        })
4515            });
4516            if repair_answer {
4517                let subject = merge_subject(
4518                    crate::graph::landing_title(state, &seen.title),
4519                    &crate::graph::landing_subject_source(state),
4520                );
4521                let contested = contested_to_ask(state);
4522                if matches!(
4523                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4524                    ApprovalGate::Repair
4525                ) {
4526                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4527                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4528                        state.save()?;
4529                    }
4530                    return Ok(pr);
4531                }
4532            }
4533            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4534            // A stop detected before publication must apply its durable
4535            // decision, even when verification returned an error meanwhile.
4536            if owner_stop(state, &mut pr, forge).await? {
4537                return Ok(pr);
4538            }
4539            let head = synced?;
4540            awaiting_head = Some(head);
4541            waited = Duration::ZERO;
4542            rechecked = false;
4543            // Read CI and approvals afresh, never from the pre-push observation.
4544            continue;
4545        }
4546
4547        // A stale base is independent of the CI rollup. Keep the public-head
4548        // lease, but synchronize before waiting for checks on the old tree.
4549        if pr.state == PrLifecycle::Open
4550            && pr.blocking == Blocking::Behind
4551            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4552        {
4553            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4554            let Some(head) = synced else {
4555                return Ok(pr);
4556            };
4557            awaiting_head = Some(head);
4558            rechecked = false;
4559            waited = Duration::ZERO;
4560            continue;
4561        }
4562
4563        if pr.state == PrLifecycle::Open {
4564            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4565                if waited >= WAIT_CEILING {
4566                    let want = awaiting_head.as_deref().unwrap_or_default();
4567                    let why = format!(
4568                        "the pull request's checks were still not about one readable head after \
4569                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4570                         someone may have pushed over it",
4571                        WAIT_CEILING.as_secs() / 60,
4572                        if want.is_empty() { "any" } else { want },
4573                        if seen.head.is_empty() {
4574                            "nothing readable"
4575                        } else {
4576                            &seen.head
4577                        },
4578                        if seen.rollup_head.is_empty() {
4579                            "nothing readable"
4580                        } else {
4581                            &seen.rollup_head
4582                        },
4583                    );
4584                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4585                    return Ok(pr);
4586                }
4587                waited += POLL;
4588                forge.poll().await;
4589                continue;
4590            }
4591            // Reset once, when the awaited head first shows up; resetting on
4592            // every re-observation would let a standing refusal wait forever.
4593            if awaiting_head.take().is_some() {
4594                // The checks now being read belong to the new head; give them
4595                // the same grace a fresh pull request gets.
4596                waited = Duration::ZERO;
4597            }
4598        }
4599
4600        // The merge-state grace is head-bound and durable. Reruns reset the
4601        // checks clock, but must not extend this deadline across resumes.
4602        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4603            let first = state
4604                .land_unsaid
4605                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4606            if !first.0.eq_ignore_ascii_case(&seen.head) {
4607                *first = (seen.head.clone(), forge.now());
4608            }
4609            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4610            state.save()?;
4611            elapsed
4612        } else {
4613            waited
4614        };
4615        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4616        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4617            if waited >= WAIT_CEILING {
4618                stop_disarmed(
4619                    forge,
4620                    state,
4621                    &repo,
4622                    &pr,
4623                    "merge state remained unreadable; refusing to merge on a guess",
4624                )
4625                .await?;
4626                return Ok(pr);
4627            }
4628            waited += POLL;
4629            forge.poll().await;
4630            continue;
4631        }
4632
4633        // A failed workflow run is rerun once, judged by its own run rather
4634        // than by the rollup's aggregate: another run still pending, or a fix
4635        // budget already spent, must not keep a flaky failure from its one
4636        // rerun. It spends no round and no attempt.
4637        if ci == CiExpectation::Expected
4638            && pr.state == PrLifecycle::Open
4639            && state.config.graph.rerun_flaky_checks
4640        {
4641            let include_optional = pr.checks == Checks::Red
4642                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4643            let failing = rerunnable_with(&seen.contexts, include_optional);
4644            let now = forge.now();
4645            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4646                RerunStep::Rerun(runs) => {
4647                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4648                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4649                        *rec = LandReruns {
4650                            head: seen.head.clone(),
4651                            runs: BTreeMap::new(),
4652                        };
4653                    }
4654                    for run in &runs {
4655                        rec.runs.insert(run.clone(), now);
4656                    }
4657                    // Durable before the call: a restart must not
4658                    // rerun the same run twice. A save that fails
4659                    // means no rerun.
4660                    state.save()?;
4661                    let mut any = false;
4662                    for run in &runs {
4663                        let names = failing
4664                            .iter()
4665                            .filter(|(_, r)| r.as_deref() == Some(run))
4666                            .map(|(l, _)| l.as_str())
4667                            .collect::<Vec<_>>()
4668                            .join(", ");
4669                        match forge.rerun(&repo, run).await {
4670                            Ok(()) => {
4671                                any = true;
4672                                state.event(
4673                                    "land",
4674                                    format!("reran failed check(s) {names} (run {run})"),
4675                                );
4676                            }
4677                            // Stays recorded: never a retry loop.
4678                            Err(e) => state.event(
4679                                "land",
4680                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4681                            ),
4682                        }
4683                    }
4684                    state.save()?;
4685                    if any {
4686                        waited = Duration::ZERO;
4687                        forge.poll().await;
4688                        continue;
4689                    }
4690                }
4691                RerunStep::Grace => {
4692                    if waited >= WAIT_CEILING {
4693                        let why = format!(
4694                            "checks were still failing after a rerun and {} minutes",
4695                            WAIT_CEILING.as_secs() / 60
4696                        );
4697                        stop(state, &repo, &pr, &why).await?;
4698                        return Ok(pr);
4699                    }
4700                    waited += POLL;
4701                    forge.poll().await;
4702                    continue;
4703                }
4704                RerunStep::Fix => {}
4705            }
4706        }
4707
4708        let step = proposed;
4709        // Armed on exactly this head: the forge is doing the waiting. A
4710        // decision to merge (or keep waiting) is only watched, never re-armed
4711        // and never re-approved; anything else - a red check, a comment, a
4712        // conflict - falls through to its own arm, which disarms first.
4713        let armed_here = state
4714            .land_armed_head
4715            .as_deref()
4716            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4717        if armed_here && matches!(step, Step::Merge | Step::Wait) {
4718            if waited >= WAIT_CEILING {
4719                let required = if seen.base.is_empty() {
4720                    None
4721                } else {
4722                    forge.required_contexts(&repo, &seen.base).await
4723                };
4724                let why = format!(
4725                    "auto-merge was armed on {} but the pull request did not merge within {} \
4726                     minutes ({})",
4727                    seen.head,
4728                    WAIT_CEILING.as_secs() / 60,
4729                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4730                );
4731                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4732                return Ok(pr);
4733            }
4734            waited += POLL;
4735            forge.poll().await;
4736            continue;
4737        }
4738        if armed_here && !matches!(step, Step::Done { .. }) {
4739            // Not merging or waiting any more: whatever is next may change the
4740            // head or give up, and neither may leave the arm standing.
4741            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4742                let why = format!("auto-merge could not be disabled: {e}");
4743                stop(state, &repo, &pr, &why).await?;
4744                return Ok(pr);
4745            }
4746        }
4747        if pr.checks == Checks::Red
4748            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4749            && pr.review_comments.is_empty()
4750            && let Some(evidence) = forge.attribution(state, &seen).await
4751            && evidence.unrelated(&seen.head, &pr.failing)
4752        {
4753            if owner_stop(state, &mut pr, forge).await? {
4754                return Ok(pr);
4755            }
4756            // Attribution does not authorize action against an unseen push.
4757            let fresh = forge.view(&repo, pr_url).await?;
4758            if fresh.head != seen.head
4759                || fresh.rollup_head != seen.rollup_head
4760                || fresh.pr.state != PrLifecycle::Open
4761                || fresh.pr.checks != Checks::Red
4762                || fresh.pr.failing != pr.failing
4763                || fresh
4764                    .pr
4765                    .review_comments
4766                    .iter()
4767                    .any(|c| !shown.contains(&c.body))
4768            {
4769                continue;
4770            }
4771            hold_unrelated(state, &pr, evidence).await?;
4772            return Ok(pr);
4773        }
4774        match step {
4775            Step::Wait => {
4776                if waited >= WAIT_CEILING {
4777                    let why = format!(
4778                        "checks were still running after {} minutes",
4779                        WAIT_CEILING.as_secs() / 60
4780                    );
4781                    stop(state, &repo, &pr, &why).await?;
4782                    return Ok(pr);
4783                }
4784                waited += POLL;
4785                forge.poll().await;
4786            }
4787            Step::Done { merged } => {
4788                if merged {
4789                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
4790                }
4791                // Auto-merge is pinned to the approved head, but the forge's
4792                // own handling of a later push is not something magi can
4793                // see: if the pull request merged on another commit, say so
4794                // loudly rather than record a clean landing.
4795                if let Some(armed) = state.land_armed_head.take() {
4796                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
4797                        let msg = format!(
4798                            "{} merged on {} but the owner approved {armed}; review what landed",
4799                            pr.url, seen.head
4800                        );
4801                        tracing::warn!("{msg}");
4802                        state.event("land", msg);
4803                        // Only an arm left by an older build can get here.
4804                        // The wording is fixed so a repeat does not relight
4805                        // the notice.
4806                        crate::notices::raise_with(
4807                            crate::notices::Notice::warn(
4808                                &format!("merged-unapproved-head:{}", state.id),
4809                                "A pull request merged on a commit the owner did not approve; \
4810                                 review what landed",
4811                            )
4812                            .link(crate::notices::Link::Run {
4813                                id: state.id.clone(),
4814                            }),
4815                            &state.config.notify,
4816                        );
4817                    }
4818                }
4819                state.status = if merged {
4820                    RunStatus::Merged
4821                } else {
4822                    RunStatus::Ready
4823                };
4824                let detail = if merged {
4825                    format!("{} was merged", pr.url)
4826                } else {
4827                    format!("{} was closed without merging", pr.url)
4828                };
4829                state.merge = Some(MergeOutcome {
4830                    mode: MergeMode::Pr,
4831                    ok: merged,
4832                    detail: detail.clone(),
4833                    empty: false,
4834                });
4835                state.event("land", detail);
4836                state.save()?;
4837                write_pr_state_through(state, pr.state);
4838                return Ok(pr);
4839            }
4840            Step::Merge => {
4841                state.check_delivery_evidence(&seen.head)?;
4842                let subject = merge_subject(
4843                    crate::graph::landing_title(state, &seen.title),
4844                    &crate::graph::landing_subject_source(state),
4845                );
4846                // The owner sees the panel before the one irreversible step,
4847                // and an unanswered question is a hold: silence never merges.
4848                //
4849                // The dedicated policy includes existing consent and post-repair
4850                // decisions; repair choice availability never grants merge authority.
4851                let contested = contested_to_ask(state);
4852                if !approval_reasons(state).is_empty() {
4853                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
4854                        .await?
4855                    {
4856                        ApprovalGate::Approved => {}
4857                        ApprovalGate::Repair => {
4858                            // The driver consumes the saved request under the existing
4859                            // run/task claim. No merge, no second run or task.
4860                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4861                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4862                                state.save()?;
4863                            }
4864                            return Ok(pr);
4865                        }
4866                        ApprovalGate::Held => {
4867                            // Another entry point may have saved a stop after
4868                            // the first read above. Apply its durable action.
4869                            if owner_stop(state, &mut pr, forge).await? {
4870                                return Ok(pr);
4871                            }
4872                            stop(
4873                                state,
4874                                &repo,
4875                                &pr,
4876                                "the owner did not approve the merge (held or unanswered)",
4877                            )
4878                            .await?;
4879                            return Ok(pr);
4880                        }
4881                        // Filed (or still standing from an earlier visit) and
4882                        // not yet answered. Park here rather than wait: the
4883                        // question survives on disk, the daemon hands this
4884                        // run's slot to something else, and a later resume
4885                        // re-enters `land`, finds the same question, and
4886                        // either merges or stops depending on what it says
4887                        // by then.
4888                        ApprovalGate::Pending => {
4889                            state.end_pass_parked(crate::run::ParkCause::Question);
4890                            state.parked = true;
4891                            state.event(
4892                                "land",
4893                                "parked awaiting merge approval - resumes once answered",
4894                            );
4895                            state.save()?;
4896                            return Ok(pr);
4897                        }
4898                    }
4899                }
4900                // Open and past the gate above, so `seen.head` is the commit
4901                // the checks were bound to and the owner approved.
4902                //
4903                // Merge directly, bound to that commit. Auto-merge is not
4904                // armed any more: the forge checks `--match-head-commit` only
4905                // when the request is made, so an arm outlives the head it
4906                // was made for, and a push of another commit whose
4907                // requirements are met first would merge without approval.
4908                // A direct merge is checked by the forge at the moment it
4909                // happens, so only the approved head can land.
4910                let observed_head = seen.head.clone();
4911                // Read the pull request again just before: the state seen
4912                // above can be a moment old.
4913                {
4914                    let fresh = forge.view(&repo, pr_url).await.ok();
4915                    if fresh.as_ref().is_some_and(|current| {
4916                        current.pr.state == PrLifecycle::Open
4917                            && current.head.eq_ignore_ascii_case(&observed_head)
4918                            && Blocking::of(&current.merge_state) == Blocking::Behind
4919                    }) {
4920                        pr.blocking = Blocking::Behind;
4921                        let synced =
4922                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4923                                .await?;
4924                        let Some(head) = synced else {
4925                            return Ok(pr);
4926                        };
4927                        awaiting_head = Some(head);
4928                        rechecked = false;
4929                        waited = Duration::ZERO;
4930                        continue 'landing;
4931                    }
4932                    if !direct_merge_is_safe(
4933                        fresh.as_ref(),
4934                        &observed_head,
4935                        &shown,
4936                        round,
4937                        budget,
4938                        waited,
4939                        ci,
4940                    ) {
4941                        if waited >= WAIT_CEILING {
4942                            let why = "the pull request did not settle on the approved head \
4943                                       before it could be merged";
4944                            stop(state, &repo, &pr, why).await?;
4945                            return Ok(pr);
4946                        }
4947                        state.event(
4948                            "land",
4949                            "the pull request changed before merging; looking again",
4950                        );
4951                        waited += POLL;
4952                        forge.poll().await;
4953                        continue;
4954                    }
4955                }
4956                let argv = merge_argv_at(pr.number, &subject, &observed_head);
4957                let out = {
4958                    let merge_lock = repo_merge_lock(&repo);
4959                    let _merge_slot = merge_lock.lock().await;
4960                    crate::pr_head::ensure_owner(state)?;
4961                    if let Some(task_id) = state
4962                        .origin
4963                        .as_ref()
4964                        .and_then(|origin| origin.task.as_ref())
4965                    {
4966                        let task = crate::queue::Queue::open()
4967                            .get(task_id)
4968                            .context("cannot verify the task owner immediately before merge")?;
4969                        if task.execution_runs().last() != Some(&state.id)
4970                            || task.operator_held()
4971                            || task.status == crate::queue::TaskStatus::Done
4972                        {
4973                            bail!(
4974                                "task ownership or an operator hold superseded this merge approval"
4975                            );
4976                        }
4977                    }
4978                    if let Some(binding) = &state.land_approval {
4979                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
4980                        if merge_consent_superseded(state, &current)?
4981                            || current.run != state.id
4982                            || !binding.head.eq_ignore_ascii_case(&observed_head)
4983                            || approval(current.resolution().as_deref()) != Approval::Merge
4984                            || current.merge_target.as_ref().is_some_and(|t| {
4985                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
4986                            })
4987                        {
4988                            bail!(
4989                                "merge decision is stale or no longer authorizes the reviewed head"
4990                            );
4991                        }
4992                    }
4993                    forge.merge(&repo, &argv).await?
4994                };
4995                if out.0 {
4996                    // Exit 0 is not proof of a merge: with a merge queue `gh`
4997                    // enqueues (or reports the pull request already queued)
4998                    // and succeeds while it is still open. Ask the forge; an
4999                    // unreadable answer is not a confirmation either, so it
5000                    // is looked at again rather than recorded as merged.
5001                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
5002                        if c.pr.state == PrLifecycle::Merged {
5003                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
5004                            true
5005                        } else {
5006                            false
5007                        }
5008                    });
5009                    if !confirmed {
5010                        if waited >= WAIT_CEILING {
5011                            let why = "the merge request succeeded but the pull request \
5012                                       could not be confirmed merged after waiting";
5013                            stop(state, &repo, &pr, why).await?;
5014                            return Ok(pr);
5015                        }
5016                        state.event(
5017                            "land",
5018                            "merge accepted but the pull request is not confirmed merged yet; waiting",
5019                        );
5020                        state.save()?;
5021                        waited += POLL;
5022                        forge.poll().await;
5023                        continue;
5024                    }
5025                    pr.state = PrLifecycle::Merged;
5026                    state.status = RunStatus::Merged;
5027                    state.merge = Some(MergeOutcome {
5028                        mode: MergeMode::Pr,
5029                        ok: true,
5030                        detail: format!("gh {}", argv.join(" ")),
5031                        empty: false,
5032                    });
5033                    // The last `state.pr` snapshot is whatever the poll before
5034                    // this merge observed - still `open` - and nothing below
5035                    // refreshes it from GitHub again, so the UI's round rail
5036                    // would otherwise keep animating a merged run forever.
5037                    if let Some(pr_record) = state.pr.as_mut() {
5038                        pr_record.state = pr.state.as_str().to_owned();
5039                    }
5040                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5041                    announce_red_merge(state, &pr).await;
5042                    state.save()?;
5043                    write_pr_state_through(state, pr.state);
5044                    return Ok(pr);
5045                }
5046                let after_seen = forge.view(&repo, pr_url).await.ok();
5047                let after = after_seen.as_ref().map(|s| s.pr.state);
5048                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
5049                    state.pr_merged_head = after_seen
5050                        .as_ref()
5051                        .map(|s| s.head.clone())
5052                        .filter(|h| !h.is_empty());
5053                    pr.state = PrLifecycle::Merged;
5054                    state.status = RunStatus::Merged;
5055                    state.merge = Some(outcome);
5056                    if let Some(pr_record) = state.pr.as_mut() {
5057                        pr_record.state = pr.state.as_str().to_owned();
5058                    }
5059                    state.event("land", format!("merged {} as `{subject}`", pr.url));
5060                    announce_red_merge(state, &pr).await;
5061                    state.save()?;
5062                    write_pr_state_through(state, pr.state);
5063                    return Ok(pr);
5064                }
5065                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
5066                match verdict {
5067                    Refused::Behind => {
5068                        pr.blocking = Blocking::Behind;
5069                        let synced =
5070                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
5071                                .await?;
5072                        let Some(head) = synced else {
5073                            return Ok(pr);
5074                        };
5075                        awaiting_head = Some(head);
5076                        rechecked = false;
5077                        waited = Duration::ZERO;
5078                        continue 'landing;
5079                    }
5080                    Refused::Final => {
5081                        let merge_state = after_seen
5082                            .as_ref()
5083                            .map(|s| s.merge_state.as_str())
5084                            .filter(|m| !m.is_empty())
5085                            .unwrap_or("unknown");
5086                        // Which refusal this was decides what a person has to
5087                        // do about it, so the two are worded apart; both carry
5088                        // the forge's own message.
5089                        let why = format!(
5090                            "the merge was refused: {} (merge state: {merge_state})",
5091                            out.1
5092                        );
5093                        stop(state, &repo, &pr, &why).await?;
5094                        return Ok(pr);
5095                    }
5096                    verdict => {
5097                        // Back to the top, which re-decides and passes the
5098                        // approval gate again, a poll later. `waited` is not
5099                        // reset here: only a pushed fix restarts it, or a
5100                        // standing refusal would wait forever.
5101                        if waited >= WAIT_CEILING {
5102                            let why = format!(
5103                                "the merge was still refused after {} minutes: {}",
5104                                WAIT_CEILING.as_secs() / 60,
5105                                out.1
5106                            );
5107                            stop(state, &repo, &pr, &why).await?;
5108                            return Ok(pr);
5109                        }
5110                        if verdict == Refused::Recheck {
5111                            rechecked = true;
5112                        }
5113                        state.event(
5114                            "land",
5115                            "merge refused while the branch policy is not satisfied yet; waiting",
5116                        );
5117                        state.save()?;
5118                        waited += POLL;
5119                        forge.poll().await;
5120                    }
5121                }
5122            }
5123            Step::Rebase => {
5124                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
5125                let Some(head) = synced else {
5126                    return Ok(pr);
5127                };
5128                awaiting_head = Some(head);
5129                rechecked = false;
5130                waited = Duration::ZERO;
5131                continue 'landing;
5132            }
5133            Step::GiveUp { reason } => {
5134                stop(state, &repo, &pr, &reason).await?;
5135                return Ok(pr);
5136            }
5137            Step::Fix { reason } => {
5138                round += 1;
5139                waited = Duration::ZERO;
5140                for c in &pr.review_comments {
5141                    shown.insert(c.body.clone());
5142                }
5143                state.event("land", format!("round {round}: {reason}"));
5144                state.save()?;
5145
5146                let logs = failing_logs(&repo, &seen.failing_urls).await;
5147                let was_red = pr.checks == Checks::Red;
5148                if owner_stop(state, &mut pr, forge).await? {
5149                    return Ok(pr);
5150                }
5151                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
5152                if owner_stop(state, &mut pr, forge).await? {
5153                    return Ok(pr);
5154                }
5155                match fixed {
5156                    Fixed::Committed { head } => {
5157                        // Whatever the next look shows may still be the
5158                        // previous head; see `awaiting_new_head`.
5159                        state.pr_pushed_head = Some(head.clone());
5160                        awaiting_head = Some(head);
5161                        rechecked = false;
5162                        waited = Duration::ZERO;
5163                        forge.poll().await;
5164                    }
5165                    Fixed::Declined if was_red => {
5166                        // Review comments may have required this round even
5167                        // when CI was unrelated. Once the fixer has read them,
5168                        // use the same structural attribution before charging
5169                        // a no-commit stop to the task.
5170                        if let Some(evidence) = forge.attribution(state, &seen).await
5171                            && evidence.unrelated(&seen.head, &pr.failing)
5172                        {
5173                            let fresh = forge.view(&repo, pr_url).await?;
5174                            if fresh.head != seen.head
5175                                || fresh.rollup_head != seen.rollup_head
5176                                || fresh.pr.state != PrLifecycle::Open
5177                                || fresh.pr.checks != Checks::Red
5178                                || fresh.pr.failing != pr.failing
5179                                || fresh
5180                                    .pr
5181                                    .review_comments
5182                                    .iter()
5183                                    .any(|c| !shown.contains(&c.body))
5184                            {
5185                                continue;
5186                            }
5187                            if owner_stop(state, &mut pr, forge).await? {
5188                                return Ok(pr);
5189                            }
5190                            hold_unrelated(state, &pr, evidence).await?;
5191                            return Ok(pr);
5192                        }
5193                        let why = format!(
5194                            "the fixer produced no commit while {} check(s) were failing \
5195                             ({}); stopping instead of looping on an unchanged tree",
5196                            pr.failing.len(),
5197                            pr.failing.join(", ")
5198                        );
5199                        stop(state, &repo, &pr, &why).await?;
5200                        return Ok(pr);
5201                    }
5202                    // Comment-driven round with no commit: the fixer read the
5203                    // comments and changed nothing, which is a decision it is
5204                    // allowed to make. The comments are recorded as shown, so
5205                    // the next observation sees a clean pull request.
5206                    Fixed::Declined => state.event(
5207                        "land",
5208                        format!("round {round}: fixer declined the comments, nothing committed"),
5209                    ),
5210                    Fixed::Deferred => {
5211                        // No fixer was available to judge these comments or
5212                        // checks. Keep the previous completed-round count and
5213                        // return without handing the PR off as a task failure.
5214                        state.status = RunStatus::Blocked;
5215                        state.save()?;
5216                        return Ok(pr);
5217                    }
5218                    Fixed::Failed(why) => {
5219                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5220                        return Ok(pr);
5221                    }
5222                }
5223                state.save()?;
5224            }
5225        }
5226    }
5227}
5228
5229/// Owner decision for a CI failure independently reproduced on the base.
5230pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5231
5232/// Durable machine-hold evidence, bound to one observed PR head.
5233#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5234pub struct CiHold {
5235    /// Head that exhibited the independently reproduced failures.
5236    pub head: String,
5237    /// Typed owner question controlling resumption.
5238    pub question: String,
5239    /// Complete structured facts used to attribute the failures.
5240    pub evidence: CiEvidence,
5241}
5242
5243/// Only structured forge annotations are compared, never log prose.
5244#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5245struct CiFailure {
5246    path: String,
5247    start_line: u64,
5248    end_line: u64,
5249    title: String,
5250    message: String,
5251}
5252
5253#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5254struct CiCheckEvidence {
5255    label: String,
5256    head_check: u64,
5257    base_check: u64,
5258    app: u64,
5259    run: String,
5260    base_run: String,
5261    head_failures: Vec<CiFailure>,
5262    base_failures: Vec<CiFailure>,
5263    rerun_exhausted: bool,
5264}
5265
5266/// Pinned Git diff and forge failure annotations used for CI attribution.
5267#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5268pub struct CiEvidence {
5269    head: String,
5270    base: String,
5271    changed: Vec<String>,
5272    checks: Vec<CiCheckEvidence>,
5273}
5274
5275impl CiEvidence {
5276    /// Every red check must have the same located failure on the base, outside
5277    /// the diff. Changes to CI/build configuration invalidate this inference.
5278    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5279        if self.head != head
5280            || self.base.is_empty()
5281            || failing.is_empty()
5282            || self.changed.iter().any(|p| {
5283                p.starts_with(".github/")
5284                    || p.starts_with(".config/")
5285                    || p.starts_with(".cargo/")
5286                    || matches!(
5287                        p.rsplit('/').next().unwrap_or(p),
5288                        "Cargo.toml"
5289                            | "Cargo.lock"
5290                            | "Makefile.toml"
5291                            | "build.rs"
5292                            | "rust-toolchain.toml"
5293                    )
5294            })
5295        {
5296            return false;
5297        }
5298        failing.iter().all(|label| {
5299            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5300            matches.len() == 1
5301                && matches[0].rerun_exhausted
5302                && !matches[0].head_failures.is_empty()
5303                && matches[0].head_failures.iter().all(|f| {
5304                    // Workflow-level exit-code annotations do not identify a
5305                    // failing test or source file, and prove nothing here.
5306                    !f.path.is_empty()
5307                        && !f.path.starts_with('.')
5308                        && !f.path.contains("..")
5309                        && !f.path.starts_with('/')
5310                        && !self.changed.contains(&f.path)
5311                        && matches[0].base_failures.contains(f)
5312                })
5313        })
5314    }
5315}
5316
5317async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5318    let out = gh(repo, &["api".into(), endpoint]).await.ok()?;
5319    if !out.ok {
5320        return None;
5321    }
5322    serde_json::from_str(&out.stdout).ok()
5323}
5324
5325async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5326    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5327    if count == 0 || count >= 100 {
5328        return None;
5329    }
5330    let id = check.get("id")?.as_u64()?;
5331    let value = ci_json(
5332        repo,
5333        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5334    )
5335    .await?;
5336    let annotations = value.as_array()?;
5337    if annotations.len() != count as usize {
5338        return None;
5339    }
5340    annotations
5341        .iter()
5342        .filter(|a| a["annotation_level"] == "failure")
5343        .map(|a| {
5344            Some(CiFailure {
5345                path: a["path"].as_str()?.into(),
5346                start_line: a["start_line"].as_u64()?,
5347                end_line: a["end_line"].as_u64()?,
5348                title: a["title"].as_str()?.into(),
5349                message: a["message"].as_str()?.into(),
5350            })
5351        })
5352        .collect()
5353}
5354
5355async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5356    let value = ci_json(
5357        repo,
5358        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5359    )
5360    .await?;
5361    let runs = value["check_runs"].as_array()?;
5362    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5363        return None;
5364    }
5365    Some(runs.clone())
5366}
5367
5368async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5369    let repo = &state.repo;
5370    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5371    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5372        .await
5373        .ok()?;
5374    if !base.ok() {
5375        return None;
5376    }
5377    let range = format!("{}...{}", base.stdout, seen.head);
5378    // No rename detection: both old and new paths must count as changed.
5379    let diff = git::git_raw(
5380        repo,
5381        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5382    )
5383    .await
5384    .ok()?;
5385    if !diff.ok() {
5386        return None;
5387    }
5388    let head_runs = ci_runs(repo, &seen.head).await?;
5389    let base_runs = ci_runs(repo, &base.stdout).await?;
5390    let mut checks = Vec::new();
5391    for label in &seen.pr.failing {
5392        let matching = |runs: &[serde_json::Value]| {
5393            runs.iter()
5394                .filter(|r| r["name"].as_str() == Some(label))
5395                .cloned()
5396                .collect::<Vec<_>>()
5397        };
5398        let heads = matching(&head_runs);
5399        let bases = matching(&base_runs);
5400        if heads.len() != 1 || bases.len() != 1 {
5401            return None;
5402        }
5403        let h = &heads[0];
5404        let b = &bases[0];
5405        if h["conclusion"] != "failure"
5406            || b["conclusion"] != "failure"
5407            || h["status"] != "completed"
5408            || b["status"] != "completed"
5409            || h["head_sha"].as_str()? != seen.head
5410            || b["head_sha"].as_str()? != base.stdout
5411            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5412        {
5413            return None;
5414        }
5415        let run = run_of(h["details_url"].as_str()?)?;
5416        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5417        if contexts.len() != 1
5418            || contexts[0].run.as_ref() != Some(&run)
5419            || contexts[0].verdict != Verdict::Fail
5420        {
5421            return None;
5422        }
5423        // A persisted request alone is not a completed rerun: require the
5424        // workflow's structured attempt number as well.
5425        let workflow =
5426            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5427        let base_run = run_of(b["details_url"].as_str()?)?;
5428        let base_workflow = ci_json(
5429            repo,
5430            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5431        )
5432        .await?;
5433        if base_workflow["head_sha"].as_str()? != base.stdout
5434            || base_workflow["head_branch"].as_str()? != seen.base
5435            || base_workflow["status"] != "completed"
5436            || base_workflow["conclusion"] != "failure"
5437            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5438        {
5439            return None;
5440        }
5441        let exhausted = state
5442            .land_reruns
5443            .as_ref()
5444            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5445            && workflow["head_sha"].as_str()? == seen.head
5446            && workflow["run_attempt"].as_u64()? > 1
5447            && workflow["status"] == "completed";
5448        checks.push(CiCheckEvidence {
5449            label: label.clone(),
5450            head_check: h["id"].as_u64()?,
5451            base_check: b["id"].as_u64()?,
5452            app: h.pointer("/app/id")?.as_u64()?,
5453            run,
5454            base_run,
5455            head_failures: ci_annotations(repo, h).await?,
5456            base_failures: ci_annotations(repo, b).await?,
5457            rerun_exhausted: exhausted,
5458        });
5459    }
5460    Some(CiEvidence {
5461        head: seen.head.clone(),
5462        base: base.stdout,
5463        changed: diff
5464            .stdout
5465            .split('\0')
5466            .filter(|p| !p.is_empty())
5467            .map(str::to_owned)
5468            .collect(),
5469        checks,
5470    })
5471}
5472
5473async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5474    let detail = serde_json::to_string(&evidence)?;
5475    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5476    let hold = "operator: 保留して後で判断する".to_owned();
5477    let mut q = ask::Question::new(
5478        state.id.clone(),
5479        CI_HOLD_NODE.into(),
5480        "land".into(),
5481        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5482        format!(
5483            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5484        ),
5485        vec![resume.clone(), hold.clone()],
5486    );
5487    q.actions.insert(
5488        resume,
5489        ask::ChoiceAction::Resume {
5490            run: state.id.clone(),
5491        },
5492    );
5493    q.actions.insert(hold, ask::ChoiceAction::Hold);
5494    ask::Questions::open().put_executable(&mut q)?;
5495    state.land_unrelated = Some(CiHold {
5496        head: evidence.head.clone(),
5497        question: q.id.clone(),
5498        evidence,
5499    });
5500    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5501    state.end_pass_parked(crate::run::ParkCause::Question);
5502    state.parked = true;
5503    state.save()?;
5504    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5505        tracing::warn!("could not notify about CI hold: {e:#}");
5506    }
5507    // A durable question and evidence are sufficient even if commenting fails.
5508    let body = stop_comment(
5509        &state.id,
5510        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5511    );
5512    let (_, body) = crate::github_text::prepare(state, "", &body);
5513    gh(
5514        &state.repo,
5515        &[
5516            "pr".into(),
5517            "comment".into(),
5518            pr.number.to_string(),
5519            "--body".into(),
5520            body,
5521        ],
5522    )
5523    .await
5524    .ok();
5525    Ok(())
5526}
5527
5528/// One observation, plus the two things [`PrState`] deliberately does not carry:
5529/// the title (needed for the squash subject) and where the failing checks'
5530/// logs live.
5531#[derive(Clone)]
5532struct Seen {
5533    pr: PrState,
5534    title: String,
5535    failing_urls: Vec<(String, String)>,
5536    /// `headRefOid`: the commit this observation, checks included, is about.
5537    head: String,
5538    /// The commit the checks belong to, read from the same GraphQL node as
5539    /// the checks themselves. Empty when unreadable.
5540    rollup_head: String,
5541    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5542    /// and DRAFT together, and a stop reason has to say which.
5543    merge_state: String,
5544    /// Every check of the rollup, for naming what an armed merge waits on.
5545    contexts: Vec<CheckInfo>,
5546    /// `baseRefName`, to look up which contexts the base requires.
5547    base: String,
5548}
5549
5550/// One check of the rollup as far as a stop reason needs it.
5551#[derive(Clone)]
5552struct CheckInfo {
5553    label: String,
5554    verdict: Verdict,
5555    required: Option<bool>,
5556    /// The workflow run the check belongs to; `None` for an external status.
5557    run: Option<String>,
5558}
5559
5560/// What to do with a red head before a fix round is spent on it.
5561#[derive(Debug, Clone, PartialEq, Eq)]
5562enum RerunStep {
5563    /// Rerun these workflow runs (each not yet rerun for this head).
5564    Rerun(Vec<String>),
5565    /// Reran already and the forge may still report the old failure: wait.
5566    Grace,
5567    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5568    Fix,
5569}
5570
5571/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5572/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5573/// pending checks in another run do not delay this run's rerun.
5574#[cfg(test)]
5575fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5576    rerunnable_with(contexts, false)
5577}
5578
5579fn rerunnable_with(
5580    contexts: &[CheckInfo],
5581    include_optional: bool,
5582) -> Vec<(String, Option<String>)> {
5583    contexts
5584        .iter()
5585        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5586        // `gh run rerun --failed` refuses a run with a job still going.
5587        .filter(|c| {
5588            c.run.as_ref().is_none_or(|r| {
5589                !contexts.iter().any(|o| {
5590                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5591                        && o.run.as_ref() == Some(r)
5592                })
5593            })
5594        })
5595        .map(|c| (c.label.clone(), c.run.clone()))
5596        .collect()
5597}
5598
5599/// Pure: rerun once per run id, wait out the grace, then hand over.
5600fn rerun_step(
5601    failing: &[(String, Option<String>)],
5602    record: Option<&LandReruns>,
5603    head: &str,
5604    now: i64,
5605) -> RerunStep {
5606    // A failure with no workflow run (an external status) cannot be rerun, and
5607    // the fixer's push re-runs everything anyway.
5608    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5609        return RerunStep::Fix;
5610    }
5611    // Reruns belong to the head they were made on.
5612    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5613    let mut fresh: Vec<String> = Vec::new();
5614    let mut recent = false;
5615    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5616        match record.and_then(|r| r.runs.get(run)) {
5617            None => {
5618                if !fresh.iter().any(|f| f == run) {
5619                    fresh.push(run.to_owned());
5620                }
5621            }
5622            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5623            Some(_) => {}
5624        }
5625    }
5626    if !fresh.is_empty() {
5627        RerunStep::Rerun(fresh)
5628    } else if recent {
5629        RerunStep::Grace
5630    } else {
5631        RerunStep::Fix
5632    }
5633}
5634
5635/// Read minimal live PR metadata (`url`, `number`, `state`, `headRefOid`,
5636/// `baseRefName`) for landing base-sync recovery admission and dispatch checks.
5637pub(crate) async fn observe_pr_summary(
5638    repo: &Path,
5639    pr_url: &str,
5640) -> Result<crate::land_sync_recovery::ObservedPr> {
5641    #[derive(serde::Deserialize)]
5642    struct Summary {
5643        #[serde(default)]
5644        url: String,
5645        #[serde(default)]
5646        number: u64,
5647        #[serde(default)]
5648        state: String,
5649        #[serde(default, rename = "headRefOid")]
5650        head_ref_oid: String,
5651        #[serde(default, rename = "baseRefName")]
5652        base_ref_name: String,
5653    }
5654    let view = gh(
5655        repo,
5656        &[
5657            "pr".to_owned(),
5658            "view".to_owned(),
5659            pr_url.to_owned(),
5660            "--json".to_owned(),
5661            "url,number,state,headRefOid,baseRefName".to_owned(),
5662        ],
5663    )
5664    .await?;
5665    if !view.ok {
5666        bail!("gh pr view {pr_url}: {}", view.combined());
5667    }
5668    let parsed: Summary = serde_json::from_str(&view.stdout).context("parse pull request json")?;
5669    Ok(crate::land_sync_recovery::ObservedPr {
5670        url: parsed.url,
5671        number: parsed.number,
5672        open: parsed.state.eq_ignore_ascii_case("OPEN"),
5673        head: parsed.head_ref_oid,
5674        base_branch: (!parsed.base_ref_name.is_empty()).then_some(parsed.base_ref_name),
5675    })
5676}
5677
5678/// Read the pull request: `gh pr view` for the top-level thread and merge
5679/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5680/// inline review comments `gh pr view` does not report.
5681async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5682    let view = gh(
5683        repo,
5684        &[
5685            "pr".to_owned(),
5686            "view".to_owned(),
5687            pr_url.to_owned(),
5688            "--json".to_owned(),
5689            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5690                .to_owned(),
5691        ],
5692    )
5693    .await?;
5694    if !view.ok {
5695        bail!("gh pr view {pr_url}: {}", view.combined());
5696    }
5697    let number = parse_pr(&view.stdout)?.number;
5698    let node = last_commit_node(repo, number).await;
5699    let mut seen = seen_from(&view.stdout, node.as_deref())?;
5700
5701    let inline = gh(
5702        repo,
5703        &[
5704            "api".to_owned(),
5705            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5706        ],
5707    )
5708    .await?;
5709    if inline.ok {
5710        match parse_inline_comments(&inline.stdout) {
5711            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5712            // An unreadable inline thread must not end a landing: the rollup
5713            // and the top-level thread are still real signal.
5714            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5715        }
5716    } else {
5717        tracing::warn!(
5718            "gh api pulls/{}/comments: {}",
5719            seen.pr.number,
5720            inline.combined()
5721        );
5722    }
5723    Ok(seen)
5724}
5725
5726/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
5727/// response. No I/O.
5728///
5729/// The commit oid and the checks are read from the *same* node, so the rollup
5730/// is bound to the commit it belongs to by construction; two reads that agree
5731/// before and after another response prove nothing about what that response
5732/// held. The view's own rollup is never used. A node that is missing,
5733/// unreadable, carries GraphQL errors, or whose checks run past the page
5734/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
5735/// as "look again" and never as a reason to merge.
5736fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5737    let mut pr = parse_pr(view_json)?;
5738    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5739
5740    let mut rollup_head = String::new();
5741    let mut failing_urls = Vec::new();
5742    let mut contexts = Vec::new();
5743    let mut checks = Checks::Unknown;
5744    let mut failing = Vec::new();
5745    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5746        (checks, failing) = rollup_verdict(&rollup);
5747        failing_urls = rollup
5748            .iter()
5749            .filter(|c| c.verdict() == Verdict::Fail)
5750            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5751            .collect();
5752        contexts = rollup
5753            .iter()
5754            .map(|c| CheckInfo {
5755                label: c.label(),
5756                verdict: c.verdict(),
5757                required: c.is_required,
5758                run: c.url().and_then(run_of),
5759            })
5760            .collect();
5761        rollup_head = oid;
5762    }
5763    pr.checks = checks;
5764    pr.failing = failing;
5765
5766    Ok(Seen {
5767        pr,
5768        title: raw.title,
5769        failing_urls,
5770        head: raw.head_ref_oid,
5771        rollup_head,
5772        merge_state: raw.merge_state_status,
5773        contexts,
5774        base: raw.base_ref_name,
5775    })
5776}
5777
5778/// The last commit's oid and its checks from one GraphQL response, `None`
5779/// when anything about it cannot be trusted.
5780fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
5781    let v: serde_json::Value = serde_json::from_str(json).ok()?;
5782    if v.get("errors").is_some_and(|e| !e.is_null()) {
5783        return None;
5784    }
5785    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
5786    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
5787    let contexts = commit.pointer("/statusCheckRollup/contexts");
5788    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
5789        // No rollup at all: the commit has no checks.
5790        return Some((oid.to_owned(), Vec::new()));
5791    };
5792    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
5793        return None;
5794    }
5795    let nodes = contexts.get("nodes")?.as_array()?;
5796    let rollup = nodes
5797        .iter()
5798        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
5799        .collect::<Result<Vec<_>, _>>()
5800        .ok()?;
5801    Some((oid.to_owned(), rollup))
5802}
5803
5804/// The pull request's last commit and its checks, in one response. `None`
5805/// when the forge could not be asked.
5806async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
5807    let out = gh(
5808        repo,
5809        &[
5810            "api".to_owned(),
5811            "graphql".to_owned(),
5812            "-F".to_owned(),
5813            "owner={owner}".to_owned(),
5814            "-F".to_owned(),
5815            "repo={repo}".to_owned(),
5816            "-F".to_owned(),
5817            format!("number={number}"),
5818            "-f".to_owned(),
5819            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
5820             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
5821             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
5822             ... on CheckRun{name status conclusion detailsUrl \
5823             isRequired(pullRequestNumber:$number)} \
5824             ... on StatusContext{context state targetUrl \
5825             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
5826                .to_owned(),
5827        ],
5828    )
5829    .await
5830    .ok()?;
5831    out.ok.then_some(out.stdout)
5832}
5833
5834/// What a fix round did.
5835#[doc(hidden)]
5836#[derive(Debug, PartialEq)]
5837pub enum Fixed {
5838    /// The fixer committed something, and this is the head that was pushed.
5839    Committed {
5840        /// The commit now at the tip of the pushed branch.
5841        head: String,
5842    },
5843    /// The fixer ran and chose to change nothing.
5844    Declined,
5845    /// Machine availability prevented a result; retry this round on resume.
5846    Deferred,
5847    /// The fixer could not run, or said nothing usable.
5848    Failed(String),
5849}
5850
5851/// Hand the failures and the comments to the fixer, then commit and push.
5852///
5853/// The fixer works in the winner's own worktree so its commits land on the
5854/// branch the pull request is built from, and it runs with `allow_write` for
5855/// the same reason.
5856#[doc(hidden)]
5857pub async fn fix_round(
5858    state: &mut RunState,
5859    pr: &PrState,
5860    round: usize,
5861    budget: usize,
5862    reason: &str,
5863    logs: &str,
5864) -> Result<Fixed> {
5865    let winner = state
5866        .winner()
5867        .cloned()
5868        .context("landing needs a winning candidate; none is recorded on this run")?;
5869    let roles = state
5870        .config
5871        .resolve_roles()
5872        .context("resolve the roster for the fix round")?;
5873    // Same chain as the review loop (see `crate::fixer`): the configured
5874    // fixers in order, otherwise the winner's own author continuing its own
5875    // conversation - the competition is over, so its context is pure benefit.
5876    let attempts = crate::fixer::attempts(state, &roles, &winner);
5877    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
5878
5879    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
5880    let mut artifacts = agent::artifacts_dir(&state.dir());
5881    if let Some(request) = state
5882        .merge_repairs
5883        .last()
5884        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
5885    {
5886        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
5887    }
5888    let prompt =
5889        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
5890            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
5891        } else {
5892            prompt
5893        };
5894    // Read before the fixer runs: it normally commits for itself, so HEAD has
5895    // already moved by the time it returns and a later read would see no
5896    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
5897    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5898    // Each id at most once, forward only: the next one is asked only when the
5899    // call advances, and only the last attempt's result is judged below, so an
5900    // exhausted chain ends as a single failed fixer does.
5901    let mut last = None;
5902    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
5903        if owner_requested_stop(state)? {
5904            return Ok(Fixed::Declined);
5905        }
5906        let mut seat = seat_of(state, &seat_key, &spec.id);
5907        let stem = if i == 0 {
5908            format!("land-{round}")
5909        } else {
5910            format!("land-{round}-{}", spec.id)
5911        };
5912        let out = agent::invoke(
5913            &spec,
5914            &mut seat,
5915            &Invocation {
5916                coordination: state.config.coordination.as_ref(),
5917                fetched_base: state.fetched_base.as_ref(),
5918                cwd: &winner.worktree,
5919                prompt: &prompt,
5920                timeout: Duration::from_secs(state.config.graph.timeout_fix),
5921                allow_write: true,
5922                sessions: state.config.graph.sessions,
5923                artifacts: &artifacts,
5924                stem: &stem,
5925                run: &state.id,
5926                node: "land",
5927                cache_dir: state.config.cache_dir().as_deref(),
5928                attachments: &[],
5929                writable: &[],
5930            },
5931        )
5932        .await;
5933        state.seats.insert(seat.key.clone(), seat);
5934        if let Some(next) = ids.get(i + 1)
5935            && agent::chain_advances(&out)
5936        {
5937            let (class, why) = crate::fixer::failure_of(&out);
5938            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
5939            continue;
5940        }
5941        last = Some((seat_key, out));
5942        break;
5943    }
5944    let (seat_key, out) = last.expect("the fixer chain always has an entry");
5945
5946    match out {
5947        Ok(o) if o.quota_exhausted() => {
5948            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
5949            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
5950            state.quota.push(loss);
5951            state.status = RunStatus::Blocked;
5952            state.save()?;
5953            // Keep partial edits reachable on the winner branch and leave a
5954            // clean tree for resume_landing_head. The resumed landing gates
5955            // this new commit before it can publish it; no push happens here.
5956            let inherited = crate::repo_lock::WaitPolicy::current();
5957            let wait = crate::repo_lock::WaitPolicy::new(
5958                Duration::from_secs(state.config.graph.timeout_resource_wait),
5959                move || inherited.cancelled(),
5960            );
5961            let _coordination = crate::repo_lock::SeatLease::operation_with(
5962                &winner.worktree,
5963                state.config.coordination.as_ref(),
5964                &wait,
5965            )
5966            .await?;
5967            let rescue = git::rescue_commit(
5968                &winner.worktree,
5969                &format!("magi: deferred land round {round} (uncommitted work)"),
5970            )
5971            .await?;
5972            state.note_withheld("land", &rescue.withheld);
5973            state.save()?;
5974            return Ok(Fixed::Deferred);
5975        }
5976        Ok(o) if !o.usable() => {
5977            return Ok(Fixed::Failed(format!(
5978                "the fixer produced nothing usable ({})",
5979                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
5980            )));
5981        }
5982        Ok(_) => {}
5983        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
5984        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
5985    }
5986
5987    if owner_requested_stop(state)? {
5988        return Ok(Fixed::Declined);
5989    }
5990
5991    // An agent that edited files but never committed would otherwise push
5992    // nothing and look like a refusal.
5993    let wait = crate::repo_lock::WaitPolicy::new(
5994        Duration::from_secs(state.config.graph.timeout_resource_wait),
5995        || false,
5996    );
5997    let coordination = crate::repo_lock::SeatLease::operation_with(
5998        &winner.worktree,
5999        state.config.coordination.as_ref(),
6000        &wait,
6001    )
6002    .await?;
6003    match git::rescue_commit(
6004        &winner.worktree,
6005        &format!("magi: land round {round} fixes (uncommitted work)"),
6006    )
6007    .await
6008    {
6009        Ok(r) => state.note_withheld("land", &r.withheld),
6010        Err(e)
6011            if state
6012                .merge_repairs
6013                .last()
6014                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
6015        {
6016            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
6017        }
6018        Err(_) => {}
6019    }
6020    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
6021    drop(coordination);
6022    if after == before {
6023        return Ok(Fixed::Declined);
6024    }
6025
6026    if owner_requested_stop(state)? {
6027        return Ok(Fixed::Declined);
6028    }
6029    crate::pr_head::ensure_owner(state)?;
6030    let remote = state.config.merge.remote.clone();
6031    anyhow::ensure!(
6032        crate::foreign_checkout::write_back(state, &after).await?,
6033        "foreign checkout delivery is blocked; see the run events"
6034    );
6035    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
6036    let push = if state.pr_head.is_some() {
6037        let expected = state
6038            .pr_pushed_head
6039            .as_deref()
6040            .context("missing public head lease")?;
6041        git::push_as(
6042            &winner.worktree,
6043            &remote,
6044            &winner.branch,
6045            &public_head,
6046            expected,
6047        )
6048        .await?
6049    } else {
6050        git::push(&winner.worktree, &remote, &winner.branch).await?
6051    };
6052    if !push.ok() {
6053        return Ok(Fixed::Failed(format!(
6054            "pushing {} to {remote} failed: {}",
6055            public_head, push.stderr
6056        )));
6057    }
6058    state.event(
6059        "land",
6060        format!("round {round}: pushed a fix to {public_head}"),
6061    );
6062    state.pr_pushed_head = Some(after.clone());
6063    state.save()?;
6064    Ok(Fixed::Committed { head: after })
6065}
6066
6067/// Fetch or create a seat, keeping its conversation across nodes.
6068pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
6069    crate::fixer::seat_for(state, key, agent)
6070}
6071
6072/// Recheck the live PR and local worktree before spending the requested fix.
6073/// A moved/closed PR is held, never repaired using obsolete evidence.
6074pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
6075    let seen = observe(&state.repo, url).await?;
6076    let winner = state.winner().context("no winning branch to repair")?;
6077    if seen.pr.state != PrLifecycle::Open || seen.head != head {
6078        anyhow::bail!(
6079            "PR is closed or its head changed; review the current head before requesting repair again"
6080        );
6081    }
6082    if git::rev_parse(&winner.worktree, "HEAD").await? != head
6083        || !git::is_clean(&winner.worktree).await?
6084    {
6085        anyhow::bail!(
6086            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
6087        );
6088    }
6089    // Always disable any forge-side reservation, including one not recorded
6090    // by this run. A repair request is never merge authorization.
6091    let view = gh(
6092        &state.repo,
6093        &[
6094            "pr".into(),
6095            "view".into(),
6096            url.into(),
6097            "--json".into(),
6098            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
6099        ],
6100    )
6101    .await?;
6102    if !view.ok {
6103        bail!("cannot check auto-merge: {}", view.combined());
6104    }
6105    let live: serde_json::Value = serde_json::from_str(&view.stdout)?;
6106    let public = state.pr_branch().unwrap_or(&winner.branch);
6107    if live["state"] != "OPEN"
6108        || live["headRefOid"] != head
6109        || live["headRefName"] != public
6110        || live["baseRefName"] != state.base_branch
6111        || live["isCrossRepository"] != false
6112    {
6113        bail!("PR changed during repair preflight; review its current head explicitly");
6114    }
6115    let auto_merge = live
6116        .get("autoMergeRequest")
6117        .context("cannot read the PR auto-merge reservation; repair held")?;
6118    if !auto_merge.is_null() {
6119        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
6120        if !out.ok {
6121            bail!("cannot disable auto-merge; repair held: {}", out.combined());
6122        }
6123    }
6124    Ok(seen.pr)
6125}
6126
6127/// What the fixer is told.
6128fn fix_prompt(
6129    state: &RunState,
6130    pr: &PrState,
6131    round: usize,
6132    budget: usize,
6133    reason: &str,
6134    logs: &str,
6135) -> String {
6136    let mut s = format!(
6137        "Your patch is open as a pull request and it is not landing. Land round \
6138         {round} of {budget}.\n\n\
6139         Pull request: {}\n\n\
6140         What is holding it: {reason}\n\n\
6141         # The task\n\n{}\n",
6142        pr.url, state.instruction
6143    );
6144
6145    if pr.failing.is_empty() {
6146        s.push_str("\n# Failing checks\n\n(none)\n");
6147    } else {
6148        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
6149        if logs.trim().is_empty() {
6150            s.push_str(
6151                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
6152            );
6153        } else {
6154            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
6155        }
6156    }
6157
6158    if pr.review_comments.is_empty() {
6159        s.push_str("\n# Review comments\n\n(none)\n");
6160    } else {
6161        s.push_str("\n# Review comments\n");
6162        for c in &pr.review_comments {
6163            let where_ = match (&c.path, c.line) {
6164                (Some(p), Some(l)) => format!(" ({p}:{l})"),
6165                (Some(p), None) => format!(" ({p})"),
6166                _ => String::new(),
6167            };
6168            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
6169        }
6170    }
6171
6172    s.push_str(
6173        "\n# Rules\n\n\
6174         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
6175            failing test; do not silence a lint with an allow attribute; do not \
6176            stretch a timeout to hide a race. If the check is right, the code is \
6177            wrong.\n\
6178         2. Change nothing the checks and the comments did not raise. A \
6179            drive-by refactor turns a one-line fix into a pull request that \
6180            needs reviewing again.\n\
6181         3. If a comment is wrong, say so with a checkable argument and change \
6182            nothing for it. A declined comment with a reason is a correct \
6183            outcome; a change made to appease a reviewer is not.\n\
6184         4. Commit in this worktree. magi pushes to the pull request's branch \
6185            for you; do not push, merge, or close anything yourself.\n\
6186         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
6187         # Output\n\n\
6188         Say what you changed and why, and what you declined and why.",
6189    );
6190
6191    let language = &state.config.graph.language;
6192    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
6193        let _ = write!(s, "\n\nWrite all prose in {language}.");
6194    }
6195    // After the language line, so the exception is the last word on it.
6196    s.push_str(&crate::prompt::github_rule(
6197        language,
6198        &state.config.graph.github_language,
6199    ));
6200    if let Some(overlay) = state.config.prompts.overlay("fix") {
6201        let _ = write!(s, "\n\n{overlay}");
6202    }
6203    s.push('\n');
6204    s.push_str(crate::prompt::child_run_ownership());
6205    s
6206}
6207
6208/// Failing log tails, the way the operator collects them by hand:
6209/// `gh run view --log-failed`.
6210async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6211    let mut out = String::new();
6212    for (name, url) in failing.iter().take(MAX_LOGS) {
6213        let args = match (job_of(url), run_of(url)) {
6214            (Some(job), _) => vec![
6215                "run".to_owned(),
6216                "view".to_owned(),
6217                "--log-failed".to_owned(),
6218                "--job".to_owned(),
6219                job,
6220            ],
6221            (None, Some(run)) => vec![
6222                "run".to_owned(),
6223                "view".to_owned(),
6224                run,
6225                "--log-failed".to_owned(),
6226            ],
6227            // Not a GitHub Actions check - an external status has no log here.
6228            (None, None) => continue,
6229        };
6230        let (ok, body) = match gh(repo, &args).await {
6231            Ok(v) => (v.ok, v.combined()),
6232            Err(e) => (false, format!("{e:#}")),
6233        };
6234        if !ok && body.trim().is_empty() {
6235            continue;
6236        }
6237        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6238    }
6239    out
6240}
6241
6242/// Job id out of a check's `detailsUrl`
6243/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
6244fn job_of(details_url: &str) -> Option<String> {
6245    let after = details_url.split("/job/").nth(1)?;
6246    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6247    (!id.is_empty()).then_some(id)
6248}
6249
6250/// Workflow run id out of a check's `detailsUrl`.
6251pub(crate) fn run_of(details_url: &str) -> Option<String> {
6252    let after = details_url.split("/actions/runs/").nth(1)?;
6253    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6254    (!id.is_empty()).then_some(id)
6255}
6256
6257/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6258/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6259/// it to that.
6260fn stop_comment(run_id: &str, why: &str) -> String {
6261    format!(
6262        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6263         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6264    )
6265}
6266
6267/// Leave the pull request open, say why on it, and mark the run blocked.
6268///
6269/// The comment is what makes an unattended stop actionable: the operator wakes
6270/// up to a pull request that explains itself rather than to a silent queue.
6271async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6272    let body = stop_comment(&state.id, why);
6273    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6274    if !body.contains(MARKER) {
6275        body = format!("{MARKER}\n{body}");
6276    }
6277    let posted = gh(
6278        repo,
6279        &[
6280            "pr".to_owned(),
6281            "comment".to_owned(),
6282            pr.number.to_string(),
6283            "--body".to_owned(),
6284            body,
6285        ],
6286    )
6287    .await;
6288    match posted {
6289        Ok(out) if out.ok => {}
6290        Ok(out) => tracing::warn!("could not comment on {}: {}", pr.url, out.combined()),
6291        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6292    }
6293    state.status = RunStatus::Blocked;
6294    state.merge = Some(MergeOutcome {
6295        mode: MergeMode::Pr,
6296        ok: false,
6297        detail: why.to_owned(),
6298        empty: false,
6299    });
6300    state.event("land", format!("stopped: {why}"));
6301    state.save()?;
6302    Ok(())
6303}
6304
6305/// Output of a `gh` subprocess, keeping machine-readable `stdout` separate from
6306/// diagnostic `stderr`.
6307///
6308/// Newer `gh` releases (for example `gh` 2.105.0) can emit advisory hints on
6309/// `stderr` even when a read-only `--json` or API command succeeds with exit
6310/// status 0. Appending `stderr` onto `stdout` before deserialization breaks
6311/// strict JSON parsing (for example `trailing characters at line 2 column 1`).
6312///
6313/// Output contract:
6314/// - **Successful structured reads** (`--json`, REST `gh api`, GraphQL, etc.):
6315///   check [`Self::ok`], then pass [`Self::stdout`] straight to a strict parser.
6316///   Never fall back to [`Self::stderr`] when `stdout` is empty, and never strip
6317///   specific hint text or heuristically extract JSON substrings.
6318/// - **Failed invocations (`!ok`)**: use [`Self::combined`] so both `stdout`
6319///   and `stderr` diagnostics stay actionable (for example `404` detection and
6320///   refused-merge details).
6321/// - **Human-facing or mutating commands** (`pr merge`, `pr close`, `pr edit`,
6322///   `pr comment`, `run rerun`, `run view --log-failed`): use
6323///   [`Self::combined`] for failure diagnostics or human-readable output.
6324#[derive(Debug, Clone, PartialEq, Eq)]
6325pub(crate) struct GhOutput {
6326    /// Whether `gh` exited with status 0.
6327    pub(crate) ok: bool,
6328    /// Process `stdout`, decoded lossily as UTF-8.
6329    pub(crate) stdout: String,
6330    /// Process `stderr`, decoded lossily as UTF-8.
6331    pub(crate) stderr: String,
6332}
6333
6334impl GhOutput {
6335    /// Build from a completed subprocess output and log non-empty `stderr`
6336    /// emitted on exit status 0 at debug level without logging command
6337    /// arguments.
6338    pub(crate) fn from_output(output: std::process::Output) -> Self {
6339        let parsed = Self {
6340            ok: output.status.success(),
6341            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
6342            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
6343        };
6344        if parsed.ok && !parsed.stderr.trim().is_empty() {
6345            tracing::debug!(
6346                stderr = parsed.stderr.trim(),
6347                "gh exited successfully with stderr diagnostics"
6348            );
6349        }
6350        parsed
6351    }
6352
6353    /// Combined trimmed `stdout` and `stderr` for failure diagnostics and
6354    /// human-facing commands.
6355    pub(crate) fn combined(&self) -> String {
6356        let out = self.stdout.trim();
6357        let err = self.stderr.trim();
6358        match (out.is_empty(), err.is_empty()) {
6359            (true, true) => String::new(),
6360            (false, true) => out.to_owned(),
6361            (true, false) => err.to_owned(),
6362            (false, false) => format!("{out}\n{err}"),
6363        }
6364    }
6365}
6366
6367/// Run `gh` in `cwd`, returning exit status with separated `stdout` and
6368/// `stderr` in [`GhOutput`].
6369///
6370/// Structured callers must check [`GhOutput::ok`] and parse [`GhOutput::stdout`]
6371/// strictly without substituting [`GhOutput::stderr`]. Failed invocations and
6372/// human-facing or mutating commands should use [`GhOutput::combined`] so both
6373/// streams remain available as diagnostics.
6374///
6375/// `GH_REPO` is stripped from the child's environment: every call site here
6376/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6377/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6378/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6379/// `GH_REPO` the operator happens to have exported for an unrelated script
6380/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6381/// below) to a different repository than the one actually on disk - which
6382/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6383/// could be made to agree with whatever repository a forged `--merged` URL
6384/// claims, defeating it entirely.
6385pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<GhOutput> {
6386    gh_with(Path::new("gh"), cwd, args).await
6387}
6388
6389pub(crate) async fn gh_with(program: &Path, cwd: &Path, args: &[String]) -> Result<GhOutput> {
6390    let out = tokio::process::Command::new(program)
6391        .args(args)
6392        .current_dir(cwd)
6393        .env_remove("GH_REPO")
6394        .quiet()
6395        .stdin(std::process::Stdio::null())
6396        .output()
6397        .await
6398        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6399    Ok(GhOutput::from_output(out))
6400}
6401
6402/// Verdict of one entry in the status rollup.
6403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6404pub(crate) enum Verdict {
6405    Pass,
6406    Fail,
6407    Pending,
6408    Unknown,
6409}
6410
6411impl Verdict {
6412    /// Short operator-facing check result.
6413    pub(crate) fn label(self) -> &'static str {
6414        match self {
6415            Self::Pass => "passed",
6416            Self::Fail => "failed",
6417            Self::Pending => "pending",
6418            Self::Unknown => "unknown",
6419        }
6420    }
6421}
6422
6423#[derive(Debug, Deserialize)]
6424#[serde(rename_all = "camelCase")]
6425struct GhPr {
6426    #[serde(default)]
6427    url: String,
6428    #[serde(default)]
6429    number: u64,
6430    #[serde(default)]
6431    state: String,
6432    #[serde(default)]
6433    title: String,
6434    #[serde(default)]
6435    status_check_rollup: Vec<GhCheck>,
6436    /// GitHub's own verdict on whether the pull request can be merged.
6437    ///
6438    /// Worth asking for because it is the only place the *required* check set
6439    /// is applied: the rollup lists every check equally, so a repository that
6440    /// deliberately does not require `coverage` still looks red here. See
6441    /// [`Blocking`].
6442    #[serde(default)]
6443    merge_state_status: String,
6444    /// The commit the pull request currently points at. Compared with the
6445    /// commit a fix round pushed, it is how the loop knows the forge has moved
6446    /// on and the rollup belongs to the new head.
6447    #[serde(default)]
6448    head_ref_oid: String,
6449    #[serde(default)]
6450    base_ref_name: String,
6451    #[serde(default)]
6452    reviews: Vec<GhReview>,
6453    #[serde(default)]
6454    comments: Vec<GhComment>,
6455}
6456
6457/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6458/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6459/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6460/// conclusion at all.
6461#[derive(Debug, Deserialize)]
6462#[serde(rename_all = "camelCase")]
6463struct GhCheck {
6464    #[serde(default)]
6465    name: Option<String>,
6466    #[serde(default)]
6467    context: Option<String>,
6468    #[serde(default)]
6469    status: Option<String>,
6470    #[serde(default)]
6471    conclusion: Option<String>,
6472    #[serde(default)]
6473    state: Option<String>,
6474    #[serde(default)]
6475    details_url: Option<String>,
6476    #[serde(default)]
6477    target_url: Option<String>,
6478    /// Whether the base branch requires this check. Only the GraphQL node
6479    /// carries it; `None` is "not read", never "not required".
6480    #[serde(default)]
6481    is_required: Option<bool>,
6482}
6483
6484impl GhCheck {
6485    /// Name to show a human and hand to the fixer.
6486    fn label(&self) -> String {
6487        self.name
6488            .clone()
6489            .or_else(|| self.context.clone())
6490            .unwrap_or_else(|| "(unnamed check)".to_owned())
6491    }
6492
6493    /// Where this check's logs live, when it has any.
6494    fn url(&self) -> Option<&str> {
6495        self.details_url
6496            .as_deref()
6497            .or(self.target_url.as_deref())
6498            .filter(|u| !u.is_empty())
6499    }
6500
6501    /// Did it pass?
6502    ///
6503    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6504    /// skips release and bot pull requests by design, and a skip that blocked
6505    /// landing would block exactly the pull requests that need no review.
6506    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6507    /// merging over one is merging over a check that never ran.
6508    fn verdict(&self) -> Verdict {
6509        if let Some(status) = self.status.as_deref() {
6510            if !status.eq_ignore_ascii_case("COMPLETED") {
6511                return Verdict::Pending;
6512            }
6513        }
6514        let outcome = self
6515            .conclusion
6516            .as_deref()
6517            .or(self.state.as_deref())
6518            .unwrap_or("");
6519        match outcome.to_ascii_uppercase().as_str() {
6520            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6521            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6522            | "ACTION_REQUIRED" => Verdict::Fail,
6523            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6524                Verdict::Pending
6525            }
6526            _ => Verdict::Unknown,
6527        }
6528    }
6529}
6530
6531#[derive(Debug, Deserialize)]
6532struct GhAuthor {
6533    #[serde(default)]
6534    login: String,
6535}
6536
6537#[derive(Debug, Deserialize)]
6538struct GhReview {
6539    #[serde(default)]
6540    author: GhAuthor,
6541    #[serde(default)]
6542    body: String,
6543}
6544
6545#[derive(Debug, Deserialize)]
6546struct GhComment {
6547    #[serde(default)]
6548    author: GhAuthor,
6549    #[serde(default)]
6550    body: String,
6551}
6552
6553#[derive(Debug, Deserialize)]
6554struct GhUser {
6555    #[serde(default)]
6556    login: String,
6557}
6558
6559#[derive(Debug, Deserialize)]
6560struct GhInline {
6561    #[serde(default)]
6562    user: GhUser,
6563    #[serde(default)]
6564    path: Option<String>,
6565    #[serde(default)]
6566    line: Option<u64>,
6567    #[serde(default)]
6568    body: String,
6569}
6570
6571impl Default for GhAuthor {
6572    fn default() -> Self {
6573        Self {
6574            login: "(unknown)".to_owned(),
6575        }
6576    }
6577}
6578
6579impl Default for GhUser {
6580    fn default() -> Self {
6581        Self {
6582            login: "(unknown)".to_owned(),
6583        }
6584    }
6585}
6586
6587#[cfg(test)]
6588pub(crate) mod tests {
6589    use super::*;
6590    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6591
6592    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6593        format!(
6594            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6595        )
6596    }
6597
6598    #[test]
6599    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6600        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6601        assert_eq!(
6602            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6603            Ok(())
6604        );
6605        for (json, why) in [
6606            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6607            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6608            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6609            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6610            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6611            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6612        ] {
6613            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6614                .unwrap_err()
6615                .why;
6616            assert!(err.contains(why), "{json}: {err}");
6617        }
6618        // A head that moved on past what was verified is left alone.
6619        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6620        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6621        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6622        assert!(
6623            !closable(
6624                &head_json("x", "main", "OPEN", false),
6625                "magi/27b2/A",
6626                "main",
6627                &[]
6628            )
6629            .unwrap_err()
6630            .retry
6631        );
6632        assert!(is_forge_url("https://github.com/o/r.git"));
6633        assert!(is_forge_url("git@github.com:o/r.git"));
6634        assert!(!is_forge_url("/tmp/origin.git"));
6635        assert!(!is_forge_url("C:\\work\\origin.git"));
6636        assert!(!is_forge_url("file:///tmp/origin.git"));
6637        assert!(forge_unavailable(
6638            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6639        ));
6640        assert!(!forge_unavailable(
6641            "gh pr list failed: error connecting to api.github.com"
6642        ));
6643        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6644        // A record that does not say whether it is a fork is not trusted.
6645        assert!(
6646            closable(
6647                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6648                "b",
6649                "main",
6650                &["aaa".to_owned()]
6651            )
6652            .is_err()
6653        );
6654    }
6655
6656    #[test]
6657    fn the_close_comment_names_the_commit_on_the_base() {
6658        let e = crate::already::Evidence {
6659            proof: crate::already::Proof::PatchId,
6660            tip: "1234567890".to_owned(),
6661            commits: vec!["0e368de0000".to_owned()],
6662        };
6663        let c = superseded_comment("main", &e);
6664        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6665    }
6666
6667    /// 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.
6668    const GREEN_OPEN: &str = r####"{
6669  "url": "https://github.com/yukimemi/magi/pull/10",
6670  "number": 10,
6671  "state": "OPEN",
6672  "mergeStateStatus": "CLEAN",
6673  "statusCheckRollup": [
6674    {
6675      "__typename": "CheckRun",
6676      "conclusion": "SKIPPED",
6677      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6678      "name": "review",
6679      "status": "COMPLETED",
6680      "workflowName": "claude-review"
6681    },
6682    {
6683      "__typename": "CheckRun",
6684      "conclusion": "SUCCESS",
6685      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6686      "name": "check (ubuntu-latest)",
6687      "status": "COMPLETED",
6688      "workflowName": "CI"
6689    },
6690    {
6691      "__typename": "CheckRun",
6692      "conclusion": "SUCCESS",
6693      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6694      "name": "rustfmt",
6695      "status": "COMPLETED",
6696      "workflowName": "CI"
6697    },
6698    {
6699      "__typename": "StatusContext",
6700      "context": "CodeRabbit",
6701      "state": "SUCCESS",
6702      "targetUrl": ""
6703    }
6704  ],
6705  "reviews": [],
6706  "comments": [
6707    {
6708      "author": {
6709        "login": "coderabbitai"
6710      },
6711      "authorAssociation": "NONE",
6712      "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"
6713    }
6714  ]
6715}"####;
6716
6717    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
6718    const RED_OPEN: &str = r####"{
6719  "url": "https://github.com/yukimemi/magi/pull/9",
6720  "number": 9,
6721  "state": "OPEN",
6722  "mergeStateStatus": "UNSTABLE",
6723  "statusCheckRollup": [
6724    {
6725      "__typename": "CheckRun",
6726      "conclusion": "SUCCESS",
6727      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6728      "name": "check (ubuntu-latest)",
6729      "status": "COMPLETED",
6730      "workflowName": "CI"
6731    },
6732    {
6733      "__typename": "CheckRun",
6734      "conclusion": "SUCCESS",
6735      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6736      "name": "rustfmt",
6737      "status": "COMPLETED",
6738      "workflowName": "CI"
6739    },
6740    {
6741      "__typename": "CheckRun",
6742      "conclusion": "FAILURE",
6743      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6744      "name": "editorconfig",
6745      "status": "COMPLETED",
6746      "workflowName": "CI"
6747    },
6748    {
6749      "__typename": "StatusContext",
6750      "context": "CodeRabbit",
6751      "state": "SUCCESS",
6752      "targetUrl": ""
6753    }
6754  ],
6755  "reviews": [],
6756  "comments": [
6757    {
6758      "author": {
6759        "login": "coderabbitai"
6760      },
6761      "authorAssociation": "NONE",
6762      "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"
6763    }
6764  ]
6765}"####;
6766
6767    /// 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.
6768    const PENDING_OPEN: &str = r####"{
6769  "url": "https://github.com/yukimemi/magi/pull/9",
6770  "number": 9,
6771  "state": "OPEN",
6772  "statusCheckRollup": [
6773    {
6774      "__typename": "CheckRun",
6775      "conclusion": "SUCCESS",
6776      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6777      "name": "check (ubuntu-latest)",
6778      "status": "COMPLETED",
6779      "workflowName": "CI"
6780    },
6781    {
6782      "__typename": "CheckRun",
6783      "conclusion": "SUCCESS",
6784      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6785      "name": "rustfmt",
6786      "status": "COMPLETED",
6787      "workflowName": "CI"
6788    },
6789    {
6790      "__typename": "CheckRun",
6791      "conclusion": null,
6792      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6793      "name": "editorconfig",
6794      "status": "IN_PROGRESS",
6795      "workflowName": "CI"
6796    },
6797    {
6798      "__typename": "StatusContext",
6799      "context": "CodeRabbit",
6800      "state": "SUCCESS",
6801      "targetUrl": ""
6802    }
6803  ],
6804  "reviews": [],
6805  "comments": []
6806}"####;
6807
6808    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
6809    const MERGED: &str = r####"{
6810  "url": "https://github.com/yukimemi/magi/pull/16",
6811  "number": 16,
6812  "state": "MERGED",
6813  "statusCheckRollup": [
6814    {
6815      "__typename": "CheckRun",
6816      "conclusion": "SUCCESS",
6817      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
6818      "name": "check (ubuntu-latest)",
6819      "status": "COMPLETED",
6820      "workflowName": "CI"
6821    },
6822    {
6823      "__typename": "CheckRun",
6824      "conclusion": "SUCCESS",
6825      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
6826      "name": "review",
6827      "status": "COMPLETED",
6828      "workflowName": "claude-review"
6829    }
6830  ],
6831  "reviews": [],
6832  "comments": []
6833}"####;
6834
6835    /// 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.
6836    const REVIEWED_OPEN: &str = r####"{
6837  "url": "https://github.com/yukimemi/magi/pull/12",
6838  "number": 12,
6839  "state": "OPEN",
6840  "statusCheckRollup": [
6841    {
6842      "__typename": "CheckRun",
6843      "conclusion": "SUCCESS",
6844      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
6845      "name": "check (ubuntu-latest)",
6846      "status": "COMPLETED",
6847      "workflowName": "CI"
6848    },
6849    {
6850      "__typename": "CheckRun",
6851      "conclusion": "SUCCESS",
6852      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
6853      "name": "review",
6854      "status": "COMPLETED",
6855      "workflowName": "claude-review"
6856    }
6857  ],
6858  "reviews": [
6859    {
6860      "author": {
6861        "login": "claude"
6862      },
6863      "state": "COMMENTED",
6864      "body": ""
6865    }
6866  ],
6867  "comments": [
6868    {
6869      "author": {
6870        "login": "coderabbitai"
6871      },
6872      "authorAssociation": "NONE",
6873      "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"
6874    },
6875    {
6876      "author": {
6877        "login": "claude"
6878      },
6879      "authorAssociation": "NONE",
6880      "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"
6881    }
6882  ]
6883}"####;
6884
6885    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
6886    const INLINE: &str = r####"[
6887  {
6888    "user": {
6889      "login": "claude[bot]"
6890    },
6891    "path": "src/graph.rs",
6892    "line": 231,
6893    "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"
6894  }
6895]"####;
6896
6897    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
6898    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
6899<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
6900
6901> [!IMPORTANT]
6902> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
6903> 
6904> This repository does not receive automatic reviews because it has fewer than 10 stars.
6905> 
6906> <details>
6907> <summary>⚙️ Run configuration</summary>
6908> 
6909> **Configuration used**: defaults
6910> 
6911> **Review profile**: CHILL
6912> 
6913> **Plan**: Team
6914> 
6915> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
6916> 
6917> </details>
6918
6919<!-- end of auto-generated comment: skip review by coderabbit.ai -->
6920
6921<!-- tips_start -->
6922
6923---
6924
6925Thanks 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.
6926
6927<details>
6928<summary>❤️ Share</summary>
6929
6930- [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"####;
6931
6932    /// 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.
6933    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
6934
6935---
6936### Reviewing PR #16
6937
6938- [x] Read AGENTS.md conventions
6939- [x] Review `src/daemon.rs` changes
6940- [x] Review `src/main.rs` changes (new `doctor` reporting)
6941- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
6942- [x] Check test coverage for new behavior
6943- [x] Run verification commands (blocked — see note)
6944- [x] Post findings"####;
6945
6946    /// The same job's real comment on pull request #12 once it had something to say.
6947    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
6948
6949---
6950### Review: `magi review <branch>` — cheap-half-only graph
6951
6952Read 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.
6953
6954**Correctness**
6955
6956- 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"####;
6957
6958    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
6959        PrState {
6960            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
6961            number: 16,
6962            state: PrLifecycle::Open,
6963            checks,
6964            // These tests are about red-means-fix, so a red here is one the
6965            // forge gates on. Without saying so they would assert the new
6966            // "merge past a check nobody requires" path by accident.
6967            blocking: if matches!(checks, Checks::Red) {
6968                Blocking::Yes
6969            } else {
6970                Blocking::No
6971            },
6972            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
6973            review_comments: (0..comments)
6974                .map(|i| ReviewComment {
6975                    author: "coderabbitai".to_owned(),
6976                    path: Some("src/graph.rs".to_owned()),
6977                    line: Some(231),
6978                    body: format!("finding {i}"),
6979                })
6980                .collect(),
6981        }
6982    }
6983
6984    #[test]
6985    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
6986        use CiExpectation::{Absent, Expected};
6987        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
6988            let p = pr(checks, &["x"], 0);
6989            for waited in [Duration::ZERO, CHECKS_GRACE] {
6990                assert_eq!(
6991                    decide_with(&p, 0, 4, waited, Expected),
6992                    decide(&p, 0, 4, waited)
6993                );
6994            }
6995        }
6996        // Nothing will ever report: no wait, no give-up, no fix round.
6997        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
6998            let p = pr(checks, &["x"], 0);
6999            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
7000            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
7001        }
7002        // Third-party statuses never change the review decision, even at budget.
7003        for comments in [0, 1] {
7004            for round in [0, 4] {
7005                let absent = decide_with(
7006                    &pr(Checks::Unknown, &[], comments),
7007                    round,
7008                    4,
7009                    CHECKS_GRACE,
7010                    Absent,
7011                );
7012                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
7013                    assert_eq!(
7014                        decide_with(
7015                            &pr(checks, &["third-party"], comments),
7016                            round,
7017                            4,
7018                            Duration::ZERO,
7019                            Absent
7020                        ),
7021                        absent
7022                    );
7023                }
7024                if comments != 0 {
7025                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
7026                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
7027                }
7028            }
7029        }
7030        let empty = pr(Checks::Unknown, &[], 0);
7031        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
7032            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
7033        }
7034        assert_eq!(
7035            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
7036            Step::Wait
7037        );
7038        assert_eq!(
7039            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
7040            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
7041        );
7042        // A conflict is not a check: it still wants the rebase.
7043        let mut p = pr(Checks::Unknown, &[], 0);
7044        p.blocking = Blocking::Conflict;
7045        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
7046        // And a pull request that left our hands is still done.
7047        p.state = PrLifecycle::Merged;
7048        assert_eq!(
7049            decide_with(&p, 0, 4, Duration::ZERO, Absent),
7050            Step::Done { merged: true }
7051        );
7052    }
7053
7054    #[test]
7055    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
7056        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
7057        assert_eq!(state.number, 10);
7058        assert_eq!(state.state, PrLifecycle::Open);
7059        assert_eq!(state.checks, Checks::Green);
7060        assert!(state.failing.is_empty());
7061        assert!(
7062            state.review_comments.is_empty(),
7063            "the only comment is CodeRabbit's trigger notice: {:?}",
7064            state.review_comments
7065        );
7066        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
7067    }
7068
7069    #[test]
7070    fn a_failing_check_parses_as_red_and_is_named() {
7071        let state = parse_pr(RED_OPEN).expect("red fixture parses");
7072        assert_eq!(state.checks, Checks::Red);
7073        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
7074        // The captured payload says `UNSTABLE` - mergeable, with a check
7075        // nobody requires red - which is exactly the shape that had to be
7076        // merged by hand. Asserted separately, in
7077        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
7078        // test is about is that a red check is *named*, so the reason a fixer
7079        // is handed says which one; so it asks the blocking question here.
7080        let mut blocking = state.clone();
7081        blocking.blocking = Blocking::Yes;
7082        match decide(&blocking, 0, 4, Duration::ZERO) {
7083            Step::Fix { reason } => {
7084                assert!(reason.contains("editorconfig"), "reason: {reason}");
7085                assert!(reason.contains("failing"), "reason: {reason}");
7086            }
7087            other => panic!("expected a fix round, got {other:?}"),
7088        }
7089    }
7090
7091    #[test]
7092    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
7093        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
7094        assert_eq!(state.checks, Checks::Pending);
7095        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
7096    }
7097
7098    #[test]
7099    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
7100        let state = parse_pr(MERGED).expect("merged fixture parses");
7101        assert_eq!(state.state, PrLifecycle::Merged);
7102        assert_eq!(
7103            decide(&state, 0, 4, Duration::ZERO),
7104            Step::Done { merged: true }
7105        );
7106    }
7107
7108    #[test]
7109    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
7110        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
7111        assert_eq!(state.checks, Checks::Green);
7112        let authors: Vec<&str> = state
7113            .review_comments
7114            .iter()
7115            .map(|c| c.author.as_str())
7116            .collect();
7117        assert_eq!(
7118            authors,
7119            vec!["claude"],
7120            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
7121        );
7122        match decide(&state, 0, 4, Duration::ZERO) {
7123            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
7124            other => panic!("expected a fix round, got {other:?}"),
7125        }
7126    }
7127
7128    #[test]
7129    fn inline_review_comments_keep_their_file_and_line() {
7130        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
7131        assert_eq!(comments.len(), 1);
7132        assert_eq!(comments[0].author, "claude[bot]");
7133        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
7134        assert_eq!(comments[0].line, Some(231));
7135        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
7136    }
7137
7138    #[test]
7139    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
7140        assert!(
7141            is_noise(CODERABBIT_TRIGGER),
7142            "CodeRabbit's trigger notice declares itself not a review"
7143        );
7144        assert!(
7145            is_noise(CLAUDE_CHECKLIST),
7146            "a progress checklist asks for nothing"
7147        );
7148        assert!(
7149            !is_noise(CLAUDE_FINDING),
7150            "a review that names a bug is input, not noise"
7151        );
7152
7153        let mut clean = pr(Checks::Green, &[], 0);
7154        clean.review_comments.push(ReviewComment {
7155            author: "coderabbitai".to_owned(),
7156            path: None,
7157            line: None,
7158            body: CODERABBIT_TRIGGER.to_owned(),
7159        });
7160        clean.review_comments.retain(|c| !is_noise(&c.body));
7161        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
7162
7163        let mut found = pr(Checks::Green, &[], 0);
7164        found.review_comments.push(ReviewComment {
7165            author: "claude".to_owned(),
7166            path: None,
7167            line: None,
7168            body: CLAUDE_FINDING.to_owned(),
7169        });
7170        found.review_comments.retain(|c| !is_noise(&c.body));
7171        assert!(matches!(
7172            decide(&found, 0, 4, Duration::ZERO),
7173            Step::Fix { .. }
7174        ));
7175    }
7176
7177    #[test]
7178    fn the_policy_table_holds_for_every_combination_that_matters() {
7179        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
7180            (
7181                "pending checks are waited for, even on the last round",
7182                pr(Checks::Pending, &[], 0),
7183                4,
7184                4,
7185                Duration::ZERO,
7186                Step::Wait,
7187            ),
7188            (
7189                "red checks are fixed",
7190                pr(Checks::Red, &["editorconfig"], 0),
7191                0,
7192                4,
7193                Duration::ZERO,
7194                Step::Fix {
7195                    reason: "1 check(s) failing: editorconfig".to_owned(),
7196                },
7197            ),
7198            (
7199                "green with comments is fixed, not merged",
7200                pr(Checks::Green, &[], 2),
7201                1,
7202                4,
7203                Duration::ZERO,
7204                Step::Fix {
7205                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
7206                        .to_owned(),
7207                },
7208            ),
7209            (
7210                "green and clean merges",
7211                pr(Checks::Green, &[], 0),
7212                3,
7213                4,
7214                Duration::ZERO,
7215                Step::Merge,
7216            ),
7217            (
7218                "an unreadable rollup is waited on while the grace lasts",
7219                pr(Checks::Unknown, &[], 0),
7220                0,
7221                4,
7222                Duration::ZERO,
7223                Step::Wait,
7224            ),
7225            (
7226                "an unreadable rollup is never merged once the grace is spent",
7227                pr(Checks::Unknown, &[], 0),
7228                0,
7229                4,
7230                CHECKS_GRACE,
7231                Step::GiveUp {
7232                    reason: "no check status is readable on the pull request after 3 minute(s); \
7233                             refusing to merge on a guess"
7234                        .to_owned(),
7235                },
7236            ),
7237        ];
7238        for (what, state, round, budget, waited, want) in cases {
7239            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
7240        }
7241    }
7242
7243    #[test]
7244    fn the_forge_verdict_survives_the_round_trip_from_gh() {
7245        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
7246        // requested but never parsed is the kind of thing that looks wired up
7247        // and answers `Unsaid` forever.
7248        let green = parse_pr(GREEN_OPEN).expect("parse");
7249        assert_eq!(green.blocking, Blocking::No);
7250        let red = parse_pr(RED_OPEN).expect("parse");
7251        assert_eq!(
7252            red.blocking,
7253            Blocking::No,
7254            "`UNSTABLE` is mergeable: the red check is one nobody requires"
7255        );
7256        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
7257        // A payload from an older `gh` has no such field at all.
7258        let quiet =
7259            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
7260        assert_eq!(quiet.blocking, Blocking::Unsaid);
7261    }
7262
7263    #[test]
7264    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
7265        // Pull request 37's only red check was `editorconfig`, failing
7266        // because the action could not fetch its own binary after
7267        // editorconfig-checker v4 renamed its release assets. The repository
7268        // does not require it. magi answered by asking a fixer to repair a
7269        // change that was fine, and the pull request had to be merged by hand.
7270        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7271        nonblocking.blocking = Blocking::No;
7272        assert_eq!(
7273            decide(&nonblocking, 0, 4, Duration::ZERO),
7274            Step::Merge,
7275            "the forge says nothing is in the way, so nothing is"
7276        );
7277
7278        // The same red, gated on: that is a fix round, as before.
7279        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7280        blocking.blocking = Blocking::Yes;
7281        assert!(matches!(
7282            decide(&blocking, 0, 4, Duration::ZERO),
7283            Step::Fix { .. }
7284        ));
7285
7286        // A review comment still outranks green-enough: a non-required red
7287        // must not become a way to merge past an unanswered reviewer.
7288        let mut commented = pr(Checks::Red, &["coverage"], 1);
7289        commented.blocking = Blocking::No;
7290        assert!(matches!(
7291            decide(&commented, 0, 4, Duration::ZERO),
7292            Step::Fix { .. }
7293        ));
7294
7295        // And silence from the forge is not consent.
7296        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7297        unsaid.blocking = Blocking::Unsaid;
7298        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7299        assert!(matches!(
7300            decide(&unsaid, 0, 4, CHECKS_GRACE),
7301            Step::Fix { .. }
7302        ));
7303    }
7304
7305    #[test]
7306    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7307        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7308        red.blocking = Blocking::No;
7309        assert_eq!(
7310            decide(&red, 0, 4, Duration::ZERO),
7311            Step::Merge,
7312            "announcing must not change the decision"
7313        );
7314        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7315        assert!(said.contains("yukimemi/magi"), "{said}");
7316        assert!(said.contains("#16"), "{said}");
7317        assert!(
7318            said.contains("https://github.com/yukimemi/magi/pull/16"),
7319            "{said}"
7320        );
7321        assert!(
7322            said.contains("test (windows-latest)") && said.contains("coverage"),
7323            "{said}"
7324        );
7325
7326        // `failing` can be left over on a green observation; only `checks` counts.
7327        let green = pr(Checks::Green, &["stale"], 0);
7328        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7329    }
7330
7331    #[test]
7332    fn red_merge_notices_omit_empty_check_details() {
7333        for checks in [vec![], vec!["", "  "]] {
7334            let red = pr(Checks::Red, &checks, 0);
7335            let summary = red_merge_summary("owner/repo", &red).unwrap();
7336            let notice = crate::notices::merged_red("run-1", &summary);
7337            assert_eq!(
7338                notice.message,
7339                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7340            );
7341            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7342        }
7343        let red = pr(Checks::Red, &["", " test ", " "], 0);
7344        let summary = red_merge_summary("owner/repo", &red).unwrap();
7345        assert!(summary.contains("with red checks: test ("), "{summary}");
7346    }
7347
7348    #[test]
7349    fn the_repo_label_comes_from_the_pull_request_url() {
7350        let p = Path::new("/tmp/checkout");
7351        assert_eq!(
7352            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7353            "yukimemi/magi"
7354        );
7355        assert_eq!(repo_label(p, "not a url"), "checkout");
7356    }
7357
7358    #[test]
7359    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7360        // Pull requests 35 and 37 were both rebased by hand: a competition
7361        // that runs for two hours against a repository merging pull requests
7362        // all day conflicts on the way in, and that is arithmetic rather
7363        // than a defect in the change.
7364        let mut conflicted = pr(Checks::Green, &[], 0);
7365        conflicted.blocking = Blocking::Conflict;
7366        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7367
7368        // Decided before the checks, and even with the rounds spent: every
7369        // check on a branch that cannot land is an answer about a state that
7370        // cannot land, and a conflict is not the change's fault.
7371        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7372        red.blocking = Blocking::Conflict;
7373        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7374
7375        // The lifecycle still wins over everything, conflict included.
7376        let mut merged = pr(Checks::Red, &[], 0);
7377        merged.blocking = Blocking::Conflict;
7378        merged.state = PrLifecycle::Merged;
7379        assert_eq!(
7380            decide(&merged, 0, 4, Duration::ZERO),
7381            Step::Done { merged: true }
7382        );
7383    }
7384
7385    #[test]
7386    fn the_forge_verdict_is_read_off_merge_state_status() {
7387        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7388        // matters: mergeable, with a non-required check red or still running.
7389        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7390            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7391            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7392        }
7393        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7394        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7395        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7396        // An older `gh`, or a token without the scope, says nothing - and
7397        // refusing to guess is the rule everywhere else in this module.
7398        for quiet in ["", "UNKNOWN"] {
7399            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7400            assert!(Blocking::of(quiet).stops_a_merge());
7401        }
7402    }
7403
7404    #[test]
7405    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7406        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7407        // The exact stderr from run ec12, in a jj-colocated repository.
7408        let jj = "could not determine current branch: failed to run git: not on any branch";
7409
7410        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7411            .expect("the forge says merged, so it merged");
7412        assert!(landed.ok);
7413        assert!(
7414            landed.detail.contains("but the pull request is merged"),
7415            "the record must not read as a clean success: {}",
7416            landed.detail
7417        );
7418        assert!(
7419            landed.detail.contains("not on any branch"),
7420            "and it must keep what the command actually said: {}",
7421            landed.detail
7422        );
7423
7424        // A pull request still open means the merge really failed.
7425        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7426        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7427        // And an unreadable answer is not evidence of success.
7428        assert!(merged_after_all(&argv, jj, None).is_none());
7429    }
7430
7431    #[test]
7432    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7433        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7434        state.state = PrLifecycle::Closed;
7435        assert_eq!(
7436            decide(&state, 0, 4, Duration::ZERO),
7437            Step::Done { merged: false },
7438            "a human closing the pull request ends the loop, whatever CI says"
7439        );
7440    }
7441
7442    #[test]
7443    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7444        let red = decide(
7445            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7446            4,
7447            4,
7448            Duration::ZERO,
7449        );
7450        match red {
7451            Step::GiveUp { reason } => {
7452                assert!(reason.contains("editorconfig"), "reason: {reason}");
7453                assert!(reason.contains("test (macos)"), "reason: {reason}");
7454                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7455            }
7456            other => panic!("expected a give-up, got {other:?}"),
7457        }
7458
7459        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7460        match commented {
7461            Step::GiveUp { reason } => {
7462                assert!(reason.contains("unresolved"), "reason: {reason}");
7463                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7464            }
7465            other => panic!("expected a give-up, got {other:?}"),
7466        }
7467    }
7468
7469    #[test]
7470    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7471        let candidate_commit = "magi: candidate A (uncommitted work)";
7472        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7473        let argv = merge_argv(16, &subject);
7474
7475        assert!(argv.contains(&"--squash".to_owned()));
7476        assert!(argv.contains(&"--delete-branch".to_owned()));
7477        assert!(argv.contains(&"--subject".to_owned()));
7478        assert_eq!(
7479            argv.last().map(String::as_str),
7480            Some("add retries to the uploader"),
7481            "the subject must not be the candidate commit message"
7482        );
7483        assert_ne!(subject, candidate_commit);
7484    }
7485
7486    #[test]
7487    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7488        assert_eq!(
7489            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7490            "feat: a queue, an unattended loop, and a phone UI"
7491        );
7492        assert_eq!(
7493            merge_subject("", "# port the retry logic\n\ndetails"),
7494            "port the retry logic",
7495            "an empty title falls back to the task's first line, heading marks stripped"
7496        );
7497    }
7498
7499    #[test]
7500    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7501        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7502        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7503        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7504        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7505        assert_eq!(run_of(""), None);
7506    }
7507
7508    #[test]
7509    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7510        let mut out = Vec::new();
7511        push_if_outstanding(
7512            &mut out,
7513            ReviewComment {
7514                author: "yukimemi".to_owned(),
7515                path: None,
7516                line: None,
7517                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7518            },
7519        );
7520        assert!(out.is_empty());
7521    }
7522
7523    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7524    /// falls back to the repository - which keeps these tests free of a
7525    /// worktree, a `git` invocation and a network.
7526    fn run_state() -> RunState {
7527        let mut state = RunState::new(
7528            std::path::PathBuf::from("/repo/magi"),
7529            "main".to_owned(),
7530            "abcdef1234".to_owned(),
7531            "add retries to the uploader".to_owned(),
7532            crate::config::Config::default(),
7533        );
7534        // These fixtures test execution flow, independent of host disk capacity.
7535        state.config.disk.min_free_bytes = 0;
7536        // Tests run in parallel against one persistent home and the ids
7537        // `RunState::new` draws from the clock can repeat, so two tests would
7538        // share a run's questions. The home also outlives the process, so the
7539        // counter alone would reuse an earlier run's ids.
7540        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7541        let nanos = std::time::SystemTime::now()
7542            .duration_since(std::time::UNIX_EPOCH)
7543            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7544        state.id = format!(
7545            "20261004-{nanos:06}-{:04x}",
7546            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7547        );
7548        state
7549    }
7550
7551    fn green_pr() -> PrState {
7552        PrState {
7553            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7554            number: 42,
7555            state: PrLifecycle::Open,
7556            checks: Checks::Green,
7557            // The forge sees nothing in the way unless a test says otherwise.
7558            blocking: Blocking::No,
7559            failing: Vec::new(),
7560            review_comments: vec![ReviewComment {
7561                author: "coderabbitai".to_owned(),
7562                path: Some("src/land.rs".to_owned()),
7563                line: Some(212),
7564                body: "this branch never checks the exit code".to_owned(),
7565            }],
7566        }
7567    }
7568
7569    #[test]
7570    fn land_fixer_defers_review_and_verification_without_a_cache() {
7571        let state = run_state();
7572        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7573        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7574        assert!(p.contains("Commit in this worktree"), "{p}");
7575    }
7576
7577    #[test]
7578    fn github_facing_land_text_is_english_whatever_the_language() {
7579        let mut state = run_state();
7580        state.config.graph.language = "ja".to_owned();
7581        let comment = stop_comment(&state.id, "checks are still red");
7582        assert!(crate::github_text::check("", &comment).is_empty());
7583        assert!(comment.is_ascii(), "{comment}");
7584        assert!(comment.starts_with(MARKER));
7585
7586        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7587        let ja_at = p.find("Write all prose in ja").unwrap();
7588        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7589        assert!(ja_at < rule_at, "{p}");
7590        assert!(p.contains("stays in Japanese"), "{p}");
7591
7592        state.config.graph.language = "en".to_owned();
7593        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7594        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7595        assert!(!p.contains("does not apply"), "{p}");
7596    }
7597
7598    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7599
7600    fn panel() -> String {
7601        approval_panel(
7602            &run_state(),
7603            &green_pr(),
7604            NUMSTAT,
7605            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7606            &[
7607                "land: ask before merging".to_owned(),
7608                "land: colour the diff".to_owned(),
7609            ],
7610            "feat: merge approval from the phone",
7611        )
7612    }
7613
7614    #[test]
7615    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7616        let html = panel();
7617        for needle in [
7618            "42",
7619            "main",
7620            "src/land.rs",
7621            "src/web.rs",
7622            "assets/logo.png",
7623            "feat: merge approval from the phone",
7624            "land: ask before merging",
7625            "land: colour the diff",
7626            "coderabbitai",
7627            "this branch never checks the exit code",
7628            "green",
7629        ] {
7630            assert!(html.contains(needle), "the panel must state `{needle}`");
7631        }
7632    }
7633
7634    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7635        crate::run::pin_test_home();
7636        let tmp = tempfile::tempdir().unwrap();
7637        let repo = tmp.path().join("repo");
7638        let remote = tmp.path().join("remote.git");
7639        std::fs::create_dir(&repo).unwrap();
7640        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7641            .await
7642            .unwrap();
7643        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7644        git::git(&repo, &["config", "user.name", "Test"])
7645            .await
7646            .unwrap();
7647        git::git(&repo, &["config", "user.email", "test@example.test"])
7648            .await
7649            .unwrap();
7650        std::fs::write(repo.join("base"), "base").unwrap();
7651        git::git(&repo, &["add", "."]).await.unwrap();
7652        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7653        git::git(
7654            &repo,
7655            &["remote", "add", "origin", remote.to_str().unwrap()],
7656        )
7657        .await
7658        .unwrap();
7659        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7660        git::git(&repo, &["checkout", "-b", "winner"])
7661            .await
7662            .unwrap();
7663        std::fs::write(repo.join("change"), "change").unwrap();
7664        git::git(&repo, &["add", "."]).await.unwrap();
7665        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7666        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7667        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7668            .await
7669            .unwrap();
7670        let mut state = run_state();
7671        state.repo = repo.clone();
7672        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7673        state.config.graph.land = true;
7674        state.config.graph.land_approval = true;
7675        state.pr_head = Some("task-head".into());
7676        state.pr_pushed_head = Some(head.clone());
7677        state.candidates = vec![winning_candidate("change")];
7678        state.candidates[0].worktree = repo;
7679        state.candidates[0].branch = "winner".into();
7680        state.tally = Some(uncontested_tally());
7681        state.gate_ran = true;
7682        state.gate_head = Some(head.clone());
7683        state.land_sync_pending = true;
7684        state.save().unwrap();
7685        (tmp, state, head)
7686    }
7687
7688    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7689        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7690        resume_landing_head(state, head, &green_pr().url, &forge, None).await
7691    }
7692
7693    async fn advance_landing_base(state: &RunState) {
7694        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7695        std::fs::write(state.repo.join("advance"), "advance").unwrap();
7696        git::git(&state.repo, &["add", "."]).await.unwrap();
7697        git::git(&state.repo, &["commit", "-m", "advance base"])
7698            .await
7699            .unwrap();
7700        git::git(&state.repo, &["push", "origin", "main"])
7701            .await
7702            .unwrap();
7703        git::git(&state.repo, &["checkout", "winner"])
7704            .await
7705            .unwrap();
7706    }
7707
7708    #[tokio::test]
7709    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
7710        let (_tmp, mut state, head) = landing_git_fixture().await;
7711        advance_landing_base(&state).await;
7712        let scratch = state.dir().join("rebase");
7713        std::fs::create_dir_all(&scratch).unwrap();
7714        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
7715        let attempts = state.land_sync_attempts;
7716        let error = rebase_landing_worktree(&mut state, "origin/main")
7717            .await
7718            .unwrap_err();
7719        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
7720        assert_eq!(state.land_sync_attempts, attempts);
7721        assert!(state.land_sync_target.is_none());
7722        assert!(state.rebase_fixes.is_empty());
7723        assert!(
7724            state
7725                .base_sync
7726                .as_ref()
7727                .is_none_or(|sync| sync.conflict.is_none())
7728        );
7729        let block = state.resource_block.as_ref().unwrap();
7730        assert_eq!(block.kind, crate::rebase::SEQUENCER_INFRASTRUCTURE);
7731        assert!(
7732            block.detail.contains("inspect scratch Git backlink"),
7733            "{}",
7734            block.detail
7735        );
7736        assert_eq!(
7737            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
7738            "keep"
7739        );
7740        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
7741        std::fs::remove_dir_all(&scratch).unwrap();
7742        state.resource_block = None;
7743        assert_eq!(
7744            rebase_landing_worktree(&mut state, "origin/main")
7745                .await
7746                .unwrap(),
7747            crate::rebase::Rebased::Applied
7748        );
7749        assert_eq!(state.land_sync_attempts, attempts + 1);
7750        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
7751        assert!(git::is_clean(&state.repo).await.unwrap());
7752        assert!(state.rebase_fixes.is_empty());
7753    }
7754
7755    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7756    {
7757        let (tmp, mut state, old) = landing_git_fixture().await;
7758        let path = tmp.path().join("foreign");
7759        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7760            .await
7761            .unwrap();
7762        state.foreign_checkout = Some(
7763            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7764                .await
7765                .unwrap(),
7766        );
7767        state.config.merge.mode = crate::config::MergeMode::Pr;
7768        state.save().unwrap();
7769        (tmp, state, old, path)
7770    }
7771
7772    #[tokio::test]
7773    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
7774        for phase in 0..4 {
7775            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7776            advance_landing_base(&state).await;
7777            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
7778            if phase == 0 {
7779                // The live Step::Rebase path uses this same synchronization
7780                // and publication pair, without going through resume.
7781                assert_eq!(
7782                    rebase_landing_worktree(&mut state, "origin/main")
7783                        .await
7784                        .unwrap(),
7785                    crate::rebase::Rebased::Applied
7786                );
7787            } else {
7788                interrupt_landing_rebase(&mut state).await;
7789                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
7790                if phase == 2 {
7791                    git::sync_to_head(&state.repo).await.unwrap();
7792                } else if phase == 3 {
7793                    // Crash after joining history, before clearing its saved
7794                    // start. Repeating restoration must not add another merge.
7795                    restore_landing_worktree(&mut state).await.unwrap();
7796                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7797                    state.land_rebase_from = Some(old.clone());
7798                    state.save().unwrap();
7799                    restore_landing_worktree(&mut state).await.unwrap();
7800                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
7801                }
7802                state.save().unwrap();
7803                state = RunState::load(&state.id).unwrap();
7804                restore_landing_worktree(&mut state).await.unwrap();
7805                assert_eq!(
7806                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
7807                    repaired_tree
7808                );
7809            }
7810            let head = if phase == 0 {
7811                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
7812                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
7813                    .await
7814                    .unwrap()
7815            } else {
7816                resume_observed_head(&mut state, &old).await.unwrap()
7817            };
7818            assert!(git::is_ancestor(&state.repo, &old, &head).await);
7819            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7820            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7821            assert_eq!(
7822                git::remote_head(&state.repo, "origin", "task-head")
7823                    .await
7824                    .unwrap(),
7825                Some(head.clone())
7826            );
7827            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7828            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
7829            assert!(state.gate_allows_progress());
7830            assert!(state.land_rebase_from.is_none());
7831            assert!(!state.land_sync_pending);
7832            assert!(git::is_clean(&path).await.unwrap());
7833        }
7834    }
7835
7836    #[tokio::test]
7837    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
7838        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7839        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7840        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7841        git::commit_all(&state.repo, "conflicting base")
7842            .await
7843            .unwrap();
7844        git::git(&state.repo, &["push", "origin", "main"])
7845            .await
7846            .unwrap();
7847        git::git(&state.repo, &["checkout", "winner"])
7848            .await
7849            .unwrap();
7850        landing_gate_fixer(
7851            &mut state,
7852            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7853        );
7854        state.config.graph.gate_fix_rounds = 0;
7855        state.config.verify.gate = vec!["exit 1".into()];
7856        assert!(resume_observed_head(&mut state, &old).await.is_err());
7857        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
7858        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7859        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
7860        assert_eq!(
7861            std::fs::read_to_string(state.repo.join("change")).unwrap(),
7862            "resolved"
7863        );
7864        // A red gate must neither deliver nor publish the repaired tree.
7865        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
7866        assert_eq!(
7867            git::remote_head(&state.repo, "origin", "task-head")
7868                .await
7869                .unwrap(),
7870            Some(old.clone())
7871        );
7872        state = RunState::load(&state.id).unwrap();
7873        state.config.verify.gate = vec!["grep -q resolved change".into()];
7874        let head = resume_observed_head(&mut state, &old).await.unwrap();
7875        assert_eq!(head, repaired);
7876        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7877        assert_eq!(
7878            std::fs::read_to_string(path.join("change")).unwrap(),
7879            "resolved"
7880        );
7881        assert_eq!(
7882            git::remote_head(&state.repo, "origin", "task-head")
7883                .await
7884                .unwrap(),
7885            Some(head.clone())
7886        );
7887        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7888        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7889        assert!(git::is_clean(&path).await.unwrap());
7890    }
7891
7892    #[tokio::test]
7893    async fn landing_resume_completes_the_last_charged_sync_attempt() {
7894        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
7895            let (_tmp, mut state, old) = landing_git_fixture().await;
7896            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7897            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7898            git::commit_all(&state.repo, "conflicting base")
7899                .await
7900                .unwrap();
7901            git::git(&state.repo, &["push", "origin", "main"])
7902                .await
7903                .unwrap();
7904            git::git(&state.repo, &["checkout", "winner"])
7905                .await
7906                .unwrap();
7907            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
7908            state.config.graph.land_rounds = 1;
7909            state.land_sync_attempts = 1;
7910            state.land_sync_target = saved_target.then(|| target.clone());
7911            state.land_rebase_from = Some(old.clone());
7912            landing_gate_fixer(
7913                &mut state,
7914                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7915            );
7916            state.config.verify.gate = vec!["grep -q resolved change".into()];
7917            state.save().unwrap();
7918            // Simulate interruption before the scratch start and at a conflict.
7919            if scratch_started {
7920                assert!(matches!(
7921                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
7922                        .await
7923                        .unwrap(),
7924                    git::RebaseStart::Conflicted(_)
7925                ));
7926            }
7927            state = RunState::load(&state.id).unwrap();
7928            let head = resume_observed_head(&mut state, &old).await.unwrap();
7929            assert_ne!(head, old);
7930            assert_eq!(state.land_sync_attempts, 1);
7931            assert!(state.land_sync_target.is_none());
7932            assert!(state.land_rebase_from.is_none());
7933            assert!(!state.land_sync_pending);
7934            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7935            assert!(state.gate_allows_progress());
7936            assert_eq!(
7937                git::remote_head(&state.repo, "origin", "task-head")
7938                    .await
7939                    .unwrap(),
7940                Some(head)
7941            );
7942            assert!(
7943                rebase_landing_worktree(&mut state, "origin/main")
7944                    .await
7945                    .unwrap_err()
7946                    .to_string()
7947                    .contains("budget exhausted")
7948            );
7949        }
7950    }
7951
7952    #[tokio::test]
7953    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
7954        let (_tmp, mut state, old) = landing_git_fixture().await;
7955        advance_landing_base(&state).await;
7956        state.config.verify.gate = vec!["test -f advance".into()];
7957        let head = resume_observed_head(&mut state, &old).await.unwrap();
7958        assert_ne!(head, old);
7959        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7960        assert!(state.gate_allows_progress());
7961        assert_eq!(
7962            git::remote_head(&state.repo, "origin", "task-head")
7963                .await
7964                .unwrap(),
7965            Some(head.clone())
7966        );
7967        assert_eq!(state.pr_pushed_head, Some(head));
7968        assert!(!state.land_sync_pending);
7969        assert!(state.config.graph.land_approval);
7970    }
7971
7972    fn landing_gate_fixer(state: &mut RunState, script: &str) {
7973        state.config.disk.min_free_bytes = 0;
7974        state.config.graph.gate_fix_rounds = 1;
7975        state.config.agents = vec![crate::config::AgentSpec {
7976            id: "mock".into(),
7977            kind: crate::config::AgentKind::Command,
7978            model: None,
7979            command: vec!["sh".into(), "-c".into(), script.into()],
7980            extra_args: Vec::new(),
7981            env: Default::default(),
7982            prompt_delivery: None,
7983            max_turn_secs: None,
7984        }];
7985        state.candidates[0].agent = "mock".into();
7986    }
7987
7988    #[tokio::test]
7989    async fn rebase_fixer_invocation_cap_survives_fallback_and_reload() {
7990        let (tmp, mut state, original) = landing_git_fixture().await;
7991        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7992        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7993        git::commit_all(&state.repo, "conflicting base")
7994            .await
7995            .unwrap();
7996        let target = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7997        git::git(&state.repo, &["checkout", "winner"])
7998            .await
7999            .unwrap();
8000        let scratch = state.dir().join("rebase");
8001        let counter = tmp.path().join("calls");
8002        landing_gate_fixer(
8003            &mut state,
8004            "echo \"$REBASE_AGENT\" >> \"$REBASE_COUNTER\"; exit 1",
8005        );
8006        let template = state.config.agents[0].clone();
8007        let ids = ["mock", "fallback1", "fallback2", "fallback3"].map(str::to_owned);
8008        state.config.agents = ids
8009            .iter()
8010            .map(|id| {
8011                let mut spec = template.clone();
8012                spec.id.clone_from(id);
8013                spec.env.insert("REBASE_AGENT".into(), id.clone());
8014                spec.env
8015                    .insert("REBASE_COUNTER".into(), git::path_arg(&counter));
8016                spec
8017            })
8018            .collect();
8019        state.config.roles.fixer = Some(crate::config::AgentChoice::Chain(ids.to_vec()));
8020        state.config.graph.review_rounds = 3;
8021        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8022        state.config.graph.timeout_resource_wait = 0;
8023        let started = git::rebase_start(&state.repo, &scratch, "winner", &target)
8024            .await
8025            .unwrap();
8026        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
8027        let home = crate::run::home();
8028        let cache = crate::build_target::resolve(&home, &scratch).unwrap();
8029        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", &scratch, &original);
8030        let crate::cache::AcquireOutcome::Acquired(lease) =
8031            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
8032        else {
8033            panic!("test target was already leased");
8034        };
8035        let error = crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8036            .await
8037            .unwrap_err();
8038        assert!(error.is::<crate::agent::IsolatedSeatWait>(), "{error:#}");
8039        assert!(!counter.exists());
8040        assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), ["change"]);
8041        drop(lease);
8042        state = RunState::load(&state.id).unwrap();
8043        for _ in 0..2 {
8044            let crate::rebase::Rebased::Stopped(why) =
8045                crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
8046                    .await
8047                    .unwrap()
8048            else {
8049                panic!("the unresolved conflict must stop");
8050            };
8051            assert!(why.contains("after 3 of 3 fixer round(s)"), "{why}");
8052            assert_eq!(
8053                std::fs::read_to_string(&counter)
8054                    .unwrap()
8055                    .lines()
8056                    .collect::<Vec<_>>(),
8057                ["mock", "fallback1", "fallback2"]
8058            );
8059            assert_eq!(
8060                git::rev_parse(&state.repo, "winner").await.unwrap(),
8061                original
8062            );
8063            state = RunState::load(&state.id).unwrap();
8064        }
8065    }
8066
8067    #[tokio::test]
8068    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
8069        let (_tmp, mut state, old) = landing_git_fixture().await;
8070        std::fs::write(state.repo.join("change"), "operator update").unwrap();
8071        git::commit_all(&state.repo, "extend winner").await.unwrap();
8072        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8073        git::git(
8074            &state.repo,
8075            &["push", "origin", "HEAD:refs/heads/task-head"],
8076        )
8077        .await
8078        .unwrap();
8079        state.config.verify.gate = vec!["exit 1".into()];
8080        state.config.graph.gate_fix_rounds = 0;
8081        assert!(resume_observed_head(&mut state, &updated).await.is_err());
8082        assert_ne!(old, updated);
8083        assert_eq!(state.gate_head.as_ref(), Some(&updated));
8084        assert!(!state.gate_allows_progress());
8085        assert!(state.land_sync_pending);
8086        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
8087        let head = resume_observed_head(&mut state, &updated).await.unwrap();
8088        assert_eq!(head, updated);
8089        assert!(state.gate_allows_progress());
8090        assert!(!state.land_sync_pending);
8091        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8092        land_with(&mut state, &green_pr().url, &forge)
8093            .await
8094            .unwrap();
8095        assert!(state.parked);
8096        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8097        assert!(forge.argvs().is_empty());
8098    }
8099
8100    #[tokio::test]
8101    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
8102        for divergent in [false, true] {
8103            let (_tmp, mut state, old) = landing_git_fixture().await;
8104            if divergent {
8105                git::git(&state.repo, &["reset", "--hard", "origin/main"])
8106                    .await
8107                    .unwrap();
8108            }
8109            std::fs::write(state.repo.join("external"), "external").unwrap();
8110            git::commit_all(&state.repo, "external update")
8111                .await
8112                .unwrap();
8113            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8114            git::git(
8115                &state.repo,
8116                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
8117            )
8118            .await
8119            .unwrap();
8120            if !divergent {
8121                git::git(&state.repo, &["reset", "--hard", &old])
8122                    .await
8123                    .unwrap();
8124            }
8125            let error = resume_observed_head(&mut state, &external)
8126                .await
8127                .unwrap_err();
8128            assert!(
8129                error
8130                    .to_string()
8131                    .contains("public head moved outside this run")
8132            );
8133            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
8134            assert_eq!(
8135                git::remote_head(&state.repo, "origin", "task-head")
8136                    .await
8137                    .unwrap(),
8138                Some(external)
8139            );
8140        }
8141    }
8142
8143    #[tokio::test]
8144    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
8145        let (_tmp, mut state, old) = landing_git_fixture().await;
8146        advance_landing_base(&state).await;
8147        landing_gate_fixer(
8148            &mut state,
8149            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8150        );
8151        state.config.verify.gate =
8152            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8153        state.config.verify.e2e = vec!["test -f advance".into()];
8154        // First save a red gate without spending a fixer round. Resume must
8155        // still offer the remaining budget for this exact same failed head.
8156        state.config.graph.gate_fix_rounds = 0;
8157        assert!(resume_observed_head(&mut state, &old).await.is_err());
8158        assert_eq!(
8159            git::remote_head(&state.repo, "origin", "task-head")
8160                .await
8161                .unwrap(),
8162            Some(old.clone())
8163        );
8164        state.config.graph.gate_fix_rounds = 1;
8165        let head = resume_observed_head(&mut state, &old).await.unwrap();
8166        assert_eq!(state.gate_fixes.len(), 1);
8167        assert!(state.gate_fixes[0].committed);
8168        assert!(state.gate_allows_progress());
8169        assert_eq!(state.gate_head.as_ref(), Some(&head));
8170        assert_eq!(
8171            git::remote_head(&state.repo, "origin", "task-head")
8172                .await
8173                .unwrap(),
8174            Some(head.clone())
8175        );
8176        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8177        land_with(&mut state, &green_pr().url, &forge)
8178            .await
8179            .unwrap();
8180        assert!(state.parked);
8181        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8182        assert!(forge.argvs().is_empty());
8183    }
8184
8185    #[tokio::test]
8186    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
8187        let (_tmp, mut state, old) = landing_git_fixture().await;
8188        advance_landing_base(&state).await;
8189        landing_gate_fixer(
8190            &mut state,
8191            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8192        );
8193        state.config.verify.gate = vec!["echo still red; exit 1".into()];
8194        for _ in 0..2 {
8195            assert!(resume_observed_head(&mut state, &old).await.is_err());
8196            assert_eq!(state.gate_fixes.len(), 1);
8197            assert_eq!(
8198                git::remote_head(&state.repo, "origin", "task-head")
8199                    .await
8200                    .unwrap(),
8201                Some(old.clone())
8202            );
8203        }
8204    }
8205
8206    #[tokio::test]
8207    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
8208        let (_tmp, mut state, old) = landing_git_fixture().await;
8209        advance_landing_base(&state).await;
8210        landing_gate_fixer(
8211            &mut state,
8212            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8213        );
8214        state.config.verify.gate =
8215            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8216        // The repair makes the gate green while breaking an e2e invariant.
8217        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
8218        let mut saved_comparison = None;
8219        for resume in 0..3 {
8220            assert!(resume_observed_head(&mut state, &old).await.is_err());
8221            state = RunState::load(&state.id).unwrap();
8222            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8223            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8224            assert_eq!(evidence.head, head);
8225            assert!(!evidence.passed);
8226            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
8227            let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
8228            if let Some(saved) = &saved_comparison {
8229                assert_eq!(comparison, saved);
8230            } else {
8231                saved_comparison = Some(comparison.clone());
8232            }
8233            assert_eq!(state.gate_fixes.len(), 1);
8234            assert_eq!(
8235                git::remote_head(&state.repo, "origin", "task-head")
8236                    .await
8237                    .unwrap(),
8238                Some(old.clone())
8239            );
8240            if resume > 0 {
8241                assert!(
8242                    state.gate_allows_progress(),
8243                    "a green gate must not bypass red e2e"
8244                );
8245            }
8246        }
8247        // A changed command is not new evidence about the already checked SHA.
8248        state.config.verify.e2e = vec!["grep -q fixed change".into()];
8249        assert!(resume_observed_head(&mut state, &old).await.is_err());
8250        assert_eq!(
8251            state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
8252            saved_comparison
8253        );
8254    }
8255
8256    #[tokio::test]
8257    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
8258        for phase in 0..3 {
8259            let (_tmp, mut state, old) = landing_git_fixture().await;
8260            advance_landing_base(&state).await;
8261            let head = resume_observed_head(&mut state, &old).await.unwrap();
8262            // Persist the shapes left by interruption, resource deferral,
8263            // and a successful check for a different (older) SHA.
8264            state.land_sync_pending = true;
8265            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
8266            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8267                if phase == 2 {
8268                    old.clone()
8269                } else {
8270                    head.clone()
8271                },
8272                phase == 2,
8273                if phase == 1 {
8274                    vec![crate::run::CommandOutcome {
8275                        command: state.config.verify.e2e[0].clone(),
8276                        code: None,
8277                        output_tail: "verification resource unavailable".into(),
8278                        duration_ms: 0,
8279                        resource_blocked: true,
8280                        ..Default::default()
8281                    }]
8282                } else {
8283                    Vec::new()
8284                },
8285            ));
8286            state.save().unwrap();
8287            for _ in 0..2 {
8288                state = RunState::load(&state.id).unwrap();
8289                assert!(resume_observed_head(&mut state, &head).await.is_err());
8290                let evidence = state.gate_repair_e2e.as_ref().unwrap();
8291                assert_eq!(evidence.head, head);
8292                assert!(!evidence.passed);
8293                assert!(!evidence.outcomes.is_empty());
8294                assert_eq!(
8295                    git::remote_head(&state.repo, "origin", "task-head")
8296                        .await
8297                        .unwrap(),
8298                    Some(head.clone())
8299                );
8300                assert!(state.land_sync_pending);
8301            }
8302        }
8303    }
8304
8305    #[tokio::test]
8306    async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
8307        for code in [None, Some(126), Some(127)] {
8308            let (_tmp, mut state, old) = landing_git_fixture().await;
8309            advance_landing_base(&state).await;
8310            let head = resume_observed_head(&mut state, &old).await.unwrap();
8311            state.land_sync_pending = true;
8312            state.config.verify.e2e = vec!["true".into()];
8313            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8314                head.clone(),
8315                false,
8316                vec![crate::run::CommandOutcome {
8317                    command: state.config.verify.e2e[0].clone(),
8318                    code,
8319                    output_tail: "verification command did not complete".into(),
8320                    ..Default::default()
8321                }],
8322            ));
8323            state.save().unwrap();
8324            state = RunState::load(&state.id).unwrap();
8325            assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
8326            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8327            assert_eq!(evidence.head, head);
8328            assert!(evidence.passed);
8329            assert_eq!(evidence.outcomes[0].code, Some(0));
8330        }
8331    }
8332
8333    async fn interrupt_landing_rebase(state: &mut RunState) {
8334        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
8335        state.save().unwrap();
8336        let scratch = state.dir().join("rebase");
8337        assert_eq!(
8338            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
8339                .await
8340                .unwrap(),
8341            crate::rebase::Rebased::Applied
8342        );
8343        assert!(!git::is_clean(&state.repo).await.unwrap());
8344    }
8345
8346    async fn landing_setup(state: &mut RunState) {
8347        git::git(
8348            &state.repo,
8349            &["config", "extensions.worktreeConfig", "true"],
8350        )
8351        .await
8352        .unwrap();
8353        state.config.worktree.setup =
8354            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8355        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8356            .await
8357            .unwrap();
8358        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8359    }
8360
8361    #[tokio::test]
8362    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8363        let (tmp, mut state, head) = landing_git_fixture().await;
8364        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8365        git::acquire_worktree_config(&state.repo).await.unwrap();
8366        let winner = tmp.path().join("landing");
8367        git::worktree_add_existing(&state.repo, &winner, "winner", false)
8368            .await
8369            .unwrap();
8370        state.candidates[0].worktree = winner.clone();
8371        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8372        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8373        state.config.disk.min_free_bytes = 0;
8374        state.config.worktree.setup = vec![crate::config::SetupStep {
8375            run: Some("touch setup-completed".into()),
8376            ..Default::default()
8377        }];
8378        #[cfg(unix)]
8379        {
8380            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8381            state.config.coordination = Some(crate::config::Coordination {
8382                contract_file: "fixture-contract".into(),
8383                contract_token: "fixture-v1".into(),
8384                lock_file: "fixture-lock".into(),
8385            });
8386        }
8387        state.land_rebase_from = Some(head);
8388        let restore = restore_landing_worktree(&mut state);
8389        // Only the registered Unix fixture can deadlock by reacquiring its
8390        // own operation lease. Don't time the whole Git/setup path elsewhere.
8391        #[cfg(unix)]
8392        let restore = async {
8393            tokio::time::timeout(Duration::from_secs(15), restore)
8394                .await
8395                .expect("landing setup must not wait for its own repository operation")
8396        };
8397        restore.await.unwrap();
8398        assert!(winner.join("setup-completed").is_file());
8399        assert!(git::is_clean(&winner).await.unwrap());
8400        assert!(state.land_rebase_from.is_none());
8401    }
8402
8403    #[tokio::test]
8404    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8405        for phase in 0..3 {
8406            let (_tmp, mut state, old) = landing_git_fixture().await;
8407            advance_landing_base(&state).await;
8408            landing_setup(&mut state).await;
8409            if phase > 0 {
8410                interrupt_landing_rebase(&mut state).await;
8411                if phase == 2 {
8412                    // Crash after clean removed setup products, before setup.
8413                    git::sync_to_head(&state.repo).await.unwrap();
8414                    assert!(!state.repo.join(".env").exists());
8415                }
8416                state = RunState::load(&state.id).unwrap();
8417            }
8418            let head = resume_observed_head(&mut state, &old).await.unwrap();
8419            assert_ne!(head, old);
8420            assert!(state.gate_allows_progress());
8421            assert!(state.land_rebase_from.is_none());
8422            assert_eq!(
8423                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8424                "secret"
8425            );
8426            assert!(git::is_clean(&state.repo).await.unwrap());
8427            assert!(
8428                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8429                    .await
8430                    .unwrap()
8431                    .contains(".env")
8432            );
8433        }
8434    }
8435
8436    #[tokio::test]
8437    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8438        let (_tmp, mut state, _) = landing_git_fixture().await;
8439        advance_landing_base(&state).await;
8440        landing_setup(&mut state).await;
8441        interrupt_landing_rebase(&mut state).await;
8442        // Exercise unusual names without asking Windows to create an invalid
8443        // control-character filename. Unix also covers embedded newlines.
8444        let locals = [
8445            "local notes",
8446            #[cfg(unix)]
8447            "local\nnotes",
8448        ];
8449        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8450            .await
8451            .unwrap();
8452        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8453        for local in locals {
8454            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8455            assert!(
8456                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8457                    .await
8458                    .unwrap()
8459                    .ok()
8460            );
8461        }
8462        restore_landing_worktree(&mut state).await.unwrap();
8463        for local in locals {
8464            assert_eq!(
8465                std::fs::read_to_string(state.repo.join(local)).unwrap(),
8466                "keep these notes"
8467            );
8468        }
8469        assert_eq!(
8470            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8471            "secret"
8472        );
8473        assert!(git::is_clean(&state.repo).await.unwrap());
8474        assert!(state.land_rebase_from.is_none());
8475    }
8476
8477    #[tokio::test]
8478    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8479        for local in ["advance", "advance/notes", "new-directory"] {
8480            let (_tmp, mut state, _) = landing_git_fixture().await;
8481            advance_landing_base(&state).await;
8482            // Also cover a local file blocking a new tracked directory.
8483            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8484            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8485            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8486            git::git(&state.repo, &["add", "."]).await.unwrap();
8487            git::git(&state.repo, &["commit", "-m", "add directory"])
8488                .await
8489                .unwrap();
8490            git::git(&state.repo, &["push", "origin", "main"])
8491                .await
8492                .unwrap();
8493            git::git(&state.repo, &["checkout", "winner"])
8494                .await
8495                .unwrap();
8496            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8497                .await
8498                .unwrap();
8499            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8500            let path = state.repo.join(local);
8501            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8502            std::fs::write(&path, "local notes").unwrap();
8503            interrupt_landing_rebase(&mut state).await;
8504            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8505            let checkpoint = state.land_rebase_from.clone();
8506            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8507            assert!(
8508                error.to_string().contains("conflicting with HEAD"),
8509                "{error:#}"
8510            );
8511            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8512            assert_eq!(
8513                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8514                before
8515            );
8516            assert_eq!(state.land_rebase_from, checkpoint);
8517        }
8518    }
8519
8520    #[tokio::test]
8521    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8522        for interrupted in [false, true] {
8523            let (_tmp, mut state, old) = landing_git_fixture().await;
8524            assert!(state.config.worktree.setup.is_empty());
8525            // A gate product exists before the base moves, without setup metadata.
8526            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8527                .await
8528                .unwrap();
8529            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8530            state.config.verify.gate =
8531                vec!["mkdir -p target && printf artifact > target/probe".into()];
8532            state.gate_ran = false;
8533            resume_observed_head(&mut state, &old).await.unwrap();
8534            assert_eq!(
8535                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8536                "artifact"
8537            );
8538            advance_landing_base(&state).await;
8539            if interrupted {
8540                interrupt_landing_rebase(&mut state).await;
8541                state = RunState::load(&state.id).unwrap();
8542            }
8543            state.config.verify.gate =
8544                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8545            let head = resume_observed_head(&mut state, &old).await.unwrap();
8546            assert_ne!(head, old);
8547            assert!(state.gate_allows_progress());
8548            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8549            assert_eq!(
8550                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8551                "artifact"
8552            );
8553            assert!(state.land_rebase_from.is_none());
8554            assert_eq!(
8555                git::remote_head(&state.repo, "origin", "task-head")
8556                    .await
8557                    .unwrap(),
8558                Some(head.clone())
8559            );
8560            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8561            land_with(&mut state, &green_pr().url, &forge)
8562                .await
8563                .unwrap();
8564            assert!(state.parked);
8565            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8566            assert!(forge.argvs().is_empty());
8567        }
8568    }
8569
8570    #[tokio::test]
8571    #[cfg(unix)]
8572    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8573        use std::os::fd::AsRawFd as _;
8574
8575        for interrupted in [false, true] {
8576            let (_tmp, mut state, _) = landing_git_fixture().await;
8577            advance_landing_base(&state).await;
8578            landing_setup(&mut state).await;
8579            if interrupted {
8580                interrupt_landing_rebase(&mut state).await;
8581            }
8582            state.config.worktree.setup =
8583                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8584            let common = crate::repo_lock::common_dir(&state.repo)
8585                .await
8586                .unwrap()
8587                .unwrap();
8588            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8589            state.config.coordination = crate::config::test_coordination();
8590            state.config.graph.timeout_resource_wait = 0;
8591            let external = std::fs::OpenOptions::new()
8592                .read(true)
8593                .write(true)
8594                .create(true)
8595                .truncate(false)
8596                .open(common.join("updater.lock"))
8597                .unwrap();
8598            // SAFETY: the descriptor belongs to `external` and remains open.
8599            let locked =
8600                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8601            assert_eq!(locked, 0);
8602            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8603            let checkpoint = state.land_rebase_from.clone();
8604            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8605            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8606            assert_eq!(
8607                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8608                before
8609            );
8610            assert_eq!(state.land_rebase_from, checkpoint);
8611            assert_eq!(
8612                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8613                "secret"
8614            );
8615
8616            drop(external);
8617            state.config.graph.timeout_resource_wait = 2;
8618            restore_landing_worktree(&mut state).await.unwrap();
8619            assert!(git::is_clean(&state.repo).await.unwrap());
8620            assert!(state.land_rebase_from.is_none());
8621            assert_eq!(
8622                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8623                "restored"
8624            );
8625        }
8626    }
8627
8628    #[tokio::test]
8629    #[cfg(unix)]
8630    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8631        use std::sync::atomic::{AtomicBool, Ordering};
8632
8633        let (_tmp, mut state, _) = landing_git_fixture().await;
8634        advance_landing_base(&state).await;
8635        landing_setup(&mut state).await;
8636        interrupt_landing_rebase(&mut state).await;
8637        let common = crate::repo_lock::common_dir(&state.repo)
8638            .await
8639            .unwrap()
8640            .unwrap();
8641        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8642        state.config.coordination = crate::config::test_coordination();
8643        let holder = crate::repo_lock::SeatLease::for_checkout(
8644            &state.repo,
8645            true,
8646            state.config.coordination.as_ref(),
8647        )
8648        .await
8649        .unwrap();
8650        assert!(holder.is_some());
8651        let cancelled = Arc::new(AtomicBool::new(false));
8652        let signal = cancelled.clone();
8653        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8654            signal.load(Ordering::SeqCst)
8655        });
8656        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8657        let checkpoint = state.land_rebase_from.clone();
8658        let (result, ()) = tokio::join!(
8659            tokio::time::timeout(
8660                Duration::from_secs(2),
8661                wait.scope(restore_landing_worktree(&mut state)),
8662            ),
8663            async {
8664                tokio::time::sleep(Duration::from_millis(100)).await;
8665                cancelled.store(true, Ordering::SeqCst);
8666            }
8667        );
8668        let error = result
8669            .expect("cancellation must release the waiting driver")
8670            .unwrap_err();
8671        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8672        assert_eq!(
8673            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8674            before
8675        );
8676        assert_eq!(state.land_rebase_from, checkpoint);
8677        assert_eq!(
8678            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8679            "secret"
8680        );
8681        drop(holder);
8682        restore_landing_worktree(&mut state).await.unwrap();
8683        assert!(state.land_rebase_from.is_none());
8684        assert!(git::is_clean(&state.repo).await.unwrap());
8685    }
8686
8687    #[tokio::test]
8688    #[cfg(unix)]
8689    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8690        use std::sync::atomic::{AtomicBool, Ordering};
8691
8692        for e2e in [false, true] {
8693            let (_tmp, mut state, head) = landing_git_fixture().await;
8694            let common = crate::repo_lock::common_dir(&state.repo)
8695                .await
8696                .unwrap()
8697                .unwrap();
8698            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8699            state.config.coordination = crate::config::test_coordination();
8700            if e2e {
8701                state.config.verify.e2e = vec!["true".into()];
8702                state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8703                    head.clone(),
8704                    false,
8705                    Vec::new(),
8706                ));
8707            } else {
8708                state.config.verify.gate = vec!["true".into()];
8709                state.gate_ran = false;
8710            }
8711            let holder = crate::repo_lock::SeatLease::for_checkout(
8712                &state.repo,
8713                true,
8714                state.config.coordination.as_ref(),
8715            )
8716            .await
8717            .unwrap();
8718            assert!(holder.is_some());
8719            let cancelled = Arc::new(AtomicBool::new(false));
8720            let signal = cancelled.clone();
8721            let waiting = Arc::new(tokio::sync::Notify::new());
8722            let observed = waiting.clone();
8723            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8724                observed.notify_one();
8725                signal.load(Ordering::SeqCst)
8726            });
8727            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8728            let url = green_pr().url;
8729            let result = {
8730                let mut publishing =
8731                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8732                // Git and fixture I/O precede local coordination. Start the
8733                // cancellation deadline only once the inherited wait policy
8734                // is polled, rather than timing those unrelated subprocesses.
8735                tokio::time::timeout(Duration::from_secs(30), async {
8736                    tokio::select! {
8737                        result = &mut publishing => panic!(
8738                            "verification must wait behind the held seat: {result:?}"
8739                        ),
8740                        () = waiting.notified() => {}
8741                    }
8742                })
8743                .await
8744                .expect("verification must reach the inherited coordination wait");
8745                cancelled.store(true, Ordering::SeqCst);
8746                tokio::time::timeout(Duration::from_secs(2), publishing).await
8747            };
8748            let error = result
8749                .expect("cancellation must release the verification waiter")
8750                .unwrap_err();
8751            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8752            assert!(error.to_string().contains("cancelled"), "{error:#}");
8753            assert!(forge.argvs().is_empty());
8754            assert_eq!(
8755                git::remote_head(&state.repo, "origin", "task-head")
8756                    .await
8757                    .unwrap(),
8758                Some(head.clone())
8759            );
8760            drop(holder);
8761            // Cancellation must release its reservation so another attempt can verify.
8762            assert_eq!(
8763                publish_landing_head(&mut state, &head, &url, &forge)
8764                    .await
8765                    .unwrap(),
8766                head
8767            );
8768        }
8769    }
8770
8771    #[tokio::test]
8772    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
8773        for staged in [false, true] {
8774            let (_tmp, mut state, old) = landing_git_fixture().await;
8775            advance_landing_base(&state).await;
8776            interrupt_landing_rebase(&mut state).await;
8777            std::fs::write(state.repo.join("change"), "user edit").unwrap();
8778            if staged {
8779                git::git(&state.repo, &["add", "change"]).await.unwrap();
8780            }
8781            assert!(resume_observed_head(&mut state, &old).await.is_err());
8782            assert_eq!(
8783                std::fs::read_to_string(state.repo.join("change")).unwrap(),
8784                "user edit"
8785            );
8786            assert_eq!(
8787                git::remote_head(&state.repo, "origin", "task-head")
8788                    .await
8789                    .unwrap(),
8790                Some(old)
8791            );
8792        }
8793    }
8794
8795    #[tokio::test]
8796    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
8797        let (_tmp, mut state, head) = landing_git_fixture().await;
8798        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8799        let id = state.id.clone();
8800        let pr = land_with(&mut state, &green_pr().url, &forge)
8801            .await
8802            .unwrap();
8803        assert_eq!(pr.state, PrLifecycle::Open);
8804        assert_eq!(state.id, id);
8805        assert!(state.parked);
8806        assert_eq!(state.status, RunStatus::Landing);
8807        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8808        assert!(forge.argvs().is_empty());
8809
8810        state.land_sync_pending = true;
8811        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
8812        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
8813        closed.pr.state = PrLifecycle::Closed;
8814        let forge = Scripted::new(vec![closed], vec![]);
8815        assert_eq!(
8816            land_with(&mut state, &green_pr().url, &forge)
8817                .await
8818                .unwrap()
8819                .state,
8820            PrLifecycle::Closed
8821        );
8822        assert_eq!(
8823            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
8824            "do not touch"
8825        );
8826        assert!(forge.argvs().is_empty());
8827    }
8828
8829    #[tokio::test]
8830    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
8831        let (_tmp, mut state, old) = landing_git_fixture().await;
8832        advance_landing_base(&state).await;
8833        state.config.verify.gate = vec!["exit 1".into()];
8834        assert!(resume_observed_head(&mut state, &old).await.is_err());
8835        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
8836        assert!(!state.gate_allows_progress());
8837        assert_eq!(
8838            git::remote_head(&state.repo, "origin", "task-head")
8839                .await
8840                .unwrap(),
8841            Some(old)
8842        );
8843        assert!(state.land_sync_pending);
8844    }
8845
8846    #[tokio::test]
8847    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
8848        let (_tmp, mut state, old) = landing_git_fixture().await;
8849        advance_landing_base(&state).await;
8850        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
8851        // Model a crash after the push but before saving its published SHA.
8852        state.pr_pushed_head = Some(old.clone());
8853        state.land_sync_pending = true;
8854        assert_eq!(
8855            resume_observed_head(&mut state, &pushed).await.unwrap(),
8856            pushed
8857        );
8858        // A writer races the observed PR snapshot: the explicit remote lease
8859        // must reject the push even though preflight saw our expected head.
8860        git::git(
8861            &state.repo,
8862            &["push", "--force", "origin", "main:refs/heads/task-head"],
8863        )
8864        .await
8865        .unwrap();
8866        assert!(
8867            publish_landing_head(
8868                &mut state,
8869                &pushed,
8870                &green_pr().url,
8871                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
8872            )
8873            .await
8874            .unwrap_err()
8875            .to_string()
8876            .contains("publishing gated")
8877        );
8878        assert!(
8879            resume_observed_head(&mut state, "foreign-head")
8880                .await
8881                .is_err()
8882        );
8883    }
8884    #[tokio::test]
8885    async fn landing_publication_refuses_a_pr_closed_during_gate() {
8886        let (_tmp, mut state, head) = landing_git_fixture().await;
8887        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
8888        closed.pr.state = PrLifecycle::Closed;
8889        let forge = Scripted::new(vec![closed], vec![]);
8890        assert!(
8891            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
8892                .await
8893                .unwrap_err()
8894                .to_string()
8895                .contains("PR closed or merged")
8896        );
8897    }
8898
8899    /// A candidate selected by the uncontested tally.
8900    fn winning_candidate(summary: &str) -> Candidate {
8901        Candidate {
8902            index: 0,
8903            label: 'A',
8904            agent: "opus".to_owned(),
8905            branch: "magi/x/A".to_owned(),
8906            worktree: PathBuf::from("/wt/A"),
8907            summary: summary.to_owned(),
8908            stat: String::new(),
8909            files: 1,
8910            commits: 1,
8911            empty: false,
8912            failed: None,
8913            verified_noop: None,
8914            duration_ms: 0,
8915            folded: false,
8916        }
8917    }
8918
8919    fn uncontested_tally() -> Tally {
8920        Tally {
8921            first_choice: BTreeMap::from([('A', 1)]),
8922            borda: BTreeMap::new(),
8923            winner: 'A',
8924            rankings: 1,
8925            unanimous_initial: true,
8926            deliberated: false,
8927            changed_votes: 0,
8928            unanimous_final: true,
8929            tie_break: None,
8930            judges: 1,
8931            present: 1,
8932            quorum: 1,
8933            met_quorum: true,
8934            uncontested: None,
8935        }
8936    }
8937
8938    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
8939        ReviewRecord {
8940            attempts: 0,
8941            reviewer,
8942            agent: agent.to_owned(),
8943            summary: summary.to_owned(),
8944            findings: Vec::new(),
8945            vote: None,
8946            failed: None,
8947            duration_ms: 0,
8948        }
8949    }
8950
8951    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
8952        let answered = reviews.len();
8953        ReviewRound {
8954            round,
8955            head: "abc1234".to_owned(),
8956            verified_head: None,
8957            verified_at: None,
8958            reviews,
8959            e2e: Vec::new(),
8960            verify_retried: false,
8961            e2e_deferred: false,
8962            e2e_defer_reason: None,
8963            fix: None,
8964            blocking: 0,
8965            answered,
8966            expected: answered,
8967            clean: true,
8968            progressed: false,
8969            vote_split: false,
8970            reconsideration: Vec::new(),
8971            verdict: None,
8972        }
8973    }
8974
8975    #[test]
8976    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
8977        let en = panel();
8978        assert!(en.contains("Task"), "{en}");
8979        assert!(en.contains("add retries to the uploader"), "{en}");
8980
8981        let mut state = run_state();
8982        state.config.graph.language = "ja".to_owned();
8983        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8984        assert!(ja.contains("タスク"), "{ja}");
8985        assert!(
8986            ja.contains("add retries to the uploader"),
8987            "the task itself is not translated: {ja}"
8988        );
8989    }
8990
8991    #[test]
8992    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
8993        // `run_state()` has no candidates, no tally and no reviews - exactly
8994        // the shape a run has before anything has judged or reviewed it, and
8995        // the panel must not print an empty box for either.
8996        let html = panel();
8997        assert!(!html.contains("What changed"), "{html}");
8998        assert!(!html.contains("Review verdict"), "{html}");
8999    }
9000
9001    #[test]
9002    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
9003        let mut state = run_state();
9004        state.candidates = vec![winning_candidate("")];
9005        state.tally = Some(uncontested_tally());
9006        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9007        assert!(
9008            !html.contains("What changed"),
9009            "an empty summary must not render an empty box: {html}"
9010        );
9011    }
9012
9013    #[test]
9014    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
9015        let mut state = run_state();
9016        state.candidates = vec![winning_candidate(
9017            "Added a retry loop around the uploader PUT call.",
9018        )];
9019        state.tally = Some(uncontested_tally());
9020        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9021        assert!(en.contains("What changed"), "{en}");
9022        assert!(
9023            en.contains("Added a retry loop around the uploader PUT call."),
9024            "{en}"
9025        );
9026
9027        state.config.graph.language = "ja".to_owned();
9028        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9029        assert!(ja.contains("変更内容"), "{ja}");
9030        assert!(
9031            ja.contains("Added a retry loop around the uploader PUT call."),
9032            "{ja}"
9033        );
9034    }
9035
9036    #[test]
9037    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
9038        let mut state = run_state();
9039        state.reviews = vec![
9040            review_round(
9041                1,
9042                vec![review_record(1, "alpha", "found a race, sent back")],
9043            ),
9044            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
9045        ];
9046        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9047        assert!(en.contains("Review verdict"), "{en}");
9048        assert!(en.contains("race is fixed, clean"), "{en}");
9049        assert!(
9050            !en.contains("found a race, sent back"),
9051            "only the round that actually cleared the merge should show: {en}"
9052        );
9053
9054        state.config.graph.language = "ja".to_owned();
9055        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9056        assert!(ja.contains("レビューの結論"), "{ja}");
9057        assert!(ja.contains("レビュアー"), "{ja}");
9058        assert!(ja.contains("race is fixed, clean"), "{ja}");
9059    }
9060
9061    /// The `incomplete_review = "warn"` policy (see
9062    /// `graph::Runner::review_loop`) can push a `clean` round to
9063    /// `state.reviews` while one seat's own record still has `failed: Some`
9064    /// and an empty `summary` - a seat that never answered, not one that
9065    /// answered with nothing to say.
9066    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
9067        ReviewRecord {
9068            attempts: 0,
9069            reviewer,
9070            agent: agent.to_owned(),
9071            summary: String::new(),
9072            findings: Vec::new(),
9073            vote: None,
9074            failed: Some(reason.to_owned()),
9075            duration_ms: 0,
9076        }
9077    }
9078
9079    #[test]
9080    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
9081        let mut state = run_state();
9082        state.reviews = vec![review_round(
9083            1,
9084            vec![
9085                review_record(1, "alpha", "clean, nothing to add"),
9086                unanswered_review_record(2, "beta", "timed out"),
9087            ],
9088        )];
9089        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9090        assert!(en.contains("clean, nothing to add"), "{en}");
9091        assert!(
9092            en.contains("produced no answer: timed out"),
9093            "a seat that never answered must say so, not render a blank box: {en}"
9094        );
9095        assert!(
9096            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
9097            "no reviewer box may be left empty: {en}"
9098        );
9099
9100        state.config.graph.language = "ja".to_owned();
9101        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
9102        assert!(ja.contains("回答なし: timed out"), "{ja}");
9103    }
9104
9105    #[test]
9106    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
9107        let html = panel();
9108        assert!(!html.contains("<script"), "no script survives the csp");
9109        assert!(!html.contains("<form"), "form-action is 'none'");
9110        let pr = green_pr();
9111        assert_eq!(
9112            html.matches("http").count(),
9113            html.matches(pr.url.as_str()).count(),
9114            "the only http url in the panel is the pull request's own link"
9115        );
9116        assert!(
9117            html.contains("target=\"_blank\""),
9118            "the PR link must open in a new tab so it escapes the iframe"
9119        );
9120        assert!(
9121            html.contains("rel=\"noopener noreferrer\""),
9122            "external links opening in new tabs must carry noopener noreferrer"
9123        );
9124    }
9125
9126    #[test]
9127    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
9128        let html = panel();
9129        assert!(
9130            html.contains(">+</span>"),
9131            "an added line carries a `+` in the gutter, not only a background"
9132        );
9133        assert!(
9134            html.contains(">-</span>"),
9135            "a removed line carries a `-` in the gutter, not only a background"
9136        );
9137        assert!(
9138            html.contains(">new line</span>"),
9139            "the marker is moved to the gutter, so the body is printed once without it"
9140        );
9141    }
9142
9143    #[test]
9144    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
9145        let total = DIFF_MAX_LINES + 100;
9146        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
9147        let html = approval_panel(
9148            &run_state(),
9149            &green_pr(),
9150            NUMSTAT,
9151            &diff,
9152            &[],
9153            "feat: something long",
9154        );
9155        assert!(
9156            html.contains(&format!("100 of {total} diff lines omitted")),
9157            "the note must say exactly how much was cut"
9158        );
9159        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
9160        assert!(
9161            !html.contains(&format!("line {DIFF_MAX_LINES}")),
9162            "nothing past the threshold is rendered"
9163        );
9164        assert!(
9165            html.contains("/repo/magi"),
9166            "the note says where the rest is"
9167        );
9168    }
9169
9170    #[test]
9171    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
9172        let html = approval_panel(
9173            &run_state(),
9174            &green_pr(),
9175            "1\t2\tsrc/<b>&\"x\"'.rs",
9176            "",
9177            &[],
9178            "subject",
9179        );
9180        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
9181        assert!(
9182            !html.contains("<b>"),
9183            "an agent-influenced path must never become markup"
9184        );
9185    }
9186
9187    #[tokio::test]
9188    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
9189        let a = std::path::PathBuf::from("/repo/a");
9190        let b = std::path::PathBuf::from("/repo/b");
9191
9192        let held = repo_merge_lock(&a).lock_owned().await;
9193
9194        // A second, concurrent land run against the *same* repository must
9195        // wait - `try_lock` fails while `held` is alive.
9196        assert!(
9197            repo_merge_lock(&a).try_lock().is_err(),
9198            "a second merge into the same repository must not proceed concurrently"
9199        );
9200
9201        // A run against a *different* repository must not be blocked by it -
9202        // this is what keeps a slow rebase or `gh pr merge` in one
9203        // repository from also stalling a land-approval resume in another.
9204        assert!(
9205            repo_merge_lock(&b).try_lock().is_ok(),
9206            "a different repository's merge lock must be independent"
9207        );
9208
9209        drop(held);
9210        assert!(
9211            repo_merge_lock(&a).try_lock().is_ok(),
9212            "the lock is released once the holder is done"
9213        );
9214    }
9215
9216    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
9217        let mut state = landing_state();
9218        let mut rec = review_record(1, "alpha", "precise rejection reason");
9219        rec.vote = Some(if reject {
9220            crate::verdict::ReviewVote::Reject
9221        } else {
9222            crate::verdict::ReviewVote::Approve
9223        });
9224        if major {
9225            rec.findings = contested().findings;
9226        }
9227        let mut round = review_round(1, vec![rec]);
9228        round.clean = false;
9229        round.blocking = usize::from(major);
9230        state.reviews.push(round);
9231        state.config.graph.review_rounds = 1;
9232        state
9233    }
9234
9235    #[test]
9236    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
9237        for every in [false, true] {
9238            for contested in [false, true] {
9239                for major in [false, true] {
9240                    for reject in [false, true] {
9241                        let mut state = repair_state(major, reject);
9242                        state.config.graph.land_approval = every;
9243                        state.config.graph.hold_contested_merge = contested;
9244                        let reasons = approval_reasons(&state);
9245                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
9246                        assert_eq!(
9247                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
9248                            contested && major
9249                        );
9250                        assert_eq!(
9251                            reasons.contains(&ApprovalReason::FinalReject),
9252                            contested && reject
9253                        );
9254                        assert_eq!(
9255                            reasons.len(),
9256                            usize::from(every)
9257                                + usize::from(contested && major)
9258                                + usize::from(contested && reject)
9259                        );
9260                    }
9261                }
9262            }
9263        }
9264    }
9265
9266    #[test]
9267    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
9268        use crate::verdict::ReviewVote::{Approve, Reject};
9269        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
9270            let mut state = repair_state(false, initial_reject);
9271            state.reviews[0]
9272                .reconsideration
9273                .push(crate::run::ReviewRevoteRecord {
9274                    reviewer: 1,
9275                    agent: "alpha".into(),
9276                    vote: Some(final_vote),
9277                    reason: "changed after reading the panel <evidence>".into(),
9278                    failed: None,
9279                });
9280            assert_eq!(
9281                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9282                final_vote == Reject
9283            );
9284            for language in ["en", "ja"] {
9285                state.config.graph.language = language.into();
9286                let evidence = approval_evidence(&state);
9287                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
9288                assert!(evidence.contains("changed after reading the panel <evidence>"));
9289                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9290                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
9291                assert!(!html.contains("<evidence>"));
9292            }
9293            state.reviews[0].reconsideration[0].vote = None;
9294            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
9295            assert_eq!(
9296                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9297                initial_reject
9298            );
9299            assert!(approval_evidence(&state).contains("timed out"));
9300        }
9301    }
9302
9303    #[tokio::test]
9304    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
9305        for every in [false, true] {
9306            for contested in [false, true] {
9307                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
9308                {
9309                    let mut state = repair_state(major, reject);
9310                    state.config.graph.land_approval = every;
9311                    state.config.graph.hold_contested_merge = contested;
9312                    let forge = Scripted::new(
9313                        vec![seen("abc", Checks::Green, "CLEAN", false)],
9314                        vec![(true, "")],
9315                    );
9316                    land_with(&mut state, URL, &forge).await.unwrap();
9317                    let expected = every || (contested && (major || reject));
9318                    assert_eq!(state.land_approval.is_some(), expected);
9319                    assert_eq!(forge.calls().contains(&"merge"), !expected);
9320                    if expected {
9321                        assert!(state.parked);
9322                    }
9323                }
9324            }
9325        }
9326    }
9327
9328    #[tokio::test]
9329    async fn reviewed_branch_hold_is_read_before_landing_decision() {
9330        for (base, control) in [
9331            (false, "land_approval"),
9332            (true, "land_approval"),
9333            (false, "hold_contested_merge"),
9334        ] {
9335            let (_tmp, mut state, _) = landing_git_fixture().await;
9336            state.config.graph.land_approval = base;
9337            state.config.graph.hold_contested_merge = false;
9338            state.reviewed_commits = Some(Vec::new());
9339            if control == "hold_contested_merge" {
9340                state.reviews = repair_state(false, true).reviews;
9341            }
9342            std::fs::write(
9343                state.repo.join("magi.toml"),
9344                format!("[graph]\n{control} = {}\n", !base),
9345            )
9346            .unwrap();
9347            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
9348            git::git(&state.repo, &["commit", "-m", "approval policy"])
9349                .await
9350                .unwrap();
9351            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9352            state.land_sync_pending = false;
9353            state.pr_pushed_head = Some(head.clone());
9354            state.gate_head = Some(head.clone());
9355            let forge = Scripted::new(
9356                vec![seen(&head, Checks::Green, "CLEAN", false)],
9357                vec![(true, "")],
9358            );
9359            land_with(&mut state, URL, &forge).await.unwrap();
9360            assert!(
9361                state.land_approval.is_some(),
9362                "base={base}, control={control}"
9363            );
9364            assert!(!forge.calls().contains(&"merge"));
9365            if !base {
9366                let question = ask::Questions::open()
9367                    .get(&state.land_approval.as_ref().unwrap().question)
9368                    .unwrap();
9369                assert!(question.detail.contains(&format!(
9370                    "{control}=true from the reviewed branch's magi.toml"
9371                )));
9372            }
9373        }
9374    }
9375
9376    #[tokio::test]
9377    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9378        for file in ["magi.toml", ".magi/config.toml"] {
9379            for control in crate::config::OwnerHold::ALL {
9380                let (_tmp, mut state, _) = landing_git_fixture().await;
9381                state.config.graph.land_approval = false;
9382                state.config.graph.hold_contested_merge = false;
9383                state.reviewed_commits = Some(Vec::new());
9384                if control == crate::config::OwnerHold::HoldContestedMerge {
9385                    state.reviews = repair_state(false, true).reviews;
9386                }
9387                let config = state.repo.join(file);
9388                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9389                std::fs::write(
9390                    &config,
9391                    format!(
9392                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9393                        control.key()
9394                    ),
9395                )
9396                .unwrap();
9397                git::git(&state.repo, &["add", file]).await.unwrap();
9398                git::git(&state.repo, &["commit", "-m", "require approval"])
9399                    .await
9400                    .unwrap();
9401                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9402                let gate = state.config.verify.gate.clone();
9403                state.observe_branch_owner_holds(&head).await;
9404                assert_eq!(state.config.verify.gate, gate);
9405                assert!(state.owner_hold(control));
9406                let holds = state.branch_owner_holds.clone();
9407                git::git(&state.repo, &["rm", file]).await.unwrap();
9408                git::git(&state.repo, &["commit", "-m", "remove config"])
9409                    .await
9410                    .unwrap();
9411                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9412                state.save().unwrap();
9413                state = RunState::load(&state.id).unwrap();
9414                state.observe_branch_owner_holds(&later).await;
9415                assert_eq!(state.branch_owner_holds, holds);
9416                assert_eq!(state.branch_owner_holds[0].head, head);
9417                state.land_sync_pending = false;
9418                state.pr_pushed_head = Some(later.clone());
9419                state.gate_head = Some(later.clone());
9420                let forge = Scripted::new(
9421                    vec![seen(&later, Checks::Green, "CLEAN", false)],
9422                    vec![(true, "")],
9423                );
9424                land_with(&mut state, URL, &forge).await.unwrap();
9425                assert!(!forge.calls().contains(&"merge"));
9426                assert!(state.parked);
9427                let question = ask::Questions::open()
9428                    .get(&state.land_approval.as_ref().unwrap().question)
9429                    .unwrap();
9430                assert!(question.detail.contains("Approval required because:"));
9431                assert!(question.detail.contains(&format!(
9432                    "{}=true from the reviewed branch's {file}",
9433                    control.key()
9434                )));
9435                assert_eq!(state.branch_owner_holds, holds);
9436                state.save().unwrap();
9437                let resumed = RunState::load(&state.id).unwrap();
9438                assert!(resumed.owner_hold(control));
9439                assert_eq!(resumed.branch_owner_holds, holds);
9440                assert_eq!(
9441                    resumed.land_approval.unwrap().question,
9442                    state.land_approval.unwrap().question
9443                );
9444            }
9445        }
9446    }
9447
9448    #[tokio::test]
9449    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9450        let mut state = repair_state(false, true);
9451        state.reviews[0].clean = true;
9452        let mut finding = contested().findings.remove(0);
9453        finding.severity = crate::verdict::Severity::Minor;
9454        state.reviews[0].reviews[0].findings.push(finding);
9455        assert!(state.open_findings().is_empty());
9456        let mut pr = green_pr();
9457        pr.review_comments.clear();
9458        for language in ["en", "ja"] {
9459            state.config.graph.language = language.into();
9460            let html = approval_panel(&state, &pr, "", "", &[], "subject");
9461            assert!(html.contains("[R3-1-1] minor"));
9462            assert!(html.contains(if language == "ja" {
9463                "内部指摘の解決を意味するものではありません"
9464            } else {
9465                "This does not mean internal findings are resolved"
9466            }));
9467            assert!(
9468                html.find(if language == "ja" {
9469                    "承認が必要な理由:"
9470                } else {
9471                    "Approval required because:"
9472                })
9473                .unwrap()
9474                    < html.find("[R3-1-1]").unwrap()
9475            );
9476        }
9477        state.config.graph.language = "en".into();
9478        let observed = seen("abc", Checks::Green, "CLEAN", false);
9479        assert_eq!(
9480            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9481                .await
9482                .unwrap(),
9483            ApprovalGate::Pending
9484        );
9485        let id = state.land_approval.as_ref().unwrap().question.clone();
9486        let q = ask::Questions::open().get(&id).unwrap();
9487        assert!(q.detail.starts_with("Approval required because:"));
9488        assert!(q.detail.contains("final reviewer reject"));
9489        assert!(q.detail.contains("[R3-1-1] minor"));
9490        assert!(
9491            q.detail
9492                .contains("No adoption or resolution evidence recorded")
9493        );
9494        state.config.graph.land_approval = false;
9495        state.config.graph.hold_contested_merge = false;
9496        state.reviews.clear();
9497        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9498        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9499        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9500        let forge = Scripted::new(vec![observed], vec![]);
9501        land_with(&mut state, URL, &forge).await.unwrap();
9502        assert!(!forge.calls().contains(&"merge"));
9503        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9504        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9505    }
9506
9507    #[tokio::test]
9508    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9509        let mut state = repair_state(false, true);
9510        state.config.graph.land_approval = false;
9511        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9512        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9513        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9514        state.reviews[0].reviews[0].summary = long_reason.clone();
9515        for i in 1..=10 {
9516            let mut finding = contested().findings.remove(0);
9517            finding.id = format!("R1-1-{i}");
9518            finding.severity = if i == 9 {
9519                crate::verdict::Severity::Major
9520            } else {
9521                crate::verdict::Severity::Minor
9522            };
9523            finding.title = long_title.clone();
9524            finding.detail = long_detail.clone();
9525            state.reviews[0].reviews[0].findings.push(finding);
9526        }
9527        state.reviews[0].fix = Some(crate::run::FixRecord {
9528            agent: "fixer".into(),
9529            addressed: vec!["R1-1-9".into()],
9530            rejected: vec![crate::verdict::Rejection {
9531                id: "R1-1-10".into(),
9532                why: long_reason.clone(),
9533            }],
9534            notes: long_detail.clone(),
9535            committed: false,
9536            failed: None,
9537            duration_ms: 0,
9538            continuation: None,
9539        });
9540        assert_eq!(
9541            approval_reasons(&state),
9542            [
9543                ApprovalReason::OpenBlockingFindings,
9544                ApprovalReason::FinalReject
9545            ]
9546        );
9547        let excerpt = approval_excerpt(&long_reason, 300);
9548        assert_eq!(excerpt.chars().count(), 300);
9549        assert!(excerpt.ends_with('…'));
9550        let boundary = "拒".repeat(300);
9551        assert_eq!(approval_excerpt(&boundary, 300), boundary);
9552        for language in ["en", "ja"] {
9553            state.config.graph.language = language.into();
9554            for revote in [
9555                None,
9556                Some(crate::verdict::ReviewVote::Reject),
9557                Some(crate::verdict::ReviewVote::Approve),
9558            ] {
9559                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9560                state.reviews[0].reconsideration.clear();
9561                if let Some(vote) = revote {
9562                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9563                    state.reviews[0]
9564                        .reconsideration
9565                        .push(crate::run::ReviewRevoteRecord {
9566                            reviewer: 1,
9567                            agent: "alpha".into(),
9568                            vote: Some(vote),
9569                            reason: long_reason.clone(),
9570                            failed: None,
9571                        });
9572                }
9573                let evidence = approval_evidence(&state);
9574                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9575                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9576                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9577                assert_eq!(
9578                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9579                    final_vote == crate::verdict::ReviewVote::Reject
9580                );
9581                assert!(evidence.contains(&excerpt));
9582                assert!(evidence.contains("[R1-1-8] minor"));
9583                assert!(evidence.contains("[R1-1-9] major"));
9584                assert!(evidence.contains("[R1-1-10] minor"));
9585                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9586                    assert!(!evidence.contains(tail));
9587                }
9588                assert!(evidence.contains(if language == "ja" {
9589                    "採用申告(解決未確認)"
9590                } else {
9591                    "claimed addressed (resolution unconfirmed)"
9592                }));
9593                assert!(evidence.contains(if language == "ja" {
9594                    "不採用理由"
9595                } else {
9596                    "declined"
9597                }));
9598                let major_evidence = evidence
9599                    .split("[R1-1-9] major")
9600                    .nth(1)
9601                    .unwrap()
9602                    .split("[R1-1-10]")
9603                    .next()
9604                    .unwrap();
9605                assert!(major_evidence.contains(if language == "ja" {
9606                    "採用申告(解決未確認)"
9607                } else {
9608                    "claimed addressed (resolution unconfirmed)"
9609                }));
9610                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9611                assert!(last_evidence.contains(if language == "ja" {
9612                    "不採用理由"
9613                } else {
9614                    "declined"
9615                }));
9616                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9617                assert!(html.contains(&esc(&evidence)));
9618                assert_eq!(
9619                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9620                        .await
9621                        .unwrap(),
9622                    ApprovalGate::Pending
9623                );
9624                let id = &state.land_approval.take().unwrap().question;
9625                let q = ask::Questions::open().get(id).unwrap();
9626                assert!(q.detail.starts_with(&evidence));
9627            }
9628            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9629        }
9630    }
9631
9632    #[test]
9633    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9634        for (major, reject) in [(true, false), (false, true), (true, true)] {
9635            let state = repair_state(major, reject);
9636            assert!(repair_available(&state));
9637            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9638        }
9639        assert!(!repair_available(&repair_state(false, false)));
9640        let mut clean = repair_state(true, false);
9641        clean.reviews[0].clean = true;
9642        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9643        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9644    }
9645
9646    #[tokio::test]
9647    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9648        let mut state = repair_state(true, false);
9649        let pr = green_pr();
9650        approval_gate(&mut state, &pr, "feat: x", None, "abc")
9651            .await
9652            .unwrap();
9653        let store = ask::Questions::open();
9654        let id = state.land_approval.as_ref().unwrap().question.clone();
9655        // Simulate an unanswered two-choice question created by an older build.
9656        store
9657            .update(&id, |q| {
9658                q.choices = vec![APPROVE.into(), HOLD.into()];
9659                Ok(())
9660            })
9661            .unwrap();
9662        let upgraded = store.get(&id).unwrap();
9663        assert_eq!(upgraded.choices, approval_choices(&state));
9664        assert!(!upgraded.actions.contains_key(HOLD));
9665        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9666        assert!(
9667            store
9668                .list()
9669                .iter()
9670                .any(|q| q.id == id && q.choices == upgraded.choices)
9671        );
9672        assert!(
9673            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9674        );
9675        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9676        store
9677            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9678            .unwrap();
9679        // An earlier build may have recorded the repair answer and stopped
9680        // before any driver consumed it. Reconcile that durable decision too.
9681        store
9682            .update(&id, |q| {
9683                q.actions.clear();
9684                Ok(())
9685            })
9686            .unwrap();
9687        assert_eq!(
9688            store.get(&id).unwrap().chosen_action(),
9689            Some(&ask::ChoiceAction::Resume {
9690                run: state.id.clone()
9691            })
9692        );
9693        let binding = state.land_approval.clone();
9694        assert_eq!(
9695            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9696                .await
9697                .unwrap(),
9698            ApprovalGate::Repair
9699        );
9700        assert!(state.land_approval.is_none());
9701        assert_eq!(state.merge_repairs.len(), 1);
9702        let request = &state.merge_repairs[0];
9703        assert_eq!(request.question, id);
9704        assert_eq!(request.head, "abc");
9705        assert_eq!(request.pr, pr.url);
9706        assert_eq!(
9707            request.reviews[0].reviews[0].summary,
9708            "precise rejection reason"
9709        );
9710        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9711        assert_eq!(
9712            request.reviews[0].reviews[0].findings[0].detail,
9713            state.reviews[0].reviews[0].findings[0].detail
9714        );
9715        // A repeated consumption of the same answer never dispatches another repair.
9716        state.land_approval = binding;
9717        assert_eq!(
9718            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9719                .await
9720                .unwrap(),
9721            ApprovalGate::Repair
9722        );
9723        assert_eq!(state.merge_repairs.len(), 1);
9724        state.land_approval = None;
9725        state.config.graph.land_approval = false;
9726        state.config.graph.hold_contested_merge = false;
9727        state.reviews.clear();
9728        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9729        assert_eq!(
9730            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9731                .await
9732                .unwrap(),
9733            ApprovalGate::Pending
9734        );
9735        let fresh_id = &state.land_approval.as_ref().unwrap().question;
9736        assert_ne!(fresh_id, &id);
9737        let fresh = store.get(fresh_id).unwrap();
9738        assert!(
9739            fresh
9740                .detail
9741                .contains("fresh owner approval after merge repair")
9742        );
9743        assert!(fresh.detail.contains("No review recorded"));
9744        assert!(!fresh.detail.contains("precise rejection reason"));
9745    }
9746
9747    #[tokio::test]
9748    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9749        for choice in [REPAIR, HOLD] {
9750            let mut state = repair_state(false, true);
9751            let observed = seen("abc", Checks::Green, "CLEAN", false);
9752            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9753                .await
9754                .unwrap();
9755            let id = state.land_approval.as_ref().unwrap().question.clone();
9756            ask::Questions::open()
9757                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9758                .unwrap();
9759            let forge = Scripted::new(vec![observed], vec![(true, "")]);
9760            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9761                .await
9762                .unwrap();
9763            assert!(
9764                forge
9765                    .argvs()
9766                    .iter()
9767                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
9768            );
9769            assert!(!forge.calls().contains(&"fix"));
9770            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
9771            assert_ne!(state.status, RunStatus::Merged);
9772        }
9773    }
9774
9775    #[test]
9776    fn only_the_merge_choice_merges_and_silence_holds() {
9777        let table = [
9778            (None, Approval::Hold),
9779            (Some("merge"), Approval::Merge),
9780            (Some(" merge\n"), Approval::Merge),
9781            (Some("hold"), Approval::Hold),
9782            (Some(""), Approval::Hold),
9783            (Some("yes"), Approval::Hold),
9784        ];
9785        for (answer, want) in table {
9786            assert_eq!(
9787                approval(answer),
9788                want,
9789                "answer {answer:?} must resolve to {want:?}"
9790            );
9791        }
9792    }
9793
9794    #[tokio::test]
9795    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
9796        let mut state = landing_state();
9797        state.config.graph.land_approval = true;
9798        let pr = green_pr();
9799
9800        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9801            .await
9802            .unwrap();
9803        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
9804        assert!(
9805            !state.parked,
9806            "approval_gate itself never sets `parked`; only its caller does"
9807        );
9808
9809        let store = ask::Questions::open();
9810        let filed: Vec<_> = store
9811            .list()
9812            .into_iter()
9813            .filter(|q| q.run == state.id)
9814            .collect();
9815        assert_eq!(filed.len(), 1, "exactly one question is filed");
9816        assert_eq!(filed[0].node, APPROVAL_NODE);
9817        assert_eq!(filed[0].choices, approval_choices(&state));
9818        assert!(filed[0].status.open());
9819
9820        // A second visit - standing in for a resumed run whose slot the
9821        // daemon handed to something else while nobody had answered - must
9822        // find the same question rather than filing a second one.
9823        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9824            .await
9825            .unwrap();
9826        assert_eq!(again, ApprovalGate::Pending);
9827        let still_one = store
9828            .list()
9829            .into_iter()
9830            .filter(|q| q.run == state.id)
9831            .count();
9832        assert_eq!(
9833            still_one, 1,
9834            "asking twice must not double-file the question"
9835        );
9836    }
9837
9838    #[tokio::test]
9839    async fn approving_the_existing_question_is_read_back_as_approved() {
9840        crate::run::pin_test_home();
9841        let mut state = run_state();
9842        state.config.graph.land_approval = true;
9843        let pr = green_pr();
9844        assert_eq!(
9845            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9846                .await
9847                .unwrap(),
9848            ApprovalGate::Pending
9849        );
9850
9851        let store = ask::Questions::open();
9852        let mut q = store
9853            .list()
9854            .into_iter()
9855            .find(|q| q.run == state.id)
9856            .expect("filed above");
9857        let talks = crate::talk::Talks::open();
9858        let cfg = crate::config::Config {
9859            agents: vec![crate::config::AgentSpec {
9860                id: "mock".into(),
9861                kind: crate::config::AgentKind::Command,
9862                model: None,
9863                command: vec!["true".into()],
9864                extra_args: Vec::new(),
9865                env: Default::default(),
9866                prompt_delivery: None,
9867                max_turn_secs: None,
9868            }],
9869            ..crate::config::Config::default()
9870        };
9871        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
9872        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
9873        crate::talk::drain(&mut talk, &talks).unwrap();
9874        assert_eq!(
9875            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9876                .await
9877                .unwrap(),
9878            ApprovalGate::Pending,
9879            "consultation cannot approve or hold the merge"
9880        );
9881        q = store.get(&q.id).unwrap();
9882        assert!(q.answer.is_none());
9883        // The owner's merge answer (from the chat or the card) is the approval.
9884        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9885        store.put(&mut q).unwrap();
9886
9887        assert_eq!(
9888            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9889                .await
9890                .unwrap(),
9891            ApprovalGate::Approved
9892        );
9893    }
9894
9895    #[tokio::test]
9896    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
9897        crate::run::pin_test_home();
9898        let store = ask::Questions::open();
9899        for via_list in [false, true] {
9900            let mut state = repair_state(false, true);
9901            let pr = green_pr();
9902            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9903                .await
9904                .unwrap();
9905            let id = state.land_approval.as_ref().unwrap().question.clone();
9906            store
9907                .update(&id, |q| {
9908                    q.actions.insert(
9909                        HOLD.to_owned(),
9910                        ask::ChoiceAction::Resume {
9911                            run: state.id.clone(),
9912                        },
9913                    );
9914                    Ok(())
9915                })
9916                .unwrap();
9917            let q = if via_list {
9918                store.list().into_iter().find(|q| q.id == id).unwrap()
9919            } else {
9920                store.get(&id).unwrap()
9921            };
9922            assert!(!q.actions.contains_key(HOLD));
9923            store
9924                .update(&id, |q| {
9925                    // Check the persisted migration, without another read upgrade.
9926                    assert!(!q.actions.contains_key(HOLD));
9927                    assert!(!upgrade_repair_choice(q, &state));
9928                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
9929                })
9930                .unwrap();
9931            assert!(store.get(&id).unwrap().chosen_action().is_none());
9932            assert_eq!(
9933                approval_gate(&mut state, &pr, "feat: x", None, "abc")
9934                    .await
9935                    .unwrap(),
9936                ApprovalGate::Held
9937            );
9938        }
9939    }
9940
9941    #[tokio::test]
9942    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
9943        crate::run::pin_test_home();
9944        let store = ask::Questions::open();
9945
9946        let mut held_state = run_state();
9947        held_state.config.graph.land_approval = true;
9948        let pr = green_pr();
9949        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9950            .await
9951            .unwrap();
9952        let mut q = store
9953            .list()
9954            .into_iter()
9955            .find(|q| q.run == held_state.id)
9956            .expect("filed above");
9957        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
9958        store.put(&mut q).unwrap();
9959        assert_eq!(
9960            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9961                .await
9962                .unwrap(),
9963            ApprovalGate::Held
9964        );
9965
9966        let mut abandoned_state = run_state();
9967        abandoned_state.config.graph.land_approval = true;
9968        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9969            .await
9970            .unwrap();
9971        let mut q = store
9972            .list()
9973            .into_iter()
9974            .find(|q| q.run == abandoned_state.id)
9975            .expect("filed above");
9976        q.abandon("no answer within the timeout");
9977        store.put(&mut q).unwrap();
9978        assert_eq!(
9979            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9980                .await
9981                .unwrap(),
9982            ApprovalGate::Pending,
9983            "an expired approval must ask again without merging"
9984        );
9985        assert_eq!(
9986            store.get(&q.id).unwrap().status,
9987            ask::QuestionStatus::Abandoned
9988        );
9989        assert_ne!(
9990            abandoned_state.land_approval.as_ref().unwrap().question,
9991            q.id
9992        );
9993    }
9994
9995    fn contested() -> ContestedHandoff {
9996        let finding = |id: &str, n: u32| crate::verdict::Finding {
9997            id: id.to_owned(),
9998            severity: crate::verdict::Severity::Major,
9999            file: Some("src/a.rs".to_owned()),
10000            line: Some(n),
10001            title: format!("problem {id}"),
10002            detail: String::new(),
10003        };
10004        ContestedHandoff {
10005            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
10006            rejecters: vec![(1, "alpha".to_owned())],
10007        }
10008    }
10009
10010    #[test]
10011    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
10012        let mut state = run_state();
10013        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
10014        state.contested_handoff = Some(contested());
10015        assert!(contested_to_ask(&state).is_some());
10016        state.config.graph.hold_contested_merge = false;
10017        assert!(
10018            contested_to_ask(&state).is_none(),
10019            "the switch restores today"
10020        );
10021    }
10022
10023    #[test]
10024    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
10025        let q = ask::Question::new(
10026            "run-1".to_owned(),
10027            APPROVAL_NODE.to_owned(),
10028            "land".to_owned(),
10029            "Merge?".to_owned(),
10030            String::new(),
10031            vec![APPROVE.to_owned(), HOLD.to_owned()],
10032        );
10033        let none = deputy_brief(&q, None);
10034        assert!(none.contains("could not be read"), "{none}");
10035        assert!(none.contains("Silence is a hold"), "{none}");
10036
10037        let mut state = run_state();
10038        state.pr = Some(crate::run::PrRecord {
10039            url: "https://example.test/pull/7".to_owned(),
10040            number: 7,
10041            state: "open".to_owned(),
10042            checks: "green".to_owned(),
10043            round: 0,
10044            rounds: 3,
10045            red_at_merge: Vec::new(),
10046        });
10047        state.contested_handoff = Some(contested());
10048        let b = deputy_brief(&q, Some(&state));
10049        assert!(b.contains("https://example.test/pull/7"), "{b}");
10050        assert!(b.contains("not recorded in this legacy question"), "{b}");
10051        assert!(!b.contains("This question was filed although"));
10052        state.contested_handoff = None;
10053        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
10054    }
10055
10056    #[test]
10057    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
10058        for lang in ["en", "ja"] {
10059            let mut cfg = crate::config::Config::default();
10060            cfg.graph.language = lang.to_owned();
10061            let w = words(&cfg.graph.language);
10062            let text = w.approval_detail(
10063                "https://github.com/yukimemi/magi/pull/42",
10064                "main",
10065                "feat: x",
10066                Some(&contested()),
10067            );
10068            assert!(text.contains("pull/42"), "{text}");
10069            assert!(
10070                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
10071                "{text}"
10072            );
10073            assert!(text.contains("R3-1-5"), "{text}");
10074            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
10075            assert!(text.contains("2"), "the rest are counted: {text}");
10076            assert!(text.contains("#1 (alpha)"), "{text}");
10077        }
10078        let plain = words("en").approval_detail("u", "main", "s", None);
10079        assert!(!plain.contains("reject"), "{plain}");
10080    }
10081
10082    #[tokio::test]
10083    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
10084        crate::run::pin_test_home();
10085        let mut state = run_state();
10086        state.config.graph.land_approval = false;
10087        state.contested_handoff = Some(contested());
10088        let pr = green_pr();
10089        let c = contested_to_ask(&state);
10090        assert_eq!(
10091            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10092                .await
10093                .unwrap(),
10094            ApprovalGate::Pending,
10095            "silence is a hold"
10096        );
10097        let store = ask::Questions::open();
10098        let filed: Vec<_> = store
10099            .list()
10100            .into_iter()
10101            .filter(|q| q.run == state.id)
10102            .collect();
10103        assert_eq!(filed.len(), 1);
10104        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
10105
10106        assert_eq!(
10107            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10108                .await
10109                .unwrap(),
10110            ApprovalGate::Pending
10111        );
10112        let mut q = store
10113            .list()
10114            .into_iter()
10115            .find(|q| q.run == state.id)
10116            .unwrap();
10117        assert_eq!(q.id, filed[0].id, "the same question after a resume");
10118        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10119        store.put(&mut q).unwrap();
10120        assert_eq!(
10121            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
10122                .await
10123                .unwrap(),
10124            ApprovalGate::Approved
10125        );
10126    }
10127
10128    #[test]
10129    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
10130        let rows = parse_numstat(NUMSTAT);
10131        assert_eq!(
10132            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
10133            ["src/web.rs", "src/land.rs", "assets/logo.png"]
10134        );
10135        assert_eq!(rows[2].added, None, "a binary file has no line counts");
10136    }
10137    #[test]
10138    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
10139        // Reported from a real run: the merge question arrived in English on a
10140        // repository with `language = "ja"`. magi's own strings have to follow
10141        // that setting too - "it is a literal in Rust" is not an answer.
10142        let mut state = run_state();
10143        state.config.graph.language = "ja".to_owned();
10144        let pr = green_pr();
10145        let commits = ["c1".to_owned()];
10146
10147        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10148        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
10149        assert!(ja.contains("squash されるコミット"), "{ja}");
10150        assert!(ja.contains("レビューコメント"), "{ja}");
10151        assert!(ja.contains("差分"), "{ja}");
10152        assert!(
10153            !ja.contains("Commits being squashed"),
10154            "no English left over"
10155        );
10156
10157        let w = words("ja");
10158        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
10159        assert!(
10160            w.approval_detail("http://x/1", "main", "feat: x", None)
10161                .contains("パネル")
10162        );
10163
10164        // The evidence itself is language-neutral and must survive either way.
10165        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
10166        assert!(ja.contains("feat: x"), "nor is the merge subject");
10167
10168        // English stays the default, and a language magi cannot check falls
10169        // back to it rather than shipping a guess.
10170        state.config.graph.language = "en".to_owned();
10171        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
10172        assert!(en.contains("Commits being squashed"), "{en}");
10173        assert_eq!(words("Klingon").html_lang, "en");
10174    }
10175
10176    /// A `gh pr list` result naming exactly one pull request whose base and
10177    /// merge time both fit the run is exactly the case
10178    /// [`find_external_merge`] exists to act on.
10179    #[test]
10180    fn pick_open_pr_classifies_by_count_and_base() {
10181        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
10182        assert_eq!(
10183            pick_open_pr(one, "main").unwrap(),
10184            OpenPr::One {
10185                url: "https://x/pull/58".into(),
10186                title: "t".into()
10187            }
10188        );
10189        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
10190        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
10191        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
10192                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
10193        assert_eq!(
10194            pick_open_pr(two, "main").unwrap(),
10195            OpenPr::Many(vec!["u1".into(), "u2".into()])
10196        );
10197        // A fork's same-named branch is not a pull request for this head.
10198        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
10199        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
10200        assert!(pick_open_pr("not json", "main").is_err());
10201        // An incomplete record is an error, never "nothing open".
10202        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
10203        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
10204    }
10205
10206    #[test]
10207    fn pick_merged_pr_picks_the_unique_match() {
10208        let json = r#"[
10209            {"url": "https://github.com/o/r/pull/42", "number": 42,
10210             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
10211        ]"#;
10212        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10213        let found = pick_merged_pr(json, "main", created_at)
10214            .expect("valid json")
10215            .expect("one unambiguous match");
10216        assert_eq!(found.url, "https://github.com/o/r/pull/42");
10217        assert_eq!(found.number, 42);
10218    }
10219
10220    /// Two candidates surviving the filter is exactly as uninformative as
10221    /// zero — a branch name can be reused across runs — so neither is
10222    /// preferred over the other and nothing is recorded automatically.
10223    #[test]
10224    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
10225        let json = r#"[
10226            {"url": "https://github.com/o/r/pull/42", "number": 42,
10227             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
10228            {"url": "https://github.com/o/r/pull/43", "number": 43,
10229             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
10230        ]"#;
10231        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10232        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10233        let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
10234        assert!(error.to_string().contains("ambiguous"), "{error:#}");
10235    }
10236
10237    /// A pull request that targets a different base branch cannot be this
10238    /// run's, whatever its head branch is named — a reused branch name from
10239    /// an unrelated task must not be recorded as this run's merge.
10240    #[test]
10241    fn pick_merged_pr_ignores_a_different_base_branch() {
10242        let json = r#"[
10243            {"url": "https://github.com/o/r/pull/42", "number": 42,
10244             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
10245        ]"#;
10246        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10247        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10248    }
10249
10250    /// A pull request merged before this run was even created cannot be this
10251    /// run's winner, no matter how its head branch is spelled.
10252    #[test]
10253    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
10254        let json = r#"[
10255            {"url": "https://github.com/o/r/pull/42", "number": 42,
10256             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
10257        ]"#;
10258        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10259        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10260    }
10261
10262    #[test]
10263    fn slug_of_pr_url_reads_host_owner_and_repo() {
10264        assert_eq!(
10265            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
10266            Some("github.com/yukimemi/shun")
10267        );
10268    }
10269
10270    #[test]
10271    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
10272        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
10273        assert_eq!(slug_of_pr_url("not a url at all"), None);
10274        assert_eq!(slug_of_pr_url("https://github.com"), None);
10275    }
10276
10277    #[test]
10278    fn slug_of_repo_url_reads_host_owner_and_repo() {
10279        assert_eq!(
10280            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
10281            Some("github.com/yukimemi/magi")
10282        );
10283        assert_eq!(slug_of_repo_url("https://github.com"), None);
10284    }
10285
10286    #[test]
10287    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
10288        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
10289            .expect("same repo, different case");
10290    }
10291
10292    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
10293    /// own in-progress run and rewrote its status from a pull request in a
10294    /// completely different repository. This is the guard that must catch
10295    /// that even when an explicit (but wrong) id is given.
10296    #[test]
10297    fn ensure_same_repo_refuses_a_different_repo() {
10298        let err =
10299            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
10300        let msg = format!("{err:#}");
10301        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10302        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
10303    }
10304
10305    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
10306    /// instance mirroring a `github.com` repository's name, say) must not be
10307    /// treated as the same repository just because the trailing path
10308    /// matches.
10309    #[test]
10310    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
10311        let err = ensure_same_repo(
10312            "github.com/yukimemi/magi",
10313            "github.example.com/yukimemi/magi",
10314        )
10315        .unwrap_err();
10316        let msg = format!("{err:#}");
10317        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10318        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
10319    }
10320
10321    /// No winner decided yet means there is no branch to ask GitHub about at
10322    /// all — `find_external_merge` must return `None` without ever spawning
10323    /// `gh`, which this proves by never providing a real repository to spawn
10324    /// it in.
10325    #[tokio::test]
10326    async fn find_external_merge_returns_none_without_a_winner() {
10327        let state = RunState::new(
10328            PathBuf::from("/no/such/repo"),
10329            "main".to_owned(),
10330            "0000000000000000000000000000000000000000".to_owned(),
10331            "irrelevant".to_owned(),
10332            crate::config::Config::default(),
10333        );
10334        assert_eq!(find_external_merge(&state).await.unwrap(), None);
10335    }
10336
10337    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
10338        let mut run = RunState::new(
10339            PathBuf::from(repo),
10340            "main".to_owned(),
10341            "abcdef1234".to_owned(),
10342            "x".to_owned(),
10343            crate::config::Config::default(),
10344        );
10345        run.id = id.to_owned();
10346        run.status = status;
10347        run.driver_exited = true;
10348        run.pr = Some(crate::run::PrRecord {
10349            number: url.rsplit('/').next().unwrap().parse().unwrap(),
10350            url: url.to_owned(),
10351            state: state.to_owned(),
10352            checks: "red".to_owned(),
10353            round: 0,
10354            rounds: 2,
10355            red_at_merge: Vec::new(),
10356        });
10357        run.save_under(home).unwrap();
10358    }
10359
10360    fn recorded(home: &Path, id: &str) -> String {
10361        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10362        serde_json::from_str::<RunState>(&body)
10363            .unwrap()
10364            .pr
10365            .unwrap()
10366            .state
10367    }
10368
10369    const PR: &str = "https://github.com/o/r/pull/7";
10370
10371    #[test]
10372    fn write_through_updates_predecessors_and_siblings_only() {
10373        let tmp = tempfile::tempdir().unwrap();
10374        let h = tmp.path();
10375        pr_run(
10376            h,
10377            "20261004-100000-aaaa",
10378            "/repo/r",
10379            RunStatus::Superseded,
10380            PR,
10381            "open",
10382        );
10383        pr_run(
10384            h,
10385            "20261004-100100-bbbb",
10386            "/repo/r",
10387            RunStatus::Blocked,
10388            PR,
10389            "open",
10390        );
10391        // Not terminal: a driver may be writing it.
10392        pr_run(
10393            h,
10394            "20261004-100200-cccc",
10395            "/repo/r",
10396            RunStatus::Landing,
10397            PR,
10398            "open",
10399        );
10400        // Another repository's pull request with the same number.
10401        pr_run(
10402            h,
10403            "20261004-100300-dddd",
10404            "/repo/other",
10405            RunStatus::Blocked,
10406            "https://github.com/o/other/pull/7",
10407            "open",
10408        );
10409        // A different pull request of the same repository.
10410        pr_run(
10411            h,
10412            "20261004-100400-eeee",
10413            "/repo/r",
10414            RunStatus::Blocked,
10415            "https://github.com/o/r/pull/8",
10416            "open",
10417        );
10418        pr_run(
10419            h,
10420            "20261004-100500-ffff",
10421            "/repo/r",
10422            RunStatus::Merged,
10423            PR,
10424            "open",
10425        );
10426        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10427
10428        assert_eq!(
10429            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10430            2
10431        );
10432        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10433        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10434        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10435        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10436        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10437        // The source's own record is the caller's to write.
10438        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10439        // Idempotent.
10440        assert_eq!(
10441            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10442            0
10443        );
10444        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10445        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10446    }
10447
10448    #[test]
10449    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10450        let home = tempfile::tempdir().unwrap();
10451        let live_id = "20261004-100000-aaaa";
10452        let unknown_id = "20261004-100100-bbbb";
10453        for id in [live_id, unknown_id] {
10454            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10455            let mut s = RunState::load_under(id, home.path()).unwrap();
10456            s.driver_exited = false;
10457            // Model legacy driver evidence, not a newly reserved unstarted run.
10458            s.driver_claimed = None;
10459            if id == live_id {
10460                s.driver_pid = Some(std::process::id());
10461                s.driver_started_at = crate::proc::process_started_at(std::process::id());
10462            }
10463            s.save_under(home.path()).unwrap();
10464            if id == unknown_id {
10465                assert_eq!(
10466                    s.liveness_under(home.path(), false),
10467                    crate::run::Liveness::Unknown
10468                );
10469            }
10470        }
10471        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10472        assert_eq!(apply_pr_states(home.path(), &known), 0);
10473        for id in [live_id, unknown_id] {
10474            assert_eq!(recorded(home.path(), id), "open");
10475        }
10476    }
10477
10478    #[test]
10479    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10480        let tmp = tempfile::tempdir().unwrap();
10481        let h = tmp.path();
10482        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10483        pr_run(
10484            h,
10485            "20261004-100000-aaaa",
10486            "/repo/r",
10487            RunStatus::Superseded,
10488            &url(1),
10489            "open",
10490        );
10491        pr_run(
10492            h,
10493            "20261004-100100-bbbb",
10494            "/repo/r",
10495            RunStatus::Blocked,
10496            &url(2),
10497            "open",
10498        );
10499        pr_run(
10500            h,
10501            "20261004-100200-cccc",
10502            "/repo/r",
10503            RunStatus::Ready,
10504            &url(3),
10505            "open",
10506        );
10507        pr_run(
10508            h,
10509            "20261004-100300-dddd",
10510            "/repo/r",
10511            RunStatus::Ready,
10512            &url(4),
10513            "open",
10514        );
10515        pr_run(
10516            h,
10517            "20261004-100400-eeee",
10518            "/repo/r",
10519            RunStatus::Implementing,
10520            &url(1),
10521            "open",
10522        );
10523        assert_eq!(stale_open_prs(h).len(), 4);
10524
10525        let mut known = BTreeMap::new();
10526        known.insert(url(1), PrLifecycle::Merged);
10527        known.insert(url(2), PrLifecycle::Closed);
10528        known.insert(url(3), PrLifecycle::Open);
10529        // #4: the forge could not be read, so it has no answer.
10530        assert_eq!(apply_pr_states(h, &known), 2);
10531        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10532        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10533        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10534        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10535        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10536        assert_eq!(apply_pr_states(h, &known), 0);
10537    }
10538
10539    // --- the land loop against a scripted forge -------------------------
10540
10541    use std::collections::VecDeque;
10542    use std::sync::Mutex;
10543
10544    /// Answers views from a script (the last one repeats), merges from a
10545    /// queue, and records every call so a test can assert the order.
10546    struct Scripted {
10547        public_repo: Option<PathBuf>,
10548        evidence: Mutex<Option<CiEvidence>>,
10549        views: Mutex<VecDeque<Seen>>,
10550        merges: Mutex<VecDeque<(bool, String)>>,
10551        fix: Mutex<Option<Fixed>>,
10552        log: Mutex<Vec<&'static str>>,
10553        argvs: Mutex<Vec<Vec<String>>>,
10554        required: Mutex<Option<BTreeSet<String>>>,
10555        /// Set once a merge answered ok: the forge then reports `merged`,
10556        /// unless `queued` says the merge only entered a queue.
10557        merged: Mutex<bool>,
10558        queued: Mutex<bool>,
10559        /// Views fail once a merge answered ok.
10560        unreadable_after_merge: Mutex<bool>,
10561        /// Workflow runs asked to rerun, and whether that call fails.
10562        reruns: Mutex<Vec<String>>,
10563        rerun_fails: Mutex<bool>,
10564        /// Unix seconds; every poll moves it on by `POLL`.
10565        clock: Mutex<i64>,
10566    }
10567
10568    impl Scripted {
10569        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10570            Self {
10571                public_repo: None,
10572                evidence: Mutex::new(None),
10573                views: Mutex::new(views.into()),
10574                merges: Mutex::new(
10575                    merges
10576                        .into_iter()
10577                        .map(|(ok, m)| (ok, m.to_owned()))
10578                        .collect(),
10579                ),
10580                fix: Mutex::new(None),
10581                log: Mutex::new(Vec::new()),
10582                argvs: Mutex::new(Vec::new()),
10583                required: Mutex::new(None),
10584                merged: Mutex::new(false),
10585                queued: Mutex::new(false),
10586                unreadable_after_merge: Mutex::new(false),
10587                reruns: Mutex::new(Vec::new()),
10588                rerun_fails: Mutex::new(false),
10589                clock: Mutex::new(1_000),
10590            }
10591        }
10592        fn argvs(&self) -> Vec<Vec<String>> {
10593            self.argvs.lock().unwrap().clone()
10594        }
10595        fn calls(&self) -> Vec<&'static str> {
10596            self.log.lock().unwrap().clone()
10597        }
10598    }
10599
10600    impl Forge for Scripted {
10601        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10602            self.evidence.lock().unwrap().clone()
10603        }
10604        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10605            self.log.lock().unwrap().push("view");
10606            if *self.unreadable_after_merge.lock().unwrap()
10607                && !self.argvs.lock().unwrap().is_empty()
10608            {
10609                anyhow::bail!("forge unreachable");
10610            }
10611            let mut seen = {
10612                let mut v = self.views.lock().unwrap();
10613                if v.len() > 1 {
10614                    v.pop_front().unwrap()
10615                } else {
10616                    v[0].clone()
10617                }
10618            };
10619            if seen.head == "@published" {
10620                let head =
10621                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10622                        .await?
10623                        .context("missing published head")?;
10624                seen.head.clone_from(&head);
10625                seen.rollup_head = head;
10626            }
10627            if *self.merged.lock().unwrap() {
10628                seen.pr.state = PrLifecycle::Merged;
10629            }
10630            Ok(seen)
10631        }
10632        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10633            self.log.lock().unwrap().push("merge");
10634            self.argvs.lock().unwrap().push(argv.to_vec());
10635            let out = self
10636                .merges
10637                .lock()
10638                .unwrap()
10639                .pop_front()
10640                .expect("unscripted merge");
10641            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10642            {
10643                *self.merged.lock().unwrap() = true;
10644            }
10645            Ok(out)
10646        }
10647        async fn poll(&self) {
10648            self.log.lock().unwrap().push("poll");
10649            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10650        }
10651        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10652            self.log.lock().unwrap().push("rerun");
10653            self.reruns.lock().unwrap().push(run.to_owned());
10654            if *self.rerun_fails.lock().unwrap() {
10655                anyhow::bail!("gh run rerun: no");
10656            }
10657            Ok(())
10658        }
10659        fn now(&self) -> i64 {
10660            *self.clock.lock().unwrap()
10661        }
10662        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10663            self.required.lock().unwrap().clone()
10664        }
10665        async fn fix(
10666            &self,
10667            _state: &mut RunState,
10668            _pr: &PrState,
10669            _round: usize,
10670            _budget: usize,
10671            _reason: &str,
10672            _logs: &str,
10673        ) -> Result<Fixed> {
10674            self.log.lock().unwrap().push("fix");
10675            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10676        }
10677    }
10678
10679    const REFUSED: &str =
10680        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10681
10682    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10683        let mut pr = green_pr();
10684        pr.checks = checks;
10685        pr.blocking = Blocking::of(merge_state);
10686        if !comments {
10687            pr.review_comments.clear();
10688        }
10689        Seen {
10690            pr,
10691            title: "feat: x".to_owned(),
10692            failing_urls: Vec::new(),
10693            head: head.to_owned(),
10694            rollup_head: head.to_owned(),
10695            merge_state: merge_state.to_owned(),
10696            contexts: Vec::new(),
10697            base: "main".to_owned(),
10698        }
10699    }
10700
10701    fn landing_state() -> RunState {
10702        crate::run::pin_test_home();
10703        let mut state = run_state();
10704        state.config.graph.land_approval = false;
10705        state
10706    }
10707
10708    #[test]
10709    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10710        assert!(!awaiting_new_head(None, "aaa"));
10711        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10712        assert!(awaiting_new_head(Some("abc123"), "def456"));
10713        assert!(awaiting_new_head(Some("abc123"), ""));
10714    }
10715
10716    #[test]
10717    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10718        let open = |c, m: &str| seen("a", c, m, false);
10719        let table = [
10720            (None, false, Refused::Pending),
10721            (
10722                Some(open(Checks::Pending, "BLOCKED")),
10723                false,
10724                Refused::Pending,
10725            ),
10726            (
10727                Some(open(Checks::Unknown, "BLOCKED")),
10728                false,
10729                Refused::Pending,
10730            ),
10731            (
10732                Some(open(Checks::Green, "UNKNOWN")),
10733                false,
10734                Refused::Pending,
10735            ),
10736            (Some(open(Checks::Green, "")), false, Refused::Pending),
10737            (
10738                Some(open(Checks::Green, "BLOCKED")),
10739                false,
10740                Refused::Recheck,
10741            ),
10742            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10743        ];
10744        for (after, rechecked, want) in table {
10745            assert_eq!(
10746                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10747                want
10748            );
10749        }
10750        let mut closed = open(Checks::Green, "CLEAN");
10751        closed.pr.state = PrLifecycle::Closed;
10752        assert_eq!(
10753            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10754            Refused::Final
10755        );
10756    }
10757
10758    #[test]
10759    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10760        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10761            let pr = seen("a", checks, "BEHIND", false).pr;
10762            assert_eq!(
10763                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10764                Step::Rebase
10765            );
10766        }
10767        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
10768            let current = seen("a", Checks::Green, status, false);
10769            assert_ne!(
10770                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10771                Step::Rebase
10772            );
10773            assert_ne!(
10774                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
10775                Refused::Behind
10776            );
10777        }
10778        let mut current = seen("a", Checks::Pending, "BEHIND", false);
10779        current.rollup_head = "old".into();
10780        assert_eq!(
10781            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10782            Refused::Behind
10783        );
10784        assert_eq!(
10785            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
10786            Refused::Pending
10787        );
10788        current.pr.state = PrLifecycle::Closed;
10789        assert_eq!(
10790            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10791            Refused::Final
10792        );
10793    }
10794
10795    #[tokio::test]
10796    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
10797        for boundary in ["initial", "premerge", "refusal"] {
10798            let (_tmp, mut state, old) = landing_git_fixture().await;
10799            state.land_sync_pending = false;
10800            advance_landing_base(&state).await;
10801            state.config.verify.gate = vec!["test -f advance".into()];
10802            state.config.verify.e2e = vec!["test -f advance".into()];
10803            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
10804                .await
10805                .unwrap();
10806            let old_binding = state.land_approval.clone().unwrap();
10807            let store = ask::Questions::open();
10808            let mut question = store.get(&old_binding.question).unwrap();
10809            question
10810                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10811                .unwrap();
10812            store.put(&mut question).unwrap();
10813            let mut views = Vec::new();
10814            if boundary != "initial" {
10815                views.push(seen(&old, Checks::Green, "CLEAN", false));
10816            }
10817            if boundary == "refusal" {
10818                views.push(seen(&old, Checks::Green, "CLEAN", false));
10819            }
10820            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
10821            behind.rollup_head = "old-ci-head".into();
10822            views.push(behind);
10823            // Publication checks the PR lease while verification has completed.
10824            views.push(seen(&old, Checks::Green, "CLEAN", false));
10825            views.push(seen("@published", Checks::Pending, "CLEAN", false));
10826            views.push(seen("@published", Checks::Green, "CLEAN", false));
10827            let merges = if boundary == "refusal" {
10828                vec![(false, REFUSED)]
10829            } else {
10830                vec![]
10831            };
10832            let mut forge = Scripted::new(views, merges);
10833            forge.public_repo = Some(state.repo.clone());
10834            let run = state.id.clone();
10835            land_with(&mut state, URL, &forge).await.unwrap();
10836            let head = state.pr_pushed_head.clone().unwrap();
10837            assert_ne!(head, old, "{boundary}");
10838            assert_eq!(state.id, run);
10839            assert_eq!(state.pr_branch(), Some("task-head"));
10840            assert_eq!(state.winner().unwrap().branch, "winner");
10841            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
10842            assert!(state.gate_allows_progress());
10843            let e2e = state.head_e2e.as_ref().unwrap();
10844            assert_eq!(e2e.head, head);
10845            assert!(e2e.passed);
10846            assert_eq!(state.land_sync_attempts, 1);
10847            assert!(!state.land_sync_pending);
10848            assert!(state.parked);
10849            let binding = state.land_approval.as_ref().unwrap();
10850            assert_eq!(binding.head, head);
10851            assert_ne!(binding.question, old_binding.question);
10852            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
10853            // The new question authorizes only the synchronized head on resume.
10854            let mut question = store.get(&binding.question).unwrap();
10855            question
10856                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10857                .unwrap();
10858            store.put(&mut question).unwrap();
10859            let forge = Scripted::new(
10860                vec![seen(&head, Checks::Green, "CLEAN", false)],
10861                vec![(true, "")],
10862            );
10863            land_with(&mut state, URL, &forge).await.unwrap();
10864            assert_eq!(state.status, RunStatus::Merged);
10865            assert_eq!(
10866                value_of(&forge.argvs()[0], "--match-head-commit"),
10867                Some(head.as_str())
10868            );
10869        }
10870    }
10871
10872    #[tokio::test]
10873    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
10874        let (_tmp, mut state, old) = landing_git_fixture().await;
10875        state.land_sync_pending = false;
10876        state.config.graph.land_approval = false;
10877        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
10878        advance_landing_base(&state).await;
10879        let mut forge = Scripted::new(
10880            vec![
10881                seen(&old, Checks::Green, "CLEAN", false),
10882                seen(&old, Checks::Green, "CLEAN", false),
10883                seen(&old, Checks::Green, "BEHIND", false),
10884                // The next observation is the publication lease check. The
10885                // refusal's evidence still applies to exactly this old head.
10886                seen(&old, Checks::Green, "CLEAN", false),
10887                seen("@published", Checks::Green, "CLEAN", false),
10888            ],
10889            vec![(false, REFUSED), (true, "")],
10890        );
10891        forge.public_repo = Some(state.repo.clone());
10892        land_with(&mut state, URL, &forge).await.unwrap();
10893        let head = state.pr_pushed_head.as_deref().unwrap();
10894        assert_ne!(head, old);
10895        assert_eq!(state.land_sync_attempts, 1);
10896        assert_eq!(state.gate_head.as_deref(), Some(head));
10897        assert_eq!(state.status, RunStatus::Merged);
10898        let requests = forge.argvs();
10899        assert_eq!(requests.len(), 2);
10900        assert_eq!(
10901            value_of(&requests[0], "--match-head-commit"),
10902            Some(old.as_str())
10903        );
10904        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
10905    }
10906
10907    #[tokio::test]
10908    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
10909        let (tmp, mut state, old) = landing_git_fixture().await;
10910        state.land_sync_pending = false;
10911        // A damaged history must not be interpreted as a missing base. Keep
10912        // the head's tree intact so worktree restoration itself can succeed.
10913        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
10914        let commit = tmp.path().join("broken-commit");
10915        std::fs::write(
10916            &commit,
10917            format!(
10918                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
10919                "f".repeat(40)
10920            ),
10921        )
10922        .unwrap();
10923        let replacement = git::git(
10924            &state.repo,
10925            &[
10926                "hash-object",
10927                "-t",
10928                "commit",
10929                "-w",
10930                commit.to_str().unwrap(),
10931            ],
10932        )
10933        .await
10934        .unwrap();
10935        git::git(&state.repo, &["replace", &old, replacement.trim()])
10936            .await
10937            .unwrap();
10938        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10939        land_with(&mut state, URL, &forge).await.unwrap();
10940        assert_eq!(state.land_sync_attempts, 0);
10941        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10942        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10943        assert!(forge.argvs().is_empty());
10944        assert!(
10945            state.events.iter().any(|e| e.message.contains(
10946                "could not determine whether the landing head contains the fetched base"
10947            ))
10948        );
10949    }
10950
10951    #[tokio::test]
10952    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
10953        let (_tmp, mut state, old) = landing_git_fixture().await;
10954        state.land_sync_pending = false;
10955        git::git(
10956            &state.repo,
10957            &["remote", "set-url", "origin", "missing-remote"],
10958        )
10959        .await
10960        .unwrap();
10961        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10962        land_with(&mut state, URL, &forge).await.unwrap();
10963        assert_eq!(state.land_sync_attempts, 0);
10964        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10965        assert!(
10966            state
10967                .events
10968                .iter()
10969                .any(|e| e.message.contains("cannot fetch landing base"))
10970        );
10971        assert!(forge.argvs().is_empty());
10972    }
10973
10974    #[tokio::test]
10975    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
10976        let (_tmp, mut state, old) = landing_git_fixture().await;
10977        state.land_sync_pending = false;
10978        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10979        land_with(&mut state, URL, &forge).await.unwrap();
10980        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10981        assert_eq!(state.land_sync_attempts, 0);
10982        assert!(
10983            state
10984                .events
10985                .iter()
10986                .any(|e| e.message.contains("already included"))
10987        );
10988        advance_landing_base(&state).await;
10989        state.land_sync_attempts = state.config.graph.land_rounds;
10990        state.land_sync_pending = true;
10991        state.save().unwrap();
10992        let mut restored = RunState::load(&state.id).unwrap();
10993        assert!(
10994            resume_observed_head(&mut restored, &old)
10995                .await
10996                .unwrap_err()
10997                .to_string()
10998                .contains("budget exhausted")
10999        );
11000        assert_eq!(
11001            git::remote_head(&state.repo, "origin", "task-head")
11002                .await
11003                .unwrap(),
11004            Some(old)
11005        );
11006    }
11007
11008    #[tokio::test]
11009    async fn a_normal_landing_merges_on_the_first_look() {
11010        let mut state = landing_state();
11011        let forge = Scripted::new(
11012            vec![seen("a", Checks::Green, "CLEAN", false)],
11013            vec![(true, "")],
11014        );
11015        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11016            .await
11017            .unwrap();
11018        // One fresh read, then the head-bound merge.
11019        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11020        assert_eq!(state.status, RunStatus::Merged);
11021    }
11022
11023    #[tokio::test]
11024    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
11025        let mut state = landing_state();
11026        let forge = Scripted::new(
11027            vec![seen("a", Checks::Green, "CLEAN", false)],
11028            std::iter::repeat_n((true, ""), 100).collect(),
11029        );
11030        *forge.queued.lock().unwrap() = true;
11031        let task = async {
11032            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11033                .await
11034                .unwrap();
11035        };
11036        // Still open after the command succeeded: it keeps watching and
11037        // never records a merge (it stops at the wait ceiling instead).
11038        task.await;
11039        assert_ne!(state.status, RunStatus::Merged);
11040    }
11041
11042    #[tokio::test]
11043    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
11044        let mut state = landing_state();
11045        let forge = Scripted::new(
11046            vec![seen("a", Checks::Green, "CLEAN", false)],
11047            std::iter::repeat_n((true, ""), 100).collect(),
11048        );
11049        *forge.unreadable_after_merge.lock().unwrap() = true;
11050        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11051            .await
11052            .ok();
11053        assert_ne!(state.status, RunStatus::Merged);
11054    }
11055
11056    #[tokio::test]
11057    async fn a_task_public_head_is_awaited_on_land_entry() {
11058        let mut state = landing_state();
11059        state.pr_head = Some("magi/task-abcd-1234".into());
11060        state.pr_pushed_head = Some("new".into());
11061        let forge = Scripted::new(
11062            vec![
11063                seen("old", Checks::Green, "CLEAN", false),
11064                seen("new", Checks::Green, "CLEAN", false),
11065            ],
11066            vec![(true, "")],
11067        );
11068        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11069            .await
11070            .unwrap();
11071        assert_eq!(
11072            forge.calls(),
11073            ["view", "poll", "view", "view", "merge", "view"]
11074        );
11075        assert_eq!(state.status, RunStatus::Merged);
11076    }
11077
11078    #[tokio::test]
11079    async fn a_superseded_public_head_owner_cannot_reenter_land() {
11080        let mut state = landing_state();
11081        state.pr_taken_over_by = Some("next".into());
11082        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
11083        assert!(
11084            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11085                .await
11086                .is_err()
11087        );
11088        assert!(forge.calls().is_empty());
11089    }
11090
11091    #[tokio::test]
11092    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
11093        let mut state = landing_state();
11094        let forge = Scripted::new(
11095            vec![
11096                seen("old", Checks::Green, "CLEAN", true),
11097                // The forge has not moved to the new head yet: still green.
11098                seen("old", Checks::Green, "CLEAN", true),
11099                seen("new", Checks::Pending, "BLOCKED", true),
11100                seen("new", Checks::Green, "CLEAN", true),
11101            ],
11102            vec![(true, "")],
11103        );
11104        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11105            head: "NEW".to_owned(),
11106        });
11107        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11108            .await
11109            .unwrap();
11110        assert_eq!(
11111            forge.calls(),
11112            [
11113                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
11114                "view"
11115            ]
11116        );
11117        assert_eq!(state.status, RunStatus::Merged);
11118    }
11119
11120    #[tokio::test]
11121    async fn a_head_that_never_arrives_stops_naming_both_commits() {
11122        let mut state = landing_state();
11123        let forge = Scripted::new(
11124            vec![
11125                seen("old", Checks::Green, "CLEAN", true),
11126                seen("someone-elses", Checks::Green, "CLEAN", true),
11127            ],
11128            vec![],
11129        );
11130        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11131            head: "mine".to_owned(),
11132        });
11133        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11134            .await
11135            .unwrap();
11136        assert!(!forge.calls().contains(&"merge"));
11137        let why = state.merge.as_ref().unwrap().detail.clone();
11138        assert!(
11139            why.contains("mine") && why.contains("someone-elses"),
11140            "{why}"
11141        );
11142        assert_eq!(state.status, RunStatus::Blocked);
11143    }
11144
11145    #[tokio::test]
11146    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
11147        let mut state = landing_state();
11148        let forge = Scripted::new(
11149            vec![
11150                seen("a", Checks::Green, "CLEAN", false),
11151                seen("a", Checks::Green, "CLEAN", false),
11152                seen("a", Checks::Pending, "BLOCKED", false),
11153                seen("a", Checks::Pending, "BLOCKED", false),
11154                seen("a", Checks::Green, "CLEAN", false),
11155            ],
11156            vec![(false, REFUSED), (true, "")],
11157        );
11158        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11159            .await
11160            .unwrap();
11161        assert_eq!(
11162            forge.calls(),
11163            [
11164                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
11165                "view"
11166            ]
11167        );
11168        assert_eq!(state.status, RunStatus::Merged);
11169    }
11170
11171    #[tokio::test]
11172    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
11173        let mut state = landing_state();
11174        let forge = Scripted::new(
11175            vec![
11176                seen("a", Checks::Green, "CLEAN", false),
11177                seen("a", Checks::Green, "BLOCKED", false),
11178            ],
11179            vec![(false, REFUSED), (false, REFUSED)],
11180        );
11181        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11182            .await
11183            .unwrap();
11184        // One re-look is allowed for the forge's own lag, then it is final.
11185        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
11186        let why = state.merge.as_ref().unwrap().detail.clone();
11187        assert!(
11188            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
11189            "{why}"
11190        );
11191        assert_eq!(state.status, RunStatus::Blocked);
11192    }
11193
11194    #[test]
11195    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
11196        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
11197        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
11198        // The pull request is still on the commit before the push.
11199        assert_eq!(bound_head("old", "old", Some("new")), None);
11200        // The checks are the previous commit's.
11201        assert_eq!(bound_head("new", "old", Some("new")), None);
11202        assert_eq!(bound_head("new", "old", None), None);
11203        // Nothing readable.
11204        assert_eq!(bound_head("", "", None), None);
11205        assert_eq!(bound_head("", "", Some("new")), None);
11206        assert_eq!(bound_head("abc", "", None), None);
11207    }
11208
11209    fn view_json(head: &str) -> String {
11210        format!(
11211            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
11212            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
11213            "reviews":[],"comments":[]}}"#
11214        )
11215    }
11216
11217    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
11218        format!(
11219            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
11220            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
11221            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
11222            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
11223        )
11224    }
11225
11226    #[test]
11227    fn rollup_is_bound_to_the_commit_in_the_same_node() {
11228        // The view already points at the new head, but the node still answers
11229        // for the old commit with its red check: the head stays unbound.
11230        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
11231        assert_eq!(s.rollup_head, "old");
11232        assert_eq!(s.pr.checks, Checks::Red);
11233        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
11234        assert_eq!(s.failing_urls.len(), 1);
11235    }
11236
11237    #[test]
11238    fn checks_come_from_the_node_not_the_view() {
11239        let view = view_json("new").replace(
11240            r#""reviews""#,
11241            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
11242        );
11243        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
11244        assert_eq!(s.pr.checks, Checks::Green);
11245        assert!(s.pr.failing.is_empty());
11246        assert_eq!(
11247            bound_head(&s.head, &s.rollup_head, Some("new")),
11248            Some("new")
11249        );
11250    }
11251
11252    #[test]
11253    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
11254        for node in [
11255            None,
11256            Some("not json".to_owned()),
11257            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
11258            Some(node_json("new", "SUCCESS", true)),
11259        ] {
11260            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
11261            assert!(s.rollup_head.is_empty());
11262            assert_eq!(s.pr.checks, Checks::Unknown);
11263            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
11264        }
11265    }
11266
11267    #[test]
11268    fn the_merge_command_is_pinned_to_the_observed_head() {
11269        let argv = merge_argv_at(7, "feat: x", "deadbeef");
11270        let at = argv
11271            .iter()
11272            .position(|a| a == "--match-head-commit")
11273            .unwrap();
11274        assert_eq!(argv[at + 1], "deadbeef");
11275    }
11276
11277    #[tokio::test]
11278    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
11279        let mut state = landing_state();
11280        // The pull request is on the pushed head but the rollup is still the
11281        // previous commit's red, non-required result.
11282        let mut stale = seen("new", Checks::Red, "CLEAN", false);
11283        stale.rollup_head = "old".to_owned();
11284        let forge = Scripted::new(
11285            vec![seen("old", Checks::Green, "CLEAN", true), stale],
11286            vec![],
11287        );
11288        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11289            head: "new".to_owned(),
11290        });
11291        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11292            .await
11293            .unwrap();
11294        assert!(!forge.calls().contains(&"merge"));
11295        assert_eq!(state.status, RunStatus::Blocked);
11296        let why = state.merge.as_ref().unwrap().detail.clone();
11297        assert!(why.contains("new") && why.contains("old"), "{why}");
11298    }
11299
11300    #[test]
11301    fn a_refusal_read_against_another_commits_checks_is_pending() {
11302        let mut after = seen("a", Checks::Green, "BLOCKED", false);
11303        after.rollup_head = "old".to_owned();
11304        assert_eq!(
11305            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
11306            Refused::Pending
11307        );
11308    }
11309
11310    #[tokio::test]
11311    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
11312        let mut state = landing_state();
11313        state.config.merge.ci = crate::config::MergeCi::None;
11314        state.config.graph.land_approval = true;
11315        let forge = Scripted::new(
11316            vec![seen("a", Checks::Unknown, "CLEAN", false)],
11317            vec![(true, "")],
11318        );
11319        land_with(&mut state, URL, &forge).await.unwrap();
11320        assert!(state.parked);
11321        assert_eq!(forge.calls(), ["view"]);
11322        let store = ask::Questions::open();
11323        let mut q = store
11324            .get(&state.land_approval.as_ref().unwrap().question)
11325            .unwrap();
11326        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11327        store.put(&mut q).unwrap();
11328
11329        land_with(&mut state, URL, &forge).await.unwrap();
11330        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
11331        assert_eq!(state.status, RunStatus::Merged);
11332        assert_eq!(
11333            value_of(&forge.argvs()[0], "--match-head-commit"),
11334            Some("a")
11335        );
11336    }
11337
11338    #[tokio::test]
11339    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
11340        let mut state = landing_state();
11341        state.config.merge.ci = crate::config::MergeCi::None;
11342        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
11343        land_with(&mut state, URL, &forge).await.unwrap();
11344        assert!(forge.reruns.lock().unwrap().is_empty());
11345        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11346        assert_eq!(state.status, RunStatus::Merged);
11347    }
11348
11349    #[test]
11350    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
11351        let shown = BTreeSet::new();
11352        let guard = |s: Option<&Seen>| {
11353            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11354        };
11355        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11356        assert!(guard(Some(&fresh)));
11357        assert!(!guard(None));
11358        fresh.rollup_head = "old".to_owned();
11359        assert!(!guard(Some(&fresh)));
11360        fresh.rollup_head = "a".to_owned();
11361        fresh.head = "b".to_owned();
11362        assert!(!guard(Some(&fresh)));
11363        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11364        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11365    }
11366
11367    #[test]
11368    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11369        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11370            let after = seen("a", checks, "BLOCKED", false);
11371            assert_eq!(
11372                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11373                Refused::Recheck
11374            );
11375            assert_eq!(
11376                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11377                Refused::Final
11378            );
11379        }
11380    }
11381
11382    #[tokio::test]
11383    async fn a_matching_head_with_red_non_required_checks_still_merges() {
11384        let mut state = landing_state();
11385        let forge = Scripted::new(
11386            vec![seen("a", Checks::Red, "CLEAN", false)],
11387            vec![(true, "")],
11388        );
11389        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11390            .await
11391            .unwrap();
11392        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11393        assert_eq!(state.status, RunStatus::Merged);
11394    }
11395
11396    #[tokio::test]
11397    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11398        let mut state = landing_state();
11399        let forge = Scripted::new(
11400            vec![
11401                seen("a", Checks::Green, "CLEAN", false),
11402                seen("a", Checks::Green, "CLEAN", false),
11403                // Re-viewed after the refusal: someone pushed.
11404                seen("b", Checks::Green, "BLOCKED", false),
11405                seen("b", Checks::Green, "CLEAN", false),
11406            ],
11407            vec![(false, REFUSED), (true, "")],
11408        );
11409        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11410            .await
11411            .unwrap();
11412        assert_eq!(
11413            forge.calls(),
11414            [
11415                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
11416            ]
11417        );
11418        assert_eq!(state.status, RunStatus::Merged);
11419    }
11420
11421    fn merged_view(head: &str) -> Seen {
11422        let mut m = seen(head, Checks::Green, "CLEAN", false);
11423        m.pr.state = PrLifecycle::Merged;
11424        m
11425    }
11426
11427    fn has(argv: &[String], flag: &str) -> bool {
11428        argv.iter().any(|a| a == flag)
11429    }
11430
11431    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11432        let at = argv.iter().position(|a| a == flag)?;
11433        argv.get(at + 1).map(String::as_str)
11434    }
11435
11436    const URL: &str = "https://github.com/o/r/pull/42";
11437
11438    #[tokio::test]
11439    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11440        let mut state = landing_state();
11441        let forge = Scripted::new(
11442            vec![
11443                seen("abc", Checks::Green, "CLEAN", false),
11444                seen("abc", Checks::Green, "CLEAN", false),
11445            ],
11446            vec![(true, "")],
11447        );
11448        land_with(&mut state, URL, &forge).await.unwrap();
11449        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11450        let argv = &forge.argvs()[0];
11451        assert!(has(argv, "--squash") && has(argv, "--subject"));
11452        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11453        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11454        assert_eq!(state.status, RunStatus::Merged);
11455        assert!(state.land_armed_head.is_none());
11456    }
11457
11458    #[tokio::test]
11459    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11460        let mut state = landing_state();
11461        state.land_armed_head = Some("a".to_owned());
11462        let forge = Scripted::new(
11463            vec![seen("a", Checks::Green, "CLEAN", false)],
11464            vec![(true, ""), (true, "")],
11465        );
11466        land_with(&mut state, URL, &forge).await.unwrap();
11467        let argvs = forge.argvs();
11468        assert!(has(&argvs[0], "--disable-auto"));
11469        assert!(!has(&argvs[1], "--auto"));
11470        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11471        assert_eq!(state.status, RunStatus::Merged);
11472        assert!(state.land_armed_head.is_none());
11473    }
11474
11475    #[tokio::test]
11476    async fn an_approval_never_carries_over_to_a_new_head() {
11477        crate::run::pin_test_home();
11478        let mut state = run_state();
11479        state.config.graph.land_approval = true;
11480        let pr = green_pr();
11481        let store = ask::Questions::open();
11482
11483        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11484            .await
11485            .unwrap();
11486        let mut q = store
11487            .list()
11488            .into_iter()
11489            .find(|q| q.run == state.id)
11490            .unwrap();
11491        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11492        store.put(&mut q).unwrap();
11493        assert_eq!(
11494            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
11495                .await
11496                .unwrap(),
11497            ApprovalGate::Approved,
11498            "the same head keeps its approval"
11499        );
11500
11501        // A new head is a new question, not the old word.
11502        assert_eq!(
11503            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11504                .await
11505                .unwrap(),
11506            ApprovalGate::Pending
11507        );
11508        let all: Vec<_> = store
11509            .list()
11510            .into_iter()
11511            .filter(|q| q.run == state.id)
11512            .collect();
11513        assert_eq!(all.len(), 2);
11514
11515        // A question recorded before heads were tracked is not reused either.
11516        state.land_approval = None;
11517        assert_eq!(
11518            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11519                .await
11520                .unwrap(),
11521            ApprovalGate::Pending
11522        );
11523        let open = store
11524            .list()
11525            .into_iter()
11526            .filter(|q| q.run == state.id && q.status.open())
11527            .count();
11528        assert_eq!(open, 1, "the superseded question was retired");
11529    }
11530
11531    #[tokio::test]
11532    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11533        let mut state = landing_state();
11534        let forge = Scripted::new(
11535            vec![
11536                seen("a", Checks::Green, "CLEAN", false),
11537                // The fresh read before the merge: someone pushed.
11538                seen("b", Checks::Green, "CLEAN", false),
11539            ],
11540            vec![(true, "")],
11541        );
11542        land_with(&mut state, URL, &forge).await.unwrap();
11543        let argvs = forge.argvs();
11544        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11545        assert!(!has(&argvs[0], "--auto"));
11546        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11547        assert_eq!(state.status, RunStatus::Merged);
11548    }
11549
11550    fn passing(label: &str) -> CheckInfo {
11551        CheckInfo {
11552            label: label.to_owned(),
11553            verdict: Verdict::Pass,
11554            required: Some(false),
11555            run: None,
11556        }
11557    }
11558
11559    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11560        (label.to_owned(), run.map(str::to_owned))
11561    }
11562
11563    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11564        LandReruns {
11565            head: head.to_owned(),
11566            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11567        }
11568    }
11569
11570    #[test]
11571    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11572        let f = [failing("test (macos)", Some("7"))];
11573        assert_eq!(
11574            rerun_step(&f, None, "h", 100),
11575            RerunStep::Rerun(vec!["7".to_owned()])
11576        );
11577        let rec = reran("h", &[("7", 100)]);
11578        let grace = crate::release_watch::RERUN_GRACE;
11579        assert_eq!(
11580            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11581            RerunStep::Grace
11582        );
11583        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11584    }
11585
11586    #[test]
11587    fn a_failure_without_a_run_id_goes_to_the_fixer() {
11588        let f = [failing("a", Some("7")), failing("ci/external", None)];
11589        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11590        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11591    }
11592
11593    #[test]
11594    fn a_moved_head_forgets_the_reruns() {
11595        let f = [failing("a", Some("7"))];
11596        let rec = reran("old", &[("7", 100)]);
11597        assert_eq!(
11598            rerun_step(&f, Some(&rec), "new", 101),
11599            RerunStep::Rerun(vec!["7".to_owned()])
11600        );
11601    }
11602
11603    #[test]
11604    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11605        let f = [
11606            failing("a", Some("7")),
11607            failing("b", Some("7")),
11608            failing("c", Some("8")),
11609        ];
11610        assert_eq!(
11611            rerun_step(&f, None, "h", 0),
11612            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11613        );
11614        let rec = reran("h", &[("7", 0)]);
11615        assert_eq!(
11616            rerun_step(&f, Some(&rec), "h", 1),
11617            RerunStep::Rerun(vec!["8".to_owned()])
11618        );
11619    }
11620
11621    #[test]
11622    fn only_blocking_failures_are_candidates_for_a_rerun() {
11623        let check = |label: &str, verdict, required, run: &str| CheckInfo {
11624            label: label.to_owned(),
11625            verdict,
11626            required,
11627            run: Some(run.to_owned()),
11628        };
11629        let got = rerunnable(&[
11630            check("passed", Verdict::Pass, Some(true), "1"),
11631            check("optional", Verdict::Fail, Some(false), "2"),
11632            check("required", Verdict::Fail, Some(true), "3"),
11633            check("unknown", Verdict::Fail, None, "4"),
11634        ]);
11635        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11636        assert_eq!(labels, ["required", "unknown"]);
11637    }
11638
11639    fn unrelated_ci_fixture() -> CiEvidence {
11640        let failure = CiFailure {
11641            path: "tests/web_render.rs".into(),
11642            start_line: 42,
11643            end_line: 42,
11644            title: "question_identity_disclosure_copy_and_live_updates".into(),
11645            message: "assertion failed".into(),
11646        };
11647        CiEvidence {
11648            head: "a".into(),
11649            base: "base-sha".into(),
11650            changed: vec![
11651                "AGENTS.md".into(),
11652                "src/talk.rs".into(),
11653                "tests/consult_investigation.rs".into(),
11654            ],
11655            checks: vec![CiCheckEvidence {
11656                label: "coverage".into(),
11657                head_check: 70,
11658                base_check: 60,
11659                app: 1,
11660                run: "7".into(),
11661                base_run: "6".into(),
11662                head_failures: vec![failure.clone()],
11663                base_failures: vec![failure],
11664                rerun_exhausted: true,
11665            }],
11666        }
11667    }
11668
11669    #[test]
11670    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11671        let good = unrelated_ci_fixture();
11672        let red = vec!["coverage".into()];
11673        assert!(good.unrelated("a", &red));
11674        assert!(!good.unrelated("another-head", &red));
11675        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11676        assert!(!good.unrelated("a", &[]));
11677        for mutation in 0..8 {
11678            let mut bad = good.clone();
11679            match mutation {
11680                0 => bad.checks[0].rerun_exhausted = false,
11681                1 => bad.checks[0].base_failures.clear(),
11682                2 => bad.checks[0].head_failures.clear(),
11683                3 => bad.changed.push("tests/web_render.rs".into()),
11684                4 => bad.changed.push(".github/workflows/ci.yml".into()),
11685                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11686                6 => bad.checks.push(bad.checks[0].clone()),
11687                _ => bad.base.clear(),
11688            }
11689            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11690        }
11691    }
11692
11693    #[test]
11694    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11695        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11696        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11697        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11698        assert!(matches!(
11699            decide(&pr, 2, 2, CHECKS_GRACE),
11700            Step::GiveUp { .. }
11701        ));
11702        let optional = CheckInfo {
11703            label: "coverage".into(),
11704            verdict: Verdict::Fail,
11705            required: Some(false),
11706            run: Some("7".into()),
11707        };
11708        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11709        assert_eq!(
11710            rerunnable_with(&[optional], true),
11711            vec![("coverage".into(), Some("7".into()))]
11712        );
11713    }
11714
11715    #[tokio::test]
11716    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11717        let mut state = landing_state();
11718        let mut red = coverage_unknown();
11719        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11720        red.pr.failing = vec!["coverage".into()];
11721        let forge = Scripted::new(vec![red], vec![]);
11722        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11723        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11724        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11725        assert!(forge.calls().contains(&"fix"));
11726        assert!(state.land_unrelated.is_some());
11727        assert!(state.parked);
11728        assert!(
11729            !state
11730                .events
11731                .iter()
11732                .any(|e| e.message.contains("fixer produced no commit"))
11733        );
11734    }
11735
11736    fn coverage_unknown() -> Seen {
11737        let mut s = red("a", Some("7"));
11738        s.pr.blocking = Blocking::Unsaid;
11739        s.merge_state = "UNKNOWN".into();
11740        s.pr.failing = vec!["coverage".into()];
11741        s.contexts[0].label = "coverage".into();
11742        s.contexts[0].required = Some(false);
11743        s
11744    }
11745
11746    #[tokio::test]
11747    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11748        let mut state = landing_state();
11749        let unknown = coverage_unknown();
11750        let mut unstable = unknown.clone();
11751        unstable.pr.blocking = Blocking::of("UNSTABLE");
11752        unstable.merge_state = "UNSTABLE".into();
11753        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11754        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11755        assert!(!forge.calls().contains(&"fix"));
11756        assert!(!forge.calls().contains(&"rerun"));
11757        assert_eq!(state.status, RunStatus::Merged);
11758        assert_eq!(state.pr.unwrap().round, 0);
11759    }
11760
11761    #[tokio::test]
11762    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11763        let mut state = landing_state();
11764        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
11765        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11766        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11767        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11768        assert!(!forge.calls().contains(&"fix"));
11769        assert!(state.parked);
11770        assert_eq!(state.status, RunStatus::Landing);
11771        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11772        let hold = state.land_unrelated.as_ref().unwrap();
11773        let q = ask::Questions::open().get(&hold.question).unwrap();
11774        assert!(
11775            q.actions
11776                .values()
11777                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
11778        );
11779        assert!(
11780            state
11781                .events
11782                .iter()
11783                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
11784        );
11785        let first = state.land_unsaid.clone();
11786        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
11787        state.parked = false;
11788        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11789        assert_eq!(state.land_unsaid, first);
11790        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11791    }
11792
11793    fn red(head: &str, run: Option<&str>) -> Seen {
11794        let mut s = seen(head, Checks::Red, "BLOCKED", false);
11795        s.pr.failing = vec!["test (macos)".to_owned()];
11796        s.contexts = vec![CheckInfo {
11797            label: "test (macos)".to_owned(),
11798            verdict: Verdict::Fail,
11799            required: Some(true),
11800            run: run.map(str::to_owned),
11801        }];
11802        s
11803    }
11804
11805    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
11806
11807    #[tokio::test]
11808    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
11809        let mut state = landing_state();
11810        let forge = Scripted::new(
11811            vec![
11812                red("a", Some("7")),
11813                seen("a", Checks::Pending, "BLOCKED", false),
11814                seen("a", Checks::Green, "CLEAN", false),
11815            ],
11816            vec![(true, "")],
11817        );
11818        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11819        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11820        assert!(!forge.calls().contains(&"fix"));
11821        assert_eq!(state.status, RunStatus::Merged);
11822        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11823        let argvs = forge.argvs();
11824        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
11825        assert!(
11826            state
11827                .events
11828                .iter()
11829                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
11830        );
11831    }
11832
11833    #[tokio::test]
11834    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
11835        let mut state = landing_state();
11836        let forge = Scripted::new(
11837            vec![
11838                red("a", Some("7")),
11839                seen("a", Checks::Green, "CLEAN", false),
11840            ],
11841            vec![(true, "")],
11842        );
11843        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11844        // The red view repeats for the grace, then the fixer is asked once.
11845        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11846        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
11847        let calls = forge.calls();
11848        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
11849        let fix_at = calls.iter().position(|c| *c == "fix");
11850        assert!(fix_at.is_none_or(|f| f > rerun_at));
11851    }
11852
11853    #[tokio::test]
11854    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
11855        let mut state = landing_state();
11856        let mut v = red("a", Some("7"));
11857        v.pr.checks = Checks::Pending;
11858        v.contexts.push(CheckInfo {
11859            label: "slow".to_owned(),
11860            verdict: Verdict::Pending,
11861            required: Some(true),
11862            run: Some("8".to_owned()),
11863        });
11864        let forge = Scripted::new(
11865            vec![v, seen("a", Checks::Green, "CLEAN", false)],
11866            vec![(true, "")],
11867        );
11868        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11869        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11870        assert_eq!(state.status, RunStatus::Merged);
11871    }
11872
11873    #[test]
11874    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
11875        let mut v = red("a", Some("7"));
11876        v.contexts.push(CheckInfo {
11877            label: "same run, still going".to_owned(),
11878            verdict: Verdict::Pending,
11879            required: Some(true),
11880            run: Some("7".to_owned()),
11881        });
11882        assert!(rerunnable(&v.contexts).is_empty());
11883    }
11884
11885    #[tokio::test]
11886    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
11887        let mut state = landing_state();
11888        state.config.graph.land_rounds = 0;
11889        let forge = Scripted::new(
11890            vec![
11891                red("a", Some("7")),
11892                seen("a", Checks::Green, "CLEAN", false),
11893            ],
11894            vec![(true, "")],
11895        );
11896        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11897        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11898        assert_eq!(state.status, RunStatus::Merged);
11899        assert!(!forge.calls().contains(&"fix"));
11900        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11901    }
11902
11903    #[tokio::test]
11904    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
11905        let mut state = landing_state();
11906        state.config.graph.land_rounds = 1;
11907        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
11908        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
11909        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11910        assert_eq!(pr.state, PrLifecycle::Open);
11911        assert_eq!(state.status, RunStatus::Blocked);
11912        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11913        assert!(
11914            state.merge_decision.is_none(),
11915            "no ordinary failure handoff"
11916        );
11917        assert!(forge.argvs().is_empty(), "no merge on outage");
11918
11919        let recovered = Scripted::new(
11920            vec![
11921                seen("a", Checks::Green, "CLEAN", true),
11922                seen("b", Checks::Green, "CLEAN", false),
11923            ],
11924            vec![(true, "")],
11925        );
11926        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
11927        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
11928        assert_eq!(state.status, RunStatus::Merged);
11929        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11930        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
11931    }
11932
11933    #[tokio::test]
11934    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
11935        let mut state = landing_state();
11936        state.config.graph.land_rounds = 1;
11937        let forge = Scripted::new(
11938            vec![
11939                seen("a", Checks::Green, "CLEAN", true),
11940                red("b", Some("7")),
11941                seen("b", Checks::Green, "CLEAN", false),
11942            ],
11943            vec![(true, "")],
11944        );
11945        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11946            head: "b".to_owned(),
11947        });
11948        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11949        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11950        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
11951        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11952        assert_eq!(state.status, RunStatus::Merged);
11953        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
11954        assert_eq!(
11955            value_of(&forge.argvs()[0], "--match-head-commit"),
11956            Some("b")
11957        );
11958    }
11959
11960    #[tokio::test]
11961    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
11962        let mut state = landing_state();
11963        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11964        *forge.rerun_fails.lock().unwrap() = true;
11965        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11966        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11967        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
11968        assert_eq!(
11969            forge.calls().iter().filter(|c| **c == "fix").count(),
11970            1,
11971            "{:?}",
11972            forge.calls()
11973        );
11974    }
11975
11976    #[tokio::test]
11977    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
11978        let mut state = landing_state();
11979        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11980        // The record was written just before the previous pass died.
11981        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
11982        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11983        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11984        assert!(forge.reruns.lock().unwrap().is_empty());
11985    }
11986
11987    #[tokio::test]
11988    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
11989        let mut state = landing_state();
11990        state.config.graph.rerun_flaky_checks = false;
11991        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11992        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11993        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11994        assert!(forge.reruns.lock().unwrap().is_empty());
11995        assert!(forge.calls().contains(&"fix"));
11996
11997        let mut state = landing_state();
11998        let forge = Scripted::new(vec![red("a", None)], vec![]);
11999        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
12000        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
12001        assert!(forge.reruns.lock().unwrap().is_empty());
12002        assert!(forge.calls().contains(&"fix"));
12003    }
12004
12005    fn names(xs: &[&str]) -> BTreeSet<String> {
12006        xs.iter().map(|x| (*x).to_owned()).collect()
12007    }
12008
12009    #[test]
12010    fn a_required_check_the_rollup_never_listed_is_named() {
12011        let req = names(&["build"]);
12012        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
12013        assert!(why.contains("never reported: build"), "{why}");
12014        assert!(!why.contains("probably waiting for a review"), "{why}");
12015    }
12016
12017    #[test]
12018    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
12019        let why = waiting_on("BLOCKED", &[passing("review")], None);
12020        assert!(why.contains("could not be read"), "{why}");
12021        assert!(!why.contains("probably waiting for a review"), "{why}");
12022    }
12023
12024    #[test]
12025    fn all_required_reported_keeps_the_review_guess() {
12026        let req = names(&["build"]);
12027        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12028        assert!(why.contains("probably waiting for a review"), "{why}");
12029        assert!(!why.contains("never reported"), "{why}");
12030    }
12031
12032    #[test]
12033    fn required_names_match_the_rollup_ignoring_case_only() {
12034        let req = names(&["Build"]);
12035        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
12036        assert!(!why.contains("never reported"), "{why}");
12037    }
12038
12039    #[test]
12040    fn required_contexts_are_read_from_protection_and_rulesets() {
12041        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
12042        assert_eq!(
12043            parse_classic_required(classic),
12044            Some(names(&["build", "lint"]))
12045        );
12046        let rules = r#"[{"type":"pull_request","parameters":{}},
12047            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
12048        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
12049        assert_eq!(parse_ruleset_required("nope"), None);
12050        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
12051    }
12052
12053    #[test]
12054    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
12055        let shown = BTreeSet::new();
12056        let ok = seen("a", Checks::Green, "CLEAN", false);
12057        let guard = |s: Option<&Seen>| {
12058            direct_merge_is_safe(
12059                s,
12060                "A",
12061                &shown,
12062                0,
12063                4,
12064                Duration::ZERO,
12065                CiExpectation::Expected,
12066            )
12067        };
12068        assert!(guard(Some(&ok)));
12069        assert!(!guard(None));
12070        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
12071        let mut stale = ok.clone();
12072        stale.rollup_head = "old".to_owned();
12073        assert!(!guard(Some(&stale)));
12074        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
12075        assert!(!guard(Some(&merged_view("a"))));
12076    }
12077
12078    #[test]
12079    fn the_rollup_node_carries_whether_each_check_is_required() {
12080        let node = node_json("new", "SUCCESS", false)
12081            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
12082        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
12083        assert_eq!(s.contexts.len(), 1);
12084        assert_eq!(s.contexts[0].required, Some(true));
12085        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
12086        assert_eq!(s.contexts[0].required, None);
12087    }
12088
12089    #[tokio::test]
12090    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
12091        let mut state = landing_state();
12092        state.land_armed_head = Some("a".to_owned());
12093        let forge = Scripted::new(
12094            vec![seen("a", Checks::Green, "CLEAN", true)],
12095            vec![(false, "disable exploded")],
12096        );
12097        land_with(&mut state, URL, &forge).await.unwrap();
12098        assert!(!forge.calls().contains(&"fix"));
12099        assert_eq!(state.status, RunStatus::Blocked);
12100        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
12101        let why = state.merge.as_ref().unwrap().detail.clone();
12102        assert!(why.contains("disable exploded"), "{why}");
12103    }
12104
12105    /// Create a cross-platform fake `gh` executable in `dir` backed by exact
12106    /// fixture files, avoiding shell quoting differences and global `PATH`
12107    /// mutation.
12108    pub(crate) fn fake_gh_script(
12109        dir: &Path,
12110        name: &str,
12111        stdout: &str,
12112        stderr: &str,
12113        exit_code: i32,
12114    ) -> PathBuf {
12115        let out_path = dir.join(format!("{name}.stdout"));
12116        let err_path = dir.join(format!("{name}.stderr"));
12117        std::fs::write(&out_path, stdout).unwrap();
12118        std::fs::write(&err_path, stderr).unwrap();
12119        #[cfg(windows)]
12120        {
12121            let script = dir.join(format!("{name}.cmd"));
12122            let mut body = String::from("@echo off\r\n");
12123            if !stdout.is_empty() {
12124                body.push_str(&format!("type \"{}\"\r\n", out_path.display()));
12125            }
12126            if !stderr.is_empty() {
12127                body.push_str(&format!("type \"{}\" 1>&2\r\n", err_path.display()));
12128            }
12129            body.push_str(&format!("exit /b {exit_code}\r\n"));
12130            std::fs::write(&script, body).unwrap();
12131            script
12132        }
12133        #[cfg(unix)]
12134        {
12135            use std::os::unix::fs::PermissionsExt as _;
12136            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
12137            let script = dir.join(name);
12138            let mut body = String::from("#!/bin/sh\n");
12139            if !stdout.is_empty() {
12140                body.push_str(&format!("cat {}\n", quote(&out_path)));
12141            }
12142            if !stderr.is_empty() {
12143                body.push_str(&format!("cat {} >&2\n", quote(&err_path)));
12144            }
12145            body.push_str(&format!("exit {exit_code}\n"));
12146            let status = std::process::Command::new("sh")
12147                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
12148                .arg(&script)
12149                .arg(&body)
12150                .status()
12151                .unwrap();
12152            assert!(status.success());
12153            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
12154            script
12155        }
12156    }
12157
12158    #[test]
12159    fn gh_output_combined_preserves_and_separates_both_streams() {
12160        let mk = |ok, stdout: &str, stderr: &str| GhOutput {
12161            ok,
12162            stdout: stdout.into(),
12163            stderr: stderr.into(),
12164        };
12165        assert_eq!(mk(true, "  ", "\n").combined(), "");
12166        assert_eq!(mk(true, "  only out \n", " \t ").combined(), "only out");
12167        assert_eq!(mk(false, "", "  only err\n").combined(), "only err");
12168        assert_eq!(
12169            mk(false, "{\"status\":\"404\"}", "gh: Not Found (HTTP 404)\n").combined(),
12170            "{\"status\":\"404\"}\ngh: Not Found (HTTP 404)"
12171        );
12172    }
12173
12174    #[tokio::test]
12175    async fn gh_separates_json_stdout_from_stderr_diagnostics() {
12176        let tmp = tempfile::tempdir().unwrap();
12177        let hint = "hint: to listen to pull request events, run `gh pr view --web`\n";
12178        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"}"#;
12179        let valid_list = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: test","baseRefName":"main","isCrossRepository":false}]"#;
12180
12181        // Valid JSON stdout + nonempty stderr hint on exit 0: structured reads
12182        // parse stdout cleanly while stderr remains available via `combined()`.
12183        let ok_view = fake_gh_script(tmp.path(), "ok-view", &format!("{valid_view}\n"), hint, 0);
12184        let out = gh_with(&ok_view, tmp.path(), &["pr".into(), "view".into()])
12185            .await
12186            .unwrap();
12187        assert!(out.ok);
12188        assert_eq!(parse_pr(&out.stdout).unwrap().state, PrLifecycle::Open);
12189        assert!(out.stderr.contains("listen to pull request events"));
12190        assert!(out.combined().contains("listen to pull request events"));
12191        assert!(out.combined().contains("feat: test"));
12192
12193        let ok_list = fake_gh_script(tmp.path(), "ok-list", &format!("{valid_list}\n"), hint, 0);
12194        assert_eq!(
12195            find_open_pr_with(&ok_list, tmp.path(), "magi/task-t", "main")
12196                .await
12197                .unwrap(),
12198            OpenPr::One {
12199                url: "https://github.com/example/repo/pull/1".into(),
12200                title: "feat: test".into(),
12201            }
12202        );
12203
12204        // Malformed stdout with trailing characters still fails strict JSON parsing.
12205        let malformed = fake_gh_script(
12206            tmp.path(),
12207            "malformed",
12208            &format!("{valid_view}\ntrailing garbage\n"),
12209            "",
12210            0,
12211        );
12212        let out = gh_with(&malformed, tmp.path(), &["pr".into(), "view".into()])
12213            .await
12214            .unwrap();
12215        assert!(out.ok);
12216        let err = parse_pr(&out.stdout).unwrap_err();
12217        assert!(
12218            format!("{err:#}").contains("trailing characters"),
12219            "{err:#}"
12220        );
12221
12222        // Empty stdout + nonempty stderr on exit 0 never substitutes stderr.
12223        let empty = fake_gh_script(tmp.path(), "empty", "", hint, 0);
12224        let out = gh_with(&empty, tmp.path(), &["pr".into(), "view".into()])
12225            .await
12226            .unwrap();
12227        assert!(out.ok);
12228        assert!(out.stdout.trim().is_empty());
12229        assert!(parse_pr(&out.stdout).is_err());
12230
12231        // Non-zero exit with valid JSON on stdout and error on stderr reports
12232        // failure and preserves both streams in `combined()`.
12233        let failed = fake_gh_script(
12234            tmp.path(),
12235            "failed",
12236            &format!("{valid_view}\n"),
12237            "gh: HTTP 404 Not Found\n",
12238            1,
12239        );
12240        let out = gh_with(&failed, tmp.path(), &["pr".into(), "view".into()])
12241            .await
12242            .unwrap();
12243        assert!(!out.ok);
12244        let diag = out.combined();
12245        assert!(diag.contains("HTTP 404 Not Found"), "{diag}");
12246        assert!(diag.contains("feat: test"), "{diag}");
12247        let list_err = find_open_pr_with(&failed, tmp.path(), "magi/task-t", "main")
12248            .await
12249            .unwrap_err()
12250            .to_string();
12251        assert!(list_err.contains("HTTP 404 Not Found"), "{list_err}");
12252    }
12253
12254    struct StaticPrObserver(crate::land_sync_recovery::ObservedPr);
12255
12256    impl crate::land_sync_recovery::PrObserver for StaticPrObserver {
12257        async fn observe_pr(
12258            &self,
12259            _repo: &Path,
12260            _pr_url: &str,
12261        ) -> Result<crate::land_sync_recovery::ObservedPr> {
12262            Ok(self.0.clone())
12263        }
12264    }
12265
12266    /// Build a real-shaped legacy landing base-sync exhaustion fixture backed by
12267    /// an isolated temp Git repo, bare origin, queue task, and open PR metadata.
12268    async fn legacy_exhausted_landing_fixture() -> (
12269        tempfile::TempDir,
12270        PathBuf,
12271        crate::queue::Queue,
12272        crate::queue::Task,
12273        RunState,
12274        String,
12275    ) {
12276        let (tmp, mut state, old) = landing_git_fixture().await;
12277        crate::run::pin_test_home();
12278        let home = crate::run::home();
12279        // Move run state under this isolated home so load_under/save_under match.
12280        state.config.graph.land_rounds = 4;
12281        state.config.graph.land_approval = true;
12282        state.config.verify.gate = vec!["git rev-parse HEAD".into()];
12283        state.config.verify.e2e = vec!["git rev-parse HEAD".into()];
12284        state.status = RunStatus::Blocked;
12285        state.driver_exited = true;
12286        state.pr = Some(crate::run::PrRecord {
12287            url: green_pr().url,
12288            number: 42,
12289            state: "open".to_owned(),
12290            checks: "green".to_owned(),
12291            round: 0,
12292            rounds: 4,
12293            red_at_merge: Vec::new(),
12294        });
12295        state.merge = Some(MergeOutcome {
12296            mode: MergeMode::Pr,
12297            ok: false,
12298            detail:
12299                "could not synchronize landing base: landing base synchronization budget exhausted"
12300                    .to_owned(),
12301            empty: false,
12302        });
12303        state.reviews = vec![serde_json::from_value(serde_json::json!({
12304            "round": 1,
12305            "head": old,
12306            "expected": 2,
12307            "answered": 2,
12308            "reviews": [],
12309            "clean": true,
12310            "e2e": [{"command": "git rev-parse HEAD", "code": 0, "output_tail": old, "duration_ms": 10}],
12311            "verified_head": old,
12312            "verified_at": jiff::Timestamp::now(),
12313            "e2e_deferred": false
12314        }))
12315        .unwrap()];
12316        let pass_cmd: crate::run::CommandOutcome = serde_json::from_value(serde_json::json!({
12317            "command": "git rev-parse HEAD",
12318            "code": 0,
12319            "output_tail": old,
12320            "duration_ms": 10
12321        }))
12322        .unwrap();
12323        state.head_e2e = Some(crate::run::GateRepairE2e::new(
12324            old.clone(),
12325            true,
12326            vec![pass_cmd.clone()],
12327        ));
12328        state.gate = vec![pass_cmd];
12329        state.gate_ran = true;
12330        state.gate_head = Some(old.clone());
12331        state.land_sync_attempts = 4;
12332        state.land_sync_target = None;
12333        state.land_sync_pending = true;
12334        state.event(
12335            "land",
12336            "stopped: could not synchronize landing base: landing base synchronization budget exhausted",
12337        );
12338
12339        let queue = crate::queue::Queue::at(home.join("queue"));
12340        let mut task = crate::queue::Task::new(
12341            "landing sync".into(),
12342            state.instruction.clone(),
12343            state.repo.clone(),
12344            crate::queue::Source::Human,
12345        );
12346        task.link_run(&state.id);
12347        task.hold_machine(Some("landing base synchronization budget exhausted".into()));
12348        queue.put(&mut task).unwrap();
12349        state.origin = Some(crate::run::Origin::queue(&task.id));
12350        state.save_under(&home).unwrap();
12351        (tmp, home, queue, task, state, old)
12352    }
12353
12354    #[tokio::test]
12355    async fn land_sync_recovery_continues_legacy_real_shaped_stop_on_existing_pr() {
12356        let (_tmp, home, queue, task, mut state, old) = legacy_exhausted_landing_fixture().await;
12357        let home = home.as_path();
12358
12359        // Advance origin/main once so landing rebase has real work to replay.
12360        advance_landing_base(&state).await;
12361
12362        state.pre_gate = vec![
12363            serde_json::from_value(serde_json::json!({
12364                "command": "prepare sources",
12365                "code": 0,
12366                "output_tail": "prepared",
12367                "duration_ms": 15
12368            }))
12369            .unwrap(),
12370        ];
12371        let pre_gate_commit = git::rev_parse(&state.repo, "HEAD^").await.unwrap();
12372        assert_ne!(pre_gate_commit, old);
12373        state.pre_gate_commit = Some(pre_gate_commit.clone());
12374        let pre_gate = serde_json::to_value(&state.pre_gate).unwrap();
12375        state.save_under(home).unwrap();
12376
12377        // Pre-recovery: legacy shape recognized, recover-base refused, ordinary resume/release refused.
12378        assert!(state.land_sync_exhausted());
12379        assert!(!state.base_sync_blocked());
12380        assert!(crate::land_sync_recovery::held_task(&queue, &task));
12381        let base_err = crate::graph::Runner::authorize_base_recovery(home, &state.id, &task.id)
12382            .await
12383            .unwrap_err();
12384        assert!(
12385            base_err.to_string().contains("run has no base-sync stop"),
12386            "{base_err:#}"
12387        );
12388        assert!(crate::handover::resume_refusal_under(&state, Some(home)).is_none());
12389        assert!(crate::base_sync_recovery::ensure_generic_release(&queue, &task).is_err());
12390
12391        // Ordinary land_with without authorization refuses without refilling budget.
12392        let pr_url = green_pr().url;
12393        let blocked_forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12394        let err = land_with(&mut state, &pr_url, &blocked_forge)
12395            .await
12396            .unwrap_err();
12397        assert!(err.to_string().contains("budget exhausted"), "{err:#}");
12398        assert_eq!(state.land_sync_attempts, 4);
12399        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12400
12401        // Attach a prior head-bound approval on `old` to prove fresh approval is required after recovery.
12402        let questions = ask::Questions::at(home.join("questions"));
12403        let mut old_q = ask::Question::new(
12404            state.id.clone(),
12405            APPROVAL_NODE.into(),
12406            "owner".into(),
12407            "old head approval".into(),
12408            String::new(),
12409            vec![APPROVE.into()],
12410        );
12411        old_q
12412            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12413            .unwrap();
12414        questions.put(&mut old_q).unwrap();
12415        state.land_approval = Some(LandApproval {
12416            question: old_q.id.clone(),
12417            head: old.clone(),
12418        });
12419        state.save_under(home).unwrap();
12420
12421        // Admit explicit recover-land-sync via two-phase control.
12422        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12423            url: pr_url.clone(),
12424            number: 42,
12425            open: true,
12426            head: old.clone(),
12427            base_branch: Some("main".to_owned()),
12428        });
12429        let outcome = crate::land_sync_recovery_control::recover_with(
12430            &queue,
12431            home,
12432            crate::land_sync_recovery_control::Request {
12433                run: state.id.clone(),
12434                head: old.clone(),
12435                actor: "cli".into(),
12436                request: "req-legacy-1".into(),
12437            },
12438            &observer,
12439        )
12440        .await
12441        .unwrap();
12442        assert!(!outcome.repeated);
12443        assert_eq!(
12444            outcome
12445                .task
12446                .resume_override
12447                .as_ref()
12448                .and_then(|pin| pin.pinned_run.as_deref()),
12449            Some(state.id.as_str())
12450        );
12451
12452        // Ordinary fast-forward of origin/main between admission and dispatch is allowed.
12453        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
12454        std::fs::write(state.repo.join("advance2"), "advance2").unwrap();
12455        git::git(&state.repo, &["add", "."]).await.unwrap();
12456        git::git(&state.repo, &["commit", "-m", "advance base again"])
12457            .await
12458            .unwrap();
12459        git::git(&state.repo, &["push", "origin", "main"])
12460            .await
12461            .unwrap();
12462        git::git(&state.repo, &["checkout", "winner"])
12463            .await
12464            .unwrap();
12465
12466        let reloaded_task = queue.get(&task.id).unwrap();
12467        assert!(matches!(
12468            crate::land_sync_recovery::dispatch_check_with(&queue, home, &reloaded_task, &observer)
12469                .await,
12470            crate::land_sync_recovery::DispatchDecision::Proceed
12471        ));
12472
12473        // Execute continuation on the existing PR using real rebase + fresh gate + fresh E2E.
12474        let mut run = RunState::load_under(&state.id, home).unwrap();
12475        assert!(run.land_sync_recovery_pending());
12476        let mut forge = Scripted::new(
12477            vec![
12478                seen(&old, Checks::Green, "BEHIND", false),
12479                seen(&old, Checks::Green, "BEHIND", false),
12480                seen("@published", Checks::Green, "CLEAN", false),
12481            ],
12482            vec![],
12483        );
12484        forge.public_repo = Some(run.repo.clone());
12485        let pr = land_with(&mut run, &pr_url, &forge).await.unwrap();
12486        assert_eq!(pr.state, PrLifecycle::Open);
12487        assert!(run.parked, "must park awaiting fresh head-bound approval");
12488
12489        // Verify attempts preserved (4 -> 5), 1 grant consumed, fresh head published,
12490        // prior verification archived, fresh gate + E2E ran on new head, fresh approval asked.
12491        let new_head = git::rev_parse(&run.repo, "HEAD").await.unwrap();
12492        assert_ne!(new_head, old);
12493        assert_eq!(run.land_sync_attempts, 5);
12494        assert_eq!(run.land_sync_recovery.extra_attempts, 1);
12495        assert_eq!(run.land_sync_budget(), 5);
12496        assert!(!run.land_sync_pending);
12497        assert_eq!(run.pr_pushed_head.as_deref(), Some(new_head.as_str()));
12498        assert_eq!(
12499            git::remote_head(&run.repo, "origin", "task-head")
12500                .await
12501                .unwrap()
12502                .as_deref(),
12503            Some(new_head.as_str())
12504        );
12505        assert!(run.gate_ran);
12506        assert_eq!(run.gate_head.as_deref(), Some(new_head.as_str()));
12507        assert!(
12508            run.head_e2e
12509                .as_ref()
12510                .is_some_and(|e| e.head == new_head && e.passed)
12511        );
12512        assert_eq!(run.reviews.len(), 1);
12513        assert!(run.reviews[0].clean);
12514        assert_eq!(run.reviews[0].answered, 2);
12515        assert!(run.reviews[0].verified_head.is_none());
12516        assert!(!run.verification_history.is_empty());
12517        assert_eq!(run.land_sync_recovery.stops.len(), 1);
12518        assert_eq!(run.land_sync_recovery.authorizations.len(), 1);
12519        let auth = &run.land_sync_recovery.authorizations[0];
12520        assert!(auth.consumed);
12521        assert!(auth.invalidated.is_none());
12522        assert!(run.pre_gate.is_empty());
12523        assert!(run.pre_gate_commit.is_none());
12524        let saved = RunState::load_under(&run.id, home).unwrap();
12525        assert!(saved.pre_gate.is_empty());
12526        assert!(saved.pre_gate_commit.is_none());
12527        let archived = saved.land_sync_recovery.authorizations[0]
12528            .archived_verification
12529            .as_ref()
12530            .unwrap();
12531        assert_eq!(serde_json::to_value(&archived.pre_gate).unwrap(), pre_gate);
12532        assert_eq!(
12533            archived.pre_gate_commit.as_deref(),
12534            Some(pre_gate_commit.as_str())
12535        );
12536
12537        let mut legacy = serde_json::to_value(archived).unwrap();
12538        let fields = legacy.as_object_mut().unwrap();
12539        fields.remove("pre_gate");
12540        fields.remove("pre_gate_commit");
12541        let legacy: crate::land_sync_recovery::ArchivedVerification =
12542            serde_json::from_value(legacy).unwrap();
12543        assert!(legacy.pre_gate.is_empty());
12544        assert!(legacy.pre_gate_commit.is_none());
12545        let new_approval = run.land_approval.as_ref().unwrap();
12546        assert_ne!(new_approval.question, old_q.id);
12547        assert_eq!(new_approval.head, new_head);
12548    }
12549
12550    #[tokio::test]
12551    async fn land_sync_recovery_observes_external_merge_without_grant() {
12552        let (_tmp, home, queue, mut task, mut state, old) =
12553            legacy_exhausted_landing_fixture().await;
12554        let pr_url = format!(
12555            "https://github.com/example/landing-merge-{}/pull/42",
12556            state.id
12557        );
12558        state.pr.as_mut().unwrap().url.clone_from(&pr_url);
12559        state.save_under(&home).unwrap();
12560        task.resume_override = Some(crate::queue::OperatorResume {
12561            question_id: String::new(),
12562            at: jiff::Timestamp::now(),
12563            conductor_rehold: None,
12564            forced: true,
12565            pinned_run: Some(state.id.clone()),
12566        });
12567        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12568            url: pr_url.clone(),
12569            number: 42,
12570            open: false,
12571            head: old.clone(),
12572            base_branch: Some("main".into()),
12573        });
12574        assert!(matches!(
12575            crate::land_sync_recovery::dispatch_check_with(&queue, &home, &task, &observer).await,
12576            crate::land_sync_recovery::DispatchDecision::Proceed
12577        ));
12578        let mut merged = merged_view(&old);
12579        merged.pr.url = pr_url.clone();
12580        let forge = Scripted::new(vec![merged], vec![]);
12581        land_with(&mut state, &pr_url, &forge).await.unwrap();
12582        assert_eq!(state.status, RunStatus::Merged);
12583        assert_eq!(state.land_sync_attempts, 4);
12584        assert_eq!(state.land_sync_recovery.extra_attempts, 0);
12585        assert_eq!(forge.calls(), ["view"]);
12586    }
12587
12588    #[tokio::test]
12589    async fn land_sync_recovery_forces_fresh_e2e_and_gate_even_when_head_unchanged() {
12590        let (tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
12591        let home = home.as_path();
12592
12593        // Create marker-writing commands for gate and e2e so we prove both execute freshly
12594        // even when HEAD does not change (origin/main is already an ancestor of winner).
12595        let gate_marker = tmp.path().join("fresh-gate-ran");
12596        let e2e_marker = tmp.path().join("fresh-e2e-ran");
12597        state.config.verify.gate = vec![format!(
12598            "git rev-parse HEAD > \"{}\"",
12599            gate_marker.display().to_string().replace('\\', "/")
12600        )];
12601        state.config.verify.e2e = vec![format!(
12602            "git rev-parse HEAD > \"{}\"",
12603            e2e_marker.display().to_string().replace('\\', "/")
12604        )];
12605        let questions = ask::Questions::at(home.join("questions"));
12606        let mut old_q = ask::Question::new(
12607            state.id.clone(),
12608            APPROVAL_NODE.into(),
12609            "owner".into(),
12610            "prior approval on same head".into(),
12611            String::new(),
12612            vec![APPROVE.into()],
12613        );
12614        old_q
12615            .answer(ask::Answer::Choice(APPROVE.to_owned()))
12616            .unwrap();
12617        questions.put(&mut old_q).unwrap();
12618        state.land_approval = Some(LandApproval {
12619            question: old_q.id.clone(),
12620            head: old.clone(),
12621        });
12622        state.save_under(home).unwrap();
12623
12624        let pr_url = green_pr().url;
12625        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12626            url: pr_url.clone(),
12627            number: 42,
12628            open: true,
12629            head: old.clone(),
12630            base_branch: Some("main".to_owned()),
12631        });
12632        crate::land_sync_recovery_control::recover_with(
12633            &queue,
12634            home,
12635            crate::land_sync_recovery_control::Request {
12636                run: state.id.clone(),
12637                head: old.clone(),
12638                actor: "cli".into(),
12639                request: "req-same-head".into(),
12640            },
12641            &observer,
12642        )
12643        .await
12644        .unwrap();
12645
12646        let mut run = RunState::load_under(&state.id, home).unwrap();
12647        let mut forge = Scripted::new(
12648            vec![
12649                seen(&old, Checks::Green, "CLEAN", false),
12650                seen(&old, Checks::Green, "CLEAN", false),
12651                seen(&old, Checks::Green, "CLEAN", false),
12652            ],
12653            vec![],
12654        );
12655        forge.public_repo = Some(run.repo.clone());
12656        land_with(&mut run, &pr_url, &forge).await.unwrap();
12657
12658        assert!(
12659            gate_marker.exists(),
12660            "fresh gate must run even on unchanged HEAD"
12661        );
12662        assert!(
12663            e2e_marker.exists(),
12664            "fresh E2E must run even on unchanged HEAD"
12665        );
12666        assert!(
12667            run.parked,
12668            "old approval before recovery must not be reused"
12669        );
12670        assert_ne!(run.land_approval.as_ref().unwrap().question, old_q.id);
12671    }
12672
12673    #[tokio::test]
12674    async fn land_sync_recovery_resumes_after_gate_repair_before_push() {
12675        let (_tmp, home, queue, _task, mut state, old) = legacy_exhausted_landing_fixture().await;
12676        landing_gate_fixer(
12677            &mut state,
12678            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
12679        );
12680        state.config.verify.gate =
12681            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
12682        state.save_under(&home).unwrap();
12683        let pr_url = green_pr().url;
12684        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12685            url: pr_url.clone(),
12686            number: 42,
12687            open: true,
12688            head: old.clone(),
12689            base_branch: Some("main".into()),
12690        });
12691        crate::land_sync_recovery_control::recover_with(
12692            &queue,
12693            &home,
12694            crate::land_sync_recovery_control::Request {
12695                run: state.id.clone(),
12696                head: old.clone(),
12697                actor: "cli".into(),
12698                request: "req-interrupted-gate-repair".into(),
12699            },
12700            &observer,
12701        )
12702        .await
12703        .unwrap();
12704        let mut run = RunState::load_under(&state.id, &home).unwrap();
12705        let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
12706        assert!(matches!(
12707            prepare_land_sync_recovery(&mut run, &pr_url, &forge)
12708                .await
12709                .unwrap(),
12710            LandSyncPrep::Continue(Some(_))
12711        ));
12712        // Interrupt at the publication check, after the real gate fixer commits.
12713        let changed = Scripted::new(
12714            vec![seen("different", Checks::Green, "CLEAN", false)],
12715            vec![],
12716        );
12717        let error = resume_landing_head(&mut run, &old, &pr_url, &changed, None)
12718            .await
12719            .unwrap_err();
12720        assert!(
12721            error.to_string().contains("PR head changed while gating"),
12722            "{error}"
12723        );
12724        let repaired = git::rev_parse(&run.repo, "HEAD").await.unwrap();
12725        assert_ne!(repaired, old);
12726        assert_eq!(run.gate_fixes.len(), 1);
12727        assert!(run.gate_fixes[0].committed);
12728        assert_eq!(
12729            git::remote_head(&run.repo, "origin", "task-head")
12730                .await
12731                .unwrap(),
12732            Some(old.clone())
12733        );
12734
12735        run.status = RunStatus::Blocked;
12736        run.save().unwrap();
12737        let mut resumed = RunState::load_under(&run.id, &home).unwrap();
12738        assert_eq!(resumed.land_sync_attempts, 5);
12739        assert!(resumed.land_sync_pending);
12740        assert!(!resumed.land_sync_exhausted());
12741        assert!(!resumed.land_sync_unstarted_grant());
12742        assert!(matches!(
12743            prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
12744                .await
12745                .unwrap(),
12746            LandSyncPrep::Continue(None)
12747        ));
12748        assert_eq!(
12749            resume_landing_head(&mut resumed, &old, &pr_url, &forge, None)
12750                .await
12751                .unwrap(),
12752            repaired
12753        );
12754        assert_eq!(resumed.land_sync_attempts, 5);
12755        assert_eq!(resumed.gate_fixes.len(), 1);
12756        assert!(!resumed.land_sync_pending);
12757        assert!(
12758            resumed.land_sync_recovery.authorizations[0]
12759                .invalidated
12760                .is_none()
12761        );
12762        assert_eq!(
12763            git::remote_head(&resumed.repo, "origin", "task-head")
12764                .await
12765                .unwrap(),
12766            Some(repaired)
12767        );
12768    }
12769
12770    #[tokio::test]
12771    async fn land_sync_recovery_repeated_exhaustion_is_bounded_by_lifetime_cap() {
12772        let (_tmp, home, queue, task, mut state, mut head) =
12773            legacy_exhausted_landing_fixture().await;
12774        let home = home.as_path();
12775        state.config.graph.land_approval = false;
12776        state.save_under(home).unwrap();
12777
12778        let pr_url = green_pr().url;
12779        let mut base_step = 0usize;
12780        let advance_step = |repo: PathBuf, step: usize| async move {
12781            git::git(&repo, &["checkout", "main"]).await.unwrap();
12782            std::fs::write(repo.join(format!("advance-{step}")), format!("step-{step}")).unwrap();
12783            git::git(&repo, &["add", "."]).await.unwrap();
12784            git::git(&repo, &["commit", "-m", &format!("advance base {step}")])
12785                .await
12786                .unwrap();
12787            git::git(&repo, &["push", "origin", "main"]).await.unwrap();
12788            git::git(&repo, &["checkout", "winner"]).await.unwrap();
12789        };
12790        for grant_num in 1..=crate::land_sync_recovery::MAX_GRANTS {
12791            base_step += 1;
12792            advance_step(state.repo.clone(), base_step).await;
12793            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12794                url: pr_url.clone(),
12795                number: 42,
12796                open: true,
12797                head: head.clone(),
12798                base_branch: Some("main".to_owned()),
12799            });
12800            crate::land_sync_recovery_control::recover_with(
12801                &queue,
12802                home,
12803                crate::land_sync_recovery_control::Request {
12804                    run: state.id.clone(),
12805                    head: head.clone(),
12806                    actor: "cli".into(),
12807                    request: format!("req-cap-{grant_num}"),
12808                },
12809                &observer,
12810            )
12811            .await
12812            .unwrap();
12813
12814            // Simulate execution consuming grant, spending the 1 attempt, and hitting exhaustion again.
12815            state = RunState::load_under(&state.id, home).unwrap();
12816            let mut forge = Scripted::new(
12817                vec![
12818                    seen(&head, Checks::Green, "BEHIND", false),
12819                    seen(&head, Checks::Green, "BEHIND", false),
12820                    seen("@published", Checks::Green, "BEHIND", false),
12821                ],
12822                vec![],
12823            );
12824            forge.public_repo = Some(state.repo.clone());
12825            let prep = prepare_land_sync_recovery(&mut state, &pr_url, &forge)
12826                .await
12827                .unwrap();
12828            assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
12829            head = resume_landing_head(&mut state, &head, &pr_url, &forge, None)
12830                .await
12831                .unwrap();
12832            assert_eq!(state.land_sync_attempts, 4 + grant_num);
12833            assert_eq!(state.land_sync_recovery.extra_attempts, grant_num);
12834
12835            // Re-exhaust on another base advance.
12836            base_step += 1;
12837            advance_step(state.repo.clone(), base_step).await;
12838            let err = rebase_landing_worktree(&mut state, "origin/main")
12839                .await
12840                .unwrap_err();
12841            assert!(err.to_string().contains("budget exhausted"), "{err:#}");
12842            state.status = RunStatus::Blocked;
12843            state.save_under(home).unwrap();
12844            assert!(state.land_sync_exhausted());
12845
12846            // Put task back to Held so the next explicit authorization can queue it.
12847            let mut t = queue.get(&task.id).unwrap();
12848            t.hold_machine(Some("re-exhausted".into()));
12849            queue.put(&mut t).unwrap();
12850        }
12851
12852        assert_eq!(
12853            state.land_sync_attempts,
12854            4 + crate::land_sync_recovery::MAX_GRANTS
12855        );
12856        assert_eq!(state.land_sync_grants_remaining(), 0);
12857        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12858            url: pr_url,
12859            number: 42,
12860            open: true,
12861            head: head.clone(),
12862            base_branch: Some("main".to_owned()),
12863        });
12864        let err = crate::land_sync_recovery_control::recover_with(
12865            &queue,
12866            home,
12867            crate::land_sync_recovery_control::Request {
12868                run: state.id.clone(),
12869                head,
12870                actor: "cli".into(),
12871                request: "req-cap-overflow".into(),
12872            },
12873            &observer,
12874        )
12875        .await
12876        .unwrap_err();
12877        assert!(
12878            err.to_string()
12879                .contains("lifetime landing base-sync recovery limit reached"),
12880            "{err:#}"
12881        );
12882    }
12883
12884    #[tokio::test]
12885    async fn land_sync_recovery_execution_revalidation_refuses_stale_pr_head_and_rewritten_base() {
12886        let pr_url = green_pr().url;
12887        // Case A: PR head moves externally between admission and execution.
12888        {
12889            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
12890            let home = home.as_path();
12891            advance_landing_base(&state).await;
12892            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12893                url: pr_url.clone(),
12894                number: 42,
12895                open: true,
12896                head: old.clone(),
12897                base_branch: Some("main".to_owned()),
12898            });
12899            crate::land_sync_recovery_control::recover_with(
12900                &queue,
12901                home,
12902                crate::land_sync_recovery_control::Request {
12903                    run: state.id.clone(),
12904                    head: old.clone(),
12905                    actor: "cli".into(),
12906                    request: "req-stale-pr".into(),
12907                },
12908                &observer,
12909            )
12910            .await
12911            .unwrap();
12912
12913            let mut run = RunState::load_under(&state.id, home).unwrap();
12914            let foreign_head = "f".repeat(40);
12915            let forge = Scripted::new(
12916                vec![seen(&foreign_head, Checks::Green, "BEHIND", false)],
12917                vec![],
12918            );
12919            land_with(&mut run, &pr_url, &forge).await.unwrap();
12920            assert_eq!(run.status, RunStatus::Blocked);
12921            assert_eq!(run.land_sync_recovery.extra_attempts, 0);
12922            assert_eq!(run.land_sync_attempts, 4);
12923            let auth = run.land_sync_recovery.authorizations.last().unwrap();
12924            assert!(auth.consumed);
12925            assert!(
12926                auth.invalidated
12927                    .as_deref()
12928                    .is_some_and(|why| why.contains("published PR head changed")),
12929                "{:?}",
12930                auth.invalidated
12931            );
12932            assert_eq!(run.pr_pushed_head.as_deref(), Some(old.as_str()));
12933        }
12934
12935        // Case B: origin/main rewritten (non-fast-forward) between admission and execution.
12936        {
12937            let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
12938            let home = home.as_path();
12939            advance_landing_base(&state).await;
12940            let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
12941                url: pr_url.clone(),
12942                number: 42,
12943                open: true,
12944                head: old.clone(),
12945                base_branch: Some("main".to_owned()),
12946            });
12947            crate::land_sync_recovery_control::recover_with(
12948                &queue,
12949                home,
12950                crate::land_sync_recovery_control::Request {
12951                    run: state.id.clone(),
12952                    head: old.clone(),
12953                    actor: "cli".into(),
12954                    request: "req-rewritten-base".into(),
12955                },
12956                &observer,
12957            )
12958            .await
12959            .unwrap();
12960
12961            // Persist consumption before the rewrite, as if the driver crashed
12962            // between granting the attempt and starting the rebase.
12963            let mut consumed = RunState::load_under(&state.id, home).unwrap();
12964            let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12965            assert!(matches!(
12966                prepare_land_sync_recovery(&mut consumed, &pr_url, &forge)
12967                    .await
12968                    .unwrap(),
12969                LandSyncPrep::Continue(Some(_))
12970            ));
12971            assert_eq!(consumed.land_sync_attempts, 4);
12972
12973            // Rewrite origin/main by amending the latest base commit and force-pushing.
12974            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
12975            std::fs::write(state.repo.join("advance"), "rewritten").unwrap();
12976            git::git(&state.repo, &["add", "."]).await.unwrap();
12977            git::git(&state.repo, &["commit", "--amend", "-m", "rewritten base"])
12978                .await
12979                .unwrap();
12980            git::git(&state.repo, &["push", "--force", "origin", "main"])
12981                .await
12982                .unwrap();
12983            git::git(&state.repo, &["checkout", "winner"])
12984                .await
12985                .unwrap();
12986
12987            let mut run = RunState::load_under(&state.id, home).unwrap();
12988            let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
12989            land_with(&mut run, &pr_url, &forge).await.unwrap();
12990            assert_eq!(run.status, RunStatus::Blocked);
12991            assert_eq!(run.land_sync_recovery.extra_attempts, 1);
12992            assert_eq!(run.land_sync_attempts, 4);
12993            assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
12994            let auth = run.land_sync_recovery.authorizations.last().unwrap();
12995            assert!(auth.consumed);
12996            assert!(
12997                auth.invalidated
12998                    .as_deref()
12999                    .is_some_and(|why| why.contains("does not fast-forward")),
13000                "{:?}",
13001                auth.invalidated
13002            );
13003            assert!(run.land_sync_exhausted());
13004            assert_eq!(run.land_sync_budget(), 4);
13005            let mut held = queue
13006                .list()
13007                .into_iter()
13008                .find(|t| t.execution_runs().last() == Some(&run.id))
13009                .unwrap();
13010            held.hold_machine(Some("recovery scope changed".into()));
13011            queue.put(&mut held).unwrap();
13012            crate::land_sync_recovery_control::recover_with(
13013                &queue,
13014                home,
13015                crate::land_sync_recovery_control::Request {
13016                    run: run.id.clone(),
13017                    head: old.clone(),
13018                    actor: "cli".into(),
13019                    request: "req-rewritten-base-new-approval".into(),
13020                },
13021                &observer,
13022            )
13023            .await
13024            .unwrap();
13025            let mut resumed = RunState::load_under(&run.id, home).unwrap();
13026            let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
13027            assert!(matches!(
13028                prepare_land_sync_recovery(&mut resumed, &pr_url, &forge)
13029                    .await
13030                    .unwrap(),
13031                LandSyncPrep::Continue(Some(_))
13032            ));
13033            assert_eq!(resumed.land_sync_recovery.extra_attempts, 2);
13034            assert_eq!(resumed.land_sync_budget(), 5);
13035            assert_eq!(resumed.land_sync_attempts, 4);
13036            assert!(
13037                resumed.land_sync_recovery.authorizations[0]
13038                    .invalidated
13039                    .is_some()
13040            );
13041        }
13042    }
13043
13044    #[tokio::test]
13045    async fn land_sync_recovery_restart_after_consume_continues_without_double_grant() {
13046        let (_tmp, home, queue, _task, state, old) = legacy_exhausted_landing_fixture().await;
13047        let home = home.as_path();
13048        let pr_url = green_pr().url;
13049        advance_landing_base(&state).await;
13050        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13051            url: pr_url.clone(),
13052            number: 42,
13053            open: true,
13054            head: old.clone(),
13055            base_branch: Some("main".to_owned()),
13056        });
13057        crate::land_sync_recovery_control::recover_with(
13058            &queue,
13059            home,
13060            crate::land_sync_recovery_control::Request {
13061                run: state.id.clone(),
13062                head: old.clone(),
13063                actor: "cli".into(),
13064                request: "req-crash-after-consume".into(),
13065            },
13066            &observer,
13067        )
13068        .await
13069        .unwrap();
13070
13071        // Simulate consuming the authorization and crashing right before rebase starts.
13072        let mut crashed = RunState::load_under(&state.id, home).unwrap();
13073        let initial_forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
13074        let prep = prepare_land_sync_recovery(&mut crashed, &pr_url, &initial_forge)
13075            .await
13076            .unwrap();
13077        assert!(matches!(prep, LandSyncPrep::Continue(Some(_))));
13078        assert_eq!(crashed.land_sync_recovery.extra_attempts, 1);
13079        assert_eq!(crashed.land_sync_attempts, 4);
13080        assert!(crashed.land_sync_recovery.authorizations[0].consumed);
13081
13082        // An unreadable base is not proof that the authorized lineage changed.
13083        let remote = git::git(&state.repo, &["remote", "get-url", "origin"])
13084            .await
13085            .unwrap();
13086        git::git(
13087            &state.repo,
13088            &["remote", "set-url", "origin", "missing-local-origin"],
13089        )
13090        .await
13091        .unwrap();
13092        let mut interrupted = RunState::load_under(&state.id, home).unwrap();
13093        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
13094        assert!(matches!(
13095            prepare_land_sync_recovery(&mut interrupted, &pr_url, &forge)
13096                .await
13097                .unwrap(),
13098            LandSyncPrep::Stop(_)
13099        ));
13100        assert!(
13101            interrupted.land_sync_recovery.authorizations[0]
13102                .invalidated
13103                .is_none()
13104        );
13105        assert_eq!(interrupted.land_sync_attempts, 4);
13106        git::git(&state.repo, &["remote", "set-url", "origin", remote.trim()])
13107            .await
13108            .unwrap();
13109        let mut held = queue
13110            .list()
13111            .into_iter()
13112            .find(|t| t.execution_runs().last() == Some(&state.id))
13113            .unwrap();
13114        held.hold_machine(Some("base observation failed".into()));
13115        queue.put(&mut held).unwrap();
13116        assert!(crate::resume::pin_queued(&queue, &state.id, None, None).unwrap());
13117        let queued = queue.get(&held.id).unwrap();
13118        assert!(matches!(
13119            crate::land_sync_recovery::dispatch_check_with(&queue, home, &queued, &observer).await,
13120            crate::land_sync_recovery::DispatchDecision::Proceed
13121        ));
13122
13123        // Reload after restart and run land_with: uses the 1 already-granted attempt, never double-grants.
13124        let mut restarted = RunState::load_under(&state.id, home).unwrap();
13125        let mut forge = Scripted::new(
13126            vec![
13127                seen(&old, Checks::Green, "BEHIND", false),
13128                seen(&old, Checks::Green, "BEHIND", false),
13129                seen("@published", Checks::Green, "CLEAN", false),
13130            ],
13131            vec![],
13132        );
13133        forge.public_repo = Some(restarted.repo.clone());
13134        land_with(&mut restarted, &pr_url, &forge).await.unwrap();
13135        assert_eq!(restarted.land_sync_recovery.extra_attempts, 1);
13136        assert_eq!(restarted.land_sync_attempts, 5);
13137        assert_eq!(restarted.land_sync_recovery.authorizations.len(), 1);
13138        assert!(!restarted.land_sync_pending);
13139    }
13140
13141    #[tokio::test]
13142    async fn land_sync_recovery_dispatch_revalidation_refuses_stale_and_superseded_state() {
13143        // 1. Without authorization, dispatch holds without spending budget.
13144        let (_tmp, home, queue, task, state, old) = legacy_exhausted_landing_fixture().await;
13145        let home = home.as_path();
13146        let pr_url = green_pr().url;
13147        let observer = StaticPrObserver(crate::land_sync_recovery::ObservedPr {
13148            url: pr_url,
13149            number: 42,
13150            open: true,
13151            head: old.clone(),
13152            base_branch: Some("main".to_owned()),
13153        });
13154        assert!(matches!(
13155            crate::land_sync_recovery::dispatch_check_with(&queue, home, &task, &observer).await,
13156            crate::land_sync_recovery::DispatchDecision::Hold { .. }
13157        ));
13158
13159        // 2. Admit authorization, then supersede with a newer owner decision before dispatch.
13160        crate::land_sync_recovery_control::recover_with(
13161            &queue,
13162            home,
13163            crate::land_sync_recovery_control::Request {
13164                run: state.id.clone(),
13165                head: old.clone(),
13166                actor: "cli".into(),
13167                request: "req-dispatch-superseded".into(),
13168            },
13169            &observer,
13170        )
13171        .await
13172        .unwrap();
13173        let mut t = queue.get(&task.id).unwrap();
13174        t.operator_decided_at = Some(
13175            t.operator_decided_at.unwrap_or_else(jiff::Timestamp::now)
13176                + jiff::SignedDuration::from_secs(10),
13177        );
13178        queue.put(&mut t).unwrap();
13179        let decision =
13180            crate::land_sync_recovery::dispatch_check_with(&queue, home, &t, &observer).await;
13181        match decision {
13182            crate::land_sync_recovery::DispatchDecision::Hold {
13183                reason,
13184                state: updated,
13185            } => {
13186                assert!(
13187                    reason.contains("newer owner decision superseded"),
13188                    "{reason}"
13189                );
13190                let auth = updated.land_sync_recovery.authorizations.last().unwrap();
13191                assert!(auth.consumed);
13192                assert!(auth.invalidated.is_some());
13193                assert_eq!(updated.land_sync_recovery.extra_attempts, 0);
13194            }
13195            crate::land_sync_recovery::DispatchDecision::Proceed => {
13196                panic!("superseded authorization must be refused at dispatch");
13197            }
13198        }
13199    }
13200}