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                    && (a.head.eq_ignore_ascii_case(head)
1764                        || q.resolution()
1765                            .as_deref()
1766                            .is_some_and(crate::merge_decision::stops))
1767            })
1768    });
1769    let reusable = match reusable {
1770        Some(q) if merge_consent_superseded(state, &q)? => None,
1771        other => other,
1772    };
1773    if reusable.is_none() {
1774        for stale in store.list_for_effects().into_iter().filter(|q| {
1775            q.run == state.id
1776                && q.node == APPROVAL_NODE
1777                && q.status.open()
1778                && !store.held_reply(&q.id)
1779        }) {
1780            let why =
1781                "the pull request head or operator decision changed; asked again for approval";
1782            if let Err(e) = store.update(&stale.id, |q| {
1783                q.abandon(why);
1784                Ok(())
1785            }) {
1786                tracing::warn!("could not retire the superseded approval question: {e:#}");
1787            }
1788        }
1789    }
1790
1791    let q = match reusable {
1792        Some(mut q) => {
1793            if upgrade_repair_choice(&mut q, state) {
1794                q = store
1795                    .update(&q.id, |current| {
1796                        upgrade_repair_choice(current, state);
1797                        Ok(())
1798                    })?
1799                    .0;
1800            }
1801            q
1802        }
1803        None => {
1804            let worktree = match state.winner() {
1805                Some(w) => w.worktree.clone(),
1806                None => state.repo.clone(),
1807            };
1808            // The diff is built from the commit being approved, not from the
1809            // branch name, which may already point somewhere else.
1810            let head = if head.is_empty() {
1811                state
1812                    .winner()
1813                    .map_or_else(|| "HEAD".to_owned(), |w| w.branch.clone())
1814            } else {
1815                head.to_owned()
1816            };
1817            // The diff is against what the remote's base holds, never the
1818            // local branch of that name; unreadable means less evidence.
1819            let remote = &state.config.merge.remote;
1820            let tracking = format!("{remote}/{}", state.base_branch);
1821            let base = if git::rev_exists(&worktree, &tracking).await {
1822                tracking
1823            } else {
1824                String::new()
1825            };
1826            let range = format!("{base}...{head}");
1827            // A failed `git` must not decide the merge: the panel degrades to
1828            // less evidence and the owner still chooses. Merging because the
1829            // diff could not be read would be the worst of both.
1830            let numstat = if base.is_empty() {
1831                String::new()
1832            } else {
1833                git::git_raw(&worktree, &["diff", "--numstat", "-M", &range])
1834                    .await
1835                    .map(|o| o.stdout)
1836                    .unwrap_or_default()
1837            };
1838            let diff = if base.is_empty() {
1839                String::new()
1840            } else {
1841                git::diff(&worktree, &base, &head).await.unwrap_or_default()
1842            };
1843            let commits: Vec<String> = if base.is_empty() {
1844                Vec::new()
1845            } else {
1846                git::git_raw(
1847                    &worktree,
1848                    &[
1849                        "log",
1850                        "--reverse",
1851                        "--format=%s",
1852                        &format!("{base}..{head}"),
1853                    ],
1854                )
1855                .await
1856                .map(|o| o.stdout)
1857                .unwrap_or_default()
1858                .lines()
1859                .filter(|l| !l.trim().is_empty())
1860                .map(str::to_owned)
1861                .collect()
1862            };
1863
1864            let w = words(&state.config.graph.language);
1865            let html = approval_panel(state, pr, &numstat, &diff, &commits, subject);
1866            let mut fresh = ask::Question::new(
1867                state.id.clone(),
1868                APPROVAL_NODE.to_owned(),
1869                "land".to_owned(),
1870                w.approval_summary(pr.number, subject),
1871                format!(
1872                    "{}\n\n{}",
1873                    approval_evidence(state),
1874                    w.approval_detail(&pr.url, &state.base_branch, subject, contested)
1875                ),
1876                approval_choices(state),
1877            );
1878            fresh.merge_target = Some(crate::merge_decision::Target {
1879                pr: pr.url.clone(),
1880                head: head.clone(),
1881                language: state.config.graph.language.clone(),
1882            });
1883            if fresh.choices.iter().any(|c| c == REPAIR) {
1884                fresh.actions.insert(
1885                    REPAIR.to_owned(),
1886                    ask::ChoiceAction::Resume {
1887                        run: state.id.clone(),
1888                    },
1889                );
1890                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.");
1891            }
1892            for choice in fresh.choices.clone() {
1893                if crate::merge_decision::stops(&choice)
1894                    && choice != HOLD
1895                    && choice != crate::merge_decision::DISMISS
1896                {
1897                    fresh.actions.insert(
1898                        choice,
1899                        ask::ChoiceAction::Resume {
1900                            run: state.id.clone(),
1901                        },
1902                    );
1903                }
1904            }
1905            store
1906                .put_panel(&mut fresh, &html, &[])
1907                .context("write the merge approval panel")?;
1908            store
1909                .put_executable(&mut fresh)
1910                .context("file the merge approval question")?;
1911            state.land_approval = Some(LandApproval {
1912                question: fresh.id.clone(),
1913                head: head.clone(),
1914            });
1915            state.event(
1916                "land",
1917                format!("asking for merge approval ({})", fresh.short()),
1918            );
1919            state.save()?;
1920            if let Err(e) = ask::notify(&state.config.notify, &fresh).await {
1921                // A broken webhook is not a reason to lose the merge: the
1922                // question is already on disk and the web UI already shows
1923                // it, so the operator still has a way in.
1924                tracing::warn!(
1925                    "could not notify about merge approval question {}: {e:#} - \
1926                     the web UI is the only surface for it now",
1927                    fresh.short()
1928                );
1929            }
1930            fresh
1931        }
1932    };
1933
1934    Ok(match q.status {
1935        ask::QuestionStatus::Open => ApprovalGate::Pending,
1936        // Nobody answered before `state.config.graph.answer_timeout` passed,
1937        // or the question was closed with no decision recorded underneath
1938        // this run - either way there is nothing left to wait on.
1939        ask::QuestionStatus::Abandoned => ApprovalGate::Held,
1940        // The merge gate does not speak `--thread`: an owner who talked back
1941        // instead of choosing never reaches `Answered`, so this arm only
1942        // ever sees an actual decision.
1943        ask::QuestionStatus::Answered => match approval(q.resolution().as_deref()) {
1944            Approval::Merge => ApprovalGate::Approved,
1945            Approval::Repair if !state.reviews.is_empty() => {
1946                if !state.merge_repairs.iter().any(|r| r.question == q.id) {
1947                    state.merge_repairs.push(crate::run::MergeRepair {
1948                        question: q.id.clone(),
1949                        head: head.to_owned(),
1950                        pr: pr.url.clone(),
1951                        reviews: state.reviews.clone(),
1952                        gate: state.gate.clone(),
1953                        gate_head: state.gate_head.clone(),
1954                        gate_fixes: state.gate_fixes.clone(),
1955                        pre_gate: state.pre_gate.clone(),
1956                        phase: crate::run::MergeRepairPhase::Requested,
1957                        failure: None,
1958                    });
1959                    state.land_approval = None;
1960                    state.event(
1961                        "repair",
1962                        "owner requested fix findings and re-review; merge is not approved",
1963                    );
1964                    state.save()?;
1965                }
1966                ApprovalGate::Repair
1967            }
1968            Approval::Repair | Approval::Hold => ApprovalGate::Held,
1969        },
1970    })
1971}
1972
1973/// Fold a rollup's entries into one verdict plus the failing checks' labels.
1974/// No I/O. An empty rollup is `Unknown`, never green.
1975fn rollup_verdict(rollup: &[GhCheck]) -> (Checks, Vec<String>) {
1976    let mut failing = Vec::new();
1977    let mut pending = false;
1978    let mut unknown = false;
1979    for check in rollup {
1980        match check.verdict() {
1981            Verdict::Pass => {}
1982            Verdict::Pending => pending = true,
1983            Verdict::Fail => failing.push(check.label()),
1984            Verdict::Unknown => unknown = true,
1985        }
1986    }
1987    let checks = if rollup.is_empty() {
1988        Checks::Unknown
1989    } else if pending {
1990        Checks::Pending
1991    } else if !failing.is_empty() {
1992        Checks::Red
1993    } else if unknown {
1994        Checks::Unknown
1995    } else {
1996        Checks::Green
1997    };
1998    (checks, failing)
1999}
2000
2001/// Parse `gh pr view --json url,number,state,statusCheckRollup,reviews,comments`
2002/// output into a [`PrState`]. No I/O.
2003pub fn parse_pr(json: &str) -> Result<PrState> {
2004    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2005    let state = match raw.state.to_ascii_uppercase().as_str() {
2006        "OPEN" => PrLifecycle::Open,
2007        "MERGED" => PrLifecycle::Merged,
2008        "CLOSED" => PrLifecycle::Closed,
2009        other => bail!("unknown pull request state `{other}`"),
2010    };
2011
2012    let (checks, failing) = rollup_verdict(&raw.status_check_rollup);
2013
2014    let mut review_comments = Vec::new();
2015    for r in raw.reviews {
2016        push_if_outstanding(
2017            &mut review_comments,
2018            ReviewComment {
2019                author: r.author.login,
2020                path: None,
2021                line: None,
2022                body: r.body,
2023            },
2024        );
2025    }
2026    for c in raw.comments {
2027        push_if_outstanding(
2028            &mut review_comments,
2029            ReviewComment {
2030                author: c.author.login,
2031                path: None,
2032                line: None,
2033                body: c.body,
2034            },
2035        );
2036    }
2037
2038    Ok(PrState {
2039        url: raw.url,
2040        number: raw.number,
2041        state,
2042        checks,
2043        failing,
2044        review_comments,
2045        blocking: Blocking::of(&raw.merge_state_status),
2046    })
2047}
2048
2049/// One rollup entry as the release watcher reads it.
2050#[derive(Debug, Clone, PartialEq, Eq)]
2051pub(crate) struct CheckView {
2052    pub name: String,
2053    pub verdict: Verdict,
2054    /// Workflow run behind the check, when its url names one.
2055    pub run: Option<String>,
2056    pub url: Option<String>,
2057}
2058
2059/// A pull request's lifecycle, head commit and per-check verdicts, without
2060/// [`rollup_verdict`]'s aggregation (a pending check anywhere hides a failure
2061/// from it, which is exactly what the release watcher must not inherit).
2062#[derive(Debug, Clone, PartialEq, Eq)]
2063pub(crate) struct RollupView {
2064    pub url: String,
2065    pub number: u64,
2066    pub state: PrLifecycle,
2067    pub head: String,
2068    pub checks: Vec<CheckView>,
2069}
2070
2071/// Parse `gh pr view --json url,number,state,headRefOid,statusCheckRollup`
2072/// output. No I/O.
2073pub(crate) fn parse_rollup(json: &str) -> Result<RollupView> {
2074    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2075    let state = match raw.state.to_ascii_uppercase().as_str() {
2076        "OPEN" => PrLifecycle::Open,
2077        "MERGED" => PrLifecycle::Merged,
2078        "CLOSED" => PrLifecycle::Closed,
2079        other => bail!("unknown pull request state `{other}`"),
2080    };
2081    let checks = raw
2082        .status_check_rollup
2083        .iter()
2084        .map(|c| CheckView {
2085            name: c.label(),
2086            verdict: c.verdict(),
2087            run: c.url().and_then(run_of),
2088            url: c.url().map(str::to_owned),
2089        })
2090        .collect();
2091    Ok(RollupView {
2092        url: raw.url,
2093        number: raw.number,
2094        state,
2095        head: raw.head_ref_oid,
2096        checks,
2097    })
2098}
2099
2100/// Read just a pull request's lifecycle state - open, merged, or closed -
2101/// with none of the checks/reviews/comments [`land`] itself needs to decide
2102/// what to do next.
2103///
2104/// For a caller that only ever wants one fact and must not risk anything
2105/// else: `magi fold --merged` uses this to confirm a URL the operator hands
2106/// it is actually a merged pull request *before* touching a run's state, so a
2107/// typo or a still-open PR fails loudly instead of quietly recording a merge
2108/// that never happened.
2109pub async fn lifecycle(repo: &Path, pr_url: &str) -> Result<PrLifecycle> {
2110    let view = gh(
2111        repo,
2112        &[
2113            "pr".to_owned(),
2114            "view".to_owned(),
2115            pr_url.to_owned(),
2116            "--json".to_owned(),
2117            "state".to_owned(),
2118        ],
2119    )
2120    .await?;
2121    if !view.0 {
2122        bail!("gh pr view {pr_url}: {}", view.1);
2123    }
2124    // `parse_pr` reads every other field of `GhPr` as its serde default
2125    // (empty string, empty vec, zero) when this narrower `--json` selection
2126    // does not carry them - harmless, since only `.state` is read back.
2127    Ok(parse_pr(&view.1)?.state)
2128}
2129
2130/// A pull request the operator merged outside of `land::land`'s own loop,
2131/// found by asking GitHub about the run's own winning branch rather than
2132/// requiring the operator to go and find the URL themselves.
2133#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2134pub struct ExternalMerge {
2135    /// The pull request's URL, ready to hand to [`correct_manual_merge`].
2136    pub url: String,
2137    /// The pull request's number.
2138    pub number: u64,
2139}
2140
2141#[derive(Debug, Deserialize)]
2142#[serde(rename_all = "camelCase")]
2143struct GhMergedPr {
2144    url: String,
2145    number: u64,
2146    merged_at: String,
2147    base_ref_name: String,
2148}
2149
2150/// Pure half of [`find_external_merge`]: given the raw `gh pr list --head
2151/// <branch> --state merged --json url,number,mergedAt,baseRefName` output,
2152/// decide whether exactly one of the pull requests it lists could actually
2153/// be *this* run's.
2154///
2155/// A branch name alone does not prove it: [`RunState::branch_for`] derives it
2156/// from the run's own short id, so a collision with some other, unrelated
2157/// task's merged pull request from a same-named branch is rare but not
2158/// impossible once branches are deleted and ids run out. Filtering on
2159/// `base_ref_name` (the branch this run actually targets) and `merged_at`
2160/// (which cannot predate the run itself) rules that case out. More than one
2161/// survivor is exactly as uninformative as zero — something this run cannot
2162/// tell apart from another — so only a unique survivor is returned.
2163fn pick_merged_pr(
2164    json: &str,
2165    base_branch: &str,
2166    created_at: Timestamp,
2167) -> Result<Option<ExternalMerge>> {
2168    pick_merged_pr_with(json, base_branch, created_at, false)
2169}
2170
2171fn pick_merged_pr_with(
2172    json: &str,
2173    base_branch: &str,
2174    created_at: Timestamp,
2175    reject_ambiguous: bool,
2176) -> Result<Option<ExternalMerge>> {
2177    let raw: Vec<GhMergedPr> =
2178        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2179    let mut matches: Vec<ExternalMerge> = Vec::new();
2180    for pr in raw {
2181        if pr.base_ref_name != base_branch {
2182            continue;
2183        }
2184        let Ok(merged_at) = pr.merged_at.parse::<Timestamp>() else {
2185            continue;
2186        };
2187        if merged_at < created_at {
2188            continue;
2189        }
2190        matches.push(ExternalMerge {
2191            url: pr.url,
2192            number: pr.number,
2193        });
2194    }
2195    anyhow::ensure!(
2196        !reject_ambiguous || matches.len() <= 1,
2197        "multiple merged pull requests match this run; merge evidence is ambiguous"
2198    );
2199    if matches.len() == 1 {
2200        Ok(matches.pop())
2201    } else {
2202        Ok(None)
2203    }
2204}
2205
2206/// What `gh pr list --head <branch> --base <base> --state open` found.
2207#[derive(Debug, Clone, PartialEq, Eq)]
2208pub enum OpenPr {
2209    /// Nothing open: the caller creates one.
2210    None,
2211    /// Exactly one: the caller adopts it instead of creating a second.
2212    One {
2213        /// The pull request's URL.
2214        url: String,
2215        /// Its current title.
2216        title: String,
2217    },
2218    /// More than one: magi does not pick between them.
2219    Many(Vec<String>),
2220}
2221
2222#[derive(Debug, Deserialize)]
2223#[serde(rename_all = "camelCase")]
2224struct GhOpenPr {
2225    // `url` and `baseRefName` are required: a record missing either must be a
2226    // parse error, not a pull request that silently fails the base filter and
2227    // reads as "none open" (which would go on to create a duplicate).
2228    url: String,
2229    #[serde(default)]
2230    title: String,
2231    base_ref_name: String,
2232    // A fork's branch of the same name is not the task head; `gh pr list --head`
2233    // matches by branch name alone, so the filter has to be ours.
2234    #[serde(default)]
2235    is_cross_repository: bool,
2236}
2237
2238/// Pure half of [`find_open_pr`]: classify the raw `--json
2239/// number,url,title,baseRefName` output. Entries whose base is not `base` are
2240/// dropped even though the query already filtered on it, so a stub or an old
2241/// `gh` that ignores `--base` cannot get a pull request into the wrong branch
2242/// adopted.
2243pub fn pick_open_pr(json: &str, base: &str) -> Result<OpenPr> {
2244    let raw: Vec<GhOpenPr> =
2245        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2246    let mut hits: Vec<GhOpenPr> = raw
2247        .into_iter()
2248        .filter(|p| p.base_ref_name == base && !p.is_cross_repository)
2249        .collect();
2250    Ok(match hits.len() {
2251        0 => OpenPr::None,
2252        1 => {
2253            let p = hits.remove(0);
2254            OpenPr::One {
2255                url: p.url,
2256                title: p.title,
2257            }
2258        }
2259        _ => OpenPr::Many(hits.into_iter().map(|p| p.url).collect()),
2260    })
2261}
2262
2263/// Open pull requests whose head is `branch` and whose base is `base`. A
2264/// failing `gh` is an error carrying its own output, never "none": guessing
2265/// there is how a duplicate gets created.
2266pub async fn find_open_pr(repo: &Path, branch: &str, base: &str) -> Result<OpenPr> {
2267    let (ok, out) = gh(
2268        repo,
2269        &[
2270            "pr".to_owned(),
2271            "list".to_owned(),
2272            "--head".to_owned(),
2273            branch.to_owned(),
2274            "--base".to_owned(),
2275            base.to_owned(),
2276            "--state".to_owned(),
2277            "open".to_owned(),
2278            "--json".to_owned(),
2279            "number,url,title,baseRefName,isCrossRepository".to_owned(),
2280        ],
2281    )
2282    .await?;
2283    if !ok {
2284        bail!("gh pr list failed: {out}");
2285    }
2286    pick_open_pr(&out, base)
2287}
2288
2289#[derive(Debug, Deserialize)]
2290#[serde(rename_all = "camelCase")]
2291struct GhPrHead {
2292    head_ref_name: String,
2293    base_ref_name: String,
2294    state: String,
2295    // Required, like `GhOpenPr`'s fields: a record that cannot say whether the
2296    // head lives in a fork must be a parse error, never "same repository".
2297    is_cross_repository: bool,
2298    // Required too: it is what ties the pull request to the commits that were
2299    // actually proven to be on the base.
2300    head_ref_oid: String,
2301}
2302
2303/// Why [`closable`] said no, and whether asking again later could say yes.
2304#[derive(Debug, Clone, PartialEq, Eq)]
2305pub struct Refusal {
2306    /// A later attempt may succeed (the head moved, the view was unreadable);
2307    /// `false` means this pull request is simply not the run's to close.
2308    pub retry: bool,
2309    /// What was wrong.
2310    pub why: String,
2311}
2312
2313impl Refusal {
2314    fn final_(why: String) -> Self {
2315        Self { retry: false, why }
2316    }
2317}
2318
2319/// Pure half of [`close_superseded_pr`]: read `gh pr view --json
2320/// headRefName,baseRefName,state,isCrossRepository` and say whether closing
2321/// is safe, `Err` carrying the reason when it is not.
2322///
2323/// Closing is outward-facing, so every property is checked on what the forge
2324/// says now, not on what magi recorded: the head must be exactly `branch` in
2325/// this repository (a fork's branch of the same name is somebody else's), the
2326/// base must be `base`, and the pull request must still be open.
2327pub fn closable(
2328    json: &str,
2329    branch: &str,
2330    base: &str,
2331    verified: &[String],
2332) -> std::result::Result<(), Refusal> {
2333    let pr: GhPrHead = serde_json::from_str(json).map_err(|e| Refusal {
2334        retry: true,
2335        why: format!("could not read the pull request ({e})"),
2336    })?;
2337    if pr.head_ref_name != branch {
2338        return Err(Refusal::final_(format!(
2339            "its head is `{}`, not this run's `{branch}`",
2340            pr.head_ref_name
2341        )));
2342    }
2343    if pr.is_cross_repository {
2344        return Err(Refusal::final_("its head lives in a fork".to_owned()));
2345    }
2346    if pr.base_ref_name != base {
2347        return Err(Refusal::final_(format!(
2348            "it targets `{}`, not `{base}`",
2349            pr.base_ref_name
2350        )));
2351    }
2352    if !pr.state.eq_ignore_ascii_case("open") {
2353        return Err(Refusal::final_(format!(
2354            "it is already {}",
2355            pr.state.to_ascii_lowercase()
2356        )));
2357    }
2358    // Last, so a pull request that is not this run's at all is reported as
2359    // such. A head that is this branch but not a commit checked against the
2360    // base (somebody pushed since) may well get checked next time: retry.
2361    if !verified.contains(&pr.head_ref_oid) {
2362        return Err(Refusal {
2363            retry: true,
2364            why: format!(
2365                "its head {} is not a commit this run checked against the base",
2366                crate::already::short_sha(&pr.head_ref_oid)
2367            ),
2368        });
2369    }
2370    Ok(())
2371}
2372
2373/// Does `remote` point at something a forge could host - a URL or an scp-style
2374/// `user@host:path` - rather than a filesystem path or nothing at all? Judged
2375/// from the URL alone, so it answers the same on every machine, whatever `gh`
2376/// happens to be installed or logged in to.
2377async fn remote_is_forge(repo: &Path, remote: &str) -> bool {
2378    let Ok(url) = git::git(repo, &["remote", "get-url", remote]).await else {
2379        return false;
2380    };
2381    is_forge_url(url.trim())
2382}
2383
2384fn is_forge_url(url: &str) -> bool {
2385    url.contains("://") && !url.starts_with("file://")
2386        || url
2387            .split_once(':')
2388            .is_some_and(|(host, _)| host.contains('@') && !host.contains(['/', '\\']))
2389}
2390
2391/// Does this `gh` failure mean there is no GitHub to ask, as opposed to a
2392/// request that failed?
2393fn forge_unavailable(message: &str) -> bool {
2394    message.contains("known GitHub host") || message.contains("spawn gh")
2395}
2396
2397/// The comment left on a pull request closed because its change is already on
2398/// the base.
2399pub fn superseded_comment(base: &str, evidence: &crate::already::Evidence) -> String {
2400    let how = match evidence.proof {
2401        crate::already::Proof::PatchId => format!(
2402            "carried by commit {} on `{base}` with the same patch",
2403            evidence.names()
2404        ),
2405        crate::already::Proof::Ancestry => {
2406            format!("already in the history of `{base}` as {}", evidence.names())
2407        }
2408        crate::already::Proof::Tree => format!(
2409            "already part of `{base}` (merging this branch changes nothing at {})",
2410            crate::already::short_sha(&evidence.tip)
2411        ),
2412    };
2413    format!(
2414        "Closing: everything this branch adds is {how}, so there is nothing left to \
2415         land. This pull request was closed automatically after that was verified; \
2416         reopen it if you disagree."
2417    )
2418}
2419
2420/// Close the open pull request for `branch`, if there is one and it is
2421/// provably this run's, with a comment naming what supersedes it. `Ok(Ok(url))` is
2422/// the URL closed; `Ok(Err(why))` is a final "nothing to close" (no pull request,
2423/// not this run's, no forge); `Err` is anything a later attempt could resolve (a
2424/// failed `gh` call, a head that moved since it was checked), which the caller
2425/// must not treat as settled.
2426///
2427/// The recorded `state.pr` is preferred, else the forge is asked for an open
2428/// pull request on `branch`; either way the candidate is re-read and passed
2429/// through [`closable`] before anything is written; `verified` lists the
2430/// commits proven to be on the base, and the pull request's head must be one.
2431pub async fn close_superseded_pr(
2432    state: &mut RunState,
2433    branch: &str,
2434    evidence: &crate::already::Evidence,
2435    verified: &[String],
2436) -> Result<std::result::Result<String, String>> {
2437    let repo = state.repo.clone();
2438    let base = state.base_branch.clone();
2439    let url = match state.pr.as_ref().filter(|p| p.state == "open") {
2440        Some(p) => p.url.clone(),
2441        // No recorded pull request. A forge that cannot be asked at all (no
2442        // GitHub remote, no `gh`) says nothing about this run, so that is
2443        // "none found"; any other lookup failure is an error, because "could
2444        // not look" is not "nothing there" and the caller must retry.
2445        None if !remote_is_forge(&repo, &state.config.merge.remote).await => {
2446            return Ok(Err(
2447                "the remote is not a forge, so there is no pull request".to_owned(),
2448            ));
2449        }
2450        None => match find_open_pr(&repo, branch, &base).await {
2451            Err(e) if forge_unavailable(&format!("{e:#}")) => {
2452                return Ok(Err(format!("no forge to ask: {e:#}")));
2453            }
2454            Err(e) => return Err(e),
2455            Ok(OpenPr::One { url, .. }) => url,
2456            Ok(OpenPr::None) => return Ok(Err("no open pull request".to_owned())),
2457            Ok(OpenPr::Many(urls)) => {
2458                return Ok(Err(format!(
2459                    "{} open pull requests name it; not choosing between them",
2460                    urls.len()
2461                )));
2462            }
2463        },
2464    };
2465    let (ok, view) = gh(
2466        &repo,
2467        &[
2468            "pr".to_owned(),
2469            "view".to_owned(),
2470            url.clone(),
2471            "--json".to_owned(),
2472            "headRefName,headRefOid,baseRefName,state,isCrossRepository".to_owned(),
2473        ],
2474    )
2475    .await?;
2476    if !ok {
2477        bail!("gh pr view {url} failed: {view}");
2478    }
2479    if let Err(refusal) = closable(&view, branch, &base, verified) {
2480        // A pull request whose head cannot be tied to what was proven is not
2481        // one to walk away from: the caller keeps the run resumable.
2482        if refusal.retry {
2483            bail!("left {url} open: {}", refusal.why);
2484        }
2485        return Ok(Err(format!("left {url} open: {}", refusal.why)));
2486    }
2487    let (ok, out) = gh(
2488        &repo,
2489        &[
2490            "pr".to_owned(),
2491            "close".to_owned(),
2492            url.clone(),
2493            "--comment".to_owned(),
2494            superseded_comment(&base, evidence),
2495        ],
2496    )
2497    .await?;
2498    if !ok {
2499        bail!("gh pr close {url} failed: {out}");
2500    }
2501    if let Some(p) = state.pr.as_mut().filter(|p| p.url == url) {
2502        p.state = "closed".to_owned();
2503    }
2504    Ok(Ok(url))
2505}
2506
2507/// `gh pr edit <url> --title <title>`, for an adopted pull request whose title
2508/// differs from the one this run computed. Only the title: the body may have
2509/// been edited by the owner and cannot be compared.
2510pub async fn set_pr_title(state: &mut RunState, repo: &Path, url: &str, title: &str) -> Result<()> {
2511    let (title, _) = crate::github_text::prepare(state, title, "");
2512    edit_pr_title(repo, url, &title).await
2513}
2514
2515/// [`set_pr_title`] for a title the owner explicitly chose to post unmodified
2516/// (`github_text::POST_ORIGINAL` or `github_text::USE_REWRITE`): the posting
2517/// gate is skipped on purpose.
2518pub async fn set_pr_title_verbatim(repo: &Path, url: &str, title: &str) -> Result<()> {
2519    edit_pr_title(repo, url, title).await
2520}
2521
2522/// Post both fields of the owner's chosen rewrite to an adopted pull request,
2523/// unmodified and without the posting gate.
2524pub async fn set_pr_text_verbatim(repo: &Path, url: &str, title: &str, body: &str) -> Result<()> {
2525    let (ok, _) = gh(
2526        repo,
2527        &[
2528            "pr".to_owned(),
2529            "edit".to_owned(),
2530            url.to_owned(),
2531            "--title".to_owned(),
2532            title.to_owned(),
2533            "--body".to_owned(),
2534            body.to_owned(),
2535        ],
2536    )
2537    .await
2538    .map_err(|_| anyhow::anyhow!("could not run gh pr edit for the chosen rewrite"))?;
2539    if !ok {
2540        // Command output may echo the chosen text; keep it out of run events.
2541        bail!("gh pr edit failed while posting the chosen rewrite");
2542    }
2543    Ok(())
2544}
2545
2546async fn edit_pr_title(repo: &Path, url: &str, title: &str) -> Result<()> {
2547    let (ok, out) = gh(
2548        repo,
2549        &[
2550            "pr".to_owned(),
2551            "edit".to_owned(),
2552            url.to_owned(),
2553            "--title".to_owned(),
2554            title.to_owned(),
2555        ],
2556    )
2557    .await?;
2558    if !ok {
2559        bail!("gh pr edit failed: {out}");
2560    }
2561    Ok(())
2562}
2563
2564/// Ask GitHub whether this run's winning candidate branch was actually merged
2565/// somewhere `land::land`'s own loop never saw — the gap `magi fold
2566/// --merged` exists to close, minus the operator having to find the URL by
2567/// hand.
2568///
2569/// `Ok(None)` covers every case where nothing can be said with confidence: no
2570/// winner decided yet (nothing to check a branch for), no merged pull request
2571/// found, or [`pick_merged_pr`] found more than one candidate and would not
2572/// guess between them. Never wired to a weaker, URL-less signal like
2573/// [`branch_is_ancestor`] — a caller wanting that has to ask for it
2574/// separately, precisely because it cannot drive an automatic correction on
2575/// its own (see that function's own doc).
2576pub async fn find_external_merge(state: &RunState) -> Result<Option<ExternalMerge>> {
2577    let Some(winner) = state.winner() else {
2578        return Ok(None);
2579    };
2580    find_external_merge_with(
2581        state,
2582        state.pr_head.as_deref().unwrap_or(&winner.branch),
2583        false,
2584    )
2585    .await
2586}
2587
2588/// Reopening needs proof of absence, not merely failure to identify one PR.
2589pub(crate) async fn find_external_merge_for_reopen(
2590    state: &RunState,
2591) -> Result<Option<ExternalMerge>> {
2592    let Some(branch) = state.pr_branch() else {
2593        anyhow::ensure!(
2594            state.pr.is_none() && state.pr_pushed_head.is_none(),
2595            "run has public PR evidence but no known branch to check"
2596        );
2597        return Ok(None);
2598    };
2599    find_external_merge_with(state, branch, true).await
2600}
2601
2602async fn find_external_merge_with(
2603    state: &RunState,
2604    branch: &str,
2605    reject_ambiguous: bool,
2606) -> Result<Option<ExternalMerge>> {
2607    let out = gh(
2608        &state.repo,
2609        &[
2610            "pr".to_owned(),
2611            "list".to_owned(),
2612            "--head".to_owned(),
2613            branch.to_owned(),
2614            "--state".to_owned(),
2615            "merged".to_owned(),
2616            "--json".to_owned(),
2617            "url,number,mergedAt,baseRefName".to_owned(),
2618        ],
2619    )
2620    .await?;
2621    if !out.0 {
2622        bail!("gh pr list --head {branch}: {}", out.1);
2623    }
2624    if reject_ambiguous {
2625        pick_merged_pr_with(&out.1, &state.base_branch, state.created_at, true)
2626    } else {
2627        pick_merged_pr(&out.1, &state.base_branch, state.created_at)
2628    }
2629}
2630
2631/// Whether `branch` is, right now, an ancestor of `base_branch` in the local
2632/// git graph — the weaker, URL-less signal that a branch landed somewhere.
2633///
2634/// Deliberately never consulted by [`find_external_merge`]: a base branch
2635/// that has moved since the run started can make an old, abandoned branch
2636/// look like an ancestor of the *current* base for reasons that have nothing
2637/// to do with a merge (a later commit that happens to supersede it, an
2638/// unrelated squash), and there is no pull request URL here to confirm
2639/// against or to land through anyway. Its only honest use is a weaker
2640/// notice — "this looks merged, go check" — never an automatic rewrite of
2641/// `status`/`merge`.
2642pub async fn branch_is_ancestor(repo: &Path, branch: &str, base_branch: &str) -> Result<bool> {
2643    let out = tokio::process::Command::new("git")
2644        .args(["merge-base", "--is-ancestor", branch, base_branch])
2645        .current_dir(repo)
2646        .quiet()
2647        .stdin(std::process::Stdio::null())
2648        .output()
2649        .await
2650        .context("spawn git merge-base --is-ancestor")?;
2651    Ok(out.status.success())
2652}
2653
2654/// Parse `host/owner/repo` out of a forge URL, with no network access.
2655///
2656/// The host is part of the slug, not discarded: `owner/repo` alone would
2657/// treat `github.example.com/o/r` and `github.com/o/r` as the same
2658/// repository, which is exactly the mix-up the same-repo guard exists to
2659/// catch. Returns `None` for anything that doesn't have a `<host>/<path>`
2660/// shape at all.
2661fn forge_slug(url: &str) -> Option<(String, &str)> {
2662    let rest = url.rsplit("://").next()?;
2663    let (host, path) = rest.split_once('/')?;
2664    if host.is_empty() {
2665        return None;
2666    }
2667    Some((host.to_ascii_lowercase(), path))
2668}
2669
2670/// Parse `host/owner/repo` out of a GitHub pull request URL, with no network
2671/// access - the first half of the same-repo guard [`correct_manual_merge`]
2672/// applies before it writes anything.
2673///
2674/// Returns `None` for anything that does not look like
2675/// `https://<host>/<owner>/<repo>/pull/<n>`, which the caller treats as
2676/// fail-closed: a URL this cannot make sense of refuses rather than guesses.
2677pub(crate) fn slug_of_pr_url(url: &str) -> Option<String> {
2678    let (host, path) = forge_slug(url)?;
2679    let mut segments = path.split('/');
2680    let owner = segments.next()?;
2681    let repo = segments.next()?;
2682    let kind = segments.next()?;
2683    if owner.is_empty() || repo.is_empty() || kind != "pull" {
2684        return None;
2685    }
2686    Some(format!("{host}/{owner}/{repo}"))
2687}
2688
2689/// Parse `host/owner/repo` out of a plain repository URL (no `/pull/<n>`
2690/// suffix), the shape `gh repo view --json url` returns - the other half of
2691/// the same-repo guard, matched against [`slug_of_pr_url`]'s output.
2692fn slug_of_repo_url(url: &str) -> Option<String> {
2693    let (host, path) = forge_slug(url)?;
2694    let mut segments = path.split('/');
2695    let owner = segments.next()?;
2696    let repo = segments.next()?;
2697    if owner.is_empty() || repo.is_empty() {
2698        return None;
2699    }
2700    Some(format!("{host}/{owner}/{repo}"))
2701}
2702
2703/// Refuse to correct a run against a pull request from a different
2704/// repository than the one it is recorded against.
2705///
2706/// This is the guard the shun/8c75 incident argued for: an operator ran
2707/// `magi fold --merged <shun PR url>` meaning to correct an old `Blocked` run
2708/// in a different repository, omitted the run id, and the id defaulted to
2709/// this machine's most recently created run - an unrelated, still-in-progress
2710/// run in a completely different repository - which then had its `status`
2711/// rewritten to `merged` from a pull request it had nothing to do with.
2712/// `correct_manual_merge` now requires an explicit id (see `magi fold`'s own
2713/// CLI help), but a mistyped or stale id could still name a run in a
2714/// different repository than the one the URL belongs to, so this checks that
2715/// independently rather than trusting the id alone.
2716///
2717/// Comparison is case-insensitive - GitHub owner/repo names are - and a
2718/// mismatch names both slugs rather than just refusing, so an operator whose
2719/// local checkout's `origin` is a fork of the repository the pull request was
2720/// opened against (a legitimate setup this cannot tell apart from a genuine
2721/// mix-up) can judge for themselves rather than being blocked with no way to
2722/// see why.
2723pub(crate) fn ensure_same_repo(run_repo_slug: &str, pr_repo_slug: &str) -> Result<()> {
2724    if run_repo_slug.eq_ignore_ascii_case(pr_repo_slug) {
2725        return Ok(());
2726    }
2727    bail!(
2728        "refusing to correct this run: it is recorded against {run_repo_slug}, but the pull \
2729         request URL belongs to {pr_repo_slug} - pass the run id whose repository the URL \
2730         actually belongs to (or, if `origin` is a fork opened against a different upstream, \
2731         verify by hand before treating this as a false positive)"
2732    );
2733}
2734
2735/// Ask the forge which `host/owner/repo` a local checkout's `origin` remote
2736/// actually resolves to, for the same-repo guard in [`correct_manual_merge`].
2737///
2738/// Asking `gh` rather than parsing `git remote -v` locally is deliberate: it
2739/// normalizes case, SSH vs. HTTPS remotes, and a renamed or transferred
2740/// repository the same way GitHub itself would recognize it, so the
2741/// comparison in [`ensure_same_repo`] is against the same canonical slug on
2742/// both sides. Reads `url` rather than `nameWithOwner` so the host is part of
2743/// the answer too - `nameWithOwner` alone cannot tell a `github.com` repo from
2744/// a same-named one on a GitHub Enterprise host.
2745async fn repo_slug(repo: &Path) -> Result<String> {
2746    let out = gh(
2747        repo,
2748        &[
2749            "repo".to_owned(),
2750            "view".to_owned(),
2751            "--json".to_owned(),
2752            "url".to_owned(),
2753        ],
2754    )
2755    .await?;
2756    if !out.0 {
2757        bail!("gh repo view --json url: {}", out.1);
2758    }
2759    #[derive(Debug, Deserialize)]
2760    struct GhRepo {
2761        url: String,
2762    }
2763    let parsed: GhRepo = serde_json::from_str(&out.1)
2764        .with_context(|| format!("parse `gh repo view` output: {}", out.1))?;
2765    slug_of_repo_url(&parsed.url)
2766        .with_context(|| format!("could not parse a host/owner/repo out of {}", parsed.url))
2767}
2768
2769/// Confirm `url` is actually a merged pull request, then rewrite `state`'s
2770/// `status` and `merge` exactly as the automatic land loop (`land::land`)
2771/// would have written them had magi opened and merged this pull request
2772/// itself.
2773///
2774/// This is `magi fold --merged`'s whole implementation, and also what the
2775/// web `fold-merged` route calls once it has a URL in hand — an operator
2776/// recovery path for a merge magi could not finish on its own: a PR title too
2777/// long for the GraphQL mutation, `gh pr create` unreachable, a stale token -
2778/// closed by hand with a pull request magi never opened and so never
2779/// recorded. Reusing `land::land` rather than writing `status`/`merge`
2780/// directly keeps this one authoritative: a merged pull request decides
2781/// `Step::Done { merged: true }` on the very first read, before any of
2782/// `land`'s own checks/fix/rebase machinery can run, which is what makes it
2783/// safe to call here even though this pull request was never magi's own.
2784///
2785/// [`ensure_same_repo`] is checked before anything else: a pull request from
2786/// a different repository than the one `state` is recorded against is
2787/// refused outright, regardless of its lifecycle. This is the guard for a
2788/// URL an *operator* hands in - the CLI or the web route - where a stale or
2789/// mistyped run id could otherwise get corrected from an unrelated
2790/// repository's pull request (see the shun/8c75 incident in `magi fold`'s own
2791/// CLI help). The automatic janitor sweep (`clean::reconcile_external_merges`)
2792/// goes through [`correct_confirmed_external_merge`] instead, which skips
2793/// this check: its `url` was never operator-supplied, it comes from
2794/// [`find_external_merge`] querying `gh` from inside `state.repo` itself, so
2795/// it is already guaranteed to name a pull request in that same repository -
2796/// re-deriving and re-checking the repository here would only be a second
2797/// `gh repo view` call that can fail for reasons that have nothing to do with
2798/// correctness (a rate limit, a network blip), turning a self-heal that would
2799/// otherwise have succeeded into a run left `Blocked` for another pass.
2800///
2801/// [`lifecycle`] is checked next and separately so a mistyped or still-open
2802/// URL fails loudly without writing anything, rather than handing an open
2803/// pull request to the full autonomous loop by accident.
2804///
2805/// Correcting `status` this way does not run `bump::after_merge`
2806/// (`src/bump.rs`): that call is made only from `graph::Runner::run_land`,
2807/// which this path never goes through. A release version bump the change
2808/// might have earned is therefore not filed automatically and has to be
2809/// requested by hand - recorded as an event on the run so the gap is visible
2810/// to whoever reads it later, not just wherever this was called from. Follow-up
2811/// tasks for findings the merge left open (`crate::followup`) *are* filed here.
2812///
2813/// Returns the status before and after, so every caller (CLI, janitor, web
2814/// route) can build its own log line or response from the same pair rather
2815/// than each re-deriving it.
2816pub async fn correct_manual_merge(
2817    state: &mut RunState,
2818    url: &str,
2819) -> Result<(RunStatus, RunStatus)> {
2820    let Some(pr_slug) = slug_of_pr_url(url) else {
2821        bail!(
2822            "could not parse an owner/repo out of {url}; refusing to guess which repository \
2823             this pull request belongs to"
2824        );
2825    };
2826    let run_slug = repo_slug(&state.repo).await?;
2827    ensure_same_repo(&run_slug, &pr_slug)?;
2828    correct_merge(state, url).await
2829}
2830
2831/// The janitor's own entry point into the same correction
2832/// [`correct_manual_merge`] performs for an operator-supplied URL, minus the
2833/// same-repo guard - see that function's own doc for why skipping it here is
2834/// safe rather than a hole: [`clean::reconcile_external_merges`] only ever
2835/// calls this with a `url` [`find_external_merge`] already found by querying
2836/// `state.repo`'s own remote, so the guard could never do anything here but
2837/// fail on its own transient errors.
2838///
2839/// [`crate::clean`] is the only caller; `pub(crate)` rather than private only
2840/// because it lives in a different module.
2841pub(crate) async fn correct_confirmed_external_merge(
2842    state: &mut RunState,
2843    url: &str,
2844) -> Result<(RunStatus, RunStatus)> {
2845    correct_merge(state, url).await
2846}
2847
2848/// Same pull request, same repository: the url, or the number within one repo.
2849fn names_same_pr(a: &RunState, url: &str, number: u64, repo: &Path) -> bool {
2850    let Some(pr) = a.pr.as_ref() else {
2851        return false;
2852    };
2853    if !url.is_empty()
2854        && pr
2855            .url
2856            .trim_end_matches('/')
2857            .eq_ignore_ascii_case(url.trim_end_matches('/'))
2858    {
2859        return true;
2860    }
2861    number > 0
2862        && pr.number == number
2863        && match (a.repo.canonicalize(), repo.canonicalize()) {
2864            (Ok(x), Ok(y)) => x == y,
2865            _ => a.repo == repo,
2866        }
2867}
2868
2869/// Rewrite `pr.state` to a final state on every run record under `home` that
2870/// `decide` picks, and report how many were rewritten.
2871///
2872/// Lifecycle writes through to other runs are deliberately narrow (task-head
2873/// ownership is recorded separately): only a **terminal** run (never one a
2874/// driver may still be writing), only a proven-stopped driver with no daemon
2875/// claim (the shared liveness judge), only a record
2876/// whose `pr.state` is still `open`, and only `merged` / `closed` ever goes in.
2877/// The record is read as folding reads it (no schema check: every bump so far
2878/// only added fields, and the whole struct round-trips) and written through
2879/// [`RunState::save_under`], the path every record uses, so nothing but
2880/// `pr.state` and an event line changes (and `updated_at`, as for any save).
2881/// A run that cannot be read or written is skipped with a warning.
2882fn rewrite_open_prs(
2883    home: &Path,
2884    decide: &mut dyn FnMut(&RunState) -> Option<PrLifecycle>,
2885) -> usize {
2886    let now = Timestamp::now();
2887    let mut changed = 0;
2888    for id in crate::run::list_ids_in(&home.join("runs")) {
2889        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2890            continue;
2891        };
2892        let path = home.join("runs").join(&id).join("run.json");
2893        let Ok(body) = std::fs::read_to_string(&path) else {
2894            continue;
2895        };
2896        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2897            continue;
2898        };
2899        if !state.status.done()
2900            || state.pr.as_ref().is_none_or(|p| p.state != "open")
2901            || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2902                != crate::run::Liveness::Dead
2903        {
2904            continue;
2905        }
2906        let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2907            continue;
2908        };
2909        if let Some(pr) = state.pr.as_mut() {
2910            pr.state = to.as_str().to_owned();
2911        }
2912        let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2913        state.event(
2914            "land",
2915            format!("recorded {url} as {}: another run settled it", to.as_str()),
2916        );
2917        match state.save_under(home) {
2918            Ok(()) => changed += 1,
2919            Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2920        }
2921    }
2922    changed
2923}
2924
2925/// A run reached a final state for its pull request: tell every other terminal
2926/// run in the same repository that names the same pull request (handed-over
2927/// predecessors, blocked attempts, anything), so their records stop saying
2928/// `open`. Best effort; `run`'s own record is the caller's.
2929pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2930    if to == PrLifecycle::Open {
2931        return;
2932    }
2933    let Some(home) = crate::run::try_home() else {
2934        return;
2935    };
2936    write_pr_state_through_in(&home, run, to);
2937}
2938
2939pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2940    let Some(pr) = run.pr.as_ref() else {
2941        return 0;
2942    };
2943    let (url, number) = (pr.url.clone(), pr.number);
2944    rewrite_open_prs(home, &mut |other| {
2945        (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2946    })
2947}
2948
2949/// Terminal runs whose record still says their pull request is open, as
2950/// `(run id, repo, url)`, for [`repair_stale_pr_states`].
2951pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
2952    let now = Timestamp::now();
2953    let mut out = Vec::new();
2954    for id in crate::run::list_ids_in(&home.join("runs")) {
2955        let path = home.join("runs").join(&id).join("run.json");
2956        let Ok(body) = std::fs::read_to_string(&path) else {
2957            continue;
2958        };
2959        let Ok(state) = serde_json::from_str::<RunState>(&body) else {
2960            continue;
2961        };
2962        if let Some(pr) = state.pr.as_ref()
2963            && state.status.done()
2964            && pr.state == "open"
2965            && !pr.url.is_empty()
2966            && !crate::daemon::is_working_on(home, &id, now)
2967        {
2968            out.push((id, state.repo.clone(), pr.url.clone()));
2969        }
2970    }
2971    out
2972}
2973
2974/// Apply forge answers (`pr url -> state`) to every stale terminal record.
2975/// A url with no answer (the forge was unreadable) changes nothing.
2976pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
2977    rewrite_open_prs(home, &mut |s| {
2978        s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
2979    })
2980}
2981
2982/// One-time (and idempotent) repair of records that froze an `open` pull
2983/// request: ask the forge about each distinct pull request that a terminal run
2984/// still calls open - at most `max_lookups` of them - and rewrite the merged
2985/// and closed ones. A genuinely open pull request is left alone, and a lookup
2986/// that fails is "unknown, change nothing". Returns `(records rewritten,
2987/// lookups that failed)`.
2988pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
2989    let mut known = BTreeMap::new();
2990    let mut failed = 0;
2991    let mut seen = BTreeSet::new();
2992    for (_, repo, url) in stale_open_prs(home) {
2993        if known.len() + failed >= max_lookups || !seen.insert(url.clone()) {
2994            continue;
2995        }
2996        match lifecycle(&repo, &url).await {
2997            Ok(state) => {
2998                known.insert(url, state);
2999            }
3000            Err(e) => {
3001                tracing::warn!("repair pr state of {url}: {e:#}");
3002                failed += 1;
3003            }
3004        }
3005    }
3006    (apply_pr_states(home, &known), failed)
3007}
3008
3009async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
3010    match lifecycle(&state.repo, url).await? {
3011        PrLifecycle::Merged => {}
3012        other => bail!(
3013            "{url} is {}, not merged; refusing to record {} as merged on a guess",
3014            other.as_str(),
3015            state.id
3016        ),
3017    }
3018    let before = state.status;
3019    if let Err(e) = land(state, url).await {
3020        // `land` sets `status` to `Landing` and saves before its first read
3021        // of the pull request — see its own doc — so a failure here (a
3022        // transient `gh` hiccup between the two forge reads this function
3023        // makes) can leave the run stuck on that in-between value with
3024        // nothing left driving it. Land it on the same terminal shape an
3025        // automated `land` failure lands on instead of leaving it stuck.
3026        state.status = RunStatus::Blocked;
3027        state.event("fold", format!("manual-merge correction failed: {e:#}"));
3028        state.save()?;
3029        return Err(e).context(format!("confirming the merge of {url}"));
3030    }
3031    state.event(
3032        "fold",
3033        "operator recorded this pull request as a manual merge; this run never \
3034         re-entered `land`, so `bump::after_merge` did not run for it - a release \
3035         bump this change might warrant has to be filed by hand",
3036    );
3037    // Unlike the bump, the findings the merge left open are filed on this
3038    // path too: nothing else would ever carry them forward.
3039    if state.status == RunStatus::Merged {
3040        crate::followup::after_merge(state, url).await;
3041    }
3042    state.save()?;
3043    Ok((before, state.status))
3044}
3045
3046/// Parse `gh api repos/{owner}/{repo}/pulls/<n>/comments` into inline review
3047/// comments. No I/O.
3048///
3049/// `gh pr view` does not surface inline comments, and inline is exactly where
3050/// both review bots put their findings - a landing loop that read only the
3051/// top-level thread would never see the thing it is supposed to fix.
3052pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3053    let raw: Vec<GhInline> =
3054        serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3055    let mut out = Vec::new();
3056    for c in raw {
3057        push_if_outstanding(
3058            &mut out,
3059            ReviewComment {
3060                author: c.user.login,
3061                path: c.path,
3062                line: c.line,
3063                body: c.body,
3064            },
3065        );
3066    }
3067    Ok(out)
3068}
3069
3070/// Keep a comment only when it asks for something.
3071///
3072/// An inline comment always does: it names a file and a line. A top-level
3073/// comment is dropped when it is empty, when it is magi's own, or when it is
3074/// [noise](is_noise).
3075fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3076    if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3077        return;
3078    }
3079    if comment.path.is_none() && is_noise(&comment.body) {
3080        return;
3081    }
3082    out.push(comment);
3083}
3084
3085/// Is this comment body machinery rather than a finding?
3086///
3087/// Two tests, both structural, because guessing from prose is how a "looks
3088/// good to me" turns into a fix round:
3089///
3090/// 1. The bot said so - the body carries one of the [`NOT_A_REVIEW`] markers
3091///    with which CodeRabbit labels its trigger notice, its walkthrough, and its
3092///    footer.
3093/// 2. It asks for nothing - once HTML comments, `<details>` blocks, headings,
3094///    horizontal rules, and the bot's own status banner are removed, every
3095///    remaining line is a task-list item. That is exactly the shape of the
3096///    comment the Claude review job posts while it is still working.
3097///
3098/// Anything else is input, including bot prose. A bot that writes a paragraph
3099/// has said something, and the fix prompt tells the fixer it may decline a
3100/// comment with an argument - a wasted sentence in a prompt is cheaper than a
3101/// missed finding.
3102pub fn is_noise(body: &str) -> bool {
3103    if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3104        return true;
3105    }
3106    let mut content = false;
3107    for line in strip_blocks(body).lines() {
3108        let line = unquote(line);
3109        if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3110            continue;
3111        }
3112        content = true;
3113        break;
3114    }
3115    !content
3116}
3117
3118/// Remove HTML comments and collapsed `<details>` blocks.
3119fn strip_blocks(body: &str) -> String {
3120    let mut out = String::with_capacity(body.len());
3121    let mut rest = body;
3122    loop {
3123        let open = ["<!--", "<details>"]
3124            .iter()
3125            .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3126            .min_by_key(|(i, _)| *i);
3127        let Some((at, tag)) = open else {
3128            out.push_str(rest);
3129            return out;
3130        };
3131        out.push_str(&rest[..at]);
3132        let after = &rest[at + tag.len()..];
3133        let close = if tag == "<!--" { "-->" } else { "</details>" };
3134        match after.find(close) {
3135            Some(end) => rest = &after[end + close.len()..],
3136            // Unterminated: the rest of the body is inside the block.
3137            None => return out,
3138        }
3139    }
3140}
3141
3142/// Strip blockquote markers, which both bots wrap their callouts in.
3143fn unquote(line: &str) -> &str {
3144    let mut s = line.trim();
3145    while let Some(rest) = s.strip_prefix('>') {
3146        s = rest.trim_start();
3147    }
3148    s.trim()
3149}
3150
3151/// `- [ ]` / `- [x]`, in any of the bullet styles GitHub renders.
3152fn is_checklist(line: &str) -> bool {
3153    let rest = line
3154        .strip_prefix("- ")
3155        .or_else(|| line.strip_prefix("* "))
3156        .unwrap_or("");
3157    let rest = rest.trim_start();
3158    matches!(
3159        rest.get(..3),
3160        Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3161    )
3162}
3163
3164/// A heading, a horizontal rule, or a callout tag - shape, never content.
3165fn is_decoration(line: &str) -> bool {
3166    line.starts_with('#')
3167        || line.starts_with("[!")
3168        || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3169}
3170
3171/// A line that is nothing but emphasis and links.
3172///
3173/// Both review jobs open with a status banner
3174/// (`**Claude finished ... in 4m 14s** —— [View job](url)`). It reads as prose
3175/// to a line-based test and asks for nothing, so it is measured the same way a
3176/// heading is: strip the markup, and if no word survives, it was decoration.
3177fn is_banner(line: &str) -> bool {
3178    let plain = drop_spans(line, "**", "**");
3179    let plain = if plain.contains("](") {
3180        drop_spans(&plain, "[", ")")
3181    } else {
3182        plain
3183    };
3184    !plain.chars().any(char::is_alphanumeric)
3185}
3186
3187/// Remove every `open` .. `close` span, including the delimiters. An
3188/// unterminated span swallows the rest of the input, which is what a reader
3189/// sees too.
3190fn drop_spans(s: &str, open: &str, close: &str) -> String {
3191    let mut out = String::with_capacity(s.len());
3192    let mut rest = s;
3193    while let Some(at) = rest.find(open) {
3194        out.push_str(&rest[..at]);
3195        let after = &rest[at + open.len()..];
3196        match after.find(close) {
3197            Some(end) => rest = &after[end + close.len()..],
3198            None => return out,
3199        }
3200    }
3201    out.push_str(rest);
3202    out
3203}
3204
3205/// The lock that keeps at most one run per repository actually moving the
3206/// base branch at a time: a rebase push, or `gh pr merge`.
3207///
3208/// Deliberately narrow. Everything else in [`land`]'s loop - watching CI,
3209/// running a fix round in the winner's own worktree, waiting on the owner's
3210/// approval - touches nothing a *different* run in the same repository could
3211/// collide with, and holding a lock across any of that would serialise one
3212/// run's CI wait (up to [`WAIT_CEILING`]) against another run's land-approval
3213/// resume, which is precisely the "must not wait on another task" property
3214/// the daemon's slot-freeing exists to give a resume. Only the two moments
3215/// that actually write to the shared base branch need mutual exclusion, and
3216/// both are brief.
3217///
3218/// One entry per repository, each its own `tokio::sync::Mutex`, so two
3219/// different repositories' runs never wait on each other. The outer
3220/// `std::sync::Mutex` guards only the map itself, held long enough to find or
3221/// insert an entry and clone its `Arc`, never across an `.await`.
3222fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3223    static LOCKS: std::sync::LazyLock<
3224        std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3225    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3226    LOCKS
3227        .lock()
3228        .unwrap_or_else(std::sync::PoisonError::into_inner)
3229        .entry(repo.to_path_buf())
3230        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3231        .clone()
3232}
3233
3234/// `owner/repo` out of a pull request url, falling back to the checkout's
3235/// directory name when the url is not the usual `host/owner/repo/pull/N`.
3236fn repo_label(repo: &Path, pr_url: &str) -> String {
3237    let parts: Vec<&str> = pr_url.split('/').collect();
3238    if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3239        && at >= 2
3240        && !parts[at - 1].is_empty()
3241        && !parts[at - 2].is_empty()
3242    {
3243        return format!("{}/{}", parts[at - 2], parts[at - 1]);
3244    }
3245    repo.file_name()
3246        .map(|n| n.to_string_lossy().into_owned())
3247        .unwrap_or_default()
3248}
3249
3250/// The operator-facing sentence for a merge that went ahead with red checks,
3251/// or `None` when the checks were not red. Judged on `checks`, not on
3252/// `failing`, which can be non-empty on a green observation.
3253fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3254    (pr.checks == Checks::Red).then(|| {
3255        let details = crate::notices::format_list(&pr.failing)
3256            .map(|names| format!(": {names}"))
3257            .unwrap_or_default();
3258        format!(
3259            "Merged {repo_name} PR #{} with red checks{details} ({})",
3260            pr.number, pr.url
3261        )
3262    })
3263}
3264
3265/// After a merge that succeeded: record which checks were red and tell the
3266/// operator. The decision to merge is already made; this only makes it audible.
3267/// Best-effort - a broken notifier never fails the run.
3268async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3269    let repo_name = repo_label(&state.repo, &pr.url);
3270    let Some(summary) = red_merge_summary(&repo_name, pr) else {
3271        return;
3272    };
3273    if let Some(rec) = state.pr.as_mut() {
3274        rec.red_at_merge = pr.failing.clone();
3275    }
3276    state.event("land", summary.clone());
3277    // The notice pages through `[notify]` itself, once, unless a question
3278    // already carries the cause.
3279    crate::notices::raise_with(
3280        crate::notices::merged_red(&state.id, &summary),
3281        &state.config.notify,
3282    );
3283}
3284
3285/// Run the loop against a real pull request until it merges or the budget runs
3286/// out.
3287///
3288/// The caller decides whether landing happens at all: this is only reached when
3289/// `graph.land` is on. Returns the last observation, so the caller can report
3290/// what magi was looking at when it stopped.
3291pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3292    land_with(state, pr_url, &GhForge).await
3293}
3294
3295/// The forge calls whose timing the loop's decisions depend on, behind a seam
3296/// so a test can script what the pull request looks like from one observation
3297/// to the next. Comments, logs and rebases stay on `gh` and `git` directly.
3298trait Forge {
3299    async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3300        let (ok, out) = gh(
3301            repo,
3302            &[
3303                "pr".into(),
3304                "close".into(),
3305                pr_url.into(),
3306                "--comment".into(),
3307                comment.into(),
3308            ],
3309        )
3310        .await?;
3311        if !ok {
3312            bail!("PR closure failed: {out}");
3313        }
3314        Ok(())
3315    }
3316    async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3317        None
3318    }
3319    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3320    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3321    async fn poll(&self);
3322    /// Rerun the failed jobs of one workflow run.
3323    async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3324    /// Unix seconds, behind the seam so a test owns the clock.
3325    fn now(&self) -> i64;
3326    /// The check contexts the base branch requires, for a stop reason only.
3327    /// `None` when they could not be read, which is not the same as none.
3328    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3329    #[allow(clippy::too_many_arguments)]
3330    async fn fix(
3331        &self,
3332        state: &mut RunState,
3333        pr: &PrState,
3334        round: usize,
3335        budget: usize,
3336        reason: &str,
3337        logs: &str,
3338    ) -> Result<Fixed>;
3339}
3340
3341struct GhForge;
3342
3343impl Forge for GhForge {
3344    async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3345        collect_ci_evidence(state, seen).await
3346    }
3347    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3348        observe(repo, pr_url).await
3349    }
3350    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3351        gh(repo, argv).await
3352    }
3353    async fn poll(&self) {
3354        tokio::time::sleep(POLL).await;
3355    }
3356    async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3357        let args = [
3358            "run".to_owned(),
3359            "rerun".to_owned(),
3360            run.to_owned(),
3361            "--failed".to_owned(),
3362        ];
3363        let (ok, out) = gh(repo, &args).await?;
3364        if !ok {
3365            bail!("gh run rerun {run}: {out}");
3366        }
3367        Ok(())
3368    }
3369    fn now(&self) -> i64 {
3370        jiff::Timestamp::now().as_second()
3371    }
3372    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3373        required_contexts_of(repo, base).await
3374    }
3375    async fn fix(
3376        &self,
3377        state: &mut RunState,
3378        pr: &PrState,
3379        round: usize,
3380        budget: usize,
3381        reason: &str,
3382        logs: &str,
3383    ) -> Result<Fixed> {
3384        fix_round(state, pr, round, budget, reason, logs).await
3385    }
3386}
3387
3388/// Percent-encode a branch name for a URL path segment (`/` included).
3389fn encode_path_segment(s: &str) -> String {
3390    let mut out = String::new();
3391    for b in s.bytes() {
3392        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3393            out.push(b as char);
3394        } else {
3395            let _ = write!(out, "%{b:02X}");
3396        }
3397    }
3398    out
3399}
3400
3401/// Read the required contexts of `base` from classic branch protection and
3402/// from rulesets, once, for a stop reason. Organisation-level rulesets that
3403/// these two endpoints do not list are missed. Any unreadable source makes the
3404/// whole answer `None`: a partial set would read as a complete one.
3405async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3406    let enc = encode_path_segment(base);
3407    let mut all = BTreeSet::new();
3408    // Classic protection answers 404 for an unprotected branch, which is
3409    // "nothing required here", not a failure to read.
3410    let classic = gh(
3411        repo,
3412        &[
3413            "api".to_owned(),
3414            format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3415        ],
3416    )
3417    .await
3418    .ok()?;
3419    if classic.0 {
3420        all.extend(parse_classic_required(&classic.1)?);
3421    } else if !classic.1.contains("404") {
3422        return None;
3423    }
3424    let rules = gh(
3425        repo,
3426        &[
3427            "api".to_owned(),
3428            format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3429        ],
3430    )
3431    .await
3432    .ok()?;
3433    if !rules.0 {
3434        return None;
3435    }
3436    all.extend(parse_ruleset_required(&rules.1)?);
3437    Some(all)
3438}
3439
3440/// `required_status_checks` of classic protection: `contexts` plus the
3441/// `checks[].context` form.
3442fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3443    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3444    let mut out = BTreeSet::new();
3445    for c in v.get("contexts")?.as_array()? {
3446        out.insert(c.as_str()?.to_owned());
3447    }
3448    for c in v
3449        .get("checks")
3450        .and_then(|c| c.as_array())
3451        .into_iter()
3452        .flatten()
3453    {
3454        if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3455            out.insert(name.to_owned());
3456        }
3457    }
3458    Some(out)
3459}
3460
3461/// `rules/branches/<base>`: every `required_status_checks` rule's contexts.
3462fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3463    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3464    let mut out = BTreeSet::new();
3465    for rule in v.as_array()? {
3466        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3467            continue;
3468        }
3469        let checks = rule
3470            .pointer("/parameters/required_status_checks")?
3471            .as_array()?;
3472        for c in checks {
3473            out.insert(c.get("context")?.as_str()?.to_owned());
3474        }
3475    }
3476    Some(out)
3477}
3478
3479/// Is the observation older than the commit a fix round pushed?
3480///
3481/// The forge takes a few seconds to move the pull request to a new head and
3482/// attach that head's check runs, and until it has, the rollup is the previous
3483/// head's - all green, which is exactly what a merge decision must not read.
3484/// An absent or different head counts as not yet: guessing "close enough"
3485/// would reopen the hole.
3486fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3487    awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3488}
3489
3490/// The commit an observation may be decided on, or `None` while it cannot be
3491/// trusted to describe one.
3492///
3493/// `None` when a pushed commit is awaited and the pull request is not on it,
3494/// when the head is unreadable, or when the rollup (`statusCheckRollup` is the
3495/// last commit's) is not the head's: that is the previous commit's checks. The
3496/// caller re-polls on `None`. A rollup that cannot be read (including one
3497/// longer than a page) leaves `rollup_head` empty, so the wait runs to
3498/// [`WAIT_CEILING`] and stops - a safe failure, never a merge.
3499fn bound_head<'a>(
3500    seen_head: &'a str,
3501    rollup_head: &str,
3502    awaiting: Option<&str>,
3503) -> Option<&'a str> {
3504    if seen_head.is_empty()
3505        || awaiting_new_head(awaiting, seen_head)
3506        || !rollup_head.eq_ignore_ascii_case(seen_head)
3507    {
3508        return None;
3509    }
3510    Some(seen_head)
3511}
3512
3513/// What a refused `gh pr merge` means.
3514#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3515enum Refused {
3516    /// An open PR on the observed head has a proven stale base.
3517    Behind,
3518    /// The branch policy is not satisfied *yet*: go back to waiting.
3519    Pending,
3520    /// Checks have settled and the merge state still says no, seen for the
3521    /// first time. The forge updates `mergeStateStatus` a moment after the last
3522    /// check finishes, so one more look is allowed before believing it.
3523    Recheck,
3524    /// Nothing is in flight and the policy still refuses: a person has to
3525    /// supply what it asks for (a review, say).
3526    Final,
3527}
3528
3529/// Judged from the pull request's state after the refusal, never from the
3530/// refusal's wording, which belongs to the forge and changes.
3531fn classify_refusal(
3532    after: Option<&Seen>,
3533    rechecked: bool,
3534    observed_head: &str,
3535    ci: CiExpectation,
3536) -> Refused {
3537    let Some(after) = after else {
3538        // Unreadable is not evidence of anything; the next loop reads again.
3539        return Refused::Pending;
3540    };
3541    if after.pr.state != PrLifecycle::Open {
3542        return Refused::Final;
3543    }
3544    // The branch moved after it was observed (the forge refuses a merge pinned
3545    // to the old commit): not a verdict on anything, look again.
3546    if !after.head.eq_ignore_ascii_case(observed_head) {
3547        return Refused::Pending;
3548    }
3549    if Blocking::of(&after.merge_state) == Blocking::Behind {
3550        return Refused::Behind;
3551    }
3552    // The same binding the loop applies: checks of another commit say nothing.
3553    if bound_head(&after.head, &after.rollup_head, None).is_none() {
3554        return Refused::Pending;
3555    }
3556    let state = after.merge_state.to_ascii_uppercase();
3557    if (ci == CiExpectation::Expected
3558        && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3559        || state.is_empty()
3560        || state == "UNKNOWN"
3561    {
3562        return Refused::Pending;
3563    }
3564    if rechecked {
3565        Refused::Final
3566    } else {
3567        Refused::Recheck
3568    }
3569}
3570
3571/// Take auto-merge back from the forge and forget that it was armed.
3572///
3573/// `Err` carries the forge's message: the caller must not push or move on, as
3574/// an armed merge left behind could still fire for a commit nobody approved.
3575async fn disarm<F: Forge>(
3576    forge: &F,
3577    state: &mut RunState,
3578    repo: &Path,
3579    number: u64,
3580) -> std::result::Result<(), String> {
3581    let argv = disable_automerge_argv(number);
3582    let out = {
3583        let merge_lock = repo_merge_lock(repo);
3584        let _merge_slot = merge_lock.lock().await;
3585        forge.merge(repo, &argv).await
3586    };
3587    match out {
3588        Ok((true, _)) => {
3589            state.land_armed_head = None;
3590            state.event("land", "auto-merge disabled");
3591            state.save().map_err(|e| format!("{e:#}"))?;
3592            Ok(())
3593        }
3594        Ok((false, msg)) => Err(msg),
3595        Err(e) => Err(format!("{e:#}")),
3596    }
3597}
3598
3599/// [`stop`], first taking back an armed auto-merge so a pull request magi
3600/// gave up on does not merge on its own later. A failure to disarm is added
3601/// to the reason rather than hiding it.
3602async fn stop_disarmed<F: Forge>(
3603    forge: &F,
3604    state: &mut RunState,
3605    repo: &Path,
3606    pr: &PrState,
3607    why: &str,
3608) -> Result<()> {
3609    if state.land_armed_head.is_none() {
3610        return stop(state, repo, pr, why).await;
3611    }
3612    match disarm(forge, state, repo, pr.number).await {
3613        Ok(()) => stop(state, repo, pr, why).await,
3614        Err(e) => {
3615            let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3616            stop(state, repo, pr, &why).await
3617        }
3618    }
3619}
3620
3621/// Check the persisted card again around awaits that can outlive an owner tap.
3622fn owner_requested_stop(state: &RunState) -> Result<bool> {
3623    let Some(binding) = &state.land_approval else {
3624        return Ok(false);
3625    };
3626    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3627    Ok(q.run == state.id
3628        && q.node == APPROVAL_NODE
3629        && q.resolution()
3630            .as_deref()
3631            .is_some_and(crate::merge_decision::stops))
3632}
3633
3634/// Read stop choices before checks, repair or rebase. These are about stopping
3635/// ownership, so a changed head never cancels them as it cancels merge consent.
3636async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3637    use crate::merge_decision as md;
3638    let Some(binding) = &state.land_approval else {
3639        return Ok(false);
3640    };
3641    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3642    let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3643        return Ok(false);
3644    };
3645    if q.run != state.id || q.node != APPROVAL_NODE {
3646        bail!("stop decision names another run");
3647    }
3648    let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3649        pr: pr.url.clone(),
3650        head: binding.head.clone(),
3651        language: state.config.graph.language.clone(),
3652    });
3653    if target.pr != pr.url {
3654        bail!("stop decision names another PR");
3655    }
3656    if state.merge_decision.is_none() {
3657        state.merge_decision = Some(md::Decision {
3658            question: q.id.clone(),
3659            target,
3660            choice: choice.clone(),
3661            closed: false,
3662            replacement_run: None,
3663            replacement_pr: None,
3664        });
3665        state.save()?;
3666    }
3667    let repo = state.repo.clone();
3668    // Always disable, including arms left by an older driver.
3669    if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3670        stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3671        return Ok(true);
3672    }
3673    if choice.eq_ignore_ascii_case(HOLD) {
3674        stop(
3675            state,
3676            &repo,
3677            pr,
3678            "owner held the decision: PR left open; no further repair or merge work",
3679        )
3680        .await?;
3681        return Ok(true);
3682    }
3683    if md::selected_agent(&choice).is_some()
3684        || state
3685            .origin
3686            .as_ref()
3687            .and_then(|o| o.task.as_ref())
3688            .is_some()
3689    {
3690        let owners: Vec<_> = crate::queue::Queue::open()
3691            .list()
3692            .into_iter()
3693            .filter(|task| task.execution_runs().last() == Some(&state.id))
3694            .collect();
3695        let owner = (owners.len() == 1).then(|| &owners[0]);
3696        if !owner.is_some_and(|task| {
3697            task.execution_runs().last() == Some(&state.id)
3698                && (!task
3699                    .operator_decided_at
3700                    .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3701                    || task.resumption.as_ref().is_some_and(|release| {
3702                        release.question_id.as_deref() == Some(q.id.as_str())
3703                            && task.operator_decided_at == Some(release.at)
3704                    }))
3705        }) {
3706            stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3707            return Ok(true);
3708        }
3709    }
3710    if pr.state == PrLifecycle::Merged {
3711        stop(
3712            state,
3713            &repo,
3714            pr,
3715            "PR already merged; withdrawal/replacement cannot be applied",
3716        )
3717        .await?;
3718        return Ok(true);
3719    }
3720    let comment = format!(
3721        "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3722        q.id, choice, state.id
3723    );
3724    if pr.state == PrLifecycle::Open {
3725        if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3726            stop(
3727                state,
3728                &repo,
3729                pr,
3730                &format!(
3731                    "owner requested closure but it failed: {e}; task held, no replacement started"
3732                ),
3733            )
3734            .await?;
3735            return Ok(true);
3736        }
3737    }
3738    let confirmed = forge.view(&repo, &pr.url).await?;
3739    if confirmed.pr.state != PrLifecycle::Closed {
3740        stop(
3741            state,
3742            &repo,
3743            pr,
3744            "PR closure was not confirmed; task held, no replacement started",
3745        )
3746        .await?;
3747        return Ok(true);
3748    }
3749    *pr = confirmed.pr;
3750    state.merge_decision.as_mut().unwrap().closed = true;
3751    if let Some(record) = &mut state.pr {
3752        record.state = "closed".into();
3753    }
3754    state.status = RunStatus::Superseded;
3755    state.merge = Some(MergeOutcome {
3756        mode: MergeMode::Pr,
3757        ok: false,
3758        detail: format!("owner decision: {choice}; PR closure confirmed"),
3759        empty: false,
3760    });
3761    state.event(
3762        "land",
3763        format!(
3764            "{} applied: PR closure confirmed; old execution retired",
3765            choice
3766        ),
3767    );
3768    state.save()?;
3769    Ok(true)
3770}
3771
3772/// Keep an unstarted verification resumable without charging a task attempt.
3773fn check_landing_resources(
3774    state: &mut RunState,
3775    node: &str,
3776    outcomes: &[crate::run::CommandOutcome],
3777) -> Result<()> {
3778    if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
3779        let detail = format!("{}: {}", blocked.command, blocked.output_tail);
3780        state
3781            .resource_block
3782            .get_or_insert_with(|| crate::run::ResourceBlock {
3783                cause: crate::run::ResourceBlockCause::Other,
3784                node: node.into(),
3785                kind: "shared build cache".into(),
3786                detail: detail.clone(),
3787                at: jiff::Timestamp::now(),
3788            });
3789        state.event("resource", &detail);
3790        state.save()?;
3791        bail!("landing verification could not start: {detail}");
3792    }
3793    Ok(())
3794}
3795
3796/// Gate the local winner and publish that exact SHA, retaining the saved lease.
3797/// A push completed before a crash is recoverable only when its SHA was gated.
3798async fn publish_landing_head<F: Forge>(
3799    state: &mut RunState,
3800    observed: &str,
3801    pr_url: &str,
3802    forge: &F,
3803) -> Result<String> {
3804    crate::pr_head::ensure_owner(state)?;
3805    let winner = state.winner().cloned().context("landing has no winner")?;
3806    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3807    let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
3808    anyhow::ensure!(
3809        observed == expected
3810            || (observed == head
3811                && state.gate_head.as_deref() == Some(&head)
3812                && state.gate_allows_progress()),
3813        "public head moved outside this run; refusing to overwrite it"
3814    );
3815    anyhow::ensure!(
3816        git::is_clean(&winner.worktree).await?,
3817        "landing worktree is dirty"
3818    );
3819    if state.gate_head.as_deref() != Some(&head)
3820        || !state.gate_ran
3821        || !state.gate_commands_allow_progress()
3822    {
3823        state.reconcile_verification_head(&head);
3824        state.gate.clear();
3825        state.gate_head = None;
3826        state.gate_ran = false;
3827        state.pre_gate.clear();
3828        state.pre_gate_commit = None;
3829        state.save()?;
3830        let inherited = crate::repo_lock::WaitPolicy::current();
3831        let wait = crate::repo_lock::WaitPolicy::new(
3832            Duration::from_secs(state.config.graph.timeout_resource_wait),
3833            move || inherited.cancelled(),
3834        );
3835        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3836        loop {
3837            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
3838                state.gate = outcomes.clone();
3839                check_landing_resources(state, "gate", &outcomes)?;
3840            }
3841            if outcomes.iter().all(|o| o.ok()) {
3842                break;
3843            }
3844            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
3845                crate::graph::GateFix::Retry => {
3846                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3847                }
3848                crate::graph::GateFix::Stop => break,
3849                crate::graph::GateFix::Defer => {
3850                    // The repair checks e2e immediately, before the next gate.
3851                    // Preserve a cache wait here as well as below; otherwise
3852                    // the daemon charges an attempt for unstarted verification.
3853                    if let Some(e2e) = &state.gate_repair_e2e {
3854                        let outcomes = e2e.outcomes.clone();
3855                        check_landing_resources(state, "e2e", &outcomes)?;
3856                    }
3857                    bail!("landing gate repair deferred");
3858                }
3859            }
3860        }
3861        state.gate = outcomes;
3862        state.gate_ran = true;
3863        state.save()?;
3864    }
3865    let inherited = crate::repo_lock::WaitPolicy::current();
3866    let wait = crate::repo_lock::WaitPolicy::new(
3867        Duration::from_secs(state.config.graph.timeout_resource_wait),
3868        move || inherited.cancelled(),
3869    );
3870    let checked = state
3871        .gate_head
3872        .clone()
3873        .context("landing gate has no checked SHA")?;
3874    anyhow::ensure!(
3875        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3876            && git::is_clean(&winner.worktree).await?,
3877        "landing tree changed after gate"
3878    );
3879    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
3880    if matches!(e2e, crate::graph::GateFix::Defer) {
3881        let outcomes = state
3882            .gate_repair_e2e
3883            .as_ref()
3884            .context("deferred landing e2e has no outcomes")?
3885            .outcomes
3886            .clone();
3887        check_landing_resources(state, "e2e", &outcomes)?;
3888    }
3889    anyhow::ensure!(
3890        matches!(e2e, crate::graph::GateFix::Retry),
3891        "post-repair e2e has not passed on the landing head; nothing published"
3892    );
3893    anyhow::ensure!(
3894        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3895            && git::is_clean(&winner.worktree).await?,
3896        "landing tree changed during post-repair e2e"
3897    );
3898    anyhow::ensure!(
3899        crate::graph::verify_current_head(state, &winner, &wait).await?,
3900        "current head e2e has not passed; nothing published"
3901    );
3902    anyhow::ensure!(
3903        state.gate_allows_progress(),
3904        "landing gate failed; nothing published"
3905    );
3906    crate::pr_head::ensure_owner(state)?;
3907    if owner_requested_stop(state)? {
3908        bail!("owner requested stop before publication");
3909    }
3910    let current = forge.view(&state.repo, pr_url).await?;
3911    anyhow::ensure!(
3912        current.pr.state == PrLifecycle::Open,
3913        "PR closed or merged while gating; nothing published"
3914    );
3915    anyhow::ensure!(
3916        current.head == observed || current.head == checked,
3917        "PR head changed while gating; nothing published"
3918    );
3919    anyhow::ensure!(
3920        crate::foreign_checkout::write_back(state, &checked).await?,
3921        "foreign checkout delivery is blocked; see the run events"
3922    );
3923    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
3924    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
3925    let refspec = format!("{checked}:refs/heads/{public}");
3926    let lock = repo_merge_lock(&state.repo);
3927    let _slot = lock.lock().await;
3928    let pushed = git::git_raw(
3929        &winner.worktree,
3930        &["push", &lease, &state.config.merge.remote, &refspec],
3931    )
3932    .await?;
3933    anyhow::ensure!(
3934        pushed.ok(),
3935        "publishing gated landing head failed: {}",
3936        pushed.stderr
3937    );
3938    state.pr_pushed_head = Some(checked.clone());
3939    state.land_sync_pending = false;
3940    state.save()?;
3941    Ok(checked)
3942}
3943
3944/// A scratch rebase moves the winner ref before its index and files. Recover
3945/// only a tree proven unchanged since the saved start; never discard edits.
3946async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
3947    let winner = state.winner().cloned().context("landing has no winner")?;
3948    let inherited = crate::repo_lock::WaitPolicy::current();
3949    let wait = crate::repo_lock::WaitPolicy::new(
3950        Duration::from_secs(state.config.graph.timeout_resource_wait),
3951        move || inherited.cancelled(),
3952    );
3953    let _coordination = crate::repo_lock::SeatLease::operation_with(
3954        &winner.worktree,
3955        state.config.coordination.as_ref(),
3956        &wait,
3957    )
3958    .await?;
3959    if !git::is_clean(&winner.worktree).await? {
3960        let from = state
3961            .land_rebase_from
3962            .as_deref()
3963            .context("landing worktree is dirty")?;
3964        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3965        anyhow::ensure!(head != from, "landing worktree is dirty");
3966        for args in [
3967            vec!["diff", "--cached", "--quiet", from],
3968            vec!["diff", "--quiet"],
3969        ] {
3970            anyhow::ensure!(
3971                git::git_raw(&winner.worktree, &args).await?.ok(),
3972                "landing worktree has edits beyond the interrupted rebase"
3973            );
3974        }
3975        // Preserve build artifacts and local files, including ignored ones.
3976        // read-tree can overwrite ignored paths, so reject collisions with
3977        // the new tree (including file/directory conflicts) before updating.
3978        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
3979        let tracked = git::git(
3980            &winner.worktree,
3981            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
3982        )
3983        .await?;
3984        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
3985            anyhow::ensure!(
3986                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
3987                    path == local
3988                        || path
3989                            .strip_prefix(local)
3990                            .is_some_and(|rest| rest.starts_with('/'))
3991                        || local
3992                            .strip_prefix(path)
3993                            .is_some_and(|rest| rest.starts_with('/'))
3994                }),
3995                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
3996            );
3997        }
3998        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
3999    }
4000    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
4001        anyhow::ensure!(
4002            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
4003            "landing synchronization started outside the foreign checkout history"
4004        );
4005        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
4006            // The rebase's tree already includes the base and the fixer's
4007            // resolutions. Retain that exact tree, but join the pre-sync
4008            // history so delivery remains fast-forward. Keep the checkpoint
4009            // until this succeeds: a crash after rebase (or after this merge)
4010            // must recover through this same idempotent path before gating.
4011            git::git(
4012                &winner.worktree,
4013                &[
4014                    "-c",
4015                    "core.hooksPath=/dev/null",
4016                    "merge",
4017                    "--strategy=ours",
4018                    "--no-ff",
4019                    "--no-autostash",
4020                    "--no-edit",
4021                    "-m",
4022                    "Merge pre-sync history into the repaired landing tree",
4023                    from,
4024                ],
4025            )
4026            .await?;
4027        }
4028    }
4029    crate::worktree_setup::prepare_with(
4030        &state.config,
4031        &state.repo,
4032        &winner.worktree,
4033        crate::build_target::Coordination::Held(_coordination.as_ref()),
4034    )
4035    .await?;
4036    state.land_rebase_from = None;
4037    state.save()?;
4038    Ok(())
4039}
4040
4041async fn rebase_landing_worktree(
4042    state: &mut RunState,
4043    onto: &str,
4044) -> Result<crate::rebase::Rebased> {
4045    restore_landing_worktree(state).await?;
4046    let winner = state.winner().cloned().context("landing has no winner")?;
4047    let scratch = state.dir().join("rebase");
4048    let target = match state.land_sync_target.clone() {
4049        Some(target) => {
4050            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4051            target
4052        }
4053        // Older records lack the target checkpoint, but Git retains the
4054        // exact target of an interrupted operation. It is a continuation too.
4055        None if crate::rebase::checked_progress(state, &scratch, "").await? => {
4056            crate::rebase::rebase_target(&scratch).await?
4057        }
4058        None => {
4059            anyhow::ensure!(
4060                state.land_sync_attempts < state.config.graph.land_rounds,
4061                "landing base synchronization budget exhausted"
4062            );
4063            let target = git::rev_parse(&state.repo, onto).await?;
4064            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4065            state.land_sync_attempts += 1;
4066            state.land_sync_target = Some(target.clone());
4067            target
4068        }
4069    };
4070    state.land_sync_target = Some(target.clone());
4071    state.land_sync_pending = true;
4072    state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4073    state.save()?;
4074    // A continuation owns the attempt already charged above, including a
4075    // crash before the scratch rebase started. Finish its pinned base first;
4076    // a newer base must use another attempt on the next observation.
4077    let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4078    state.land_sync_target = None;
4079    state.save()?;
4080    if result == crate::rebase::Rebased::Applied {
4081        restore_landing_worktree(state).await?;
4082    }
4083    Ok(result)
4084}
4085
4086/// Reconcile a stopped landing before changing its branch. This also handles
4087/// old records whose graph status or merge detail no longer identifies land.
4088async fn resume_landing_head<F: Forge>(
4089    state: &mut RunState,
4090    observed: &str,
4091    pr_url: &str,
4092    forge: &F,
4093    reason: Option<Blocking>,
4094) -> Result<String> {
4095    crate::pr_head::ensure_owner(state)?;
4096    let winner = state.winner().cloned().context("landing has no winner")?;
4097    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4098    let expected = state
4099        .pr_pushed_head
4100        .as_deref()
4101        .or(state.gate_head.as_deref())
4102        .context("missing public head lease")?;
4103    anyhow::ensure!(
4104        observed == expected
4105            || (observed == local
4106                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4107                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4108        "public head moved outside this run; refusing to sync"
4109    );
4110    // An operator may have extended and published the winner while approval
4111    // was pending. Matching local/public history can be adopted as the lease,
4112    // but publish_landing_head must gate its new SHA before proceeding. A
4113    // remote-only or divergent update still cannot be overwritten.
4114    // Save reconciliation before rebasing again; a prior push may have reached
4115    // the remote immediately before the previous driver's last save.
4116    state.pr_pushed_head = Some(observed.to_owned());
4117    state.save()?;
4118    restore_landing_worktree(state).await?;
4119    // Recover a rebase that finished before its completion checkpoint was
4120    // saved. Restoration above has already reconciled its files and ancestry.
4121    let scratch = state.dir().join("rebase");
4122    if let Some(target) = state.land_sync_target.clone()
4123        && !crate::rebase::checked_progress(state, &scratch, "").await?
4124        && git::ancestry(&winner.worktree, &target, &local).await?
4125    {
4126        state.land_sync_target = None;
4127        state.save()?;
4128    }
4129    let remote = state.config.merge.remote.clone();
4130    let base = state.base_branch.clone();
4131    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4132    anyhow::ensure!(
4133        fetched.ok(),
4134        "cannot fetch landing base: {}",
4135        fetched.stderr
4136    );
4137    anyhow::ensure!(
4138        !owner_requested_stop(state)?,
4139        "owner requested stop before base synchronization"
4140    );
4141    let onto = format!("{remote}/{base}");
4142    let tip = git::rev_parse(&state.repo, &onto).await?;
4143    let contains_base = git::ancestry(&state.repo, &tip, &local)
4144        .await
4145        .context("could not determine whether the landing head contains the fetched base")?;
4146    anyhow::ensure!(
4147        reason != Some(Blocking::Behind) || !contains_base,
4148        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4149    );
4150    if !contains_base || reason == Some(Blocking::Conflict) {
4151        match rebase_landing_worktree(state, &onto).await? {
4152            crate::rebase::Rebased::Applied => {}
4153            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4154        }
4155    }
4156    if reason == Some(Blocking::Behind) {
4157        anyhow::ensure!(
4158            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4159            "BEHIND synchronization left the head unchanged"
4160        );
4161    }
4162    publish_landing_head(state, observed, pr_url, forge).await
4163}
4164
4165/// Share the synchronization path with structured evidence retained after a refusal.
4166async fn synchronize_landing<F: Forge>(
4167    state: &mut RunState,
4168    pr: &mut PrState,
4169    observed: &str,
4170    pr_url: &str,
4171    forge: &F,
4172) -> Result<Option<String>> {
4173    if owner_stop(state, pr, forge).await? {
4174        return Ok(None);
4175    }
4176    state.event(
4177        "land",
4178        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4179    );
4180    state.save()?;
4181    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4182    if owner_stop(state, pr, forge).await? {
4183        return Ok(None);
4184    }
4185    match synced {
4186        Ok(head) => {
4187            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4188                crate::graph::refresh_reviewed_commits(state, &branch).await;
4189            }
4190            Ok(Some(head))
4191        }
4192        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4193        Err(e) => {
4194            let repo = state.repo.clone();
4195            stop(
4196                state,
4197                &repo,
4198                pr,
4199                &format!("could not synchronize landing base: {e:#}"),
4200            )
4201            .await?;
4202            Ok(None)
4203        }
4204    }
4205}
4206
4207async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4208    crate::pr_head::ensure_owner(state)?;
4209    state.land_unrelated = None;
4210    let reopening_hold = crate::merge_decision::resumable_hold(state);
4211    let repo = state.repo.clone();
4212    let budget = state.config.graph.land_rounds;
4213    let mut round = 0usize;
4214    let ci = state.config.merge.ci.expectation();
4215    if ci == CiExpectation::Absent {
4216        state.event(
4217            "land",
4218            "CI not expected ([merge] ci = \"none\"); check status ignored",
4219        );
4220    }
4221    let mut waited = Duration::ZERO;
4222    // Comment bodies the fixer has already been shown. A comment is
4223    // outstanding until it has been handed over once; after that it is a
4224    // recorded decision, not an open question, and re-feeding it would loop the
4225    // budget away on a comment the fixer already declined with an argument.
4226    let mut shown: BTreeSet<String> = BTreeSet::new();
4227    // Await the last successfully published head, including across resumes.
4228    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4229    // Whether a settled-checks refusal has already been given its one re-look.
4230    let mut rechecked = false;
4231
4232    // Marks the run resumable through exactly this function, not through a
4233    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4234    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4235    // status specifically to know a resumed run belongs back in `land`
4236    // rather than at a second `gh pr create`. Set on every entry - fresh or
4237    // resumed - because a resume that parked here again must keep reading
4238    // `Landing`, not whatever a first pass through `merge` left behind.
4239    state.status = RunStatus::Landing;
4240    state.event("land", format!("watching {pr_url}"));
4241    state.save()?;
4242
4243    // An armed merge recorded by an earlier pass may or may not have reached
4244    // the forge (the record is written before the call). It is taken back on
4245    // the first observation, where a pull request is known to stop with.
4246    let mut resumed_armed = state.land_armed_head.is_some();
4247
4248    'landing: loop {
4249        let seen = forge.view(&repo, pr_url).await?;
4250        let mut pr = seen.pr.clone();
4251        pr.review_comments.retain(|c| !shown.contains(&c.body));
4252        state.pr = Some(crate::run::PrRecord {
4253            url: pr.url.clone(),
4254            number: pr.number,
4255            state: pr.state.as_str().to_owned(),
4256            checks: pr.checks.as_str().to_owned(),
4257            round,
4258            rounds: budget,
4259            red_at_merge: Vec::new(),
4260        });
4261        state.save()?;
4262
4263        if pr.state == PrLifecycle::Open {
4264            state.observe_branch_owner_holds(&seen.head).await;
4265            state.save()?;
4266        }
4267        crate::pr_head::ensure_owner(state)?;
4268        if reopening_hold {
4269            anyhow::ensure!(
4270                pr.state == PrLifecycle::Open,
4271                "held PR is no longer open; cannot request a fresh decision"
4272            );
4273            // An explicit resume authorizes a fresh question only. Preserve the
4274            // answered card, and never enter repair/rebase/merge on this pass.
4275            disarm(forge, state, &repo, pr.number)
4276                .await
4277                .map_err(anyhow::Error::msg)?;
4278            let previous = state.merge_decision.take();
4279            let binding = state.land_approval.take();
4280            state.config.graph.land_approval = true;
4281            let subject = merge_subject(
4282                crate::graph::landing_title(state, &seen.title),
4283                &crate::graph::landing_subject_source(state),
4284            );
4285            let contested = contested_to_ask(state);
4286            if let Err(error) =
4287                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4288            {
4289                state.merge_decision = previous;
4290                state.land_approval = binding;
4291                return Err(error);
4292            }
4293            state.end_pass_parked(crate::run::ParkCause::Question);
4294            state.parked = true;
4295            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()));
4296            state.save()?;
4297            return Ok(pr);
4298        }
4299        if owner_stop(state, &mut pr, forge).await? {
4300            return Ok(pr);
4301        }
4302
4303        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4304            // An approval already given for the same head is reused, so
4305            // nothing is asked twice. A failed disable
4306            // stops the run with the record kept: pushing on could change the
4307            // head under an arm that is still live.
4308            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4309                let why = format!(
4310                    "a previous pass may have armed auto-merge and it could not be disabled \
4311                     on resume: {e}"
4312                );
4313                stop(state, &repo, &pr, &why).await?;
4314                return Ok(pr);
4315            }
4316        }
4317
4318        // The head moved away from the one auto-merge was armed on, by
4319        // someone other than this loop. The arm is pinned and would refuse to
4320        // merge the new commit, but the approval was for the old one: take it
4321        // back and go through the normal path again.
4322        if pr.state == PrLifecycle::Open
4323            && !seen.head.is_empty()
4324            && state
4325                .land_armed_head
4326                .as_deref()
4327                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4328        {
4329            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4330                let why = format!(
4331                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4332                );
4333                stop(state, &repo, &pr, &why).await?;
4334                return Ok(pr);
4335            }
4336        }
4337
4338        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4339            // Disarming can outlive an owner answer. Consume it before our
4340            // own rebase invalidates the head shown on the decision card.
4341            if owner_stop(state, &mut pr, forge).await? {
4342                return Ok(pr);
4343            }
4344            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4345                binding.head.eq_ignore_ascii_case(&seen.head)
4346                    && ask::Questions::open()
4347                        .get_for_effects(&binding.question)
4348                        .is_ok_and(|q| {
4349                            q.run == state.id
4350                                && q.node == APPROVAL_NODE
4351                                && q.status == ask::QuestionStatus::Answered
4352                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4353                        })
4354            });
4355            if repair_answer {
4356                let subject = merge_subject(
4357                    crate::graph::landing_title(state, &seen.title),
4358                    &crate::graph::landing_subject_source(state),
4359                );
4360                let contested = contested_to_ask(state);
4361                if matches!(
4362                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4363                    ApprovalGate::Repair
4364                ) {
4365                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4366                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4367                        state.save()?;
4368                    }
4369                    return Ok(pr);
4370                }
4371            }
4372            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4373            // A stop detected before publication must apply its durable
4374            // decision, even when verification returned an error meanwhile.
4375            if owner_stop(state, &mut pr, forge).await? {
4376                return Ok(pr);
4377            }
4378            let head = synced?;
4379            awaiting_head = Some(head);
4380            waited = Duration::ZERO;
4381            rechecked = false;
4382            // Read CI and approvals afresh, never from the pre-push observation.
4383            continue;
4384        }
4385
4386        // A stale base is independent of the CI rollup. Keep the public-head
4387        // lease, but synchronize before waiting for checks on the old tree.
4388        if pr.state == PrLifecycle::Open
4389            && pr.blocking == Blocking::Behind
4390            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4391        {
4392            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4393            let Some(head) = synced else {
4394                return Ok(pr);
4395            };
4396            awaiting_head = Some(head);
4397            rechecked = false;
4398            waited = Duration::ZERO;
4399            continue;
4400        }
4401
4402        if pr.state == PrLifecycle::Open {
4403            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4404                if waited >= WAIT_CEILING {
4405                    let want = awaiting_head.as_deref().unwrap_or_default();
4406                    let why = format!(
4407                        "the pull request's checks were still not about one readable head after \
4408                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4409                         someone may have pushed over it",
4410                        WAIT_CEILING.as_secs() / 60,
4411                        if want.is_empty() { "any" } else { want },
4412                        if seen.head.is_empty() {
4413                            "nothing readable"
4414                        } else {
4415                            &seen.head
4416                        },
4417                        if seen.rollup_head.is_empty() {
4418                            "nothing readable"
4419                        } else {
4420                            &seen.rollup_head
4421                        },
4422                    );
4423                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4424                    return Ok(pr);
4425                }
4426                waited += POLL;
4427                forge.poll().await;
4428                continue;
4429            }
4430            // Reset once, when the awaited head first shows up; resetting on
4431            // every re-observation would let a standing refusal wait forever.
4432            if awaiting_head.take().is_some() {
4433                // The checks now being read belong to the new head; give them
4434                // the same grace a fresh pull request gets.
4435                waited = Duration::ZERO;
4436            }
4437        }
4438
4439        // The merge-state grace is head-bound and durable. Reruns reset the
4440        // checks clock, but must not extend this deadline across resumes.
4441        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4442            let first = state
4443                .land_unsaid
4444                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4445            if !first.0.eq_ignore_ascii_case(&seen.head) {
4446                *first = (seen.head.clone(), forge.now());
4447            }
4448            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4449            state.save()?;
4450            elapsed
4451        } else {
4452            waited
4453        };
4454        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4455        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4456            if waited >= WAIT_CEILING {
4457                stop_disarmed(
4458                    forge,
4459                    state,
4460                    &repo,
4461                    &pr,
4462                    "merge state remained unreadable; refusing to merge on a guess",
4463                )
4464                .await?;
4465                return Ok(pr);
4466            }
4467            waited += POLL;
4468            forge.poll().await;
4469            continue;
4470        }
4471
4472        // A failed workflow run is rerun once, judged by its own run rather
4473        // than by the rollup's aggregate: another run still pending, or a fix
4474        // budget already spent, must not keep a flaky failure from its one
4475        // rerun. It spends no round and no attempt.
4476        if ci == CiExpectation::Expected
4477            && pr.state == PrLifecycle::Open
4478            && state.config.graph.rerun_flaky_checks
4479        {
4480            let include_optional = pr.checks == Checks::Red
4481                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4482            let failing = rerunnable_with(&seen.contexts, include_optional);
4483            let now = forge.now();
4484            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4485                RerunStep::Rerun(runs) => {
4486                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4487                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4488                        *rec = LandReruns {
4489                            head: seen.head.clone(),
4490                            runs: BTreeMap::new(),
4491                        };
4492                    }
4493                    for run in &runs {
4494                        rec.runs.insert(run.clone(), now);
4495                    }
4496                    // Durable before the call: a restart must not
4497                    // rerun the same run twice. A save that fails
4498                    // means no rerun.
4499                    state.save()?;
4500                    let mut any = false;
4501                    for run in &runs {
4502                        let names = failing
4503                            .iter()
4504                            .filter(|(_, r)| r.as_deref() == Some(run))
4505                            .map(|(l, _)| l.as_str())
4506                            .collect::<Vec<_>>()
4507                            .join(", ");
4508                        match forge.rerun(&repo, run).await {
4509                            Ok(()) => {
4510                                any = true;
4511                                state.event(
4512                                    "land",
4513                                    format!("reran failed check(s) {names} (run {run})"),
4514                                );
4515                            }
4516                            // Stays recorded: never a retry loop.
4517                            Err(e) => state.event(
4518                                "land",
4519                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4520                            ),
4521                        }
4522                    }
4523                    state.save()?;
4524                    if any {
4525                        waited = Duration::ZERO;
4526                        forge.poll().await;
4527                        continue;
4528                    }
4529                }
4530                RerunStep::Grace => {
4531                    if waited >= WAIT_CEILING {
4532                        let why = format!(
4533                            "checks were still failing after a rerun and {} minutes",
4534                            WAIT_CEILING.as_secs() / 60
4535                        );
4536                        stop(state, &repo, &pr, &why).await?;
4537                        return Ok(pr);
4538                    }
4539                    waited += POLL;
4540                    forge.poll().await;
4541                    continue;
4542                }
4543                RerunStep::Fix => {}
4544            }
4545        }
4546
4547        let step = proposed;
4548        // Armed on exactly this head: the forge is doing the waiting. A
4549        // decision to merge (or keep waiting) is only watched, never re-armed
4550        // and never re-approved; anything else - a red check, a comment, a
4551        // conflict - falls through to its own arm, which disarms first.
4552        let armed_here = state
4553            .land_armed_head
4554            .as_deref()
4555            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4556        if armed_here && matches!(step, Step::Merge | Step::Wait) {
4557            if waited >= WAIT_CEILING {
4558                let required = if seen.base.is_empty() {
4559                    None
4560                } else {
4561                    forge.required_contexts(&repo, &seen.base).await
4562                };
4563                let why = format!(
4564                    "auto-merge was armed on {} but the pull request did not merge within {} \
4565                     minutes ({})",
4566                    seen.head,
4567                    WAIT_CEILING.as_secs() / 60,
4568                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4569                );
4570                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4571                return Ok(pr);
4572            }
4573            waited += POLL;
4574            forge.poll().await;
4575            continue;
4576        }
4577        if armed_here && !matches!(step, Step::Done { .. }) {
4578            // Not merging or waiting any more: whatever is next may change the
4579            // head or give up, and neither may leave the arm standing.
4580            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4581                let why = format!("auto-merge could not be disabled: {e}");
4582                stop(state, &repo, &pr, &why).await?;
4583                return Ok(pr);
4584            }
4585        }
4586        if pr.checks == Checks::Red
4587            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4588            && pr.review_comments.is_empty()
4589            && let Some(evidence) = forge.attribution(state, &seen).await
4590            && evidence.unrelated(&seen.head, &pr.failing)
4591        {
4592            if owner_stop(state, &mut pr, forge).await? {
4593                return Ok(pr);
4594            }
4595            // Attribution does not authorize action against an unseen push.
4596            let fresh = forge.view(&repo, pr_url).await?;
4597            if fresh.head != seen.head
4598                || fresh.rollup_head != seen.rollup_head
4599                || fresh.pr.state != PrLifecycle::Open
4600                || fresh.pr.checks != Checks::Red
4601                || fresh.pr.failing != pr.failing
4602                || fresh
4603                    .pr
4604                    .review_comments
4605                    .iter()
4606                    .any(|c| !shown.contains(&c.body))
4607            {
4608                continue;
4609            }
4610            hold_unrelated(state, &pr, evidence).await?;
4611            return Ok(pr);
4612        }
4613        match step {
4614            Step::Wait => {
4615                if waited >= WAIT_CEILING {
4616                    let why = format!(
4617                        "checks were still running after {} minutes",
4618                        WAIT_CEILING.as_secs() / 60
4619                    );
4620                    stop(state, &repo, &pr, &why).await?;
4621                    return Ok(pr);
4622                }
4623                waited += POLL;
4624                forge.poll().await;
4625            }
4626            Step::Done { merged } => {
4627                if merged {
4628                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
4629                }
4630                // Auto-merge is pinned to the approved head, but the forge's
4631                // own handling of a later push is not something magi can
4632                // see: if the pull request merged on another commit, say so
4633                // loudly rather than record a clean landing.
4634                if let Some(armed) = state.land_armed_head.take() {
4635                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
4636                        let msg = format!(
4637                            "{} merged on {} but the owner approved {armed}; review what landed",
4638                            pr.url, seen.head
4639                        );
4640                        tracing::warn!("{msg}");
4641                        state.event("land", msg);
4642                        // Only an arm left by an older build can get here.
4643                        // The wording is fixed so a repeat does not relight
4644                        // the notice.
4645                        crate::notices::raise_with(
4646                            crate::notices::Notice::warn(
4647                                &format!("merged-unapproved-head:{}", state.id),
4648                                "A pull request merged on a commit the owner did not approve; \
4649                                 review what landed",
4650                            )
4651                            .link(crate::notices::Link::Run {
4652                                id: state.id.clone(),
4653                            }),
4654                            &state.config.notify,
4655                        );
4656                    }
4657                }
4658                state.status = if merged {
4659                    RunStatus::Merged
4660                } else {
4661                    RunStatus::Ready
4662                };
4663                let detail = if merged {
4664                    format!("{} was merged", pr.url)
4665                } else {
4666                    format!("{} was closed without merging", pr.url)
4667                };
4668                state.merge = Some(MergeOutcome {
4669                    mode: MergeMode::Pr,
4670                    ok: merged,
4671                    detail: detail.clone(),
4672                    empty: false,
4673                });
4674                state.event("land", detail);
4675                state.save()?;
4676                write_pr_state_through(state, pr.state);
4677                return Ok(pr);
4678            }
4679            Step::Merge => {
4680                state.check_delivery_evidence(&seen.head)?;
4681                let subject = merge_subject(
4682                    crate::graph::landing_title(state, &seen.title),
4683                    &crate::graph::landing_subject_source(state),
4684                );
4685                // The owner sees the panel before the one irreversible step,
4686                // and an unanswered question is a hold: silence never merges.
4687                //
4688                // The dedicated policy includes existing consent and post-repair
4689                // decisions; repair choice availability never grants merge authority.
4690                let contested = contested_to_ask(state);
4691                if !approval_reasons(state).is_empty() {
4692                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
4693                        .await?
4694                    {
4695                        ApprovalGate::Approved => {}
4696                        ApprovalGate::Repair => {
4697                            // The driver consumes the saved request under the existing
4698                            // run/task claim. No merge, no second run or task.
4699                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4700                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4701                                state.save()?;
4702                            }
4703                            return Ok(pr);
4704                        }
4705                        ApprovalGate::Held => {
4706                            // Another entry point may have saved a stop after
4707                            // the first read above. Apply its durable action.
4708                            if owner_stop(state, &mut pr, forge).await? {
4709                                return Ok(pr);
4710                            }
4711                            stop(
4712                                state,
4713                                &repo,
4714                                &pr,
4715                                "the owner did not approve the merge (held or unanswered)",
4716                            )
4717                            .await?;
4718                            return Ok(pr);
4719                        }
4720                        // Filed (or still standing from an earlier visit) and
4721                        // not yet answered. Park here rather than wait: the
4722                        // question survives on disk, the daemon hands this
4723                        // run's slot to something else, and a later resume
4724                        // re-enters `land`, finds the same question, and
4725                        // either merges or stops depending on what it says
4726                        // by then.
4727                        ApprovalGate::Pending => {
4728                            state.end_pass_parked(crate::run::ParkCause::Question);
4729                            state.parked = true;
4730                            state.event(
4731                                "land",
4732                                "parked awaiting merge approval - resumes once answered",
4733                            );
4734                            state.save()?;
4735                            return Ok(pr);
4736                        }
4737                    }
4738                }
4739                // Open and past the gate above, so `seen.head` is the commit
4740                // the checks were bound to and the owner approved.
4741                //
4742                // Merge directly, bound to that commit. Auto-merge is not
4743                // armed any more: the forge checks `--match-head-commit` only
4744                // when the request is made, so an arm outlives the head it
4745                // was made for, and a push of another commit whose
4746                // requirements are met first would merge without approval.
4747                // A direct merge is checked by the forge at the moment it
4748                // happens, so only the approved head can land.
4749                let observed_head = seen.head.clone();
4750                // Read the pull request again just before: the state seen
4751                // above can be a moment old.
4752                {
4753                    let fresh = forge.view(&repo, pr_url).await.ok();
4754                    if fresh.as_ref().is_some_and(|current| {
4755                        current.pr.state == PrLifecycle::Open
4756                            && current.head.eq_ignore_ascii_case(&observed_head)
4757                            && Blocking::of(&current.merge_state) == Blocking::Behind
4758                    }) {
4759                        pr.blocking = Blocking::Behind;
4760                        let synced =
4761                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4762                                .await?;
4763                        let Some(head) = synced else {
4764                            return Ok(pr);
4765                        };
4766                        awaiting_head = Some(head);
4767                        rechecked = false;
4768                        waited = Duration::ZERO;
4769                        continue 'landing;
4770                    }
4771                    if !direct_merge_is_safe(
4772                        fresh.as_ref(),
4773                        &observed_head,
4774                        &shown,
4775                        round,
4776                        budget,
4777                        waited,
4778                        ci,
4779                    ) {
4780                        if waited >= WAIT_CEILING {
4781                            let why = "the pull request did not settle on the approved head \
4782                                       before it could be merged";
4783                            stop(state, &repo, &pr, why).await?;
4784                            return Ok(pr);
4785                        }
4786                        state.event(
4787                            "land",
4788                            "the pull request changed before merging; looking again",
4789                        );
4790                        waited += POLL;
4791                        forge.poll().await;
4792                        continue;
4793                    }
4794                }
4795                let argv = merge_argv_at(pr.number, &subject, &observed_head);
4796                let out = {
4797                    let merge_lock = repo_merge_lock(&repo);
4798                    let _merge_slot = merge_lock.lock().await;
4799                    crate::pr_head::ensure_owner(state)?;
4800                    if let Some(task_id) = state
4801                        .origin
4802                        .as_ref()
4803                        .and_then(|origin| origin.task.as_ref())
4804                    {
4805                        let task = crate::queue::Queue::open()
4806                            .get(task_id)
4807                            .context("cannot verify the task owner immediately before merge")?;
4808                        if task.execution_runs().last() != Some(&state.id)
4809                            || task.operator_held()
4810                            || task.status == crate::queue::TaskStatus::Done
4811                        {
4812                            bail!(
4813                                "task ownership or an operator hold superseded this merge approval"
4814                            );
4815                        }
4816                    }
4817                    if let Some(binding) = &state.land_approval {
4818                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
4819                        if merge_consent_superseded(state, &current)?
4820                            || current.run != state.id
4821                            || !binding.head.eq_ignore_ascii_case(&observed_head)
4822                            || approval(current.resolution().as_deref()) != Approval::Merge
4823                            || current.merge_target.as_ref().is_some_and(|t| {
4824                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
4825                            })
4826                        {
4827                            bail!(
4828                                "merge decision is stale or no longer authorizes the reviewed head"
4829                            );
4830                        }
4831                    }
4832                    forge.merge(&repo, &argv).await?
4833                };
4834                if out.0 {
4835                    // Exit 0 is not proof of a merge: with a merge queue `gh`
4836                    // enqueues (or reports the pull request already queued)
4837                    // and succeeds while it is still open. Ask the forge; an
4838                    // unreadable answer is not a confirmation either, so it
4839                    // is looked at again rather than recorded as merged.
4840                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
4841                        if c.pr.state == PrLifecycle::Merged {
4842                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
4843                            true
4844                        } else {
4845                            false
4846                        }
4847                    });
4848                    if !confirmed {
4849                        if waited >= WAIT_CEILING {
4850                            let why = "the merge request succeeded but the pull request \
4851                                       could not be confirmed merged after waiting";
4852                            stop(state, &repo, &pr, why).await?;
4853                            return Ok(pr);
4854                        }
4855                        state.event(
4856                            "land",
4857                            "merge accepted but the pull request is not confirmed merged yet; waiting",
4858                        );
4859                        state.save()?;
4860                        waited += POLL;
4861                        forge.poll().await;
4862                        continue;
4863                    }
4864                    pr.state = PrLifecycle::Merged;
4865                    state.status = RunStatus::Merged;
4866                    state.merge = Some(MergeOutcome {
4867                        mode: MergeMode::Pr,
4868                        ok: true,
4869                        detail: format!("gh {}", argv.join(" ")),
4870                        empty: false,
4871                    });
4872                    // The last `state.pr` snapshot is whatever the poll before
4873                    // this merge observed - still `open` - and nothing below
4874                    // refreshes it from GitHub again, so the UI's round rail
4875                    // would otherwise keep animating a merged run forever.
4876                    if let Some(pr_record) = state.pr.as_mut() {
4877                        pr_record.state = pr.state.as_str().to_owned();
4878                    }
4879                    state.event("land", format!("merged {} as `{subject}`", pr.url));
4880                    announce_red_merge(state, &pr).await;
4881                    state.save()?;
4882                    write_pr_state_through(state, pr.state);
4883                    return Ok(pr);
4884                }
4885                let after_seen = forge.view(&repo, pr_url).await.ok();
4886                let after = after_seen.as_ref().map(|s| s.pr.state);
4887                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
4888                    state.pr_merged_head = after_seen
4889                        .as_ref()
4890                        .map(|s| s.head.clone())
4891                        .filter(|h| !h.is_empty());
4892                    pr.state = PrLifecycle::Merged;
4893                    state.status = RunStatus::Merged;
4894                    state.merge = Some(outcome);
4895                    if let Some(pr_record) = state.pr.as_mut() {
4896                        pr_record.state = pr.state.as_str().to_owned();
4897                    }
4898                    state.event("land", format!("merged {} as `{subject}`", pr.url));
4899                    announce_red_merge(state, &pr).await;
4900                    state.save()?;
4901                    write_pr_state_through(state, pr.state);
4902                    return Ok(pr);
4903                }
4904                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
4905                match verdict {
4906                    Refused::Behind => {
4907                        pr.blocking = Blocking::Behind;
4908                        let synced =
4909                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4910                                .await?;
4911                        let Some(head) = synced else {
4912                            return Ok(pr);
4913                        };
4914                        awaiting_head = Some(head);
4915                        rechecked = false;
4916                        waited = Duration::ZERO;
4917                        continue 'landing;
4918                    }
4919                    Refused::Final => {
4920                        let merge_state = after_seen
4921                            .as_ref()
4922                            .map(|s| s.merge_state.as_str())
4923                            .filter(|m| !m.is_empty())
4924                            .unwrap_or("unknown");
4925                        // Which refusal this was decides what a person has to
4926                        // do about it, so the two are worded apart; both carry
4927                        // the forge's own message.
4928                        let why = format!(
4929                            "the merge was refused: {} (merge state: {merge_state})",
4930                            out.1
4931                        );
4932                        stop(state, &repo, &pr, &why).await?;
4933                        return Ok(pr);
4934                    }
4935                    verdict => {
4936                        // Back to the top, which re-decides and passes the
4937                        // approval gate again, a poll later. `waited` is not
4938                        // reset here: only a pushed fix restarts it, or a
4939                        // standing refusal would wait forever.
4940                        if waited >= WAIT_CEILING {
4941                            let why = format!(
4942                                "the merge was still refused after {} minutes: {}",
4943                                WAIT_CEILING.as_secs() / 60,
4944                                out.1
4945                            );
4946                            stop(state, &repo, &pr, &why).await?;
4947                            return Ok(pr);
4948                        }
4949                        if verdict == Refused::Recheck {
4950                            rechecked = true;
4951                        }
4952                        state.event(
4953                            "land",
4954                            "merge refused while the branch policy is not satisfied yet; waiting",
4955                        );
4956                        state.save()?;
4957                        waited += POLL;
4958                        forge.poll().await;
4959                    }
4960                }
4961            }
4962            Step::Rebase => {
4963                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4964                let Some(head) = synced else {
4965                    return Ok(pr);
4966                };
4967                awaiting_head = Some(head);
4968                rechecked = false;
4969                waited = Duration::ZERO;
4970                continue 'landing;
4971            }
4972            Step::GiveUp { reason } => {
4973                stop(state, &repo, &pr, &reason).await?;
4974                return Ok(pr);
4975            }
4976            Step::Fix { reason } => {
4977                round += 1;
4978                waited = Duration::ZERO;
4979                for c in &pr.review_comments {
4980                    shown.insert(c.body.clone());
4981                }
4982                state.event("land", format!("round {round}: {reason}"));
4983                state.save()?;
4984
4985                let logs = failing_logs(&repo, &seen.failing_urls).await;
4986                let was_red = pr.checks == Checks::Red;
4987                if owner_stop(state, &mut pr, forge).await? {
4988                    return Ok(pr);
4989                }
4990                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
4991                if owner_stop(state, &mut pr, forge).await? {
4992                    return Ok(pr);
4993                }
4994                match fixed {
4995                    Fixed::Committed { head } => {
4996                        // Whatever the next look shows may still be the
4997                        // previous head; see `awaiting_new_head`.
4998                        state.pr_pushed_head = Some(head.clone());
4999                        awaiting_head = Some(head);
5000                        rechecked = false;
5001                        waited = Duration::ZERO;
5002                        forge.poll().await;
5003                    }
5004                    Fixed::Declined if was_red => {
5005                        // Review comments may have required this round even
5006                        // when CI was unrelated. Once the fixer has read them,
5007                        // use the same structural attribution before charging
5008                        // a no-commit stop to the task.
5009                        if let Some(evidence) = forge.attribution(state, &seen).await
5010                            && evidence.unrelated(&seen.head, &pr.failing)
5011                        {
5012                            let fresh = forge.view(&repo, pr_url).await?;
5013                            if fresh.head != seen.head
5014                                || fresh.rollup_head != seen.rollup_head
5015                                || fresh.pr.state != PrLifecycle::Open
5016                                || fresh.pr.checks != Checks::Red
5017                                || fresh.pr.failing != pr.failing
5018                                || fresh
5019                                    .pr
5020                                    .review_comments
5021                                    .iter()
5022                                    .any(|c| !shown.contains(&c.body))
5023                            {
5024                                continue;
5025                            }
5026                            if owner_stop(state, &mut pr, forge).await? {
5027                                return Ok(pr);
5028                            }
5029                            hold_unrelated(state, &pr, evidence).await?;
5030                            return Ok(pr);
5031                        }
5032                        let why = format!(
5033                            "the fixer produced no commit while {} check(s) were failing \
5034                             ({}); stopping instead of looping on an unchanged tree",
5035                            pr.failing.len(),
5036                            pr.failing.join(", ")
5037                        );
5038                        stop(state, &repo, &pr, &why).await?;
5039                        return Ok(pr);
5040                    }
5041                    // Comment-driven round with no commit: the fixer read the
5042                    // comments and changed nothing, which is a decision it is
5043                    // allowed to make. The comments are recorded as shown, so
5044                    // the next observation sees a clean pull request.
5045                    Fixed::Declined => state.event(
5046                        "land",
5047                        format!("round {round}: fixer declined the comments, nothing committed"),
5048                    ),
5049                    Fixed::Deferred => {
5050                        // No fixer was available to judge these comments or
5051                        // checks. Keep the previous completed-round count and
5052                        // return without handing the PR off as a task failure.
5053                        state.status = RunStatus::Blocked;
5054                        state.save()?;
5055                        return Ok(pr);
5056                    }
5057                    Fixed::Failed(why) => {
5058                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5059                        return Ok(pr);
5060                    }
5061                }
5062                state.save()?;
5063            }
5064        }
5065    }
5066}
5067
5068/// Owner decision for a CI failure independently reproduced on the base.
5069pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5070
5071/// Durable machine-hold evidence, bound to one observed PR head.
5072#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5073pub struct CiHold {
5074    /// Head that exhibited the independently reproduced failures.
5075    pub head: String,
5076    /// Typed owner question controlling resumption.
5077    pub question: String,
5078    /// Complete structured facts used to attribute the failures.
5079    pub evidence: CiEvidence,
5080}
5081
5082/// Only structured forge annotations are compared, never log prose.
5083#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5084struct CiFailure {
5085    path: String,
5086    start_line: u64,
5087    end_line: u64,
5088    title: String,
5089    message: String,
5090}
5091
5092#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5093struct CiCheckEvidence {
5094    label: String,
5095    head_check: u64,
5096    base_check: u64,
5097    app: u64,
5098    run: String,
5099    base_run: String,
5100    head_failures: Vec<CiFailure>,
5101    base_failures: Vec<CiFailure>,
5102    rerun_exhausted: bool,
5103}
5104
5105/// Pinned Git diff and forge failure annotations used for CI attribution.
5106#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5107pub struct CiEvidence {
5108    head: String,
5109    base: String,
5110    changed: Vec<String>,
5111    checks: Vec<CiCheckEvidence>,
5112}
5113
5114impl CiEvidence {
5115    /// Every red check must have the same located failure on the base, outside
5116    /// the diff. Changes to CI/build configuration invalidate this inference.
5117    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5118        if self.head != head
5119            || self.base.is_empty()
5120            || failing.is_empty()
5121            || self.changed.iter().any(|p| {
5122                p.starts_with(".github/")
5123                    || p.starts_with(".config/")
5124                    || p.starts_with(".cargo/")
5125                    || matches!(
5126                        p.rsplit('/').next().unwrap_or(p),
5127                        "Cargo.toml"
5128                            | "Cargo.lock"
5129                            | "Makefile.toml"
5130                            | "build.rs"
5131                            | "rust-toolchain.toml"
5132                    )
5133            })
5134        {
5135            return false;
5136        }
5137        failing.iter().all(|label| {
5138            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5139            matches.len() == 1
5140                && matches[0].rerun_exhausted
5141                && !matches[0].head_failures.is_empty()
5142                && matches[0].head_failures.iter().all(|f| {
5143                    // Workflow-level exit-code annotations do not identify a
5144                    // failing test or source file, and prove nothing here.
5145                    !f.path.is_empty()
5146                        && !f.path.starts_with('.')
5147                        && !f.path.contains("..")
5148                        && !f.path.starts_with('/')
5149                        && !self.changed.contains(&f.path)
5150                        && matches[0].base_failures.contains(f)
5151                })
5152        })
5153    }
5154}
5155
5156async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5157    let (ok, body) = gh(repo, &["api".into(), endpoint]).await.ok()?;
5158    if !ok {
5159        return None;
5160    }
5161    serde_json::from_str(&body).ok()
5162}
5163
5164async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5165    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5166    if count == 0 || count >= 100 {
5167        return None;
5168    }
5169    let id = check.get("id")?.as_u64()?;
5170    let value = ci_json(
5171        repo,
5172        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5173    )
5174    .await?;
5175    let annotations = value.as_array()?;
5176    if annotations.len() != count as usize {
5177        return None;
5178    }
5179    annotations
5180        .iter()
5181        .filter(|a| a["annotation_level"] == "failure")
5182        .map(|a| {
5183            Some(CiFailure {
5184                path: a["path"].as_str()?.into(),
5185                start_line: a["start_line"].as_u64()?,
5186                end_line: a["end_line"].as_u64()?,
5187                title: a["title"].as_str()?.into(),
5188                message: a["message"].as_str()?.into(),
5189            })
5190        })
5191        .collect()
5192}
5193
5194async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5195    let value = ci_json(
5196        repo,
5197        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5198    )
5199    .await?;
5200    let runs = value["check_runs"].as_array()?;
5201    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5202        return None;
5203    }
5204    Some(runs.clone())
5205}
5206
5207async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5208    let repo = &state.repo;
5209    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5210    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5211        .await
5212        .ok()?;
5213    if !base.ok() {
5214        return None;
5215    }
5216    let range = format!("{}...{}", base.stdout, seen.head);
5217    // No rename detection: both old and new paths must count as changed.
5218    let diff = git::git_raw(
5219        repo,
5220        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5221    )
5222    .await
5223    .ok()?;
5224    if !diff.ok() {
5225        return None;
5226    }
5227    let head_runs = ci_runs(repo, &seen.head).await?;
5228    let base_runs = ci_runs(repo, &base.stdout).await?;
5229    let mut checks = Vec::new();
5230    for label in &seen.pr.failing {
5231        let matching = |runs: &[serde_json::Value]| {
5232            runs.iter()
5233                .filter(|r| r["name"].as_str() == Some(label))
5234                .cloned()
5235                .collect::<Vec<_>>()
5236        };
5237        let heads = matching(&head_runs);
5238        let bases = matching(&base_runs);
5239        if heads.len() != 1 || bases.len() != 1 {
5240            return None;
5241        }
5242        let h = &heads[0];
5243        let b = &bases[0];
5244        if h["conclusion"] != "failure"
5245            || b["conclusion"] != "failure"
5246            || h["status"] != "completed"
5247            || b["status"] != "completed"
5248            || h["head_sha"].as_str()? != seen.head
5249            || b["head_sha"].as_str()? != base.stdout
5250            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5251        {
5252            return None;
5253        }
5254        let run = run_of(h["details_url"].as_str()?)?;
5255        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5256        if contexts.len() != 1
5257            || contexts[0].run.as_ref() != Some(&run)
5258            || contexts[0].verdict != Verdict::Fail
5259        {
5260            return None;
5261        }
5262        // A persisted request alone is not a completed rerun: require the
5263        // workflow's structured attempt number as well.
5264        let workflow =
5265            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5266        let base_run = run_of(b["details_url"].as_str()?)?;
5267        let base_workflow = ci_json(
5268            repo,
5269            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5270        )
5271        .await?;
5272        if base_workflow["head_sha"].as_str()? != base.stdout
5273            || base_workflow["head_branch"].as_str()? != seen.base
5274            || base_workflow["status"] != "completed"
5275            || base_workflow["conclusion"] != "failure"
5276            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5277        {
5278            return None;
5279        }
5280        let exhausted = state
5281            .land_reruns
5282            .as_ref()
5283            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5284            && workflow["head_sha"].as_str()? == seen.head
5285            && workflow["run_attempt"].as_u64()? > 1
5286            && workflow["status"] == "completed";
5287        checks.push(CiCheckEvidence {
5288            label: label.clone(),
5289            head_check: h["id"].as_u64()?,
5290            base_check: b["id"].as_u64()?,
5291            app: h.pointer("/app/id")?.as_u64()?,
5292            run,
5293            base_run,
5294            head_failures: ci_annotations(repo, h).await?,
5295            base_failures: ci_annotations(repo, b).await?,
5296            rerun_exhausted: exhausted,
5297        });
5298    }
5299    Some(CiEvidence {
5300        head: seen.head.clone(),
5301        base: base.stdout,
5302        changed: diff
5303            .stdout
5304            .split('\0')
5305            .filter(|p| !p.is_empty())
5306            .map(str::to_owned)
5307            .collect(),
5308        checks,
5309    })
5310}
5311
5312async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5313    let detail = serde_json::to_string(&evidence)?;
5314    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5315    let hold = "operator: 保留して後で判断する".to_owned();
5316    let mut q = ask::Question::new(
5317        state.id.clone(),
5318        CI_HOLD_NODE.into(),
5319        "land".into(),
5320        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5321        format!(
5322            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5323        ),
5324        vec![resume.clone(), hold.clone()],
5325    );
5326    q.actions.insert(
5327        resume,
5328        ask::ChoiceAction::Resume {
5329            run: state.id.clone(),
5330        },
5331    );
5332    q.actions.insert(hold, ask::ChoiceAction::Hold);
5333    ask::Questions::open().put_executable(&mut q)?;
5334    state.land_unrelated = Some(CiHold {
5335        head: evidence.head.clone(),
5336        question: q.id.clone(),
5337        evidence,
5338    });
5339    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5340    state.end_pass_parked(crate::run::ParkCause::Question);
5341    state.parked = true;
5342    state.save()?;
5343    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5344        tracing::warn!("could not notify about CI hold: {e:#}");
5345    }
5346    // A durable question and evidence are sufficient even if commenting fails.
5347    let body = stop_comment(
5348        &state.id,
5349        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5350    );
5351    let (_, body) = crate::github_text::prepare(state, "", &body);
5352    gh(
5353        &state.repo,
5354        &[
5355            "pr".into(),
5356            "comment".into(),
5357            pr.number.to_string(),
5358            "--body".into(),
5359            body,
5360        ],
5361    )
5362    .await
5363    .ok();
5364    Ok(())
5365}
5366
5367/// One observation, plus the two things [`PrState`] deliberately does not carry:
5368/// the title (needed for the squash subject) and where the failing checks'
5369/// logs live.
5370#[derive(Clone)]
5371struct Seen {
5372    pr: PrState,
5373    title: String,
5374    failing_urls: Vec<(String, String)>,
5375    /// `headRefOid`: the commit this observation, checks included, is about.
5376    head: String,
5377    /// The commit the checks belong to, read from the same GraphQL node as
5378    /// the checks themselves. Empty when unreadable.
5379    rollup_head: String,
5380    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5381    /// and DRAFT together, and a stop reason has to say which.
5382    merge_state: String,
5383    /// Every check of the rollup, for naming what an armed merge waits on.
5384    contexts: Vec<CheckInfo>,
5385    /// `baseRefName`, to look up which contexts the base requires.
5386    base: String,
5387}
5388
5389/// One check of the rollup as far as a stop reason needs it.
5390#[derive(Clone)]
5391struct CheckInfo {
5392    label: String,
5393    verdict: Verdict,
5394    required: Option<bool>,
5395    /// The workflow run the check belongs to; `None` for an external status.
5396    run: Option<String>,
5397}
5398
5399/// What to do with a red head before a fix round is spent on it.
5400#[derive(Debug, Clone, PartialEq, Eq)]
5401enum RerunStep {
5402    /// Rerun these workflow runs (each not yet rerun for this head).
5403    Rerun(Vec<String>),
5404    /// Reran already and the forge may still report the old failure: wait.
5405    Grace,
5406    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5407    Fix,
5408}
5409
5410/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5411/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5412/// pending checks in another run do not delay this run's rerun.
5413#[cfg(test)]
5414fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5415    rerunnable_with(contexts, false)
5416}
5417
5418fn rerunnable_with(
5419    contexts: &[CheckInfo],
5420    include_optional: bool,
5421) -> Vec<(String, Option<String>)> {
5422    contexts
5423        .iter()
5424        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5425        // `gh run rerun --failed` refuses a run with a job still going.
5426        .filter(|c| {
5427            c.run.as_ref().is_none_or(|r| {
5428                !contexts.iter().any(|o| {
5429                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5430                        && o.run.as_ref() == Some(r)
5431                })
5432            })
5433        })
5434        .map(|c| (c.label.clone(), c.run.clone()))
5435        .collect()
5436}
5437
5438/// Pure: rerun once per run id, wait out the grace, then hand over.
5439fn rerun_step(
5440    failing: &[(String, Option<String>)],
5441    record: Option<&LandReruns>,
5442    head: &str,
5443    now: i64,
5444) -> RerunStep {
5445    // A failure with no workflow run (an external status) cannot be rerun, and
5446    // the fixer's push re-runs everything anyway.
5447    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5448        return RerunStep::Fix;
5449    }
5450    // Reruns belong to the head they were made on.
5451    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5452    let mut fresh: Vec<String> = Vec::new();
5453    let mut recent = false;
5454    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5455        match record.and_then(|r| r.runs.get(run)) {
5456            None => {
5457                if !fresh.iter().any(|f| f == run) {
5458                    fresh.push(run.to_owned());
5459                }
5460            }
5461            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5462            Some(_) => {}
5463        }
5464    }
5465    if !fresh.is_empty() {
5466        RerunStep::Rerun(fresh)
5467    } else if recent {
5468        RerunStep::Grace
5469    } else {
5470        RerunStep::Fix
5471    }
5472}
5473
5474/// Read the pull request: `gh pr view` for the top-level thread and merge
5475/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5476/// inline review comments `gh pr view` does not report.
5477async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5478    let view = gh(
5479        repo,
5480        &[
5481            "pr".to_owned(),
5482            "view".to_owned(),
5483            pr_url.to_owned(),
5484            "--json".to_owned(),
5485            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5486                .to_owned(),
5487        ],
5488    )
5489    .await?;
5490    if !view.0 {
5491        bail!("gh pr view {pr_url}: {}", view.1);
5492    }
5493    let number = parse_pr(&view.1)?.number;
5494    let node = last_commit_node(repo, number).await;
5495    let mut seen = seen_from(&view.1, node.as_deref())?;
5496
5497    let inline = gh(
5498        repo,
5499        &[
5500            "api".to_owned(),
5501            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5502        ],
5503    )
5504    .await?;
5505    if inline.0 {
5506        match parse_inline_comments(&inline.1) {
5507            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5508            // An unreadable inline thread must not end a landing: the rollup
5509            // and the top-level thread are still real signal.
5510            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5511        }
5512    } else {
5513        tracing::warn!("gh api pulls/{}/comments: {}", seen.pr.number, inline.1);
5514    }
5515    Ok(seen)
5516}
5517
5518/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
5519/// response. No I/O.
5520///
5521/// The commit oid and the checks are read from the *same* node, so the rollup
5522/// is bound to the commit it belongs to by construction; two reads that agree
5523/// before and after another response prove nothing about what that response
5524/// held. The view's own rollup is never used. A node that is missing,
5525/// unreadable, carries GraphQL errors, or whose checks run past the page
5526/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
5527/// as "look again" and never as a reason to merge.
5528fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5529    let mut pr = parse_pr(view_json)?;
5530    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5531
5532    let mut rollup_head = String::new();
5533    let mut failing_urls = Vec::new();
5534    let mut contexts = Vec::new();
5535    let mut checks = Checks::Unknown;
5536    let mut failing = Vec::new();
5537    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5538        (checks, failing) = rollup_verdict(&rollup);
5539        failing_urls = rollup
5540            .iter()
5541            .filter(|c| c.verdict() == Verdict::Fail)
5542            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5543            .collect();
5544        contexts = rollup
5545            .iter()
5546            .map(|c| CheckInfo {
5547                label: c.label(),
5548                verdict: c.verdict(),
5549                required: c.is_required,
5550                run: c.url().and_then(run_of),
5551            })
5552            .collect();
5553        rollup_head = oid;
5554    }
5555    pr.checks = checks;
5556    pr.failing = failing;
5557
5558    Ok(Seen {
5559        pr,
5560        title: raw.title,
5561        failing_urls,
5562        head: raw.head_ref_oid,
5563        rollup_head,
5564        merge_state: raw.merge_state_status,
5565        contexts,
5566        base: raw.base_ref_name,
5567    })
5568}
5569
5570/// The last commit's oid and its checks from one GraphQL response, `None`
5571/// when anything about it cannot be trusted.
5572fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
5573    let v: serde_json::Value = serde_json::from_str(json).ok()?;
5574    if v.get("errors").is_some_and(|e| !e.is_null()) {
5575        return None;
5576    }
5577    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
5578    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
5579    let contexts = commit.pointer("/statusCheckRollup/contexts");
5580    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
5581        // No rollup at all: the commit has no checks.
5582        return Some((oid.to_owned(), Vec::new()));
5583    };
5584    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
5585        return None;
5586    }
5587    let nodes = contexts.get("nodes")?.as_array()?;
5588    let rollup = nodes
5589        .iter()
5590        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
5591        .collect::<Result<Vec<_>, _>>()
5592        .ok()?;
5593    Some((oid.to_owned(), rollup))
5594}
5595
5596/// The pull request's last commit and its checks, in one response. `None`
5597/// when the forge could not be asked.
5598async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
5599    let out = gh(
5600        repo,
5601        &[
5602            "api".to_owned(),
5603            "graphql".to_owned(),
5604            "-F".to_owned(),
5605            "owner={owner}".to_owned(),
5606            "-F".to_owned(),
5607            "repo={repo}".to_owned(),
5608            "-F".to_owned(),
5609            format!("number={number}"),
5610            "-f".to_owned(),
5611            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
5612             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
5613             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
5614             ... on CheckRun{name status conclusion detailsUrl \
5615             isRequired(pullRequestNumber:$number)} \
5616             ... on StatusContext{context state targetUrl \
5617             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
5618                .to_owned(),
5619        ],
5620    )
5621    .await
5622    .ok()?;
5623    out.0.then_some(out.1)
5624}
5625
5626/// What a fix round did.
5627#[doc(hidden)]
5628#[derive(Debug, PartialEq)]
5629pub enum Fixed {
5630    /// The fixer committed something, and this is the head that was pushed.
5631    Committed {
5632        /// The commit now at the tip of the pushed branch.
5633        head: String,
5634    },
5635    /// The fixer ran and chose to change nothing.
5636    Declined,
5637    /// Machine availability prevented a result; retry this round on resume.
5638    Deferred,
5639    /// The fixer could not run, or said nothing usable.
5640    Failed(String),
5641}
5642
5643/// Hand the failures and the comments to the fixer, then commit and push.
5644///
5645/// The fixer works in the winner's own worktree so its commits land on the
5646/// branch the pull request is built from, and it runs with `allow_write` for
5647/// the same reason.
5648#[doc(hidden)]
5649pub async fn fix_round(
5650    state: &mut RunState,
5651    pr: &PrState,
5652    round: usize,
5653    budget: usize,
5654    reason: &str,
5655    logs: &str,
5656) -> Result<Fixed> {
5657    let winner = state
5658        .winner()
5659        .cloned()
5660        .context("landing needs a winning candidate; none is recorded on this run")?;
5661    let roles = state
5662        .config
5663        .resolve_roles()
5664        .context("resolve the roster for the fix round")?;
5665    // Same chain as the review loop (see `crate::fixer`): the configured
5666    // fixers in order, otherwise the winner's own author continuing its own
5667    // conversation - the competition is over, so its context is pure benefit.
5668    let attempts = crate::fixer::attempts(state, &roles, &winner);
5669    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
5670
5671    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
5672    let mut artifacts = agent::artifacts_dir(&state.dir());
5673    if let Some(request) = state
5674        .merge_repairs
5675        .last()
5676        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
5677    {
5678        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
5679    }
5680    let prompt =
5681        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
5682            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
5683        } else {
5684            prompt
5685        };
5686    // Read before the fixer runs: it normally commits for itself, so HEAD has
5687    // already moved by the time it returns and a later read would see no
5688    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
5689    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5690    // Each id at most once, forward only: the next one is asked only when the
5691    // call advances, and only the last attempt's result is judged below, so an
5692    // exhausted chain ends as a single failed fixer does.
5693    let mut last = None;
5694    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
5695        if owner_requested_stop(state)? {
5696            return Ok(Fixed::Declined);
5697        }
5698        let mut seat = seat_of(state, &seat_key, &spec.id);
5699        let stem = if i == 0 {
5700            format!("land-{round}")
5701        } else {
5702            format!("land-{round}-{}", spec.id)
5703        };
5704        let out = agent::invoke(
5705            &spec,
5706            &mut seat,
5707            &Invocation {
5708                coordination: state.config.coordination.as_ref(),
5709                fetched_base: state.fetched_base.as_ref(),
5710                cwd: &winner.worktree,
5711                prompt: &prompt,
5712                timeout: Duration::from_secs(state.config.graph.timeout_fix),
5713                allow_write: true,
5714                sessions: state.config.graph.sessions,
5715                artifacts: &artifacts,
5716                stem: &stem,
5717                run: &state.id,
5718                node: "land",
5719                cache_dir: state.config.cache_dir().as_deref(),
5720                attachments: &[],
5721                writable: &[],
5722            },
5723        )
5724        .await;
5725        state.seats.insert(seat.key.clone(), seat);
5726        if let Some(next) = ids.get(i + 1)
5727            && agent::chain_advances(&out)
5728        {
5729            let (class, why) = crate::fixer::failure_of(&out);
5730            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
5731            continue;
5732        }
5733        last = Some((seat_key, out));
5734        break;
5735    }
5736    let (seat_key, out) = last.expect("the fixer chain always has an entry");
5737
5738    match out {
5739        Ok(o) if o.quota_exhausted() => {
5740            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
5741            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
5742            state.quota.push(loss);
5743            state.status = RunStatus::Blocked;
5744            state.save()?;
5745            // Keep partial edits reachable on the winner branch and leave a
5746            // clean tree for resume_landing_head. The resumed landing gates
5747            // this new commit before it can publish it; no push happens here.
5748            let inherited = crate::repo_lock::WaitPolicy::current();
5749            let wait = crate::repo_lock::WaitPolicy::new(
5750                Duration::from_secs(state.config.graph.timeout_resource_wait),
5751                move || inherited.cancelled(),
5752            );
5753            let _coordination = crate::repo_lock::SeatLease::operation_with(
5754                &winner.worktree,
5755                state.config.coordination.as_ref(),
5756                &wait,
5757            )
5758            .await?;
5759            let rescue = git::rescue_commit(
5760                &winner.worktree,
5761                &format!("magi: deferred land round {round} (uncommitted work)"),
5762            )
5763            .await?;
5764            state.note_withheld("land", &rescue.withheld);
5765            state.save()?;
5766            return Ok(Fixed::Deferred);
5767        }
5768        Ok(o) if !o.usable() => {
5769            return Ok(Fixed::Failed(format!(
5770                "the fixer produced nothing usable ({})",
5771                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
5772            )));
5773        }
5774        Ok(_) => {}
5775        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
5776        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
5777    }
5778
5779    if owner_requested_stop(state)? {
5780        return Ok(Fixed::Declined);
5781    }
5782
5783    // An agent that edited files but never committed would otherwise push
5784    // nothing and look like a refusal.
5785    let wait = crate::repo_lock::WaitPolicy::new(
5786        Duration::from_secs(state.config.graph.timeout_resource_wait),
5787        || false,
5788    );
5789    let coordination = crate::repo_lock::SeatLease::operation_with(
5790        &winner.worktree,
5791        state.config.coordination.as_ref(),
5792        &wait,
5793    )
5794    .await?;
5795    match git::rescue_commit(
5796        &winner.worktree,
5797        &format!("magi: land round {round} fixes (uncommitted work)"),
5798    )
5799    .await
5800    {
5801        Ok(r) => state.note_withheld("land", &r.withheld),
5802        Err(e)
5803            if state
5804                .merge_repairs
5805                .last()
5806                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
5807        {
5808            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
5809        }
5810        Err(_) => {}
5811    }
5812    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5813    drop(coordination);
5814    if after == before {
5815        return Ok(Fixed::Declined);
5816    }
5817
5818    if owner_requested_stop(state)? {
5819        return Ok(Fixed::Declined);
5820    }
5821    crate::pr_head::ensure_owner(state)?;
5822    let remote = state.config.merge.remote.clone();
5823    anyhow::ensure!(
5824        crate::foreign_checkout::write_back(state, &after).await?,
5825        "foreign checkout delivery is blocked; see the run events"
5826    );
5827    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
5828    let push = if state.pr_head.is_some() {
5829        let expected = state
5830            .pr_pushed_head
5831            .as_deref()
5832            .context("missing public head lease")?;
5833        git::push_as(
5834            &winner.worktree,
5835            &remote,
5836            &winner.branch,
5837            &public_head,
5838            expected,
5839        )
5840        .await?
5841    } else {
5842        git::push(&winner.worktree, &remote, &winner.branch).await?
5843    };
5844    if !push.ok() {
5845        return Ok(Fixed::Failed(format!(
5846            "pushing {} to {remote} failed: {}",
5847            public_head, push.stderr
5848        )));
5849    }
5850    state.event(
5851        "land",
5852        format!("round {round}: pushed a fix to {public_head}"),
5853    );
5854    state.pr_pushed_head = Some(after.clone());
5855    state.save()?;
5856    Ok(Fixed::Committed { head: after })
5857}
5858
5859/// Fetch or create a seat, keeping its conversation across nodes.
5860pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
5861    crate::fixer::seat_for(state, key, agent)
5862}
5863
5864/// Recheck the live PR and local worktree before spending the requested fix.
5865/// A moved/closed PR is held, never repaired using obsolete evidence.
5866pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
5867    let seen = observe(&state.repo, url).await?;
5868    let winner = state.winner().context("no winning branch to repair")?;
5869    if seen.pr.state != PrLifecycle::Open || seen.head != head {
5870        anyhow::bail!(
5871            "PR is closed or its head changed; review the current head before requesting repair again"
5872        );
5873    }
5874    if git::rev_parse(&winner.worktree, "HEAD").await? != head
5875        || !git::is_clean(&winner.worktree).await?
5876    {
5877        anyhow::bail!(
5878            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
5879        );
5880    }
5881    // Always disable any forge-side reservation, including one not recorded
5882    // by this run. A repair request is never merge authorization.
5883    let view = gh(
5884        &state.repo,
5885        &[
5886            "pr".into(),
5887            "view".into(),
5888            url.into(),
5889            "--json".into(),
5890            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
5891        ],
5892    )
5893    .await?;
5894    if !view.0 {
5895        bail!("cannot check auto-merge: {}", view.1);
5896    }
5897    let live: serde_json::Value = serde_json::from_str(&view.1)?;
5898    let public = state.pr_branch().unwrap_or(&winner.branch);
5899    if live["state"] != "OPEN"
5900        || live["headRefOid"] != head
5901        || live["headRefName"] != public
5902        || live["baseRefName"] != state.base_branch
5903        || live["isCrossRepository"] != false
5904    {
5905        bail!("PR changed during repair preflight; review its current head explicitly");
5906    }
5907    let auto_merge = live
5908        .get("autoMergeRequest")
5909        .context("cannot read the PR auto-merge reservation; repair held")?;
5910    if !auto_merge.is_null() {
5911        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
5912        if !out.0 {
5913            bail!("cannot disable auto-merge; repair held: {}", out.1);
5914        }
5915    }
5916    Ok(seen.pr)
5917}
5918
5919/// What the fixer is told.
5920fn fix_prompt(
5921    state: &RunState,
5922    pr: &PrState,
5923    round: usize,
5924    budget: usize,
5925    reason: &str,
5926    logs: &str,
5927) -> String {
5928    let mut s = format!(
5929        "Your patch is open as a pull request and it is not landing. Land round \
5930         {round} of {budget}.\n\n\
5931         Pull request: {}\n\n\
5932         What is holding it: {reason}\n\n\
5933         # The task\n\n{}\n",
5934        pr.url, state.instruction
5935    );
5936
5937    if pr.failing.is_empty() {
5938        s.push_str("\n# Failing checks\n\n(none)\n");
5939    } else {
5940        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
5941        if logs.trim().is_empty() {
5942            s.push_str(
5943                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
5944            );
5945        } else {
5946            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
5947        }
5948    }
5949
5950    if pr.review_comments.is_empty() {
5951        s.push_str("\n# Review comments\n\n(none)\n");
5952    } else {
5953        s.push_str("\n# Review comments\n");
5954        for c in &pr.review_comments {
5955            let where_ = match (&c.path, c.line) {
5956                (Some(p), Some(l)) => format!(" ({p}:{l})"),
5957                (Some(p), None) => format!(" ({p})"),
5958                _ => String::new(),
5959            };
5960            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
5961        }
5962    }
5963
5964    s.push_str(
5965        "\n# Rules\n\n\
5966         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
5967            failing test; do not silence a lint with an allow attribute; do not \
5968            stretch a timeout to hide a race. If the check is right, the code is \
5969            wrong.\n\
5970         2. Change nothing the checks and the comments did not raise. A \
5971            drive-by refactor turns a one-line fix into a pull request that \
5972            needs reviewing again.\n\
5973         3. If a comment is wrong, say so with a checkable argument and change \
5974            nothing for it. A declined comment with a reason is a correct \
5975            outcome; a change made to appease a reviewer is not.\n\
5976         4. Commit in this worktree. magi pushes to the pull request's branch \
5977            for you; do not push, merge, or close anything yourself.\n\
5978         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
5979         # Output\n\n\
5980         Say what you changed and why, and what you declined and why.",
5981    );
5982
5983    let language = &state.config.graph.language;
5984    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
5985        let _ = write!(s, "\n\nWrite all prose in {language}.");
5986    }
5987    // After the language line, so the exception is the last word on it.
5988    s.push_str(&crate::prompt::github_rule(
5989        language,
5990        &state.config.graph.github_language,
5991    ));
5992    if let Some(overlay) = state.config.prompts.overlay("fix") {
5993        let _ = write!(s, "\n\n{overlay}");
5994    }
5995    s.push('\n');
5996    s.push_str(crate::prompt::child_run_ownership());
5997    s
5998}
5999
6000/// Failing log tails, the way the operator collects them by hand:
6001/// `gh run view --log-failed`.
6002async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6003    let mut out = String::new();
6004    for (name, url) in failing.iter().take(MAX_LOGS) {
6005        let args = match (job_of(url), run_of(url)) {
6006            (Some(job), _) => vec![
6007                "run".to_owned(),
6008                "view".to_owned(),
6009                "--log-failed".to_owned(),
6010                "--job".to_owned(),
6011                job,
6012            ],
6013            (None, Some(run)) => vec![
6014                "run".to_owned(),
6015                "view".to_owned(),
6016                run,
6017                "--log-failed".to_owned(),
6018            ],
6019            // Not a GitHub Actions check - an external status has no log here.
6020            (None, None) => continue,
6021        };
6022        let (ok, body) = match gh(repo, &args).await {
6023            Ok(v) => v,
6024            Err(e) => (false, format!("{e:#}")),
6025        };
6026        if !ok && body.trim().is_empty() {
6027            continue;
6028        }
6029        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6030    }
6031    out
6032}
6033
6034/// Job id out of a check's `detailsUrl`
6035/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
6036fn job_of(details_url: &str) -> Option<String> {
6037    let after = details_url.split("/job/").nth(1)?;
6038    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6039    (!id.is_empty()).then_some(id)
6040}
6041
6042/// Workflow run id out of a check's `detailsUrl`.
6043pub(crate) fn run_of(details_url: &str) -> Option<String> {
6044    let after = details_url.split("/actions/runs/").nth(1)?;
6045    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6046    (!id.is_empty()).then_some(id)
6047}
6048
6049/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6050/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6051/// it to that.
6052fn stop_comment(run_id: &str, why: &str) -> String {
6053    format!(
6054        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6055         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6056    )
6057}
6058
6059/// Leave the pull request open, say why on it, and mark the run blocked.
6060///
6061/// The comment is what makes an unattended stop actionable: the operator wakes
6062/// up to a pull request that explains itself rather than to a silent queue.
6063async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6064    let body = stop_comment(&state.id, why);
6065    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6066    if !body.contains(MARKER) {
6067        body = format!("{MARKER}\n{body}");
6068    }
6069    let posted = gh(
6070        repo,
6071        &[
6072            "pr".to_owned(),
6073            "comment".to_owned(),
6074            pr.number.to_string(),
6075            "--body".to_owned(),
6076            body,
6077        ],
6078    )
6079    .await;
6080    match posted {
6081        Ok((true, _)) => {}
6082        Ok((false, out)) => tracing::warn!("could not comment on {}: {out}", pr.url),
6083        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6084    }
6085    state.status = RunStatus::Blocked;
6086    state.merge = Some(MergeOutcome {
6087        mode: MergeMode::Pr,
6088        ok: false,
6089        detail: why.to_owned(),
6090        empty: false,
6091    });
6092    state.event("land", format!("stopped: {why}"));
6093    state.save()?;
6094    Ok(())
6095}
6096
6097/// Run `gh` in `repo`, returning success and the combined output.
6098///
6099/// Combined because `gh` reports a refused merge on stderr and the pull request
6100/// json on stdout, and both are evidence.
6101///
6102/// `GH_REPO` is stripped from the child's environment: every call site here
6103/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6104/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6105/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6106/// `GH_REPO` the operator happens to have exported for an unrelated script
6107/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6108/// below) to a different repository than the one actually on disk - which
6109/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6110/// could be made to agree with whatever repository a forged `--merged` URL
6111/// claims, defeating it entirely.
6112pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<(bool, String)> {
6113    let out = tokio::process::Command::new("gh")
6114        .args(args)
6115        .current_dir(cwd)
6116        .env_remove("GH_REPO")
6117        .quiet()
6118        .stdin(std::process::Stdio::null())
6119        .output()
6120        .await
6121        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6122    let mut body = String::from_utf8_lossy(&out.stdout).into_owned();
6123    let err = String::from_utf8_lossy(&out.stderr);
6124    if body.trim().is_empty() {
6125        body = err.into_owned();
6126    } else if !err.trim().is_empty() {
6127        body.push_str(&err);
6128    }
6129    Ok((out.status.success(), body.trim().to_owned()))
6130}
6131
6132/// Verdict of one entry in the status rollup.
6133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6134pub(crate) enum Verdict {
6135    Pass,
6136    Fail,
6137    Pending,
6138    Unknown,
6139}
6140
6141impl Verdict {
6142    /// Short operator-facing check result.
6143    pub(crate) fn label(self) -> &'static str {
6144        match self {
6145            Self::Pass => "passed",
6146            Self::Fail => "failed",
6147            Self::Pending => "pending",
6148            Self::Unknown => "unknown",
6149        }
6150    }
6151}
6152
6153#[derive(Debug, Deserialize)]
6154#[serde(rename_all = "camelCase")]
6155struct GhPr {
6156    #[serde(default)]
6157    url: String,
6158    #[serde(default)]
6159    number: u64,
6160    #[serde(default)]
6161    state: String,
6162    #[serde(default)]
6163    title: String,
6164    #[serde(default)]
6165    status_check_rollup: Vec<GhCheck>,
6166    /// GitHub's own verdict on whether the pull request can be merged.
6167    ///
6168    /// Worth asking for because it is the only place the *required* check set
6169    /// is applied: the rollup lists every check equally, so a repository that
6170    /// deliberately does not require `coverage` still looks red here. See
6171    /// [`Blocking`].
6172    #[serde(default)]
6173    merge_state_status: String,
6174    /// The commit the pull request currently points at. Compared with the
6175    /// commit a fix round pushed, it is how the loop knows the forge has moved
6176    /// on and the rollup belongs to the new head.
6177    #[serde(default)]
6178    head_ref_oid: String,
6179    #[serde(default)]
6180    base_ref_name: String,
6181    #[serde(default)]
6182    reviews: Vec<GhReview>,
6183    #[serde(default)]
6184    comments: Vec<GhComment>,
6185}
6186
6187/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6188/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6189/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6190/// conclusion at all.
6191#[derive(Debug, Deserialize)]
6192#[serde(rename_all = "camelCase")]
6193struct GhCheck {
6194    #[serde(default)]
6195    name: Option<String>,
6196    #[serde(default)]
6197    context: Option<String>,
6198    #[serde(default)]
6199    status: Option<String>,
6200    #[serde(default)]
6201    conclusion: Option<String>,
6202    #[serde(default)]
6203    state: Option<String>,
6204    #[serde(default)]
6205    details_url: Option<String>,
6206    #[serde(default)]
6207    target_url: Option<String>,
6208    /// Whether the base branch requires this check. Only the GraphQL node
6209    /// carries it; `None` is "not read", never "not required".
6210    #[serde(default)]
6211    is_required: Option<bool>,
6212}
6213
6214impl GhCheck {
6215    /// Name to show a human and hand to the fixer.
6216    fn label(&self) -> String {
6217        self.name
6218            .clone()
6219            .or_else(|| self.context.clone())
6220            .unwrap_or_else(|| "(unnamed check)".to_owned())
6221    }
6222
6223    /// Where this check's logs live, when it has any.
6224    fn url(&self) -> Option<&str> {
6225        self.details_url
6226            .as_deref()
6227            .or(self.target_url.as_deref())
6228            .filter(|u| !u.is_empty())
6229    }
6230
6231    /// Did it pass?
6232    ///
6233    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6234    /// skips release and bot pull requests by design, and a skip that blocked
6235    /// landing would block exactly the pull requests that need no review.
6236    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6237    /// merging over one is merging over a check that never ran.
6238    fn verdict(&self) -> Verdict {
6239        if let Some(status) = self.status.as_deref() {
6240            if !status.eq_ignore_ascii_case("COMPLETED") {
6241                return Verdict::Pending;
6242            }
6243        }
6244        let outcome = self
6245            .conclusion
6246            .as_deref()
6247            .or(self.state.as_deref())
6248            .unwrap_or("");
6249        match outcome.to_ascii_uppercase().as_str() {
6250            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6251            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6252            | "ACTION_REQUIRED" => Verdict::Fail,
6253            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6254                Verdict::Pending
6255            }
6256            _ => Verdict::Unknown,
6257        }
6258    }
6259}
6260
6261#[derive(Debug, Deserialize)]
6262struct GhAuthor {
6263    #[serde(default)]
6264    login: String,
6265}
6266
6267#[derive(Debug, Deserialize)]
6268struct GhReview {
6269    #[serde(default)]
6270    author: GhAuthor,
6271    #[serde(default)]
6272    body: String,
6273}
6274
6275#[derive(Debug, Deserialize)]
6276struct GhComment {
6277    #[serde(default)]
6278    author: GhAuthor,
6279    #[serde(default)]
6280    body: String,
6281}
6282
6283#[derive(Debug, Deserialize)]
6284struct GhUser {
6285    #[serde(default)]
6286    login: String,
6287}
6288
6289#[derive(Debug, Deserialize)]
6290struct GhInline {
6291    #[serde(default)]
6292    user: GhUser,
6293    #[serde(default)]
6294    path: Option<String>,
6295    #[serde(default)]
6296    line: Option<u64>,
6297    #[serde(default)]
6298    body: String,
6299}
6300
6301impl Default for GhAuthor {
6302    fn default() -> Self {
6303        Self {
6304            login: "(unknown)".to_owned(),
6305        }
6306    }
6307}
6308
6309impl Default for GhUser {
6310    fn default() -> Self {
6311        Self {
6312            login: "(unknown)".to_owned(),
6313        }
6314    }
6315}
6316
6317#[cfg(test)]
6318pub(crate) mod tests {
6319    use super::*;
6320    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6321
6322    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6323        format!(
6324            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6325        )
6326    }
6327
6328    #[test]
6329    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6330        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6331        assert_eq!(
6332            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6333            Ok(())
6334        );
6335        for (json, why) in [
6336            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6337            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6338            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6339            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6340            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6341            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6342        ] {
6343            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6344                .unwrap_err()
6345                .why;
6346            assert!(err.contains(why), "{json}: {err}");
6347        }
6348        // A head that moved on past what was verified is left alone.
6349        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6350        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6351        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6352        assert!(
6353            !closable(
6354                &head_json("x", "main", "OPEN", false),
6355                "magi/27b2/A",
6356                "main",
6357                &[]
6358            )
6359            .unwrap_err()
6360            .retry
6361        );
6362        assert!(is_forge_url("https://github.com/o/r.git"));
6363        assert!(is_forge_url("git@github.com:o/r.git"));
6364        assert!(!is_forge_url("/tmp/origin.git"));
6365        assert!(!is_forge_url("C:\\work\\origin.git"));
6366        assert!(!is_forge_url("file:///tmp/origin.git"));
6367        assert!(forge_unavailable(
6368            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6369        ));
6370        assert!(!forge_unavailable(
6371            "gh pr list failed: error connecting to api.github.com"
6372        ));
6373        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6374        // A record that does not say whether it is a fork is not trusted.
6375        assert!(
6376            closable(
6377                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6378                "b",
6379                "main",
6380                &["aaa".to_owned()]
6381            )
6382            .is_err()
6383        );
6384    }
6385
6386    #[test]
6387    fn the_close_comment_names_the_commit_on_the_base() {
6388        let e = crate::already::Evidence {
6389            proof: crate::already::Proof::PatchId,
6390            tip: "1234567890".to_owned(),
6391            commits: vec!["0e368de0000".to_owned()],
6392        };
6393        let c = superseded_comment("main", &e);
6394        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6395    }
6396
6397    /// 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.
6398    const GREEN_OPEN: &str = r####"{
6399  "url": "https://github.com/yukimemi/magi/pull/10",
6400  "number": 10,
6401  "state": "OPEN",
6402  "mergeStateStatus": "CLEAN",
6403  "statusCheckRollup": [
6404    {
6405      "__typename": "CheckRun",
6406      "conclusion": "SKIPPED",
6407      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6408      "name": "review",
6409      "status": "COMPLETED",
6410      "workflowName": "claude-review"
6411    },
6412    {
6413      "__typename": "CheckRun",
6414      "conclusion": "SUCCESS",
6415      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6416      "name": "check (ubuntu-latest)",
6417      "status": "COMPLETED",
6418      "workflowName": "CI"
6419    },
6420    {
6421      "__typename": "CheckRun",
6422      "conclusion": "SUCCESS",
6423      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6424      "name": "rustfmt",
6425      "status": "COMPLETED",
6426      "workflowName": "CI"
6427    },
6428    {
6429      "__typename": "StatusContext",
6430      "context": "CodeRabbit",
6431      "state": "SUCCESS",
6432      "targetUrl": ""
6433    }
6434  ],
6435  "reviews": [],
6436  "comments": [
6437    {
6438      "author": {
6439        "login": "coderabbitai"
6440      },
6441      "authorAssociation": "NONE",
6442      "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"
6443    }
6444  ]
6445}"####;
6446
6447    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
6448    const RED_OPEN: &str = r####"{
6449  "url": "https://github.com/yukimemi/magi/pull/9",
6450  "number": 9,
6451  "state": "OPEN",
6452  "mergeStateStatus": "UNSTABLE",
6453  "statusCheckRollup": [
6454    {
6455      "__typename": "CheckRun",
6456      "conclusion": "SUCCESS",
6457      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6458      "name": "check (ubuntu-latest)",
6459      "status": "COMPLETED",
6460      "workflowName": "CI"
6461    },
6462    {
6463      "__typename": "CheckRun",
6464      "conclusion": "SUCCESS",
6465      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6466      "name": "rustfmt",
6467      "status": "COMPLETED",
6468      "workflowName": "CI"
6469    },
6470    {
6471      "__typename": "CheckRun",
6472      "conclusion": "FAILURE",
6473      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6474      "name": "editorconfig",
6475      "status": "COMPLETED",
6476      "workflowName": "CI"
6477    },
6478    {
6479      "__typename": "StatusContext",
6480      "context": "CodeRabbit",
6481      "state": "SUCCESS",
6482      "targetUrl": ""
6483    }
6484  ],
6485  "reviews": [],
6486  "comments": [
6487    {
6488      "author": {
6489        "login": "coderabbitai"
6490      },
6491      "authorAssociation": "NONE",
6492      "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"
6493    }
6494  ]
6495}"####;
6496
6497    /// 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.
6498    const PENDING_OPEN: &str = r####"{
6499  "url": "https://github.com/yukimemi/magi/pull/9",
6500  "number": 9,
6501  "state": "OPEN",
6502  "statusCheckRollup": [
6503    {
6504      "__typename": "CheckRun",
6505      "conclusion": "SUCCESS",
6506      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6507      "name": "check (ubuntu-latest)",
6508      "status": "COMPLETED",
6509      "workflowName": "CI"
6510    },
6511    {
6512      "__typename": "CheckRun",
6513      "conclusion": "SUCCESS",
6514      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6515      "name": "rustfmt",
6516      "status": "COMPLETED",
6517      "workflowName": "CI"
6518    },
6519    {
6520      "__typename": "CheckRun",
6521      "conclusion": null,
6522      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6523      "name": "editorconfig",
6524      "status": "IN_PROGRESS",
6525      "workflowName": "CI"
6526    },
6527    {
6528      "__typename": "StatusContext",
6529      "context": "CodeRabbit",
6530      "state": "SUCCESS",
6531      "targetUrl": ""
6532    }
6533  ],
6534  "reviews": [],
6535  "comments": []
6536}"####;
6537
6538    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
6539    const MERGED: &str = r####"{
6540  "url": "https://github.com/yukimemi/magi/pull/16",
6541  "number": 16,
6542  "state": "MERGED",
6543  "statusCheckRollup": [
6544    {
6545      "__typename": "CheckRun",
6546      "conclusion": "SUCCESS",
6547      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
6548      "name": "check (ubuntu-latest)",
6549      "status": "COMPLETED",
6550      "workflowName": "CI"
6551    },
6552    {
6553      "__typename": "CheckRun",
6554      "conclusion": "SUCCESS",
6555      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
6556      "name": "review",
6557      "status": "COMPLETED",
6558      "workflowName": "claude-review"
6559    }
6560  ],
6561  "reviews": [],
6562  "comments": []
6563}"####;
6564
6565    /// 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.
6566    const REVIEWED_OPEN: &str = r####"{
6567  "url": "https://github.com/yukimemi/magi/pull/12",
6568  "number": 12,
6569  "state": "OPEN",
6570  "statusCheckRollup": [
6571    {
6572      "__typename": "CheckRun",
6573      "conclusion": "SUCCESS",
6574      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
6575      "name": "check (ubuntu-latest)",
6576      "status": "COMPLETED",
6577      "workflowName": "CI"
6578    },
6579    {
6580      "__typename": "CheckRun",
6581      "conclusion": "SUCCESS",
6582      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
6583      "name": "review",
6584      "status": "COMPLETED",
6585      "workflowName": "claude-review"
6586    }
6587  ],
6588  "reviews": [
6589    {
6590      "author": {
6591        "login": "claude"
6592      },
6593      "state": "COMMENTED",
6594      "body": ""
6595    }
6596  ],
6597  "comments": [
6598    {
6599      "author": {
6600        "login": "coderabbitai"
6601      },
6602      "authorAssociation": "NONE",
6603      "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"
6604    },
6605    {
6606      "author": {
6607        "login": "claude"
6608      },
6609      "authorAssociation": "NONE",
6610      "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"
6611    }
6612  ]
6613}"####;
6614
6615    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
6616    const INLINE: &str = r####"[
6617  {
6618    "user": {
6619      "login": "claude[bot]"
6620    },
6621    "path": "src/graph.rs",
6622    "line": 231,
6623    "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"
6624  }
6625]"####;
6626
6627    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
6628    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
6629<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
6630
6631> [!IMPORTANT]
6632> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
6633> 
6634> This repository does not receive automatic reviews because it has fewer than 10 stars.
6635> 
6636> <details>
6637> <summary>⚙️ Run configuration</summary>
6638> 
6639> **Configuration used**: defaults
6640> 
6641> **Review profile**: CHILL
6642> 
6643> **Plan**: Team
6644> 
6645> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
6646> 
6647> </details>
6648
6649<!-- end of auto-generated comment: skip review by coderabbit.ai -->
6650
6651<!-- tips_start -->
6652
6653---
6654
6655Thanks 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.
6656
6657<details>
6658<summary>❤️ Share</summary>
6659
6660- [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"####;
6661
6662    /// 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.
6663    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
6664
6665---
6666### Reviewing PR #16
6667
6668- [x] Read AGENTS.md conventions
6669- [x] Review `src/daemon.rs` changes
6670- [x] Review `src/main.rs` changes (new `doctor` reporting)
6671- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
6672- [x] Check test coverage for new behavior
6673- [x] Run verification commands (blocked — see note)
6674- [x] Post findings"####;
6675
6676    /// The same job's real comment on pull request #12 once it had something to say.
6677    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
6678
6679---
6680### Review: `magi review <branch>` — cheap-half-only graph
6681
6682Read 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.
6683
6684**Correctness**
6685
6686- 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"####;
6687
6688    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
6689        PrState {
6690            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
6691            number: 16,
6692            state: PrLifecycle::Open,
6693            checks,
6694            // These tests are about red-means-fix, so a red here is one the
6695            // forge gates on. Without saying so they would assert the new
6696            // "merge past a check nobody requires" path by accident.
6697            blocking: if matches!(checks, Checks::Red) {
6698                Blocking::Yes
6699            } else {
6700                Blocking::No
6701            },
6702            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
6703            review_comments: (0..comments)
6704                .map(|i| ReviewComment {
6705                    author: "coderabbitai".to_owned(),
6706                    path: Some("src/graph.rs".to_owned()),
6707                    line: Some(231),
6708                    body: format!("finding {i}"),
6709                })
6710                .collect(),
6711        }
6712    }
6713
6714    #[test]
6715    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
6716        use CiExpectation::{Absent, Expected};
6717        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
6718            let p = pr(checks, &["x"], 0);
6719            for waited in [Duration::ZERO, CHECKS_GRACE] {
6720                assert_eq!(
6721                    decide_with(&p, 0, 4, waited, Expected),
6722                    decide(&p, 0, 4, waited)
6723                );
6724            }
6725        }
6726        // Nothing will ever report: no wait, no give-up, no fix round.
6727        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
6728            let p = pr(checks, &["x"], 0);
6729            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
6730            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
6731        }
6732        // Third-party statuses never change the review decision, even at budget.
6733        for comments in [0, 1] {
6734            for round in [0, 4] {
6735                let absent = decide_with(
6736                    &pr(Checks::Unknown, &[], comments),
6737                    round,
6738                    4,
6739                    CHECKS_GRACE,
6740                    Absent,
6741                );
6742                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
6743                    assert_eq!(
6744                        decide_with(
6745                            &pr(checks, &["third-party"], comments),
6746                            round,
6747                            4,
6748                            Duration::ZERO,
6749                            Absent
6750                        ),
6751                        absent
6752                    );
6753                }
6754                if comments != 0 {
6755                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
6756                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
6757                }
6758            }
6759        }
6760        let empty = pr(Checks::Unknown, &[], 0);
6761        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
6762            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
6763        }
6764        assert_eq!(
6765            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
6766            Step::Wait
6767        );
6768        assert_eq!(
6769            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
6770            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
6771        );
6772        // A conflict is not a check: it still wants the rebase.
6773        let mut p = pr(Checks::Unknown, &[], 0);
6774        p.blocking = Blocking::Conflict;
6775        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
6776        // And a pull request that left our hands is still done.
6777        p.state = PrLifecycle::Merged;
6778        assert_eq!(
6779            decide_with(&p, 0, 4, Duration::ZERO, Absent),
6780            Step::Done { merged: true }
6781        );
6782    }
6783
6784    #[test]
6785    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
6786        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
6787        assert_eq!(state.number, 10);
6788        assert_eq!(state.state, PrLifecycle::Open);
6789        assert_eq!(state.checks, Checks::Green);
6790        assert!(state.failing.is_empty());
6791        assert!(
6792            state.review_comments.is_empty(),
6793            "the only comment is CodeRabbit's trigger notice: {:?}",
6794            state.review_comments
6795        );
6796        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
6797    }
6798
6799    #[test]
6800    fn a_failing_check_parses_as_red_and_is_named() {
6801        let state = parse_pr(RED_OPEN).expect("red fixture parses");
6802        assert_eq!(state.checks, Checks::Red);
6803        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
6804        // The captured payload says `UNSTABLE` - mergeable, with a check
6805        // nobody requires red - which is exactly the shape that had to be
6806        // merged by hand. Asserted separately, in
6807        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
6808        // test is about is that a red check is *named*, so the reason a fixer
6809        // is handed says which one; so it asks the blocking question here.
6810        let mut blocking = state.clone();
6811        blocking.blocking = Blocking::Yes;
6812        match decide(&blocking, 0, 4, Duration::ZERO) {
6813            Step::Fix { reason } => {
6814                assert!(reason.contains("editorconfig"), "reason: {reason}");
6815                assert!(reason.contains("failing"), "reason: {reason}");
6816            }
6817            other => panic!("expected a fix round, got {other:?}"),
6818        }
6819    }
6820
6821    #[test]
6822    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
6823        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
6824        assert_eq!(state.checks, Checks::Pending);
6825        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
6826    }
6827
6828    #[test]
6829    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
6830        let state = parse_pr(MERGED).expect("merged fixture parses");
6831        assert_eq!(state.state, PrLifecycle::Merged);
6832        assert_eq!(
6833            decide(&state, 0, 4, Duration::ZERO),
6834            Step::Done { merged: true }
6835        );
6836    }
6837
6838    #[test]
6839    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
6840        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
6841        assert_eq!(state.checks, Checks::Green);
6842        let authors: Vec<&str> = state
6843            .review_comments
6844            .iter()
6845            .map(|c| c.author.as_str())
6846            .collect();
6847        assert_eq!(
6848            authors,
6849            vec!["claude"],
6850            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
6851        );
6852        match decide(&state, 0, 4, Duration::ZERO) {
6853            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
6854            other => panic!("expected a fix round, got {other:?}"),
6855        }
6856    }
6857
6858    #[test]
6859    fn inline_review_comments_keep_their_file_and_line() {
6860        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
6861        assert_eq!(comments.len(), 1);
6862        assert_eq!(comments[0].author, "claude[bot]");
6863        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
6864        assert_eq!(comments[0].line, Some(231));
6865        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
6866    }
6867
6868    #[test]
6869    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
6870        assert!(
6871            is_noise(CODERABBIT_TRIGGER),
6872            "CodeRabbit's trigger notice declares itself not a review"
6873        );
6874        assert!(
6875            is_noise(CLAUDE_CHECKLIST),
6876            "a progress checklist asks for nothing"
6877        );
6878        assert!(
6879            !is_noise(CLAUDE_FINDING),
6880            "a review that names a bug is input, not noise"
6881        );
6882
6883        let mut clean = pr(Checks::Green, &[], 0);
6884        clean.review_comments.push(ReviewComment {
6885            author: "coderabbitai".to_owned(),
6886            path: None,
6887            line: None,
6888            body: CODERABBIT_TRIGGER.to_owned(),
6889        });
6890        clean.review_comments.retain(|c| !is_noise(&c.body));
6891        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
6892
6893        let mut found = pr(Checks::Green, &[], 0);
6894        found.review_comments.push(ReviewComment {
6895            author: "claude".to_owned(),
6896            path: None,
6897            line: None,
6898            body: CLAUDE_FINDING.to_owned(),
6899        });
6900        found.review_comments.retain(|c| !is_noise(&c.body));
6901        assert!(matches!(
6902            decide(&found, 0, 4, Duration::ZERO),
6903            Step::Fix { .. }
6904        ));
6905    }
6906
6907    #[test]
6908    fn the_policy_table_holds_for_every_combination_that_matters() {
6909        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
6910            (
6911                "pending checks are waited for, even on the last round",
6912                pr(Checks::Pending, &[], 0),
6913                4,
6914                4,
6915                Duration::ZERO,
6916                Step::Wait,
6917            ),
6918            (
6919                "red checks are fixed",
6920                pr(Checks::Red, &["editorconfig"], 0),
6921                0,
6922                4,
6923                Duration::ZERO,
6924                Step::Fix {
6925                    reason: "1 check(s) failing: editorconfig".to_owned(),
6926                },
6927            ),
6928            (
6929                "green with comments is fixed, not merged",
6930                pr(Checks::Green, &[], 2),
6931                1,
6932                4,
6933                Duration::ZERO,
6934                Step::Fix {
6935                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
6936                        .to_owned(),
6937                },
6938            ),
6939            (
6940                "green and clean merges",
6941                pr(Checks::Green, &[], 0),
6942                3,
6943                4,
6944                Duration::ZERO,
6945                Step::Merge,
6946            ),
6947            (
6948                "an unreadable rollup is waited on while the grace lasts",
6949                pr(Checks::Unknown, &[], 0),
6950                0,
6951                4,
6952                Duration::ZERO,
6953                Step::Wait,
6954            ),
6955            (
6956                "an unreadable rollup is never merged once the grace is spent",
6957                pr(Checks::Unknown, &[], 0),
6958                0,
6959                4,
6960                CHECKS_GRACE,
6961                Step::GiveUp {
6962                    reason: "no check status is readable on the pull request after 3 minute(s); \
6963                             refusing to merge on a guess"
6964                        .to_owned(),
6965                },
6966            ),
6967        ];
6968        for (what, state, round, budget, waited, want) in cases {
6969            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
6970        }
6971    }
6972
6973    #[test]
6974    fn the_forge_verdict_survives_the_round_trip_from_gh() {
6975        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
6976        // requested but never parsed is the kind of thing that looks wired up
6977        // and answers `Unsaid` forever.
6978        let green = parse_pr(GREEN_OPEN).expect("parse");
6979        assert_eq!(green.blocking, Blocking::No);
6980        let red = parse_pr(RED_OPEN).expect("parse");
6981        assert_eq!(
6982            red.blocking,
6983            Blocking::No,
6984            "`UNSTABLE` is mergeable: the red check is one nobody requires"
6985        );
6986        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
6987        // A payload from an older `gh` has no such field at all.
6988        let quiet =
6989            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
6990        assert_eq!(quiet.blocking, Blocking::Unsaid);
6991    }
6992
6993    #[test]
6994    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
6995        // Pull request 37's only red check was `editorconfig`, failing
6996        // because the action could not fetch its own binary after
6997        // editorconfig-checker v4 renamed its release assets. The repository
6998        // does not require it. magi answered by asking a fixer to repair a
6999        // change that was fine, and the pull request had to be merged by hand.
7000        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7001        nonblocking.blocking = Blocking::No;
7002        assert_eq!(
7003            decide(&nonblocking, 0, 4, Duration::ZERO),
7004            Step::Merge,
7005            "the forge says nothing is in the way, so nothing is"
7006        );
7007
7008        // The same red, gated on: that is a fix round, as before.
7009        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7010        blocking.blocking = Blocking::Yes;
7011        assert!(matches!(
7012            decide(&blocking, 0, 4, Duration::ZERO),
7013            Step::Fix { .. }
7014        ));
7015
7016        // A review comment still outranks green-enough: a non-required red
7017        // must not become a way to merge past an unanswered reviewer.
7018        let mut commented = pr(Checks::Red, &["coverage"], 1);
7019        commented.blocking = Blocking::No;
7020        assert!(matches!(
7021            decide(&commented, 0, 4, Duration::ZERO),
7022            Step::Fix { .. }
7023        ));
7024
7025        // And silence from the forge is not consent.
7026        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7027        unsaid.blocking = Blocking::Unsaid;
7028        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7029        assert!(matches!(
7030            decide(&unsaid, 0, 4, CHECKS_GRACE),
7031            Step::Fix { .. }
7032        ));
7033    }
7034
7035    #[test]
7036    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7037        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7038        red.blocking = Blocking::No;
7039        assert_eq!(
7040            decide(&red, 0, 4, Duration::ZERO),
7041            Step::Merge,
7042            "announcing must not change the decision"
7043        );
7044        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7045        assert!(said.contains("yukimemi/magi"), "{said}");
7046        assert!(said.contains("#16"), "{said}");
7047        assert!(
7048            said.contains("https://github.com/yukimemi/magi/pull/16"),
7049            "{said}"
7050        );
7051        assert!(
7052            said.contains("test (windows-latest)") && said.contains("coverage"),
7053            "{said}"
7054        );
7055
7056        // `failing` can be left over on a green observation; only `checks` counts.
7057        let green = pr(Checks::Green, &["stale"], 0);
7058        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7059    }
7060
7061    #[test]
7062    fn red_merge_notices_omit_empty_check_details() {
7063        for checks in [vec![], vec!["", "  "]] {
7064            let red = pr(Checks::Red, &checks, 0);
7065            let summary = red_merge_summary("owner/repo", &red).unwrap();
7066            let notice = crate::notices::merged_red("run-1", &summary);
7067            assert_eq!(
7068                notice.message,
7069                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7070            );
7071            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7072        }
7073        let red = pr(Checks::Red, &["", " test ", " "], 0);
7074        let summary = red_merge_summary("owner/repo", &red).unwrap();
7075        assert!(summary.contains("with red checks: test ("), "{summary}");
7076    }
7077
7078    #[test]
7079    fn the_repo_label_comes_from_the_pull_request_url() {
7080        let p = Path::new("/tmp/checkout");
7081        assert_eq!(
7082            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7083            "yukimemi/magi"
7084        );
7085        assert_eq!(repo_label(p, "not a url"), "checkout");
7086    }
7087
7088    #[test]
7089    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7090        // Pull requests 35 and 37 were both rebased by hand: a competition
7091        // that runs for two hours against a repository merging pull requests
7092        // all day conflicts on the way in, and that is arithmetic rather
7093        // than a defect in the change.
7094        let mut conflicted = pr(Checks::Green, &[], 0);
7095        conflicted.blocking = Blocking::Conflict;
7096        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7097
7098        // Decided before the checks, and even with the rounds spent: every
7099        // check on a branch that cannot land is an answer about a state that
7100        // cannot land, and a conflict is not the change's fault.
7101        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7102        red.blocking = Blocking::Conflict;
7103        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7104
7105        // The lifecycle still wins over everything, conflict included.
7106        let mut merged = pr(Checks::Red, &[], 0);
7107        merged.blocking = Blocking::Conflict;
7108        merged.state = PrLifecycle::Merged;
7109        assert_eq!(
7110            decide(&merged, 0, 4, Duration::ZERO),
7111            Step::Done { merged: true }
7112        );
7113    }
7114
7115    #[test]
7116    fn the_forge_verdict_is_read_off_merge_state_status() {
7117        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7118        // matters: mergeable, with a non-required check red or still running.
7119        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7120            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7121            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7122        }
7123        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7124        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7125        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7126        // An older `gh`, or a token without the scope, says nothing - and
7127        // refusing to guess is the rule everywhere else in this module.
7128        for quiet in ["", "UNKNOWN"] {
7129            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7130            assert!(Blocking::of(quiet).stops_a_merge());
7131        }
7132    }
7133
7134    #[test]
7135    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7136        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7137        // The exact stderr from run ec12, in a jj-colocated repository.
7138        let jj = "could not determine current branch: failed to run git: not on any branch";
7139
7140        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7141            .expect("the forge says merged, so it merged");
7142        assert!(landed.ok);
7143        assert!(
7144            landed.detail.contains("but the pull request is merged"),
7145            "the record must not read as a clean success: {}",
7146            landed.detail
7147        );
7148        assert!(
7149            landed.detail.contains("not on any branch"),
7150            "and it must keep what the command actually said: {}",
7151            landed.detail
7152        );
7153
7154        // A pull request still open means the merge really failed.
7155        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7156        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7157        // And an unreadable answer is not evidence of success.
7158        assert!(merged_after_all(&argv, jj, None).is_none());
7159    }
7160
7161    #[test]
7162    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7163        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7164        state.state = PrLifecycle::Closed;
7165        assert_eq!(
7166            decide(&state, 0, 4, Duration::ZERO),
7167            Step::Done { merged: false },
7168            "a human closing the pull request ends the loop, whatever CI says"
7169        );
7170    }
7171
7172    #[test]
7173    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7174        let red = decide(
7175            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7176            4,
7177            4,
7178            Duration::ZERO,
7179        );
7180        match red {
7181            Step::GiveUp { reason } => {
7182                assert!(reason.contains("editorconfig"), "reason: {reason}");
7183                assert!(reason.contains("test (macos)"), "reason: {reason}");
7184                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7185            }
7186            other => panic!("expected a give-up, got {other:?}"),
7187        }
7188
7189        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7190        match commented {
7191            Step::GiveUp { reason } => {
7192                assert!(reason.contains("unresolved"), "reason: {reason}");
7193                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7194            }
7195            other => panic!("expected a give-up, got {other:?}"),
7196        }
7197    }
7198
7199    #[test]
7200    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7201        let candidate_commit = "magi: candidate A (uncommitted work)";
7202        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7203        let argv = merge_argv(16, &subject);
7204
7205        assert!(argv.contains(&"--squash".to_owned()));
7206        assert!(argv.contains(&"--delete-branch".to_owned()));
7207        assert!(argv.contains(&"--subject".to_owned()));
7208        assert_eq!(
7209            argv.last().map(String::as_str),
7210            Some("add retries to the uploader"),
7211            "the subject must not be the candidate commit message"
7212        );
7213        assert_ne!(subject, candidate_commit);
7214    }
7215
7216    #[test]
7217    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7218        assert_eq!(
7219            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7220            "feat: a queue, an unattended loop, and a phone UI"
7221        );
7222        assert_eq!(
7223            merge_subject("", "# port the retry logic\n\ndetails"),
7224            "port the retry logic",
7225            "an empty title falls back to the task's first line, heading marks stripped"
7226        );
7227    }
7228
7229    #[test]
7230    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7231        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7232        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7233        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7234        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7235        assert_eq!(run_of(""), None);
7236    }
7237
7238    #[test]
7239    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7240        let mut out = Vec::new();
7241        push_if_outstanding(
7242            &mut out,
7243            ReviewComment {
7244                author: "yukimemi".to_owned(),
7245                path: None,
7246                line: None,
7247                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7248            },
7249        );
7250        assert!(out.is_empty());
7251    }
7252
7253    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7254    /// falls back to the repository - which keeps these tests free of a
7255    /// worktree, a `git` invocation and a network.
7256    fn run_state() -> RunState {
7257        let mut state = RunState::new(
7258            std::path::PathBuf::from("/repo/magi"),
7259            "main".to_owned(),
7260            "abcdef1234".to_owned(),
7261            "add retries to the uploader".to_owned(),
7262            crate::config::Config::default(),
7263        );
7264        // These fixtures test execution flow, independent of host disk capacity.
7265        state.config.disk.min_free_bytes = 0;
7266        // Tests run in parallel against one persistent home and the ids
7267        // `RunState::new` draws from the clock can repeat, so two tests would
7268        // share a run's questions. The home also outlives the process, so the
7269        // counter alone would reuse an earlier run's ids.
7270        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7271        let nanos = std::time::SystemTime::now()
7272            .duration_since(std::time::UNIX_EPOCH)
7273            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7274        state.id = format!(
7275            "20261004-{nanos:06}-{:04x}",
7276            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7277        );
7278        state
7279    }
7280
7281    fn green_pr() -> PrState {
7282        PrState {
7283            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7284            number: 42,
7285            state: PrLifecycle::Open,
7286            checks: Checks::Green,
7287            // The forge sees nothing in the way unless a test says otherwise.
7288            blocking: Blocking::No,
7289            failing: Vec::new(),
7290            review_comments: vec![ReviewComment {
7291                author: "coderabbitai".to_owned(),
7292                path: Some("src/land.rs".to_owned()),
7293                line: Some(212),
7294                body: "this branch never checks the exit code".to_owned(),
7295            }],
7296        }
7297    }
7298
7299    #[test]
7300    fn land_fixer_defers_review_and_verification_without_a_cache() {
7301        let state = run_state();
7302        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7303        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7304        assert!(p.contains("Commit in this worktree"), "{p}");
7305    }
7306
7307    #[test]
7308    fn github_facing_land_text_is_english_whatever_the_language() {
7309        let mut state = run_state();
7310        state.config.graph.language = "ja".to_owned();
7311        let comment = stop_comment(&state.id, "checks are still red");
7312        assert!(crate::github_text::check("", &comment).is_empty());
7313        assert!(comment.is_ascii(), "{comment}");
7314        assert!(comment.starts_with(MARKER));
7315
7316        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7317        let ja_at = p.find("Write all prose in ja").unwrap();
7318        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7319        assert!(ja_at < rule_at, "{p}");
7320        assert!(p.contains("stays in Japanese"), "{p}");
7321
7322        state.config.graph.language = "en".to_owned();
7323        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7324        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7325        assert!(!p.contains("does not apply"), "{p}");
7326    }
7327
7328    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7329
7330    fn panel() -> String {
7331        approval_panel(
7332            &run_state(),
7333            &green_pr(),
7334            NUMSTAT,
7335            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7336            &[
7337                "land: ask before merging".to_owned(),
7338                "land: colour the diff".to_owned(),
7339            ],
7340            "feat: merge approval from the phone",
7341        )
7342    }
7343
7344    #[test]
7345    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7346        let html = panel();
7347        for needle in [
7348            "42",
7349            "main",
7350            "src/land.rs",
7351            "src/web.rs",
7352            "assets/logo.png",
7353            "feat: merge approval from the phone",
7354            "land: ask before merging",
7355            "land: colour the diff",
7356            "coderabbitai",
7357            "this branch never checks the exit code",
7358            "green",
7359        ] {
7360            assert!(html.contains(needle), "the panel must state `{needle}`");
7361        }
7362    }
7363
7364    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7365        crate::run::pin_test_home();
7366        let tmp = tempfile::tempdir().unwrap();
7367        let repo = tmp.path().join("repo");
7368        let remote = tmp.path().join("remote.git");
7369        std::fs::create_dir(&repo).unwrap();
7370        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7371            .await
7372            .unwrap();
7373        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7374        git::git(&repo, &["config", "user.name", "Test"])
7375            .await
7376            .unwrap();
7377        git::git(&repo, &["config", "user.email", "test@example.test"])
7378            .await
7379            .unwrap();
7380        std::fs::write(repo.join("base"), "base").unwrap();
7381        git::git(&repo, &["add", "."]).await.unwrap();
7382        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7383        git::git(
7384            &repo,
7385            &["remote", "add", "origin", remote.to_str().unwrap()],
7386        )
7387        .await
7388        .unwrap();
7389        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7390        git::git(&repo, &["checkout", "-b", "winner"])
7391            .await
7392            .unwrap();
7393        std::fs::write(repo.join("change"), "change").unwrap();
7394        git::git(&repo, &["add", "."]).await.unwrap();
7395        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7396        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7397        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7398            .await
7399            .unwrap();
7400        let mut state = run_state();
7401        state.repo = repo.clone();
7402        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7403        state.config.graph.land = true;
7404        state.config.graph.land_approval = true;
7405        state.pr_head = Some("task-head".into());
7406        state.pr_pushed_head = Some(head.clone());
7407        state.candidates = vec![winning_candidate("change")];
7408        state.candidates[0].worktree = repo;
7409        state.candidates[0].branch = "winner".into();
7410        state.tally = Some(uncontested_tally());
7411        state.gate_ran = true;
7412        state.gate_head = Some(head.clone());
7413        state.land_sync_pending = true;
7414        state.save().unwrap();
7415        (tmp, state, head)
7416    }
7417
7418    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7419        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7420        resume_landing_head(state, head, &green_pr().url, &forge, None).await
7421    }
7422
7423    async fn advance_landing_base(state: &RunState) {
7424        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7425        std::fs::write(state.repo.join("advance"), "advance").unwrap();
7426        git::git(&state.repo, &["add", "."]).await.unwrap();
7427        git::git(&state.repo, &["commit", "-m", "advance base"])
7428            .await
7429            .unwrap();
7430        git::git(&state.repo, &["push", "origin", "main"])
7431            .await
7432            .unwrap();
7433        git::git(&state.repo, &["checkout", "winner"])
7434            .await
7435            .unwrap();
7436    }
7437
7438    #[tokio::test]
7439    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
7440        let (_tmp, mut state, head) = landing_git_fixture().await;
7441        advance_landing_base(&state).await;
7442        let scratch = state.dir().join("rebase");
7443        std::fs::create_dir_all(&scratch).unwrap();
7444        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
7445        let attempts = state.land_sync_attempts;
7446        let error = rebase_landing_worktree(&mut state, "origin/main")
7447            .await
7448            .unwrap_err();
7449        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
7450        assert_eq!(state.land_sync_attempts, attempts);
7451        assert!(state.land_sync_target.is_none());
7452        assert!(state.rebase_fixes.is_empty());
7453        assert!(
7454            state
7455                .base_sync
7456                .as_ref()
7457                .is_none_or(|sync| sync.conflict.is_none())
7458        );
7459        let block = state.resource_block.as_ref().unwrap();
7460        assert_eq!(block.kind, crate::rebase::SEQUENCER_INFRASTRUCTURE);
7461        assert!(
7462            block.detail.contains("inspect scratch Git backlink"),
7463            "{}",
7464            block.detail
7465        );
7466        assert_eq!(
7467            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
7468            "keep"
7469        );
7470        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
7471        std::fs::remove_dir_all(&scratch).unwrap();
7472        state.resource_block = None;
7473        assert_eq!(
7474            rebase_landing_worktree(&mut state, "origin/main")
7475                .await
7476                .unwrap(),
7477            crate::rebase::Rebased::Applied
7478        );
7479        assert_eq!(state.land_sync_attempts, attempts + 1);
7480        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
7481        assert!(git::is_clean(&state.repo).await.unwrap());
7482        assert!(state.rebase_fixes.is_empty());
7483    }
7484
7485    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7486    {
7487        let (tmp, mut state, old) = landing_git_fixture().await;
7488        let path = tmp.path().join("foreign");
7489        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7490            .await
7491            .unwrap();
7492        state.foreign_checkout = Some(
7493            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7494                .await
7495                .unwrap(),
7496        );
7497        state.config.merge.mode = crate::config::MergeMode::Pr;
7498        state.save().unwrap();
7499        (tmp, state, old, path)
7500    }
7501
7502    #[tokio::test]
7503    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
7504        for phase in 0..4 {
7505            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7506            advance_landing_base(&state).await;
7507            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
7508            if phase == 0 {
7509                // The live Step::Rebase path uses this same synchronization
7510                // and publication pair, without going through resume.
7511                assert_eq!(
7512                    rebase_landing_worktree(&mut state, "origin/main")
7513                        .await
7514                        .unwrap(),
7515                    crate::rebase::Rebased::Applied
7516                );
7517            } else {
7518                interrupt_landing_rebase(&mut state).await;
7519                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
7520                if phase == 2 {
7521                    git::sync_to_head(&state.repo).await.unwrap();
7522                } else if phase == 3 {
7523                    // Crash after joining history, before clearing its saved
7524                    // start. Repeating restoration must not add another merge.
7525                    restore_landing_worktree(&mut state).await.unwrap();
7526                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7527                    state.land_rebase_from = Some(old.clone());
7528                    state.save().unwrap();
7529                    restore_landing_worktree(&mut state).await.unwrap();
7530                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
7531                }
7532                state.save().unwrap();
7533                state = RunState::load(&state.id).unwrap();
7534                restore_landing_worktree(&mut state).await.unwrap();
7535                assert_eq!(
7536                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
7537                    repaired_tree
7538                );
7539            }
7540            let head = if phase == 0 {
7541                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
7542                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
7543                    .await
7544                    .unwrap()
7545            } else {
7546                resume_observed_head(&mut state, &old).await.unwrap()
7547            };
7548            assert!(git::is_ancestor(&state.repo, &old, &head).await);
7549            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7550            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7551            assert_eq!(
7552                git::remote_head(&state.repo, "origin", "task-head")
7553                    .await
7554                    .unwrap(),
7555                Some(head.clone())
7556            );
7557            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7558            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
7559            assert!(state.gate_allows_progress());
7560            assert!(state.land_rebase_from.is_none());
7561            assert!(!state.land_sync_pending);
7562            assert!(git::is_clean(&path).await.unwrap());
7563        }
7564    }
7565
7566    #[tokio::test]
7567    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
7568        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7569        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7570        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7571        git::commit_all(&state.repo, "conflicting base")
7572            .await
7573            .unwrap();
7574        git::git(&state.repo, &["push", "origin", "main"])
7575            .await
7576            .unwrap();
7577        git::git(&state.repo, &["checkout", "winner"])
7578            .await
7579            .unwrap();
7580        landing_gate_fixer(
7581            &mut state,
7582            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7583        );
7584        state.config.graph.gate_fix_rounds = 0;
7585        state.config.verify.gate = vec!["exit 1".into()];
7586        assert!(resume_observed_head(&mut state, &old).await.is_err());
7587        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
7588        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7589        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
7590        assert_eq!(
7591            std::fs::read_to_string(state.repo.join("change")).unwrap(),
7592            "resolved"
7593        );
7594        // A red gate must neither deliver nor publish the repaired tree.
7595        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
7596        assert_eq!(
7597            git::remote_head(&state.repo, "origin", "task-head")
7598                .await
7599                .unwrap(),
7600            Some(old.clone())
7601        );
7602        state = RunState::load(&state.id).unwrap();
7603        state.config.verify.gate = vec!["grep -q resolved change".into()];
7604        let head = resume_observed_head(&mut state, &old).await.unwrap();
7605        assert_eq!(head, repaired);
7606        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7607        assert_eq!(
7608            std::fs::read_to_string(path.join("change")).unwrap(),
7609            "resolved"
7610        );
7611        assert_eq!(
7612            git::remote_head(&state.repo, "origin", "task-head")
7613                .await
7614                .unwrap(),
7615            Some(head.clone())
7616        );
7617        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7618        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7619        assert!(git::is_clean(&path).await.unwrap());
7620    }
7621
7622    #[tokio::test]
7623    async fn landing_resume_completes_the_last_charged_sync_attempt() {
7624        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
7625            let (_tmp, mut state, old) = landing_git_fixture().await;
7626            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7627            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7628            git::commit_all(&state.repo, "conflicting base")
7629                .await
7630                .unwrap();
7631            git::git(&state.repo, &["push", "origin", "main"])
7632                .await
7633                .unwrap();
7634            git::git(&state.repo, &["checkout", "winner"])
7635                .await
7636                .unwrap();
7637            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
7638            state.config.graph.land_rounds = 1;
7639            state.land_sync_attempts = 1;
7640            state.land_sync_target = saved_target.then(|| target.clone());
7641            state.land_rebase_from = Some(old.clone());
7642            landing_gate_fixer(
7643                &mut state,
7644                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7645            );
7646            state.config.verify.gate = vec!["grep -q resolved change".into()];
7647            state.save().unwrap();
7648            // Simulate interruption before the scratch start and at a conflict.
7649            if scratch_started {
7650                assert!(matches!(
7651                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
7652                        .await
7653                        .unwrap(),
7654                    git::RebaseStart::Conflicted(_)
7655                ));
7656            }
7657            state = RunState::load(&state.id).unwrap();
7658            let head = resume_observed_head(&mut state, &old).await.unwrap();
7659            assert_ne!(head, old);
7660            assert_eq!(state.land_sync_attempts, 1);
7661            assert!(state.land_sync_target.is_none());
7662            assert!(state.land_rebase_from.is_none());
7663            assert!(!state.land_sync_pending);
7664            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7665            assert!(state.gate_allows_progress());
7666            assert_eq!(
7667                git::remote_head(&state.repo, "origin", "task-head")
7668                    .await
7669                    .unwrap(),
7670                Some(head)
7671            );
7672            assert!(
7673                rebase_landing_worktree(&mut state, "origin/main")
7674                    .await
7675                    .unwrap_err()
7676                    .to_string()
7677                    .contains("budget exhausted")
7678            );
7679        }
7680    }
7681
7682    #[tokio::test]
7683    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
7684        let (_tmp, mut state, old) = landing_git_fixture().await;
7685        advance_landing_base(&state).await;
7686        state.config.verify.gate = vec!["test -f advance".into()];
7687        let head = resume_observed_head(&mut state, &old).await.unwrap();
7688        assert_ne!(head, old);
7689        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7690        assert!(state.gate_allows_progress());
7691        assert_eq!(
7692            git::remote_head(&state.repo, "origin", "task-head")
7693                .await
7694                .unwrap(),
7695            Some(head.clone())
7696        );
7697        assert_eq!(state.pr_pushed_head, Some(head));
7698        assert!(!state.land_sync_pending);
7699        assert!(state.config.graph.land_approval);
7700    }
7701
7702    fn landing_gate_fixer(state: &mut RunState, script: &str) {
7703        state.config.disk.min_free_bytes = 0;
7704        state.config.graph.gate_fix_rounds = 1;
7705        state.config.agents = vec![crate::config::AgentSpec {
7706            id: "mock".into(),
7707            kind: crate::config::AgentKind::Command,
7708            model: None,
7709            command: vec!["sh".into(), "-c".into(), script.into()],
7710            extra_args: Vec::new(),
7711            env: Default::default(),
7712            prompt_delivery: None,
7713            max_turn_secs: None,
7714        }];
7715        state.candidates[0].agent = "mock".into();
7716    }
7717
7718    #[tokio::test]
7719    async fn rebase_fixer_invocation_cap_survives_fallback_and_reload() {
7720        let (tmp, mut state, original) = landing_git_fixture().await;
7721        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7722        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7723        git::commit_all(&state.repo, "conflicting base")
7724            .await
7725            .unwrap();
7726        let target = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7727        git::git(&state.repo, &["checkout", "winner"])
7728            .await
7729            .unwrap();
7730        let scratch = state.dir().join("rebase");
7731        let counter = tmp.path().join("calls");
7732        landing_gate_fixer(
7733            &mut state,
7734            "echo \"$REBASE_AGENT\" >> \"$REBASE_COUNTER\"; exit 1",
7735        );
7736        let template = state.config.agents[0].clone();
7737        let ids = ["mock", "fallback1", "fallback2", "fallback3"].map(str::to_owned);
7738        state.config.agents = ids
7739            .iter()
7740            .map(|id| {
7741                let mut spec = template.clone();
7742                spec.id.clone_from(id);
7743                spec.env.insert("REBASE_AGENT".into(), id.clone());
7744                spec.env
7745                    .insert("REBASE_COUNTER".into(), git::path_arg(&counter));
7746                spec
7747            })
7748            .collect();
7749        state.config.roles.fixer = Some(crate::config::AgentChoice::Chain(ids.to_vec()));
7750        state.config.graph.review_rounds = 3;
7751        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
7752        state.config.graph.timeout_resource_wait = 0;
7753        let started = git::rebase_start(&state.repo, &scratch, "winner", &target)
7754            .await
7755            .unwrap();
7756        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
7757        let home = crate::run::home();
7758        let cache = crate::build_target::resolve(&home, &scratch).unwrap();
7759        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", &scratch, &original);
7760        let crate::cache::AcquireOutcome::Acquired(lease) =
7761            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
7762        else {
7763            panic!("test target was already leased");
7764        };
7765        let error = crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
7766            .await
7767            .unwrap_err();
7768        assert!(error.is::<crate::agent::IsolatedSeatWait>(), "{error:#}");
7769        assert!(!counter.exists());
7770        assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), ["change"]);
7771        drop(lease);
7772        state = RunState::load(&state.id).unwrap();
7773        for _ in 0..2 {
7774            let crate::rebase::Rebased::Stopped(why) =
7775                crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
7776                    .await
7777                    .unwrap()
7778            else {
7779                panic!("the unresolved conflict must stop");
7780            };
7781            assert!(why.contains("after 3 of 3 fixer round(s)"), "{why}");
7782            assert_eq!(
7783                std::fs::read_to_string(&counter)
7784                    .unwrap()
7785                    .lines()
7786                    .collect::<Vec<_>>(),
7787                ["mock", "fallback1", "fallback2"]
7788            );
7789            assert_eq!(
7790                git::rev_parse(&state.repo, "winner").await.unwrap(),
7791                original
7792            );
7793            state = RunState::load(&state.id).unwrap();
7794        }
7795    }
7796
7797    #[tokio::test]
7798    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
7799        let (_tmp, mut state, old) = landing_git_fixture().await;
7800        std::fs::write(state.repo.join("change"), "operator update").unwrap();
7801        git::commit_all(&state.repo, "extend winner").await.unwrap();
7802        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7803        git::git(
7804            &state.repo,
7805            &["push", "origin", "HEAD:refs/heads/task-head"],
7806        )
7807        .await
7808        .unwrap();
7809        state.config.verify.gate = vec!["exit 1".into()];
7810        state.config.graph.gate_fix_rounds = 0;
7811        assert!(resume_observed_head(&mut state, &updated).await.is_err());
7812        assert_ne!(old, updated);
7813        assert_eq!(state.gate_head.as_ref(), Some(&updated));
7814        assert!(!state.gate_allows_progress());
7815        assert!(state.land_sync_pending);
7816        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
7817        let head = resume_observed_head(&mut state, &updated).await.unwrap();
7818        assert_eq!(head, updated);
7819        assert!(state.gate_allows_progress());
7820        assert!(!state.land_sync_pending);
7821        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7822        land_with(&mut state, &green_pr().url, &forge)
7823            .await
7824            .unwrap();
7825        assert!(state.parked);
7826        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7827        assert!(forge.argvs().is_empty());
7828    }
7829
7830    #[tokio::test]
7831    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
7832        for divergent in [false, true] {
7833            let (_tmp, mut state, old) = landing_git_fixture().await;
7834            if divergent {
7835                git::git(&state.repo, &["reset", "--hard", "origin/main"])
7836                    .await
7837                    .unwrap();
7838            }
7839            std::fs::write(state.repo.join("external"), "external").unwrap();
7840            git::commit_all(&state.repo, "external update")
7841                .await
7842                .unwrap();
7843            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7844            git::git(
7845                &state.repo,
7846                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
7847            )
7848            .await
7849            .unwrap();
7850            if !divergent {
7851                git::git(&state.repo, &["reset", "--hard", &old])
7852                    .await
7853                    .unwrap();
7854            }
7855            let error = resume_observed_head(&mut state, &external)
7856                .await
7857                .unwrap_err();
7858            assert!(
7859                error
7860                    .to_string()
7861                    .contains("public head moved outside this run")
7862            );
7863            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
7864            assert_eq!(
7865                git::remote_head(&state.repo, "origin", "task-head")
7866                    .await
7867                    .unwrap(),
7868                Some(external)
7869            );
7870        }
7871    }
7872
7873    #[tokio::test]
7874    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
7875        let (_tmp, mut state, old) = landing_git_fixture().await;
7876        advance_landing_base(&state).await;
7877        landing_gate_fixer(
7878            &mut state,
7879            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7880        );
7881        state.config.verify.gate =
7882            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7883        state.config.verify.e2e = vec!["test -f advance".into()];
7884        // First save a red gate without spending a fixer round. Resume must
7885        // still offer the remaining budget for this exact same failed head.
7886        state.config.graph.gate_fix_rounds = 0;
7887        assert!(resume_observed_head(&mut state, &old).await.is_err());
7888        assert_eq!(
7889            git::remote_head(&state.repo, "origin", "task-head")
7890                .await
7891                .unwrap(),
7892            Some(old.clone())
7893        );
7894        state.config.graph.gate_fix_rounds = 1;
7895        let head = resume_observed_head(&mut state, &old).await.unwrap();
7896        assert_eq!(state.gate_fixes.len(), 1);
7897        assert!(state.gate_fixes[0].committed);
7898        assert!(state.gate_allows_progress());
7899        assert_eq!(state.gate_head.as_ref(), Some(&head));
7900        assert_eq!(
7901            git::remote_head(&state.repo, "origin", "task-head")
7902                .await
7903                .unwrap(),
7904            Some(head.clone())
7905        );
7906        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7907        land_with(&mut state, &green_pr().url, &forge)
7908            .await
7909            .unwrap();
7910        assert!(state.parked);
7911        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7912        assert!(forge.argvs().is_empty());
7913    }
7914
7915    #[tokio::test]
7916    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
7917        let (_tmp, mut state, old) = landing_git_fixture().await;
7918        advance_landing_base(&state).await;
7919        landing_gate_fixer(
7920            &mut state,
7921            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7922        );
7923        state.config.verify.gate = vec!["echo still red; exit 1".into()];
7924        for _ in 0..2 {
7925            assert!(resume_observed_head(&mut state, &old).await.is_err());
7926            assert_eq!(state.gate_fixes.len(), 1);
7927            assert_eq!(
7928                git::remote_head(&state.repo, "origin", "task-head")
7929                    .await
7930                    .unwrap(),
7931                Some(old.clone())
7932            );
7933        }
7934    }
7935
7936    #[tokio::test]
7937    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
7938        let (_tmp, mut state, old) = landing_git_fixture().await;
7939        advance_landing_base(&state).await;
7940        landing_gate_fixer(
7941            &mut state,
7942            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7943        );
7944        state.config.verify.gate =
7945            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7946        // The repair makes the gate green while breaking an e2e invariant.
7947        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
7948        let mut saved_comparison = None;
7949        for resume in 0..3 {
7950            assert!(resume_observed_head(&mut state, &old).await.is_err());
7951            state = RunState::load(&state.id).unwrap();
7952            let evidence = state.gate_repair_e2e.as_ref().unwrap();
7953            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7954            assert_eq!(evidence.head, head);
7955            assert!(!evidence.passed);
7956            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
7957            let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
7958            if let Some(saved) = &saved_comparison {
7959                assert_eq!(comparison, saved);
7960            } else {
7961                saved_comparison = Some(comparison.clone());
7962            }
7963            assert_eq!(state.gate_fixes.len(), 1);
7964            assert_eq!(
7965                git::remote_head(&state.repo, "origin", "task-head")
7966                    .await
7967                    .unwrap(),
7968                Some(old.clone())
7969            );
7970            if resume > 0 {
7971                assert!(
7972                    state.gate_allows_progress(),
7973                    "a green gate must not bypass red e2e"
7974                );
7975            }
7976        }
7977        // A changed command is not new evidence about the already checked SHA.
7978        state.config.verify.e2e = vec!["grep -q fixed change".into()];
7979        assert!(resume_observed_head(&mut state, &old).await.is_err());
7980        assert_eq!(
7981            state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
7982            saved_comparison
7983        );
7984    }
7985
7986    #[tokio::test]
7987    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
7988        for phase in 0..3 {
7989            let (_tmp, mut state, old) = landing_git_fixture().await;
7990            advance_landing_base(&state).await;
7991            let head = resume_observed_head(&mut state, &old).await.unwrap();
7992            // Persist the shapes left by interruption, resource deferral,
7993            // and a successful check for a different (older) SHA.
7994            state.land_sync_pending = true;
7995            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
7996            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
7997                if phase == 2 {
7998                    old.clone()
7999                } else {
8000                    head.clone()
8001                },
8002                phase == 2,
8003                if phase == 1 {
8004                    vec![crate::run::CommandOutcome {
8005                        command: state.config.verify.e2e[0].clone(),
8006                        code: None,
8007                        output_tail: "verification resource unavailable".into(),
8008                        duration_ms: 0,
8009                        resource_blocked: true,
8010                        ..Default::default()
8011                    }]
8012                } else {
8013                    Vec::new()
8014                },
8015            ));
8016            state.save().unwrap();
8017            for _ in 0..2 {
8018                state = RunState::load(&state.id).unwrap();
8019                assert!(resume_observed_head(&mut state, &head).await.is_err());
8020                let evidence = state.gate_repair_e2e.as_ref().unwrap();
8021                assert_eq!(evidence.head, head);
8022                assert!(!evidence.passed);
8023                assert!(!evidence.outcomes.is_empty());
8024                assert_eq!(
8025                    git::remote_head(&state.repo, "origin", "task-head")
8026                        .await
8027                        .unwrap(),
8028                    Some(head.clone())
8029                );
8030                assert!(state.land_sync_pending);
8031            }
8032        }
8033    }
8034
8035    #[tokio::test]
8036    async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
8037        for code in [None, Some(126), Some(127)] {
8038            let (_tmp, mut state, old) = landing_git_fixture().await;
8039            advance_landing_base(&state).await;
8040            let head = resume_observed_head(&mut state, &old).await.unwrap();
8041            state.land_sync_pending = true;
8042            state.config.verify.e2e = vec!["true".into()];
8043            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8044                head.clone(),
8045                false,
8046                vec![crate::run::CommandOutcome {
8047                    command: state.config.verify.e2e[0].clone(),
8048                    code,
8049                    output_tail: "verification command did not complete".into(),
8050                    ..Default::default()
8051                }],
8052            ));
8053            state.save().unwrap();
8054            state = RunState::load(&state.id).unwrap();
8055            assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
8056            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8057            assert_eq!(evidence.head, head);
8058            assert!(evidence.passed);
8059            assert_eq!(evidence.outcomes[0].code, Some(0));
8060        }
8061    }
8062
8063    async fn interrupt_landing_rebase(state: &mut RunState) {
8064        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
8065        state.save().unwrap();
8066        let scratch = state.dir().join("rebase");
8067        assert_eq!(
8068            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
8069                .await
8070                .unwrap(),
8071            crate::rebase::Rebased::Applied
8072        );
8073        assert!(!git::is_clean(&state.repo).await.unwrap());
8074    }
8075
8076    async fn landing_setup(state: &mut RunState) {
8077        git::git(
8078            &state.repo,
8079            &["config", "extensions.worktreeConfig", "true"],
8080        )
8081        .await
8082        .unwrap();
8083        state.config.worktree.setup =
8084            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8085        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8086            .await
8087            .unwrap();
8088        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8089    }
8090
8091    #[tokio::test]
8092    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8093        let (tmp, mut state, head) = landing_git_fixture().await;
8094        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8095        git::acquire_worktree_config(&state.repo).await.unwrap();
8096        let winner = tmp.path().join("landing");
8097        git::worktree_add_existing(&state.repo, &winner, "winner", false)
8098            .await
8099            .unwrap();
8100        state.candidates[0].worktree = winner.clone();
8101        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8102        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8103        state.config.disk.min_free_bytes = 0;
8104        state.config.worktree.setup = vec![crate::config::SetupStep {
8105            run: Some("touch setup-completed".into()),
8106            ..Default::default()
8107        }];
8108        #[cfg(unix)]
8109        {
8110            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8111            state.config.coordination = Some(crate::config::Coordination {
8112                contract_file: "fixture-contract".into(),
8113                contract_token: "fixture-v1".into(),
8114                lock_file: "fixture-lock".into(),
8115            });
8116        }
8117        state.land_rebase_from = Some(head);
8118        let restore = restore_landing_worktree(&mut state);
8119        // Only the registered Unix fixture can deadlock by reacquiring its
8120        // own operation lease. Don't time the whole Git/setup path elsewhere.
8121        #[cfg(unix)]
8122        let restore = async {
8123            tokio::time::timeout(Duration::from_secs(15), restore)
8124                .await
8125                .expect("landing setup must not wait for its own repository operation")
8126        };
8127        restore.await.unwrap();
8128        assert!(winner.join("setup-completed").is_file());
8129        assert!(git::is_clean(&winner).await.unwrap());
8130        assert!(state.land_rebase_from.is_none());
8131    }
8132
8133    #[tokio::test]
8134    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8135        for phase in 0..3 {
8136            let (_tmp, mut state, old) = landing_git_fixture().await;
8137            advance_landing_base(&state).await;
8138            landing_setup(&mut state).await;
8139            if phase > 0 {
8140                interrupt_landing_rebase(&mut state).await;
8141                if phase == 2 {
8142                    // Crash after clean removed setup products, before setup.
8143                    git::sync_to_head(&state.repo).await.unwrap();
8144                    assert!(!state.repo.join(".env").exists());
8145                }
8146                state = RunState::load(&state.id).unwrap();
8147            }
8148            let head = resume_observed_head(&mut state, &old).await.unwrap();
8149            assert_ne!(head, old);
8150            assert!(state.gate_allows_progress());
8151            assert!(state.land_rebase_from.is_none());
8152            assert_eq!(
8153                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8154                "secret"
8155            );
8156            assert!(git::is_clean(&state.repo).await.unwrap());
8157            assert!(
8158                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8159                    .await
8160                    .unwrap()
8161                    .contains(".env")
8162            );
8163        }
8164    }
8165
8166    #[tokio::test]
8167    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8168        let (_tmp, mut state, _) = landing_git_fixture().await;
8169        advance_landing_base(&state).await;
8170        landing_setup(&mut state).await;
8171        interrupt_landing_rebase(&mut state).await;
8172        // Exercise unusual names without asking Windows to create an invalid
8173        // control-character filename. Unix also covers embedded newlines.
8174        let locals = [
8175            "local notes",
8176            #[cfg(unix)]
8177            "local\nnotes",
8178        ];
8179        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8180            .await
8181            .unwrap();
8182        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
8183        for local in locals {
8184            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8185            assert!(
8186                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8187                    .await
8188                    .unwrap()
8189                    .ok()
8190            );
8191        }
8192        restore_landing_worktree(&mut state).await.unwrap();
8193        for local in locals {
8194            assert_eq!(
8195                std::fs::read_to_string(state.repo.join(local)).unwrap(),
8196                "keep these notes"
8197            );
8198        }
8199        assert_eq!(
8200            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8201            "secret"
8202        );
8203        assert!(git::is_clean(&state.repo).await.unwrap());
8204        assert!(state.land_rebase_from.is_none());
8205    }
8206
8207    #[tokio::test]
8208    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8209        for local in ["advance", "advance/notes", "new-directory"] {
8210            let (_tmp, mut state, _) = landing_git_fixture().await;
8211            advance_landing_base(&state).await;
8212            // Also cover a local file blocking a new tracked directory.
8213            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8214            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8215            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8216            git::git(&state.repo, &["add", "."]).await.unwrap();
8217            git::git(&state.repo, &["commit", "-m", "add directory"])
8218                .await
8219                .unwrap();
8220            git::git(&state.repo, &["push", "origin", "main"])
8221                .await
8222                .unwrap();
8223            git::git(&state.repo, &["checkout", "winner"])
8224                .await
8225                .unwrap();
8226            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8227                .await
8228                .unwrap();
8229            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8230            let path = state.repo.join(local);
8231            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8232            std::fs::write(&path, "local notes").unwrap();
8233            interrupt_landing_rebase(&mut state).await;
8234            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8235            let checkpoint = state.land_rebase_from.clone();
8236            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8237            assert!(
8238                error.to_string().contains("conflicting with HEAD"),
8239                "{error:#}"
8240            );
8241            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8242            assert_eq!(
8243                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8244                before
8245            );
8246            assert_eq!(state.land_rebase_from, checkpoint);
8247        }
8248    }
8249
8250    #[tokio::test]
8251    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8252        for interrupted in [false, true] {
8253            let (_tmp, mut state, old) = landing_git_fixture().await;
8254            assert!(state.config.worktree.setup.is_empty());
8255            // A gate product exists before the base moves, without setup metadata.
8256            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8257                .await
8258                .unwrap();
8259            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8260            state.config.verify.gate =
8261                vec!["mkdir -p target && printf artifact > target/probe".into()];
8262            state.gate_ran = false;
8263            resume_observed_head(&mut state, &old).await.unwrap();
8264            assert_eq!(
8265                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8266                "artifact"
8267            );
8268            advance_landing_base(&state).await;
8269            if interrupted {
8270                interrupt_landing_rebase(&mut state).await;
8271                state = RunState::load(&state.id).unwrap();
8272            }
8273            state.config.verify.gate =
8274                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8275            let head = resume_observed_head(&mut state, &old).await.unwrap();
8276            assert_ne!(head, old);
8277            assert!(state.gate_allows_progress());
8278            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8279            assert_eq!(
8280                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8281                "artifact"
8282            );
8283            assert!(state.land_rebase_from.is_none());
8284            assert_eq!(
8285                git::remote_head(&state.repo, "origin", "task-head")
8286                    .await
8287                    .unwrap(),
8288                Some(head.clone())
8289            );
8290            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8291            land_with(&mut state, &green_pr().url, &forge)
8292                .await
8293                .unwrap();
8294            assert!(state.parked);
8295            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8296            assert!(forge.argvs().is_empty());
8297        }
8298    }
8299
8300    #[tokio::test]
8301    #[cfg(unix)]
8302    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8303        use std::os::fd::AsRawFd as _;
8304
8305        for interrupted in [false, true] {
8306            let (_tmp, mut state, _) = landing_git_fixture().await;
8307            advance_landing_base(&state).await;
8308            landing_setup(&mut state).await;
8309            if interrupted {
8310                interrupt_landing_rebase(&mut state).await;
8311            }
8312            state.config.worktree.setup =
8313                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8314            let common = crate::repo_lock::common_dir(&state.repo)
8315                .await
8316                .unwrap()
8317                .unwrap();
8318            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8319            state.config.coordination = crate::config::test_coordination();
8320            state.config.graph.timeout_resource_wait = 0;
8321            let external = std::fs::OpenOptions::new()
8322                .read(true)
8323                .write(true)
8324                .create(true)
8325                .truncate(false)
8326                .open(common.join("updater.lock"))
8327                .unwrap();
8328            // SAFETY: the descriptor belongs to `external` and remains open.
8329            let locked =
8330                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8331            assert_eq!(locked, 0);
8332            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8333            let checkpoint = state.land_rebase_from.clone();
8334            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8335            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8336            assert_eq!(
8337                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8338                before
8339            );
8340            assert_eq!(state.land_rebase_from, checkpoint);
8341            assert_eq!(
8342                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8343                "secret"
8344            );
8345
8346            drop(external);
8347            state.config.graph.timeout_resource_wait = 2;
8348            restore_landing_worktree(&mut state).await.unwrap();
8349            assert!(git::is_clean(&state.repo).await.unwrap());
8350            assert!(state.land_rebase_from.is_none());
8351            assert_eq!(
8352                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8353                "restored"
8354            );
8355        }
8356    }
8357
8358    #[tokio::test]
8359    #[cfg(unix)]
8360    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8361        use std::sync::atomic::{AtomicBool, Ordering};
8362
8363        let (_tmp, mut state, _) = landing_git_fixture().await;
8364        advance_landing_base(&state).await;
8365        landing_setup(&mut state).await;
8366        interrupt_landing_rebase(&mut state).await;
8367        let common = crate::repo_lock::common_dir(&state.repo)
8368            .await
8369            .unwrap()
8370            .unwrap();
8371        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8372        state.config.coordination = crate::config::test_coordination();
8373        let holder = crate::repo_lock::SeatLease::for_checkout(
8374            &state.repo,
8375            true,
8376            state.config.coordination.as_ref(),
8377        )
8378        .await
8379        .unwrap();
8380        assert!(holder.is_some());
8381        let cancelled = Arc::new(AtomicBool::new(false));
8382        let signal = cancelled.clone();
8383        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8384            signal.load(Ordering::SeqCst)
8385        });
8386        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8387        let checkpoint = state.land_rebase_from.clone();
8388        let (result, ()) = tokio::join!(
8389            tokio::time::timeout(
8390                Duration::from_secs(2),
8391                wait.scope(restore_landing_worktree(&mut state)),
8392            ),
8393            async {
8394                tokio::time::sleep(Duration::from_millis(100)).await;
8395                cancelled.store(true, Ordering::SeqCst);
8396            }
8397        );
8398        let error = result
8399            .expect("cancellation must release the waiting driver")
8400            .unwrap_err();
8401        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8402        assert_eq!(
8403            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8404            before
8405        );
8406        assert_eq!(state.land_rebase_from, checkpoint);
8407        assert_eq!(
8408            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8409            "secret"
8410        );
8411        drop(holder);
8412        restore_landing_worktree(&mut state).await.unwrap();
8413        assert!(state.land_rebase_from.is_none());
8414        assert!(git::is_clean(&state.repo).await.unwrap());
8415    }
8416
8417    #[tokio::test]
8418    #[cfg(unix)]
8419    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8420        use std::sync::atomic::{AtomicBool, Ordering};
8421
8422        for e2e in [false, true] {
8423            let (_tmp, mut state, head) = landing_git_fixture().await;
8424            let common = crate::repo_lock::common_dir(&state.repo)
8425                .await
8426                .unwrap()
8427                .unwrap();
8428            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8429            state.config.coordination = crate::config::test_coordination();
8430            if e2e {
8431                state.config.verify.e2e = vec!["true".into()];
8432                state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8433                    head.clone(),
8434                    false,
8435                    Vec::new(),
8436                ));
8437            } else {
8438                state.config.verify.gate = vec!["true".into()];
8439                state.gate_ran = false;
8440            }
8441            let holder = crate::repo_lock::SeatLease::for_checkout(
8442                &state.repo,
8443                true,
8444                state.config.coordination.as_ref(),
8445            )
8446            .await
8447            .unwrap();
8448            assert!(holder.is_some());
8449            let cancelled = Arc::new(AtomicBool::new(false));
8450            let signal = cancelled.clone();
8451            let waiting = Arc::new(tokio::sync::Notify::new());
8452            let observed = waiting.clone();
8453            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8454                observed.notify_one();
8455                signal.load(Ordering::SeqCst)
8456            });
8457            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8458            let url = green_pr().url;
8459            let result = {
8460                let mut publishing =
8461                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8462                // Git and fixture I/O precede local coordination. Start the
8463                // cancellation deadline only once the inherited wait policy
8464                // is polled, rather than timing those unrelated subprocesses.
8465                tokio::time::timeout(Duration::from_secs(30), async {
8466                    tokio::select! {
8467                        result = &mut publishing => panic!(
8468                            "verification must wait behind the held seat: {result:?}"
8469                        ),
8470                        () = waiting.notified() => {}
8471                    }
8472                })
8473                .await
8474                .expect("verification must reach the inherited coordination wait");
8475                cancelled.store(true, Ordering::SeqCst);
8476                tokio::time::timeout(Duration::from_secs(2), publishing).await
8477            };
8478            let error = result
8479                .expect("cancellation must release the verification waiter")
8480                .unwrap_err();
8481            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8482            assert!(error.to_string().contains("cancelled"), "{error:#}");
8483            assert!(forge.argvs().is_empty());
8484            assert_eq!(
8485                git::remote_head(&state.repo, "origin", "task-head")
8486                    .await
8487                    .unwrap(),
8488                Some(head.clone())
8489            );
8490            drop(holder);
8491            // Cancellation must release its reservation so another attempt can verify.
8492            assert_eq!(
8493                publish_landing_head(&mut state, &head, &url, &forge)
8494                    .await
8495                    .unwrap(),
8496                head
8497            );
8498        }
8499    }
8500
8501    #[tokio::test]
8502    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
8503        for staged in [false, true] {
8504            let (_tmp, mut state, old) = landing_git_fixture().await;
8505            advance_landing_base(&state).await;
8506            interrupt_landing_rebase(&mut state).await;
8507            std::fs::write(state.repo.join("change"), "user edit").unwrap();
8508            if staged {
8509                git::git(&state.repo, &["add", "change"]).await.unwrap();
8510            }
8511            assert!(resume_observed_head(&mut state, &old).await.is_err());
8512            assert_eq!(
8513                std::fs::read_to_string(state.repo.join("change")).unwrap(),
8514                "user edit"
8515            );
8516            assert_eq!(
8517                git::remote_head(&state.repo, "origin", "task-head")
8518                    .await
8519                    .unwrap(),
8520                Some(old)
8521            );
8522        }
8523    }
8524
8525    #[tokio::test]
8526    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
8527        let (_tmp, mut state, head) = landing_git_fixture().await;
8528        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8529        let id = state.id.clone();
8530        let pr = land_with(&mut state, &green_pr().url, &forge)
8531            .await
8532            .unwrap();
8533        assert_eq!(pr.state, PrLifecycle::Open);
8534        assert_eq!(state.id, id);
8535        assert!(state.parked);
8536        assert_eq!(state.status, RunStatus::Landing);
8537        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8538        assert!(forge.argvs().is_empty());
8539
8540        state.land_sync_pending = true;
8541        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
8542        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
8543        closed.pr.state = PrLifecycle::Closed;
8544        let forge = Scripted::new(vec![closed], vec![]);
8545        assert_eq!(
8546            land_with(&mut state, &green_pr().url, &forge)
8547                .await
8548                .unwrap()
8549                .state,
8550            PrLifecycle::Closed
8551        );
8552        assert_eq!(
8553            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
8554            "do not touch"
8555        );
8556        assert!(forge.argvs().is_empty());
8557    }
8558
8559    #[tokio::test]
8560    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
8561        let (_tmp, mut state, old) = landing_git_fixture().await;
8562        advance_landing_base(&state).await;
8563        state.config.verify.gate = vec!["exit 1".into()];
8564        assert!(resume_observed_head(&mut state, &old).await.is_err());
8565        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
8566        assert!(!state.gate_allows_progress());
8567        assert_eq!(
8568            git::remote_head(&state.repo, "origin", "task-head")
8569                .await
8570                .unwrap(),
8571            Some(old)
8572        );
8573        assert!(state.land_sync_pending);
8574    }
8575
8576    #[tokio::test]
8577    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
8578        let (_tmp, mut state, old) = landing_git_fixture().await;
8579        advance_landing_base(&state).await;
8580        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
8581        // Model a crash after the push but before saving its published SHA.
8582        state.pr_pushed_head = Some(old.clone());
8583        state.land_sync_pending = true;
8584        assert_eq!(
8585            resume_observed_head(&mut state, &pushed).await.unwrap(),
8586            pushed
8587        );
8588        // A writer races the observed PR snapshot: the explicit remote lease
8589        // must reject the push even though preflight saw our expected head.
8590        git::git(
8591            &state.repo,
8592            &["push", "--force", "origin", "main:refs/heads/task-head"],
8593        )
8594        .await
8595        .unwrap();
8596        assert!(
8597            publish_landing_head(
8598                &mut state,
8599                &pushed,
8600                &green_pr().url,
8601                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
8602            )
8603            .await
8604            .unwrap_err()
8605            .to_string()
8606            .contains("publishing gated")
8607        );
8608        assert!(
8609            resume_observed_head(&mut state, "foreign-head")
8610                .await
8611                .is_err()
8612        );
8613    }
8614    #[tokio::test]
8615    async fn landing_publication_refuses_a_pr_closed_during_gate() {
8616        let (_tmp, mut state, head) = landing_git_fixture().await;
8617        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
8618        closed.pr.state = PrLifecycle::Closed;
8619        let forge = Scripted::new(vec![closed], vec![]);
8620        assert!(
8621            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
8622                .await
8623                .unwrap_err()
8624                .to_string()
8625                .contains("PR closed or merged")
8626        );
8627    }
8628
8629    /// A candidate selected by the uncontested tally.
8630    fn winning_candidate(summary: &str) -> Candidate {
8631        Candidate {
8632            index: 0,
8633            label: 'A',
8634            agent: "opus".to_owned(),
8635            branch: "magi/x/A".to_owned(),
8636            worktree: PathBuf::from("/wt/A"),
8637            summary: summary.to_owned(),
8638            stat: String::new(),
8639            files: 1,
8640            commits: 1,
8641            empty: false,
8642            failed: None,
8643            verified_noop: None,
8644            duration_ms: 0,
8645            folded: false,
8646        }
8647    }
8648
8649    fn uncontested_tally() -> Tally {
8650        Tally {
8651            first_choice: BTreeMap::from([('A', 1)]),
8652            borda: BTreeMap::new(),
8653            winner: 'A',
8654            rankings: 1,
8655            unanimous_initial: true,
8656            deliberated: false,
8657            changed_votes: 0,
8658            unanimous_final: true,
8659            tie_break: None,
8660            judges: 1,
8661            present: 1,
8662            quorum: 1,
8663            met_quorum: true,
8664            uncontested: None,
8665        }
8666    }
8667
8668    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
8669        ReviewRecord {
8670            attempts: 0,
8671            reviewer,
8672            agent: agent.to_owned(),
8673            summary: summary.to_owned(),
8674            findings: Vec::new(),
8675            vote: None,
8676            failed: None,
8677            duration_ms: 0,
8678        }
8679    }
8680
8681    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
8682        let answered = reviews.len();
8683        ReviewRound {
8684            round,
8685            head: "abc1234".to_owned(),
8686            verified_head: None,
8687            verified_at: None,
8688            reviews,
8689            e2e: Vec::new(),
8690            verify_retried: false,
8691            e2e_deferred: false,
8692            e2e_defer_reason: None,
8693            fix: None,
8694            blocking: 0,
8695            answered,
8696            expected: answered,
8697            clean: true,
8698            progressed: false,
8699            vote_split: false,
8700            reconsideration: Vec::new(),
8701            verdict: None,
8702        }
8703    }
8704
8705    #[test]
8706    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
8707        let en = panel();
8708        assert!(en.contains("Task"), "{en}");
8709        assert!(en.contains("add retries to the uploader"), "{en}");
8710
8711        let mut state = run_state();
8712        state.config.graph.language = "ja".to_owned();
8713        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8714        assert!(ja.contains("タスク"), "{ja}");
8715        assert!(
8716            ja.contains("add retries to the uploader"),
8717            "the task itself is not translated: {ja}"
8718        );
8719    }
8720
8721    #[test]
8722    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
8723        // `run_state()` has no candidates, no tally and no reviews - exactly
8724        // the shape a run has before anything has judged or reviewed it, and
8725        // the panel must not print an empty box for either.
8726        let html = panel();
8727        assert!(!html.contains("What changed"), "{html}");
8728        assert!(!html.contains("Review verdict"), "{html}");
8729    }
8730
8731    #[test]
8732    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
8733        let mut state = run_state();
8734        state.candidates = vec![winning_candidate("")];
8735        state.tally = Some(uncontested_tally());
8736        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8737        assert!(
8738            !html.contains("What changed"),
8739            "an empty summary must not render an empty box: {html}"
8740        );
8741    }
8742
8743    #[test]
8744    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
8745        let mut state = run_state();
8746        state.candidates = vec![winning_candidate(
8747            "Added a retry loop around the uploader PUT call.",
8748        )];
8749        state.tally = Some(uncontested_tally());
8750        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8751        assert!(en.contains("What changed"), "{en}");
8752        assert!(
8753            en.contains("Added a retry loop around the uploader PUT call."),
8754            "{en}"
8755        );
8756
8757        state.config.graph.language = "ja".to_owned();
8758        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8759        assert!(ja.contains("変更内容"), "{ja}");
8760        assert!(
8761            ja.contains("Added a retry loop around the uploader PUT call."),
8762            "{ja}"
8763        );
8764    }
8765
8766    #[test]
8767    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
8768        let mut state = run_state();
8769        state.reviews = vec![
8770            review_round(
8771                1,
8772                vec![review_record(1, "alpha", "found a race, sent back")],
8773            ),
8774            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
8775        ];
8776        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8777        assert!(en.contains("Review verdict"), "{en}");
8778        assert!(en.contains("race is fixed, clean"), "{en}");
8779        assert!(
8780            !en.contains("found a race, sent back"),
8781            "only the round that actually cleared the merge should show: {en}"
8782        );
8783
8784        state.config.graph.language = "ja".to_owned();
8785        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8786        assert!(ja.contains("レビューの結論"), "{ja}");
8787        assert!(ja.contains("レビュアー"), "{ja}");
8788        assert!(ja.contains("race is fixed, clean"), "{ja}");
8789    }
8790
8791    /// The `incomplete_review = "warn"` policy (see
8792    /// `graph::Runner::review_loop`) can push a `clean` round to
8793    /// `state.reviews` while one seat's own record still has `failed: Some`
8794    /// and an empty `summary` - a seat that never answered, not one that
8795    /// answered with nothing to say.
8796    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
8797        ReviewRecord {
8798            attempts: 0,
8799            reviewer,
8800            agent: agent.to_owned(),
8801            summary: String::new(),
8802            findings: Vec::new(),
8803            vote: None,
8804            failed: Some(reason.to_owned()),
8805            duration_ms: 0,
8806        }
8807    }
8808
8809    #[test]
8810    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
8811        let mut state = run_state();
8812        state.reviews = vec![review_round(
8813            1,
8814            vec![
8815                review_record(1, "alpha", "clean, nothing to add"),
8816                unanswered_review_record(2, "beta", "timed out"),
8817            ],
8818        )];
8819        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8820        assert!(en.contains("clean, nothing to add"), "{en}");
8821        assert!(
8822            en.contains("produced no answer: timed out"),
8823            "a seat that never answered must say so, not render a blank box: {en}"
8824        );
8825        assert!(
8826            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
8827            "no reviewer box may be left empty: {en}"
8828        );
8829
8830        state.config.graph.language = "ja".to_owned();
8831        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8832        assert!(ja.contains("回答なし: timed out"), "{ja}");
8833    }
8834
8835    #[test]
8836    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
8837        let html = panel();
8838        assert!(!html.contains("<script"), "no script survives the csp");
8839        assert!(!html.contains("<form"), "form-action is 'none'");
8840        let pr = green_pr();
8841        assert_eq!(
8842            html.matches("http").count(),
8843            html.matches(pr.url.as_str()).count(),
8844            "the only http url in the panel is the pull request's own link"
8845        );
8846        assert!(
8847            html.contains("target=\"_blank\""),
8848            "the PR link must open in a new tab so it escapes the iframe"
8849        );
8850        assert!(
8851            html.contains("rel=\"noopener noreferrer\""),
8852            "external links opening in new tabs must carry noopener noreferrer"
8853        );
8854    }
8855
8856    #[test]
8857    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
8858        let html = panel();
8859        assert!(
8860            html.contains(">+</span>"),
8861            "an added line carries a `+` in the gutter, not only a background"
8862        );
8863        assert!(
8864            html.contains(">-</span>"),
8865            "a removed line carries a `-` in the gutter, not only a background"
8866        );
8867        assert!(
8868            html.contains(">new line</span>"),
8869            "the marker is moved to the gutter, so the body is printed once without it"
8870        );
8871    }
8872
8873    #[test]
8874    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
8875        let total = DIFF_MAX_LINES + 100;
8876        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
8877        let html = approval_panel(
8878            &run_state(),
8879            &green_pr(),
8880            NUMSTAT,
8881            &diff,
8882            &[],
8883            "feat: something long",
8884        );
8885        assert!(
8886            html.contains(&format!("100 of {total} diff lines omitted")),
8887            "the note must say exactly how much was cut"
8888        );
8889        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
8890        assert!(
8891            !html.contains(&format!("line {DIFF_MAX_LINES}")),
8892            "nothing past the threshold is rendered"
8893        );
8894        assert!(
8895            html.contains("/repo/magi"),
8896            "the note says where the rest is"
8897        );
8898    }
8899
8900    #[test]
8901    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
8902        let html = approval_panel(
8903            &run_state(),
8904            &green_pr(),
8905            "1\t2\tsrc/<b>&\"x\"'.rs",
8906            "",
8907            &[],
8908            "subject",
8909        );
8910        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
8911        assert!(
8912            !html.contains("<b>"),
8913            "an agent-influenced path must never become markup"
8914        );
8915    }
8916
8917    #[tokio::test]
8918    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
8919        let a = std::path::PathBuf::from("/repo/a");
8920        let b = std::path::PathBuf::from("/repo/b");
8921
8922        let held = repo_merge_lock(&a).lock_owned().await;
8923
8924        // A second, concurrent land run against the *same* repository must
8925        // wait - `try_lock` fails while `held` is alive.
8926        assert!(
8927            repo_merge_lock(&a).try_lock().is_err(),
8928            "a second merge into the same repository must not proceed concurrently"
8929        );
8930
8931        // A run against a *different* repository must not be blocked by it -
8932        // this is what keeps a slow rebase or `gh pr merge` in one
8933        // repository from also stalling a land-approval resume in another.
8934        assert!(
8935            repo_merge_lock(&b).try_lock().is_ok(),
8936            "a different repository's merge lock must be independent"
8937        );
8938
8939        drop(held);
8940        assert!(
8941            repo_merge_lock(&a).try_lock().is_ok(),
8942            "the lock is released once the holder is done"
8943        );
8944    }
8945
8946    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
8947        let mut state = landing_state();
8948        let mut rec = review_record(1, "alpha", "precise rejection reason");
8949        rec.vote = Some(if reject {
8950            crate::verdict::ReviewVote::Reject
8951        } else {
8952            crate::verdict::ReviewVote::Approve
8953        });
8954        if major {
8955            rec.findings = contested().findings;
8956        }
8957        let mut round = review_round(1, vec![rec]);
8958        round.clean = false;
8959        round.blocking = usize::from(major);
8960        state.reviews.push(round);
8961        state.config.graph.review_rounds = 1;
8962        state
8963    }
8964
8965    #[test]
8966    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
8967        for every in [false, true] {
8968            for contested in [false, true] {
8969                for major in [false, true] {
8970                    for reject in [false, true] {
8971                        let mut state = repair_state(major, reject);
8972                        state.config.graph.land_approval = every;
8973                        state.config.graph.hold_contested_merge = contested;
8974                        let reasons = approval_reasons(&state);
8975                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
8976                        assert_eq!(
8977                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
8978                            contested && major
8979                        );
8980                        assert_eq!(
8981                            reasons.contains(&ApprovalReason::FinalReject),
8982                            contested && reject
8983                        );
8984                        assert_eq!(
8985                            reasons.len(),
8986                            usize::from(every)
8987                                + usize::from(contested && major)
8988                                + usize::from(contested && reject)
8989                        );
8990                    }
8991                }
8992            }
8993        }
8994    }
8995
8996    #[test]
8997    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
8998        use crate::verdict::ReviewVote::{Approve, Reject};
8999        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
9000            let mut state = repair_state(false, initial_reject);
9001            state.reviews[0]
9002                .reconsideration
9003                .push(crate::run::ReviewRevoteRecord {
9004                    reviewer: 1,
9005                    agent: "alpha".into(),
9006                    vote: Some(final_vote),
9007                    reason: "changed after reading the panel <evidence>".into(),
9008                    failed: None,
9009                });
9010            assert_eq!(
9011                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9012                final_vote == Reject
9013            );
9014            for language in ["en", "ja"] {
9015                state.config.graph.language = language.into();
9016                let evidence = approval_evidence(&state);
9017                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
9018                assert!(evidence.contains("changed after reading the panel <evidence>"));
9019                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9020                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
9021                assert!(!html.contains("<evidence>"));
9022            }
9023            state.reviews[0].reconsideration[0].vote = None;
9024            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
9025            assert_eq!(
9026                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9027                initial_reject
9028            );
9029            assert!(approval_evidence(&state).contains("timed out"));
9030        }
9031    }
9032
9033    #[tokio::test]
9034    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
9035        for every in [false, true] {
9036            for contested in [false, true] {
9037                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
9038                {
9039                    let mut state = repair_state(major, reject);
9040                    state.config.graph.land_approval = every;
9041                    state.config.graph.hold_contested_merge = contested;
9042                    let forge = Scripted::new(
9043                        vec![seen("abc", Checks::Green, "CLEAN", false)],
9044                        vec![(true, "")],
9045                    );
9046                    land_with(&mut state, URL, &forge).await.unwrap();
9047                    let expected = every || (contested && (major || reject));
9048                    assert_eq!(state.land_approval.is_some(), expected);
9049                    assert_eq!(forge.calls().contains(&"merge"), !expected);
9050                    if expected {
9051                        assert!(state.parked);
9052                    }
9053                }
9054            }
9055        }
9056    }
9057
9058    #[tokio::test]
9059    async fn reviewed_branch_hold_is_read_before_landing_decision() {
9060        for (base, control) in [
9061            (false, "land_approval"),
9062            (true, "land_approval"),
9063            (false, "hold_contested_merge"),
9064        ] {
9065            let (_tmp, mut state, _) = landing_git_fixture().await;
9066            state.config.graph.land_approval = base;
9067            state.config.graph.hold_contested_merge = false;
9068            state.reviewed_commits = Some(Vec::new());
9069            if control == "hold_contested_merge" {
9070                state.reviews = repair_state(false, true).reviews;
9071            }
9072            std::fs::write(
9073                state.repo.join("magi.toml"),
9074                format!("[graph]\n{control} = {}\n", !base),
9075            )
9076            .unwrap();
9077            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
9078            git::git(&state.repo, &["commit", "-m", "approval policy"])
9079                .await
9080                .unwrap();
9081            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9082            state.land_sync_pending = false;
9083            state.pr_pushed_head = Some(head.clone());
9084            state.gate_head = Some(head.clone());
9085            let forge = Scripted::new(
9086                vec![seen(&head, Checks::Green, "CLEAN", false)],
9087                vec![(true, "")],
9088            );
9089            land_with(&mut state, URL, &forge).await.unwrap();
9090            assert!(
9091                state.land_approval.is_some(),
9092                "base={base}, control={control}"
9093            );
9094            assert!(!forge.calls().contains(&"merge"));
9095            if !base {
9096                let question = ask::Questions::open()
9097                    .get(&state.land_approval.as_ref().unwrap().question)
9098                    .unwrap();
9099                assert!(question.detail.contains(&format!(
9100                    "{control}=true from the reviewed branch's magi.toml"
9101                )));
9102            }
9103        }
9104    }
9105
9106    #[tokio::test]
9107    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9108        for file in ["magi.toml", ".magi/config.toml"] {
9109            for control in crate::config::OwnerHold::ALL {
9110                let (_tmp, mut state, _) = landing_git_fixture().await;
9111                state.config.graph.land_approval = false;
9112                state.config.graph.hold_contested_merge = false;
9113                state.reviewed_commits = Some(Vec::new());
9114                if control == crate::config::OwnerHold::HoldContestedMerge {
9115                    state.reviews = repair_state(false, true).reviews;
9116                }
9117                let config = state.repo.join(file);
9118                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9119                std::fs::write(
9120                    &config,
9121                    format!(
9122                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9123                        control.key()
9124                    ),
9125                )
9126                .unwrap();
9127                git::git(&state.repo, &["add", file]).await.unwrap();
9128                git::git(&state.repo, &["commit", "-m", "require approval"])
9129                    .await
9130                    .unwrap();
9131                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9132                let gate = state.config.verify.gate.clone();
9133                state.observe_branch_owner_holds(&head).await;
9134                assert_eq!(state.config.verify.gate, gate);
9135                assert!(state.owner_hold(control));
9136                let holds = state.branch_owner_holds.clone();
9137                git::git(&state.repo, &["rm", file]).await.unwrap();
9138                git::git(&state.repo, &["commit", "-m", "remove config"])
9139                    .await
9140                    .unwrap();
9141                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9142                state.save().unwrap();
9143                state = RunState::load(&state.id).unwrap();
9144                state.observe_branch_owner_holds(&later).await;
9145                assert_eq!(state.branch_owner_holds, holds);
9146                assert_eq!(state.branch_owner_holds[0].head, head);
9147                state.land_sync_pending = false;
9148                state.pr_pushed_head = Some(later.clone());
9149                state.gate_head = Some(later.clone());
9150                let forge = Scripted::new(
9151                    vec![seen(&later, Checks::Green, "CLEAN", false)],
9152                    vec![(true, "")],
9153                );
9154                land_with(&mut state, URL, &forge).await.unwrap();
9155                assert!(!forge.calls().contains(&"merge"));
9156                assert!(state.parked);
9157                let question = ask::Questions::open()
9158                    .get(&state.land_approval.as_ref().unwrap().question)
9159                    .unwrap();
9160                assert!(question.detail.contains("Approval required because:"));
9161                assert!(question.detail.contains(&format!(
9162                    "{}=true from the reviewed branch's {file}",
9163                    control.key()
9164                )));
9165                assert_eq!(state.branch_owner_holds, holds);
9166                state.save().unwrap();
9167                let resumed = RunState::load(&state.id).unwrap();
9168                assert!(resumed.owner_hold(control));
9169                assert_eq!(resumed.branch_owner_holds, holds);
9170                assert_eq!(
9171                    resumed.land_approval.unwrap().question,
9172                    state.land_approval.unwrap().question
9173                );
9174            }
9175        }
9176    }
9177
9178    #[tokio::test]
9179    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9180        let mut state = repair_state(false, true);
9181        state.reviews[0].clean = true;
9182        let mut finding = contested().findings.remove(0);
9183        finding.severity = crate::verdict::Severity::Minor;
9184        state.reviews[0].reviews[0].findings.push(finding);
9185        assert!(state.open_findings().is_empty());
9186        let mut pr = green_pr();
9187        pr.review_comments.clear();
9188        for language in ["en", "ja"] {
9189            state.config.graph.language = language.into();
9190            let html = approval_panel(&state, &pr, "", "", &[], "subject");
9191            assert!(html.contains("[R3-1-1] minor"));
9192            assert!(html.contains(if language == "ja" {
9193                "内部指摘の解決を意味するものではありません"
9194            } else {
9195                "This does not mean internal findings are resolved"
9196            }));
9197            assert!(
9198                html.find(if language == "ja" {
9199                    "承認が必要な理由:"
9200                } else {
9201                    "Approval required because:"
9202                })
9203                .unwrap()
9204                    < html.find("[R3-1-1]").unwrap()
9205            );
9206        }
9207        state.config.graph.language = "en".into();
9208        let observed = seen("abc", Checks::Green, "CLEAN", false);
9209        assert_eq!(
9210            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9211                .await
9212                .unwrap(),
9213            ApprovalGate::Pending
9214        );
9215        let id = state.land_approval.as_ref().unwrap().question.clone();
9216        let q = ask::Questions::open().get(&id).unwrap();
9217        assert!(q.detail.starts_with("Approval required because:"));
9218        assert!(q.detail.contains("final reviewer reject"));
9219        assert!(q.detail.contains("[R3-1-1] minor"));
9220        assert!(
9221            q.detail
9222                .contains("No adoption or resolution evidence recorded")
9223        );
9224        state.config.graph.land_approval = false;
9225        state.config.graph.hold_contested_merge = false;
9226        state.reviews.clear();
9227        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9228        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9229        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9230        let forge = Scripted::new(vec![observed], vec![]);
9231        land_with(&mut state, URL, &forge).await.unwrap();
9232        assert!(!forge.calls().contains(&"merge"));
9233        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9234        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9235    }
9236
9237    #[tokio::test]
9238    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9239        let mut state = repair_state(false, true);
9240        state.config.graph.land_approval = false;
9241        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9242        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9243        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9244        state.reviews[0].reviews[0].summary = long_reason.clone();
9245        for i in 1..=10 {
9246            let mut finding = contested().findings.remove(0);
9247            finding.id = format!("R1-1-{i}");
9248            finding.severity = if i == 9 {
9249                crate::verdict::Severity::Major
9250            } else {
9251                crate::verdict::Severity::Minor
9252            };
9253            finding.title = long_title.clone();
9254            finding.detail = long_detail.clone();
9255            state.reviews[0].reviews[0].findings.push(finding);
9256        }
9257        state.reviews[0].fix = Some(crate::run::FixRecord {
9258            agent: "fixer".into(),
9259            addressed: vec!["R1-1-9".into()],
9260            rejected: vec![crate::verdict::Rejection {
9261                id: "R1-1-10".into(),
9262                why: long_reason.clone(),
9263            }],
9264            notes: long_detail.clone(),
9265            committed: false,
9266            failed: None,
9267            duration_ms: 0,
9268            continuation: None,
9269        });
9270        assert_eq!(
9271            approval_reasons(&state),
9272            [
9273                ApprovalReason::OpenBlockingFindings,
9274                ApprovalReason::FinalReject
9275            ]
9276        );
9277        let excerpt = approval_excerpt(&long_reason, 300);
9278        assert_eq!(excerpt.chars().count(), 300);
9279        assert!(excerpt.ends_with('…'));
9280        let boundary = "拒".repeat(300);
9281        assert_eq!(approval_excerpt(&boundary, 300), boundary);
9282        for language in ["en", "ja"] {
9283            state.config.graph.language = language.into();
9284            for revote in [
9285                None,
9286                Some(crate::verdict::ReviewVote::Reject),
9287                Some(crate::verdict::ReviewVote::Approve),
9288            ] {
9289                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9290                state.reviews[0].reconsideration.clear();
9291                if let Some(vote) = revote {
9292                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9293                    state.reviews[0]
9294                        .reconsideration
9295                        .push(crate::run::ReviewRevoteRecord {
9296                            reviewer: 1,
9297                            agent: "alpha".into(),
9298                            vote: Some(vote),
9299                            reason: long_reason.clone(),
9300                            failed: None,
9301                        });
9302                }
9303                let evidence = approval_evidence(&state);
9304                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9305                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9306                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9307                assert_eq!(
9308                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9309                    final_vote == crate::verdict::ReviewVote::Reject
9310                );
9311                assert!(evidence.contains(&excerpt));
9312                assert!(evidence.contains("[R1-1-8] minor"));
9313                assert!(evidence.contains("[R1-1-9] major"));
9314                assert!(evidence.contains("[R1-1-10] minor"));
9315                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9316                    assert!(!evidence.contains(tail));
9317                }
9318                assert!(evidence.contains(if language == "ja" {
9319                    "採用申告(解決未確認)"
9320                } else {
9321                    "claimed addressed (resolution unconfirmed)"
9322                }));
9323                assert!(evidence.contains(if language == "ja" {
9324                    "不採用理由"
9325                } else {
9326                    "declined"
9327                }));
9328                let major_evidence = evidence
9329                    .split("[R1-1-9] major")
9330                    .nth(1)
9331                    .unwrap()
9332                    .split("[R1-1-10]")
9333                    .next()
9334                    .unwrap();
9335                assert!(major_evidence.contains(if language == "ja" {
9336                    "採用申告(解決未確認)"
9337                } else {
9338                    "claimed addressed (resolution unconfirmed)"
9339                }));
9340                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9341                assert!(last_evidence.contains(if language == "ja" {
9342                    "不採用理由"
9343                } else {
9344                    "declined"
9345                }));
9346                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9347                assert!(html.contains(&esc(&evidence)));
9348                assert_eq!(
9349                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9350                        .await
9351                        .unwrap(),
9352                    ApprovalGate::Pending
9353                );
9354                let id = &state.land_approval.take().unwrap().question;
9355                let q = ask::Questions::open().get(id).unwrap();
9356                assert!(q.detail.starts_with(&evidence));
9357            }
9358            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9359        }
9360    }
9361
9362    #[test]
9363    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9364        for (major, reject) in [(true, false), (false, true), (true, true)] {
9365            let state = repair_state(major, reject);
9366            assert!(repair_available(&state));
9367            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9368        }
9369        assert!(!repair_available(&repair_state(false, false)));
9370        let mut clean = repair_state(true, false);
9371        clean.reviews[0].clean = true;
9372        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9373        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9374    }
9375
9376    #[tokio::test]
9377    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9378        let mut state = repair_state(true, false);
9379        let pr = green_pr();
9380        approval_gate(&mut state, &pr, "feat: x", None, "abc")
9381            .await
9382            .unwrap();
9383        let store = ask::Questions::open();
9384        let id = state.land_approval.as_ref().unwrap().question.clone();
9385        // Simulate an unanswered two-choice question created by an older build.
9386        store
9387            .update(&id, |q| {
9388                q.choices = vec![APPROVE.into(), HOLD.into()];
9389                Ok(())
9390            })
9391            .unwrap();
9392        let upgraded = store.get(&id).unwrap();
9393        assert_eq!(upgraded.choices, approval_choices(&state));
9394        assert!(!upgraded.actions.contains_key(HOLD));
9395        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9396        assert!(
9397            store
9398                .list()
9399                .iter()
9400                .any(|q| q.id == id && q.choices == upgraded.choices)
9401        );
9402        assert!(
9403            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9404        );
9405        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9406        store
9407            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9408            .unwrap();
9409        // An earlier build may have recorded the repair answer and stopped
9410        // before any driver consumed it. Reconcile that durable decision too.
9411        store
9412            .update(&id, |q| {
9413                q.actions.clear();
9414                Ok(())
9415            })
9416            .unwrap();
9417        assert_eq!(
9418            store.get(&id).unwrap().chosen_action(),
9419            Some(&ask::ChoiceAction::Resume {
9420                run: state.id.clone()
9421            })
9422        );
9423        let binding = state.land_approval.clone();
9424        assert_eq!(
9425            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9426                .await
9427                .unwrap(),
9428            ApprovalGate::Repair
9429        );
9430        assert!(state.land_approval.is_none());
9431        assert_eq!(state.merge_repairs.len(), 1);
9432        let request = &state.merge_repairs[0];
9433        assert_eq!(request.question, id);
9434        assert_eq!(request.head, "abc");
9435        assert_eq!(request.pr, pr.url);
9436        assert_eq!(
9437            request.reviews[0].reviews[0].summary,
9438            "precise rejection reason"
9439        );
9440        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9441        assert_eq!(
9442            request.reviews[0].reviews[0].findings[0].detail,
9443            state.reviews[0].reviews[0].findings[0].detail
9444        );
9445        // A repeated consumption of the same answer never dispatches another repair.
9446        state.land_approval = binding;
9447        assert_eq!(
9448            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9449                .await
9450                .unwrap(),
9451            ApprovalGate::Repair
9452        );
9453        assert_eq!(state.merge_repairs.len(), 1);
9454        state.land_approval = None;
9455        state.config.graph.land_approval = false;
9456        state.config.graph.hold_contested_merge = false;
9457        state.reviews.clear();
9458        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9459        assert_eq!(
9460            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9461                .await
9462                .unwrap(),
9463            ApprovalGate::Pending
9464        );
9465        let fresh_id = &state.land_approval.as_ref().unwrap().question;
9466        assert_ne!(fresh_id, &id);
9467        let fresh = store.get(fresh_id).unwrap();
9468        assert!(
9469            fresh
9470                .detail
9471                .contains("fresh owner approval after merge repair")
9472        );
9473        assert!(fresh.detail.contains("No review recorded"));
9474        assert!(!fresh.detail.contains("precise rejection reason"));
9475    }
9476
9477    #[tokio::test]
9478    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9479        for choice in [REPAIR, HOLD] {
9480            let mut state = repair_state(false, true);
9481            let observed = seen("abc", Checks::Green, "CLEAN", false);
9482            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9483                .await
9484                .unwrap();
9485            let id = state.land_approval.as_ref().unwrap().question.clone();
9486            ask::Questions::open()
9487                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9488                .unwrap();
9489            let forge = Scripted::new(vec![observed], vec![(true, "")]);
9490            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9491                .await
9492                .unwrap();
9493            assert!(
9494                forge
9495                    .argvs()
9496                    .iter()
9497                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
9498            );
9499            assert!(!forge.calls().contains(&"fix"));
9500            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
9501            assert_ne!(state.status, RunStatus::Merged);
9502        }
9503    }
9504
9505    #[test]
9506    fn only_the_merge_choice_merges_and_silence_holds() {
9507        let table = [
9508            (None, Approval::Hold),
9509            (Some("merge"), Approval::Merge),
9510            (Some(" merge\n"), Approval::Merge),
9511            (Some("hold"), Approval::Hold),
9512            (Some(""), Approval::Hold),
9513            (Some("yes"), Approval::Hold),
9514        ];
9515        for (answer, want) in table {
9516            assert_eq!(
9517                approval(answer),
9518                want,
9519                "answer {answer:?} must resolve to {want:?}"
9520            );
9521        }
9522    }
9523
9524    #[tokio::test]
9525    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
9526        let mut state = landing_state();
9527        state.config.graph.land_approval = true;
9528        let pr = green_pr();
9529
9530        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9531            .await
9532            .unwrap();
9533        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
9534        assert!(
9535            !state.parked,
9536            "approval_gate itself never sets `parked`; only its caller does"
9537        );
9538
9539        let store = ask::Questions::open();
9540        let filed: Vec<_> = store
9541            .list()
9542            .into_iter()
9543            .filter(|q| q.run == state.id)
9544            .collect();
9545        assert_eq!(filed.len(), 1, "exactly one question is filed");
9546        assert_eq!(filed[0].node, APPROVAL_NODE);
9547        assert_eq!(filed[0].choices, approval_choices(&state));
9548        assert!(filed[0].status.open());
9549
9550        // A second visit - standing in for a resumed run whose slot the
9551        // daemon handed to something else while nobody had answered - must
9552        // find the same question rather than filing a second one.
9553        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9554            .await
9555            .unwrap();
9556        assert_eq!(again, ApprovalGate::Pending);
9557        let still_one = store
9558            .list()
9559            .into_iter()
9560            .filter(|q| q.run == state.id)
9561            .count();
9562        assert_eq!(
9563            still_one, 1,
9564            "asking twice must not double-file the question"
9565        );
9566    }
9567
9568    #[tokio::test]
9569    async fn approving_the_existing_question_is_read_back_as_approved() {
9570        crate::run::pin_test_home();
9571        let mut state = run_state();
9572        state.config.graph.land_approval = true;
9573        let pr = green_pr();
9574        assert_eq!(
9575            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9576                .await
9577                .unwrap(),
9578            ApprovalGate::Pending
9579        );
9580
9581        let store = ask::Questions::open();
9582        let mut q = store
9583            .list()
9584            .into_iter()
9585            .find(|q| q.run == state.id)
9586            .expect("filed above");
9587        let talks = crate::talk::Talks::open();
9588        let cfg = crate::config::Config {
9589            agents: vec![crate::config::AgentSpec {
9590                id: "mock".into(),
9591                kind: crate::config::AgentKind::Command,
9592                model: None,
9593                command: vec!["true".into()],
9594                extra_args: Vec::new(),
9595                env: Default::default(),
9596                prompt_delivery: None,
9597                max_turn_secs: None,
9598            }],
9599            ..crate::config::Config::default()
9600        };
9601        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
9602        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
9603        crate::talk::drain(&mut talk, &talks).unwrap();
9604        assert_eq!(
9605            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9606                .await
9607                .unwrap(),
9608            ApprovalGate::Pending,
9609            "consultation cannot approve or hold the merge"
9610        );
9611        q = store.get(&q.id).unwrap();
9612        assert!(q.answer.is_none());
9613        // The owner's merge answer (from the chat or the card) is the approval.
9614        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9615        store.put(&mut q).unwrap();
9616
9617        assert_eq!(
9618            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9619                .await
9620                .unwrap(),
9621            ApprovalGate::Approved
9622        );
9623    }
9624
9625    #[tokio::test]
9626    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
9627        crate::run::pin_test_home();
9628        let store = ask::Questions::open();
9629        for via_list in [false, true] {
9630            let mut state = repair_state(false, true);
9631            let pr = green_pr();
9632            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9633                .await
9634                .unwrap();
9635            let id = state.land_approval.as_ref().unwrap().question.clone();
9636            store
9637                .update(&id, |q| {
9638                    q.actions.insert(
9639                        HOLD.to_owned(),
9640                        ask::ChoiceAction::Resume {
9641                            run: state.id.clone(),
9642                        },
9643                    );
9644                    Ok(())
9645                })
9646                .unwrap();
9647            let q = if via_list {
9648                store.list().into_iter().find(|q| q.id == id).unwrap()
9649            } else {
9650                store.get(&id).unwrap()
9651            };
9652            assert!(!q.actions.contains_key(HOLD));
9653            store
9654                .update(&id, |q| {
9655                    // Check the persisted migration, without another read upgrade.
9656                    assert!(!q.actions.contains_key(HOLD));
9657                    assert!(!upgrade_repair_choice(q, &state));
9658                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
9659                })
9660                .unwrap();
9661            assert!(store.get(&id).unwrap().chosen_action().is_none());
9662            assert_eq!(
9663                approval_gate(&mut state, &pr, "feat: x", None, "abc")
9664                    .await
9665                    .unwrap(),
9666                ApprovalGate::Held
9667            );
9668        }
9669    }
9670
9671    #[tokio::test]
9672    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
9673        crate::run::pin_test_home();
9674        let store = ask::Questions::open();
9675
9676        let mut held_state = run_state();
9677        held_state.config.graph.land_approval = true;
9678        let pr = green_pr();
9679        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9680            .await
9681            .unwrap();
9682        let mut q = store
9683            .list()
9684            .into_iter()
9685            .find(|q| q.run == held_state.id)
9686            .expect("filed above");
9687        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
9688        store.put(&mut q).unwrap();
9689        assert_eq!(
9690            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9691                .await
9692                .unwrap(),
9693            ApprovalGate::Held
9694        );
9695
9696        let mut abandoned_state = run_state();
9697        abandoned_state.config.graph.land_approval = true;
9698        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9699            .await
9700            .unwrap();
9701        let mut q = store
9702            .list()
9703            .into_iter()
9704            .find(|q| q.run == abandoned_state.id)
9705            .expect("filed above");
9706        q.abandon("no answer within the timeout");
9707        store.put(&mut q).unwrap();
9708        assert_eq!(
9709            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9710                .await
9711                .unwrap(),
9712            ApprovalGate::Pending,
9713            "an expired approval must ask again without merging"
9714        );
9715        assert_eq!(
9716            store.get(&q.id).unwrap().status,
9717            ask::QuestionStatus::Abandoned
9718        );
9719        assert_ne!(
9720            abandoned_state.land_approval.as_ref().unwrap().question,
9721            q.id
9722        );
9723    }
9724
9725    fn contested() -> ContestedHandoff {
9726        let finding = |id: &str, n: u32| crate::verdict::Finding {
9727            id: id.to_owned(),
9728            severity: crate::verdict::Severity::Major,
9729            file: Some("src/a.rs".to_owned()),
9730            line: Some(n),
9731            title: format!("problem {id}"),
9732            detail: String::new(),
9733        };
9734        ContestedHandoff {
9735            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
9736            rejecters: vec![(1, "alpha".to_owned())],
9737        }
9738    }
9739
9740    #[test]
9741    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
9742        let mut state = run_state();
9743        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
9744        state.contested_handoff = Some(contested());
9745        assert!(contested_to_ask(&state).is_some());
9746        state.config.graph.hold_contested_merge = false;
9747        assert!(
9748            contested_to_ask(&state).is_none(),
9749            "the switch restores today"
9750        );
9751    }
9752
9753    #[test]
9754    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
9755        let q = ask::Question::new(
9756            "run-1".to_owned(),
9757            APPROVAL_NODE.to_owned(),
9758            "land".to_owned(),
9759            "Merge?".to_owned(),
9760            String::new(),
9761            vec![APPROVE.to_owned(), HOLD.to_owned()],
9762        );
9763        let none = deputy_brief(&q, None);
9764        assert!(none.contains("could not be read"), "{none}");
9765        assert!(none.contains("Silence is a hold"), "{none}");
9766
9767        let mut state = run_state();
9768        state.pr = Some(crate::run::PrRecord {
9769            url: "https://example.test/pull/7".to_owned(),
9770            number: 7,
9771            state: "open".to_owned(),
9772            checks: "green".to_owned(),
9773            round: 0,
9774            rounds: 3,
9775            red_at_merge: Vec::new(),
9776        });
9777        state.contested_handoff = Some(contested());
9778        let b = deputy_brief(&q, Some(&state));
9779        assert!(b.contains("https://example.test/pull/7"), "{b}");
9780        assert!(b.contains("not recorded in this legacy question"), "{b}");
9781        assert!(!b.contains("This question was filed although"));
9782        state.contested_handoff = None;
9783        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
9784    }
9785
9786    #[test]
9787    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
9788        for lang in ["en", "ja"] {
9789            let mut cfg = crate::config::Config::default();
9790            cfg.graph.language = lang.to_owned();
9791            let w = words(&cfg.graph.language);
9792            let text = w.approval_detail(
9793                "https://github.com/yukimemi/magi/pull/42",
9794                "main",
9795                "feat: x",
9796                Some(&contested()),
9797            );
9798            assert!(text.contains("pull/42"), "{text}");
9799            assert!(
9800                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
9801                "{text}"
9802            );
9803            assert!(text.contains("R3-1-5"), "{text}");
9804            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
9805            assert!(text.contains("2"), "the rest are counted: {text}");
9806            assert!(text.contains("#1 (alpha)"), "{text}");
9807        }
9808        let plain = words("en").approval_detail("u", "main", "s", None);
9809        assert!(!plain.contains("reject"), "{plain}");
9810    }
9811
9812    #[tokio::test]
9813    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
9814        crate::run::pin_test_home();
9815        let mut state = run_state();
9816        state.config.graph.land_approval = false;
9817        state.contested_handoff = Some(contested());
9818        let pr = green_pr();
9819        let c = contested_to_ask(&state);
9820        assert_eq!(
9821            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9822                .await
9823                .unwrap(),
9824            ApprovalGate::Pending,
9825            "silence is a hold"
9826        );
9827        let store = ask::Questions::open();
9828        let filed: Vec<_> = store
9829            .list()
9830            .into_iter()
9831            .filter(|q| q.run == state.id)
9832            .collect();
9833        assert_eq!(filed.len(), 1);
9834        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
9835
9836        assert_eq!(
9837            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9838                .await
9839                .unwrap(),
9840            ApprovalGate::Pending
9841        );
9842        let mut q = store
9843            .list()
9844            .into_iter()
9845            .find(|q| q.run == state.id)
9846            .unwrap();
9847        assert_eq!(q.id, filed[0].id, "the same question after a resume");
9848        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9849        store.put(&mut q).unwrap();
9850        assert_eq!(
9851            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9852                .await
9853                .unwrap(),
9854            ApprovalGate::Approved
9855        );
9856    }
9857
9858    #[test]
9859    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
9860        let rows = parse_numstat(NUMSTAT);
9861        assert_eq!(
9862            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
9863            ["src/web.rs", "src/land.rs", "assets/logo.png"]
9864        );
9865        assert_eq!(rows[2].added, None, "a binary file has no line counts");
9866    }
9867    #[test]
9868    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
9869        // Reported from a real run: the merge question arrived in English on a
9870        // repository with `language = "ja"`. magi's own strings have to follow
9871        // that setting too - "it is a literal in Rust" is not an answer.
9872        let mut state = run_state();
9873        state.config.graph.language = "ja".to_owned();
9874        let pr = green_pr();
9875        let commits = ["c1".to_owned()];
9876
9877        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9878        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
9879        assert!(ja.contains("squash されるコミット"), "{ja}");
9880        assert!(ja.contains("レビューコメント"), "{ja}");
9881        assert!(ja.contains("差分"), "{ja}");
9882        assert!(
9883            !ja.contains("Commits being squashed"),
9884            "no English left over"
9885        );
9886
9887        let w = words("ja");
9888        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
9889        assert!(
9890            w.approval_detail("http://x/1", "main", "feat: x", None)
9891                .contains("パネル")
9892        );
9893
9894        // The evidence itself is language-neutral and must survive either way.
9895        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
9896        assert!(ja.contains("feat: x"), "nor is the merge subject");
9897
9898        // English stays the default, and a language magi cannot check falls
9899        // back to it rather than shipping a guess.
9900        state.config.graph.language = "en".to_owned();
9901        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9902        assert!(en.contains("Commits being squashed"), "{en}");
9903        assert_eq!(words("Klingon").html_lang, "en");
9904    }
9905
9906    /// A `gh pr list` result naming exactly one pull request whose base and
9907    /// merge time both fit the run is exactly the case
9908    /// [`find_external_merge`] exists to act on.
9909    #[test]
9910    fn pick_open_pr_classifies_by_count_and_base() {
9911        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
9912        assert_eq!(
9913            pick_open_pr(one, "main").unwrap(),
9914            OpenPr::One {
9915                url: "https://x/pull/58".into(),
9916                title: "t".into()
9917            }
9918        );
9919        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
9920        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
9921        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
9922                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
9923        assert_eq!(
9924            pick_open_pr(two, "main").unwrap(),
9925            OpenPr::Many(vec!["u1".into(), "u2".into()])
9926        );
9927        // A fork's same-named branch is not a pull request for this head.
9928        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
9929        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
9930        assert!(pick_open_pr("not json", "main").is_err());
9931        // An incomplete record is an error, never "nothing open".
9932        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
9933        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
9934    }
9935
9936    #[test]
9937    fn pick_merged_pr_picks_the_unique_match() {
9938        let json = r#"[
9939            {"url": "https://github.com/o/r/pull/42", "number": 42,
9940             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
9941        ]"#;
9942        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9943        let found = pick_merged_pr(json, "main", created_at)
9944            .expect("valid json")
9945            .expect("one unambiguous match");
9946        assert_eq!(found.url, "https://github.com/o/r/pull/42");
9947        assert_eq!(found.number, 42);
9948    }
9949
9950    /// Two candidates surviving the filter is exactly as uninformative as
9951    /// zero — a branch name can be reused across runs — so neither is
9952    /// preferred over the other and nothing is recorded automatically.
9953    #[test]
9954    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
9955        let json = r#"[
9956            {"url": "https://github.com/o/r/pull/42", "number": 42,
9957             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
9958            {"url": "https://github.com/o/r/pull/43", "number": 43,
9959             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
9960        ]"#;
9961        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9962        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9963        let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
9964        assert!(error.to_string().contains("ambiguous"), "{error:#}");
9965    }
9966
9967    /// A pull request that targets a different base branch cannot be this
9968    /// run's, whatever its head branch is named — a reused branch name from
9969    /// an unrelated task must not be recorded as this run's merge.
9970    #[test]
9971    fn pick_merged_pr_ignores_a_different_base_branch() {
9972        let json = r#"[
9973            {"url": "https://github.com/o/r/pull/42", "number": 42,
9974             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
9975        ]"#;
9976        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9977        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9978    }
9979
9980    /// A pull request merged before this run was even created cannot be this
9981    /// run's winner, no matter how its head branch is spelled.
9982    #[test]
9983    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
9984        let json = r#"[
9985            {"url": "https://github.com/o/r/pull/42", "number": 42,
9986             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
9987        ]"#;
9988        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9989        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9990    }
9991
9992    #[test]
9993    fn slug_of_pr_url_reads_host_owner_and_repo() {
9994        assert_eq!(
9995            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
9996            Some("github.com/yukimemi/shun")
9997        );
9998    }
9999
10000    #[test]
10001    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
10002        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
10003        assert_eq!(slug_of_pr_url("not a url at all"), None);
10004        assert_eq!(slug_of_pr_url("https://github.com"), None);
10005    }
10006
10007    #[test]
10008    fn slug_of_repo_url_reads_host_owner_and_repo() {
10009        assert_eq!(
10010            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
10011            Some("github.com/yukimemi/magi")
10012        );
10013        assert_eq!(slug_of_repo_url("https://github.com"), None);
10014    }
10015
10016    #[test]
10017    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
10018        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
10019            .expect("same repo, different case");
10020    }
10021
10022    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
10023    /// own in-progress run and rewrote its status from a pull request in a
10024    /// completely different repository. This is the guard that must catch
10025    /// that even when an explicit (but wrong) id is given.
10026    #[test]
10027    fn ensure_same_repo_refuses_a_different_repo() {
10028        let err =
10029            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
10030        let msg = format!("{err:#}");
10031        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10032        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
10033    }
10034
10035    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
10036    /// instance mirroring a `github.com` repository's name, say) must not be
10037    /// treated as the same repository just because the trailing path
10038    /// matches.
10039    #[test]
10040    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
10041        let err = ensure_same_repo(
10042            "github.com/yukimemi/magi",
10043            "github.example.com/yukimemi/magi",
10044        )
10045        .unwrap_err();
10046        let msg = format!("{err:#}");
10047        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10048        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
10049    }
10050
10051    /// No winner decided yet means there is no branch to ask GitHub about at
10052    /// all — `find_external_merge` must return `None` without ever spawning
10053    /// `gh`, which this proves by never providing a real repository to spawn
10054    /// it in.
10055    #[tokio::test]
10056    async fn find_external_merge_returns_none_without_a_winner() {
10057        let state = RunState::new(
10058            PathBuf::from("/no/such/repo"),
10059            "main".to_owned(),
10060            "0000000000000000000000000000000000000000".to_owned(),
10061            "irrelevant".to_owned(),
10062            crate::config::Config::default(),
10063        );
10064        assert_eq!(find_external_merge(&state).await.unwrap(), None);
10065    }
10066
10067    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
10068        let mut run = RunState::new(
10069            PathBuf::from(repo),
10070            "main".to_owned(),
10071            "abcdef1234".to_owned(),
10072            "x".to_owned(),
10073            crate::config::Config::default(),
10074        );
10075        run.id = id.to_owned();
10076        run.status = status;
10077        run.driver_exited = true;
10078        run.pr = Some(crate::run::PrRecord {
10079            number: url.rsplit('/').next().unwrap().parse().unwrap(),
10080            url: url.to_owned(),
10081            state: state.to_owned(),
10082            checks: "red".to_owned(),
10083            round: 0,
10084            rounds: 2,
10085            red_at_merge: Vec::new(),
10086        });
10087        run.save_under(home).unwrap();
10088    }
10089
10090    fn recorded(home: &Path, id: &str) -> String {
10091        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10092        serde_json::from_str::<RunState>(&body)
10093            .unwrap()
10094            .pr
10095            .unwrap()
10096            .state
10097    }
10098
10099    const PR: &str = "https://github.com/o/r/pull/7";
10100
10101    #[test]
10102    fn write_through_updates_predecessors_and_siblings_only() {
10103        let tmp = tempfile::tempdir().unwrap();
10104        let h = tmp.path();
10105        pr_run(
10106            h,
10107            "20261004-100000-aaaa",
10108            "/repo/r",
10109            RunStatus::Superseded,
10110            PR,
10111            "open",
10112        );
10113        pr_run(
10114            h,
10115            "20261004-100100-bbbb",
10116            "/repo/r",
10117            RunStatus::Blocked,
10118            PR,
10119            "open",
10120        );
10121        // Not terminal: a driver may be writing it.
10122        pr_run(
10123            h,
10124            "20261004-100200-cccc",
10125            "/repo/r",
10126            RunStatus::Landing,
10127            PR,
10128            "open",
10129        );
10130        // Another repository's pull request with the same number.
10131        pr_run(
10132            h,
10133            "20261004-100300-dddd",
10134            "/repo/other",
10135            RunStatus::Blocked,
10136            "https://github.com/o/other/pull/7",
10137            "open",
10138        );
10139        // A different pull request of the same repository.
10140        pr_run(
10141            h,
10142            "20261004-100400-eeee",
10143            "/repo/r",
10144            RunStatus::Blocked,
10145            "https://github.com/o/r/pull/8",
10146            "open",
10147        );
10148        pr_run(
10149            h,
10150            "20261004-100500-ffff",
10151            "/repo/r",
10152            RunStatus::Merged,
10153            PR,
10154            "open",
10155        );
10156        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10157
10158        assert_eq!(
10159            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10160            2
10161        );
10162        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10163        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10164        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10165        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10166        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10167        // The source's own record is the caller's to write.
10168        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10169        // Idempotent.
10170        assert_eq!(
10171            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10172            0
10173        );
10174        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10175        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10176    }
10177
10178    #[test]
10179    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10180        let home = tempfile::tempdir().unwrap();
10181        let live_id = "20261004-100000-aaaa";
10182        let unknown_id = "20261004-100100-bbbb";
10183        for id in [live_id, unknown_id] {
10184            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10185            let mut s = RunState::load_under(id, home.path()).unwrap();
10186            s.driver_exited = false;
10187            // Model legacy driver evidence, not a newly reserved unstarted run.
10188            s.driver_claimed = None;
10189            if id == live_id {
10190                s.driver_pid = Some(std::process::id());
10191                s.driver_started_at = crate::proc::process_started_at(std::process::id());
10192            }
10193            s.save_under(home.path()).unwrap();
10194            if id == unknown_id {
10195                assert_eq!(
10196                    s.liveness_under(home.path(), false),
10197                    crate::run::Liveness::Unknown
10198                );
10199            }
10200        }
10201        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10202        assert_eq!(apply_pr_states(home.path(), &known), 0);
10203        for id in [live_id, unknown_id] {
10204            assert_eq!(recorded(home.path(), id), "open");
10205        }
10206    }
10207
10208    #[test]
10209    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10210        let tmp = tempfile::tempdir().unwrap();
10211        let h = tmp.path();
10212        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10213        pr_run(
10214            h,
10215            "20261004-100000-aaaa",
10216            "/repo/r",
10217            RunStatus::Superseded,
10218            &url(1),
10219            "open",
10220        );
10221        pr_run(
10222            h,
10223            "20261004-100100-bbbb",
10224            "/repo/r",
10225            RunStatus::Blocked,
10226            &url(2),
10227            "open",
10228        );
10229        pr_run(
10230            h,
10231            "20261004-100200-cccc",
10232            "/repo/r",
10233            RunStatus::Ready,
10234            &url(3),
10235            "open",
10236        );
10237        pr_run(
10238            h,
10239            "20261004-100300-dddd",
10240            "/repo/r",
10241            RunStatus::Ready,
10242            &url(4),
10243            "open",
10244        );
10245        pr_run(
10246            h,
10247            "20261004-100400-eeee",
10248            "/repo/r",
10249            RunStatus::Implementing,
10250            &url(1),
10251            "open",
10252        );
10253        assert_eq!(stale_open_prs(h).len(), 4);
10254
10255        let mut known = BTreeMap::new();
10256        known.insert(url(1), PrLifecycle::Merged);
10257        known.insert(url(2), PrLifecycle::Closed);
10258        known.insert(url(3), PrLifecycle::Open);
10259        // #4: the forge could not be read, so it has no answer.
10260        assert_eq!(apply_pr_states(h, &known), 2);
10261        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10262        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10263        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10264        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10265        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10266        assert_eq!(apply_pr_states(h, &known), 0);
10267    }
10268
10269    // --- the land loop against a scripted forge -------------------------
10270
10271    use std::collections::VecDeque;
10272    use std::sync::Mutex;
10273
10274    /// Answers views from a script (the last one repeats), merges from a
10275    /// queue, and records every call so a test can assert the order.
10276    struct Scripted {
10277        public_repo: Option<PathBuf>,
10278        evidence: Mutex<Option<CiEvidence>>,
10279        views: Mutex<VecDeque<Seen>>,
10280        merges: Mutex<VecDeque<(bool, String)>>,
10281        fix: Mutex<Option<Fixed>>,
10282        log: Mutex<Vec<&'static str>>,
10283        argvs: Mutex<Vec<Vec<String>>>,
10284        required: Mutex<Option<BTreeSet<String>>>,
10285        /// Set once a merge answered ok: the forge then reports `merged`,
10286        /// unless `queued` says the merge only entered a queue.
10287        merged: Mutex<bool>,
10288        queued: Mutex<bool>,
10289        /// Views fail once a merge answered ok.
10290        unreadable_after_merge: Mutex<bool>,
10291        /// Workflow runs asked to rerun, and whether that call fails.
10292        reruns: Mutex<Vec<String>>,
10293        rerun_fails: Mutex<bool>,
10294        /// Unix seconds; every poll moves it on by `POLL`.
10295        clock: Mutex<i64>,
10296    }
10297
10298    impl Scripted {
10299        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10300            Self {
10301                public_repo: None,
10302                evidence: Mutex::new(None),
10303                views: Mutex::new(views.into()),
10304                merges: Mutex::new(
10305                    merges
10306                        .into_iter()
10307                        .map(|(ok, m)| (ok, m.to_owned()))
10308                        .collect(),
10309                ),
10310                fix: Mutex::new(None),
10311                log: Mutex::new(Vec::new()),
10312                argvs: Mutex::new(Vec::new()),
10313                required: Mutex::new(None),
10314                merged: Mutex::new(false),
10315                queued: Mutex::new(false),
10316                unreadable_after_merge: Mutex::new(false),
10317                reruns: Mutex::new(Vec::new()),
10318                rerun_fails: Mutex::new(false),
10319                clock: Mutex::new(1_000),
10320            }
10321        }
10322        fn argvs(&self) -> Vec<Vec<String>> {
10323            self.argvs.lock().unwrap().clone()
10324        }
10325        fn calls(&self) -> Vec<&'static str> {
10326            self.log.lock().unwrap().clone()
10327        }
10328    }
10329
10330    impl Forge for Scripted {
10331        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10332            self.evidence.lock().unwrap().clone()
10333        }
10334        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10335            self.log.lock().unwrap().push("view");
10336            if *self.unreadable_after_merge.lock().unwrap()
10337                && !self.argvs.lock().unwrap().is_empty()
10338            {
10339                anyhow::bail!("forge unreachable");
10340            }
10341            let mut seen = {
10342                let mut v = self.views.lock().unwrap();
10343                if v.len() > 1 {
10344                    v.pop_front().unwrap()
10345                } else {
10346                    v[0].clone()
10347                }
10348            };
10349            if seen.head == "@published" {
10350                let head =
10351                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10352                        .await?
10353                        .context("missing published head")?;
10354                seen.head.clone_from(&head);
10355                seen.rollup_head = head;
10356            }
10357            if *self.merged.lock().unwrap() {
10358                seen.pr.state = PrLifecycle::Merged;
10359            }
10360            Ok(seen)
10361        }
10362        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10363            self.log.lock().unwrap().push("merge");
10364            self.argvs.lock().unwrap().push(argv.to_vec());
10365            let out = self
10366                .merges
10367                .lock()
10368                .unwrap()
10369                .pop_front()
10370                .expect("unscripted merge");
10371            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10372            {
10373                *self.merged.lock().unwrap() = true;
10374            }
10375            Ok(out)
10376        }
10377        async fn poll(&self) {
10378            self.log.lock().unwrap().push("poll");
10379            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10380        }
10381        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10382            self.log.lock().unwrap().push("rerun");
10383            self.reruns.lock().unwrap().push(run.to_owned());
10384            if *self.rerun_fails.lock().unwrap() {
10385                anyhow::bail!("gh run rerun: no");
10386            }
10387            Ok(())
10388        }
10389        fn now(&self) -> i64 {
10390            *self.clock.lock().unwrap()
10391        }
10392        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10393            self.required.lock().unwrap().clone()
10394        }
10395        async fn fix(
10396            &self,
10397            _state: &mut RunState,
10398            _pr: &PrState,
10399            _round: usize,
10400            _budget: usize,
10401            _reason: &str,
10402            _logs: &str,
10403        ) -> Result<Fixed> {
10404            self.log.lock().unwrap().push("fix");
10405            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10406        }
10407    }
10408
10409    const REFUSED: &str =
10410        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10411
10412    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10413        let mut pr = green_pr();
10414        pr.checks = checks;
10415        pr.blocking = Blocking::of(merge_state);
10416        if !comments {
10417            pr.review_comments.clear();
10418        }
10419        Seen {
10420            pr,
10421            title: "feat: x".to_owned(),
10422            failing_urls: Vec::new(),
10423            head: head.to_owned(),
10424            rollup_head: head.to_owned(),
10425            merge_state: merge_state.to_owned(),
10426            contexts: Vec::new(),
10427            base: "main".to_owned(),
10428        }
10429    }
10430
10431    fn landing_state() -> RunState {
10432        crate::run::pin_test_home();
10433        let mut state = run_state();
10434        state.config.graph.land_approval = false;
10435        state
10436    }
10437
10438    #[test]
10439    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10440        assert!(!awaiting_new_head(None, "aaa"));
10441        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10442        assert!(awaiting_new_head(Some("abc123"), "def456"));
10443        assert!(awaiting_new_head(Some("abc123"), ""));
10444    }
10445
10446    #[test]
10447    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10448        let open = |c, m: &str| seen("a", c, m, false);
10449        let table = [
10450            (None, false, Refused::Pending),
10451            (
10452                Some(open(Checks::Pending, "BLOCKED")),
10453                false,
10454                Refused::Pending,
10455            ),
10456            (
10457                Some(open(Checks::Unknown, "BLOCKED")),
10458                false,
10459                Refused::Pending,
10460            ),
10461            (
10462                Some(open(Checks::Green, "UNKNOWN")),
10463                false,
10464                Refused::Pending,
10465            ),
10466            (Some(open(Checks::Green, "")), false, Refused::Pending),
10467            (
10468                Some(open(Checks::Green, "BLOCKED")),
10469                false,
10470                Refused::Recheck,
10471            ),
10472            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10473        ];
10474        for (after, rechecked, want) in table {
10475            assert_eq!(
10476                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10477                want
10478            );
10479        }
10480        let mut closed = open(Checks::Green, "CLEAN");
10481        closed.pr.state = PrLifecycle::Closed;
10482        assert_eq!(
10483            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10484            Refused::Final
10485        );
10486    }
10487
10488    #[test]
10489    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10490        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10491            let pr = seen("a", checks, "BEHIND", false).pr;
10492            assert_eq!(
10493                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10494                Step::Rebase
10495            );
10496        }
10497        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
10498            let current = seen("a", Checks::Green, status, false);
10499            assert_ne!(
10500                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10501                Step::Rebase
10502            );
10503            assert_ne!(
10504                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
10505                Refused::Behind
10506            );
10507        }
10508        let mut current = seen("a", Checks::Pending, "BEHIND", false);
10509        current.rollup_head = "old".into();
10510        assert_eq!(
10511            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10512            Refused::Behind
10513        );
10514        assert_eq!(
10515            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
10516            Refused::Pending
10517        );
10518        current.pr.state = PrLifecycle::Closed;
10519        assert_eq!(
10520            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10521            Refused::Final
10522        );
10523    }
10524
10525    #[tokio::test]
10526    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
10527        for boundary in ["initial", "premerge", "refusal"] {
10528            let (_tmp, mut state, old) = landing_git_fixture().await;
10529            state.land_sync_pending = false;
10530            advance_landing_base(&state).await;
10531            state.config.verify.gate = vec!["test -f advance".into()];
10532            state.config.verify.e2e = vec!["test -f advance".into()];
10533            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
10534                .await
10535                .unwrap();
10536            let old_binding = state.land_approval.clone().unwrap();
10537            let store = ask::Questions::open();
10538            let mut question = store.get(&old_binding.question).unwrap();
10539            question
10540                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10541                .unwrap();
10542            store.put(&mut question).unwrap();
10543            let mut views = Vec::new();
10544            if boundary != "initial" {
10545                views.push(seen(&old, Checks::Green, "CLEAN", false));
10546            }
10547            if boundary == "refusal" {
10548                views.push(seen(&old, Checks::Green, "CLEAN", false));
10549            }
10550            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
10551            behind.rollup_head = "old-ci-head".into();
10552            views.push(behind);
10553            // Publication checks the PR lease while verification has completed.
10554            views.push(seen(&old, Checks::Green, "CLEAN", false));
10555            views.push(seen("@published", Checks::Pending, "CLEAN", false));
10556            views.push(seen("@published", Checks::Green, "CLEAN", false));
10557            let merges = if boundary == "refusal" {
10558                vec![(false, REFUSED)]
10559            } else {
10560                vec![]
10561            };
10562            let mut forge = Scripted::new(views, merges);
10563            forge.public_repo = Some(state.repo.clone());
10564            let run = state.id.clone();
10565            land_with(&mut state, URL, &forge).await.unwrap();
10566            let head = state.pr_pushed_head.clone().unwrap();
10567            assert_ne!(head, old, "{boundary}");
10568            assert_eq!(state.id, run);
10569            assert_eq!(state.pr_branch(), Some("task-head"));
10570            assert_eq!(state.winner().unwrap().branch, "winner");
10571            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
10572            assert!(state.gate_allows_progress());
10573            let e2e = state.head_e2e.as_ref().unwrap();
10574            assert_eq!(e2e.head, head);
10575            assert!(e2e.passed);
10576            assert_eq!(state.land_sync_attempts, 1);
10577            assert!(!state.land_sync_pending);
10578            assert!(state.parked);
10579            let binding = state.land_approval.as_ref().unwrap();
10580            assert_eq!(binding.head, head);
10581            assert_ne!(binding.question, old_binding.question);
10582            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
10583            // The new question authorizes only the synchronized head on resume.
10584            let mut question = store.get(&binding.question).unwrap();
10585            question
10586                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10587                .unwrap();
10588            store.put(&mut question).unwrap();
10589            let forge = Scripted::new(
10590                vec![seen(&head, Checks::Green, "CLEAN", false)],
10591                vec![(true, "")],
10592            );
10593            land_with(&mut state, URL, &forge).await.unwrap();
10594            assert_eq!(state.status, RunStatus::Merged);
10595            assert_eq!(
10596                value_of(&forge.argvs()[0], "--match-head-commit"),
10597                Some(head.as_str())
10598            );
10599        }
10600    }
10601
10602    #[tokio::test]
10603    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
10604        let (_tmp, mut state, old) = landing_git_fixture().await;
10605        state.land_sync_pending = false;
10606        state.config.graph.land_approval = false;
10607        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
10608        advance_landing_base(&state).await;
10609        let mut forge = Scripted::new(
10610            vec![
10611                seen(&old, Checks::Green, "CLEAN", false),
10612                seen(&old, Checks::Green, "CLEAN", false),
10613                seen(&old, Checks::Green, "BEHIND", false),
10614                // The next observation is the publication lease check. The
10615                // refusal's evidence still applies to exactly this old head.
10616                seen(&old, Checks::Green, "CLEAN", false),
10617                seen("@published", Checks::Green, "CLEAN", false),
10618            ],
10619            vec![(false, REFUSED), (true, "")],
10620        );
10621        forge.public_repo = Some(state.repo.clone());
10622        land_with(&mut state, URL, &forge).await.unwrap();
10623        let head = state.pr_pushed_head.as_deref().unwrap();
10624        assert_ne!(head, old);
10625        assert_eq!(state.land_sync_attempts, 1);
10626        assert_eq!(state.gate_head.as_deref(), Some(head));
10627        assert_eq!(state.status, RunStatus::Merged);
10628        let requests = forge.argvs();
10629        assert_eq!(requests.len(), 2);
10630        assert_eq!(
10631            value_of(&requests[0], "--match-head-commit"),
10632            Some(old.as_str())
10633        );
10634        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
10635    }
10636
10637    #[tokio::test]
10638    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
10639        let (tmp, mut state, old) = landing_git_fixture().await;
10640        state.land_sync_pending = false;
10641        // A damaged history must not be interpreted as a missing base. Keep
10642        // the head's tree intact so worktree restoration itself can succeed.
10643        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
10644        let commit = tmp.path().join("broken-commit");
10645        std::fs::write(
10646            &commit,
10647            format!(
10648                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
10649                "f".repeat(40)
10650            ),
10651        )
10652        .unwrap();
10653        let replacement = git::git(
10654            &state.repo,
10655            &[
10656                "hash-object",
10657                "-t",
10658                "commit",
10659                "-w",
10660                commit.to_str().unwrap(),
10661            ],
10662        )
10663        .await
10664        .unwrap();
10665        git::git(&state.repo, &["replace", &old, replacement.trim()])
10666            .await
10667            .unwrap();
10668        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10669        land_with(&mut state, URL, &forge).await.unwrap();
10670        assert_eq!(state.land_sync_attempts, 0);
10671        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10672        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10673        assert!(forge.argvs().is_empty());
10674        assert!(
10675            state.events.iter().any(|e| e.message.contains(
10676                "could not determine whether the landing head contains the fetched base"
10677            ))
10678        );
10679    }
10680
10681    #[tokio::test]
10682    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
10683        let (_tmp, mut state, old) = landing_git_fixture().await;
10684        state.land_sync_pending = false;
10685        git::git(
10686            &state.repo,
10687            &["remote", "set-url", "origin", "missing-remote"],
10688        )
10689        .await
10690        .unwrap();
10691        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10692        land_with(&mut state, URL, &forge).await.unwrap();
10693        assert_eq!(state.land_sync_attempts, 0);
10694        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10695        assert!(
10696            state
10697                .events
10698                .iter()
10699                .any(|e| e.message.contains("cannot fetch landing base"))
10700        );
10701        assert!(forge.argvs().is_empty());
10702    }
10703
10704    #[tokio::test]
10705    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
10706        let (_tmp, mut state, old) = landing_git_fixture().await;
10707        state.land_sync_pending = false;
10708        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10709        land_with(&mut state, URL, &forge).await.unwrap();
10710        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10711        assert_eq!(state.land_sync_attempts, 0);
10712        assert!(
10713            state
10714                .events
10715                .iter()
10716                .any(|e| e.message.contains("already included"))
10717        );
10718        advance_landing_base(&state).await;
10719        state.land_sync_attempts = state.config.graph.land_rounds;
10720        state.land_sync_pending = true;
10721        state.save().unwrap();
10722        let mut restored = RunState::load(&state.id).unwrap();
10723        assert!(
10724            resume_observed_head(&mut restored, &old)
10725                .await
10726                .unwrap_err()
10727                .to_string()
10728                .contains("budget exhausted")
10729        );
10730        assert_eq!(
10731            git::remote_head(&state.repo, "origin", "task-head")
10732                .await
10733                .unwrap(),
10734            Some(old)
10735        );
10736    }
10737
10738    #[tokio::test]
10739    async fn a_normal_landing_merges_on_the_first_look() {
10740        let mut state = landing_state();
10741        let forge = Scripted::new(
10742            vec![seen("a", Checks::Green, "CLEAN", false)],
10743            vec![(true, "")],
10744        );
10745        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10746            .await
10747            .unwrap();
10748        // One fresh read, then the head-bound merge.
10749        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10750        assert_eq!(state.status, RunStatus::Merged);
10751    }
10752
10753    #[tokio::test]
10754    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
10755        let mut state = landing_state();
10756        let forge = Scripted::new(
10757            vec![seen("a", Checks::Green, "CLEAN", false)],
10758            std::iter::repeat_n((true, ""), 100).collect(),
10759        );
10760        *forge.queued.lock().unwrap() = true;
10761        let task = async {
10762            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10763                .await
10764                .unwrap();
10765        };
10766        // Still open after the command succeeded: it keeps watching and
10767        // never records a merge (it stops at the wait ceiling instead).
10768        task.await;
10769        assert_ne!(state.status, RunStatus::Merged);
10770    }
10771
10772    #[tokio::test]
10773    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
10774        let mut state = landing_state();
10775        let forge = Scripted::new(
10776            vec![seen("a", Checks::Green, "CLEAN", false)],
10777            std::iter::repeat_n((true, ""), 100).collect(),
10778        );
10779        *forge.unreadable_after_merge.lock().unwrap() = true;
10780        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10781            .await
10782            .ok();
10783        assert_ne!(state.status, RunStatus::Merged);
10784    }
10785
10786    #[tokio::test]
10787    async fn a_task_public_head_is_awaited_on_land_entry() {
10788        let mut state = landing_state();
10789        state.pr_head = Some("magi/task-abcd-1234".into());
10790        state.pr_pushed_head = Some("new".into());
10791        let forge = Scripted::new(
10792            vec![
10793                seen("old", Checks::Green, "CLEAN", false),
10794                seen("new", Checks::Green, "CLEAN", false),
10795            ],
10796            vec![(true, "")],
10797        );
10798        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10799            .await
10800            .unwrap();
10801        assert_eq!(
10802            forge.calls(),
10803            ["view", "poll", "view", "view", "merge", "view"]
10804        );
10805        assert_eq!(state.status, RunStatus::Merged);
10806    }
10807
10808    #[tokio::test]
10809    async fn a_superseded_public_head_owner_cannot_reenter_land() {
10810        let mut state = landing_state();
10811        state.pr_taken_over_by = Some("next".into());
10812        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
10813        assert!(
10814            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10815                .await
10816                .is_err()
10817        );
10818        assert!(forge.calls().is_empty());
10819    }
10820
10821    #[tokio::test]
10822    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
10823        let mut state = landing_state();
10824        let forge = Scripted::new(
10825            vec![
10826                seen("old", Checks::Green, "CLEAN", true),
10827                // The forge has not moved to the new head yet: still green.
10828                seen("old", Checks::Green, "CLEAN", true),
10829                seen("new", Checks::Pending, "BLOCKED", true),
10830                seen("new", Checks::Green, "CLEAN", true),
10831            ],
10832            vec![(true, "")],
10833        );
10834        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10835            head: "NEW".to_owned(),
10836        });
10837        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10838            .await
10839            .unwrap();
10840        assert_eq!(
10841            forge.calls(),
10842            [
10843                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
10844                "view"
10845            ]
10846        );
10847        assert_eq!(state.status, RunStatus::Merged);
10848    }
10849
10850    #[tokio::test]
10851    async fn a_head_that_never_arrives_stops_naming_both_commits() {
10852        let mut state = landing_state();
10853        let forge = Scripted::new(
10854            vec![
10855                seen("old", Checks::Green, "CLEAN", true),
10856                seen("someone-elses", Checks::Green, "CLEAN", true),
10857            ],
10858            vec![],
10859        );
10860        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10861            head: "mine".to_owned(),
10862        });
10863        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10864            .await
10865            .unwrap();
10866        assert!(!forge.calls().contains(&"merge"));
10867        let why = state.merge.as_ref().unwrap().detail.clone();
10868        assert!(
10869            why.contains("mine") && why.contains("someone-elses"),
10870            "{why}"
10871        );
10872        assert_eq!(state.status, RunStatus::Blocked);
10873    }
10874
10875    #[tokio::test]
10876    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
10877        let mut state = landing_state();
10878        let forge = Scripted::new(
10879            vec![
10880                seen("a", Checks::Green, "CLEAN", false),
10881                seen("a", Checks::Green, "CLEAN", false),
10882                seen("a", Checks::Pending, "BLOCKED", false),
10883                seen("a", Checks::Pending, "BLOCKED", false),
10884                seen("a", Checks::Green, "CLEAN", false),
10885            ],
10886            vec![(false, REFUSED), (true, "")],
10887        );
10888        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10889            .await
10890            .unwrap();
10891        assert_eq!(
10892            forge.calls(),
10893            [
10894                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
10895                "view"
10896            ]
10897        );
10898        assert_eq!(state.status, RunStatus::Merged);
10899    }
10900
10901    #[tokio::test]
10902    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
10903        let mut state = landing_state();
10904        let forge = Scripted::new(
10905            vec![
10906                seen("a", Checks::Green, "CLEAN", false),
10907                seen("a", Checks::Green, "BLOCKED", false),
10908            ],
10909            vec![(false, REFUSED), (false, REFUSED)],
10910        );
10911        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10912            .await
10913            .unwrap();
10914        // One re-look is allowed for the forge's own lag, then it is final.
10915        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
10916        let why = state.merge.as_ref().unwrap().detail.clone();
10917        assert!(
10918            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
10919            "{why}"
10920        );
10921        assert_eq!(state.status, RunStatus::Blocked);
10922    }
10923
10924    #[test]
10925    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
10926        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
10927        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
10928        // The pull request is still on the commit before the push.
10929        assert_eq!(bound_head("old", "old", Some("new")), None);
10930        // The checks are the previous commit's.
10931        assert_eq!(bound_head("new", "old", Some("new")), None);
10932        assert_eq!(bound_head("new", "old", None), None);
10933        // Nothing readable.
10934        assert_eq!(bound_head("", "", None), None);
10935        assert_eq!(bound_head("", "", Some("new")), None);
10936        assert_eq!(bound_head("abc", "", None), None);
10937    }
10938
10939    fn view_json(head: &str) -> String {
10940        format!(
10941            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
10942            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
10943            "reviews":[],"comments":[]}}"#
10944        )
10945    }
10946
10947    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
10948        format!(
10949            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
10950            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
10951            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
10952            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
10953        )
10954    }
10955
10956    #[test]
10957    fn rollup_is_bound_to_the_commit_in_the_same_node() {
10958        // The view already points at the new head, but the node still answers
10959        // for the old commit with its red check: the head stays unbound.
10960        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
10961        assert_eq!(s.rollup_head, "old");
10962        assert_eq!(s.pr.checks, Checks::Red);
10963        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
10964        assert_eq!(s.failing_urls.len(), 1);
10965    }
10966
10967    #[test]
10968    fn checks_come_from_the_node_not_the_view() {
10969        let view = view_json("new").replace(
10970            r#""reviews""#,
10971            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
10972        );
10973        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
10974        assert_eq!(s.pr.checks, Checks::Green);
10975        assert!(s.pr.failing.is_empty());
10976        assert_eq!(
10977            bound_head(&s.head, &s.rollup_head, Some("new")),
10978            Some("new")
10979        );
10980    }
10981
10982    #[test]
10983    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
10984        for node in [
10985            None,
10986            Some("not json".to_owned()),
10987            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
10988            Some(node_json("new", "SUCCESS", true)),
10989        ] {
10990            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
10991            assert!(s.rollup_head.is_empty());
10992            assert_eq!(s.pr.checks, Checks::Unknown);
10993            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
10994        }
10995    }
10996
10997    #[test]
10998    fn the_merge_command_is_pinned_to_the_observed_head() {
10999        let argv = merge_argv_at(7, "feat: x", "deadbeef");
11000        let at = argv
11001            .iter()
11002            .position(|a| a == "--match-head-commit")
11003            .unwrap();
11004        assert_eq!(argv[at + 1], "deadbeef");
11005    }
11006
11007    #[tokio::test]
11008    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
11009        let mut state = landing_state();
11010        // The pull request is on the pushed head but the rollup is still the
11011        // previous commit's red, non-required result.
11012        let mut stale = seen("new", Checks::Red, "CLEAN", false);
11013        stale.rollup_head = "old".to_owned();
11014        let forge = Scripted::new(
11015            vec![seen("old", Checks::Green, "CLEAN", true), stale],
11016            vec![],
11017        );
11018        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11019            head: "new".to_owned(),
11020        });
11021        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11022            .await
11023            .unwrap();
11024        assert!(!forge.calls().contains(&"merge"));
11025        assert_eq!(state.status, RunStatus::Blocked);
11026        let why = state.merge.as_ref().unwrap().detail.clone();
11027        assert!(why.contains("new") && why.contains("old"), "{why}");
11028    }
11029
11030    #[test]
11031    fn a_refusal_read_against_another_commits_checks_is_pending() {
11032        let mut after = seen("a", Checks::Green, "BLOCKED", false);
11033        after.rollup_head = "old".to_owned();
11034        assert_eq!(
11035            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
11036            Refused::Pending
11037        );
11038    }
11039
11040    #[tokio::test]
11041    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
11042        let mut state = landing_state();
11043        state.config.merge.ci = crate::config::MergeCi::None;
11044        state.config.graph.land_approval = true;
11045        let forge = Scripted::new(
11046            vec![seen("a", Checks::Unknown, "CLEAN", false)],
11047            vec![(true, "")],
11048        );
11049        land_with(&mut state, URL, &forge).await.unwrap();
11050        assert!(state.parked);
11051        assert_eq!(forge.calls(), ["view"]);
11052        let store = ask::Questions::open();
11053        let mut q = store
11054            .get(&state.land_approval.as_ref().unwrap().question)
11055            .unwrap();
11056        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11057        store.put(&mut q).unwrap();
11058
11059        land_with(&mut state, URL, &forge).await.unwrap();
11060        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
11061        assert_eq!(state.status, RunStatus::Merged);
11062        assert_eq!(
11063            value_of(&forge.argvs()[0], "--match-head-commit"),
11064            Some("a")
11065        );
11066    }
11067
11068    #[tokio::test]
11069    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
11070        let mut state = landing_state();
11071        state.config.merge.ci = crate::config::MergeCi::None;
11072        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
11073        land_with(&mut state, URL, &forge).await.unwrap();
11074        assert!(forge.reruns.lock().unwrap().is_empty());
11075        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11076        assert_eq!(state.status, RunStatus::Merged);
11077    }
11078
11079    #[test]
11080    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
11081        let shown = BTreeSet::new();
11082        let guard = |s: Option<&Seen>| {
11083            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11084        };
11085        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11086        assert!(guard(Some(&fresh)));
11087        assert!(!guard(None));
11088        fresh.rollup_head = "old".to_owned();
11089        assert!(!guard(Some(&fresh)));
11090        fresh.rollup_head = "a".to_owned();
11091        fresh.head = "b".to_owned();
11092        assert!(!guard(Some(&fresh)));
11093        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11094        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11095    }
11096
11097    #[test]
11098    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11099        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11100            let after = seen("a", checks, "BLOCKED", false);
11101            assert_eq!(
11102                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11103                Refused::Recheck
11104            );
11105            assert_eq!(
11106                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11107                Refused::Final
11108            );
11109        }
11110    }
11111
11112    #[tokio::test]
11113    async fn a_matching_head_with_red_non_required_checks_still_merges() {
11114        let mut state = landing_state();
11115        let forge = Scripted::new(
11116            vec![seen("a", Checks::Red, "CLEAN", false)],
11117            vec![(true, "")],
11118        );
11119        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11120            .await
11121            .unwrap();
11122        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11123        assert_eq!(state.status, RunStatus::Merged);
11124    }
11125
11126    #[tokio::test]
11127    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11128        let mut state = landing_state();
11129        let forge = Scripted::new(
11130            vec![
11131                seen("a", Checks::Green, "CLEAN", false),
11132                seen("a", Checks::Green, "CLEAN", false),
11133                // Re-viewed after the refusal: someone pushed.
11134                seen("b", Checks::Green, "BLOCKED", false),
11135                seen("b", Checks::Green, "CLEAN", false),
11136            ],
11137            vec![(false, REFUSED), (true, "")],
11138        );
11139        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11140            .await
11141            .unwrap();
11142        assert_eq!(
11143            forge.calls(),
11144            [
11145                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
11146            ]
11147        );
11148        assert_eq!(state.status, RunStatus::Merged);
11149    }
11150
11151    fn merged_view(head: &str) -> Seen {
11152        let mut m = seen(head, Checks::Green, "CLEAN", false);
11153        m.pr.state = PrLifecycle::Merged;
11154        m
11155    }
11156
11157    fn has(argv: &[String], flag: &str) -> bool {
11158        argv.iter().any(|a| a == flag)
11159    }
11160
11161    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11162        let at = argv.iter().position(|a| a == flag)?;
11163        argv.get(at + 1).map(String::as_str)
11164    }
11165
11166    const URL: &str = "https://github.com/o/r/pull/42";
11167
11168    #[tokio::test]
11169    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11170        let mut state = landing_state();
11171        let forge = Scripted::new(
11172            vec![
11173                seen("abc", Checks::Green, "CLEAN", false),
11174                seen("abc", Checks::Green, "CLEAN", false),
11175            ],
11176            vec![(true, "")],
11177        );
11178        land_with(&mut state, URL, &forge).await.unwrap();
11179        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11180        let argv = &forge.argvs()[0];
11181        assert!(has(argv, "--squash") && has(argv, "--subject"));
11182        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11183        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11184        assert_eq!(state.status, RunStatus::Merged);
11185        assert!(state.land_armed_head.is_none());
11186    }
11187
11188    #[tokio::test]
11189    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11190        let mut state = landing_state();
11191        state.land_armed_head = Some("a".to_owned());
11192        let forge = Scripted::new(
11193            vec![seen("a", Checks::Green, "CLEAN", false)],
11194            vec![(true, ""), (true, "")],
11195        );
11196        land_with(&mut state, URL, &forge).await.unwrap();
11197        let argvs = forge.argvs();
11198        assert!(has(&argvs[0], "--disable-auto"));
11199        assert!(!has(&argvs[1], "--auto"));
11200        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11201        assert_eq!(state.status, RunStatus::Merged);
11202        assert!(state.land_armed_head.is_none());
11203    }
11204
11205    #[tokio::test]
11206    async fn an_approval_never_carries_over_to_a_new_head() {
11207        crate::run::pin_test_home();
11208        let mut state = run_state();
11209        state.config.graph.land_approval = true;
11210        let pr = green_pr();
11211        let store = ask::Questions::open();
11212
11213        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11214            .await
11215            .unwrap();
11216        let mut q = store
11217            .list()
11218            .into_iter()
11219            .find(|q| q.run == state.id)
11220            .unwrap();
11221        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11222        store.put(&mut q).unwrap();
11223        assert_eq!(
11224            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
11225                .await
11226                .unwrap(),
11227            ApprovalGate::Approved,
11228            "the same head keeps its approval"
11229        );
11230
11231        // A new head is a new question, not the old word.
11232        assert_eq!(
11233            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11234                .await
11235                .unwrap(),
11236            ApprovalGate::Pending
11237        );
11238        let all: Vec<_> = store
11239            .list()
11240            .into_iter()
11241            .filter(|q| q.run == state.id)
11242            .collect();
11243        assert_eq!(all.len(), 2);
11244
11245        // A question recorded before heads were tracked is not reused either.
11246        state.land_approval = None;
11247        assert_eq!(
11248            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11249                .await
11250                .unwrap(),
11251            ApprovalGate::Pending
11252        );
11253        let open = store
11254            .list()
11255            .into_iter()
11256            .filter(|q| q.run == state.id && q.status.open())
11257            .count();
11258        assert_eq!(open, 1, "the superseded question was retired");
11259    }
11260
11261    #[tokio::test]
11262    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11263        let mut state = landing_state();
11264        let forge = Scripted::new(
11265            vec![
11266                seen("a", Checks::Green, "CLEAN", false),
11267                // The fresh read before the merge: someone pushed.
11268                seen("b", Checks::Green, "CLEAN", false),
11269            ],
11270            vec![(true, "")],
11271        );
11272        land_with(&mut state, URL, &forge).await.unwrap();
11273        let argvs = forge.argvs();
11274        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11275        assert!(!has(&argvs[0], "--auto"));
11276        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11277        assert_eq!(state.status, RunStatus::Merged);
11278    }
11279
11280    fn passing(label: &str) -> CheckInfo {
11281        CheckInfo {
11282            label: label.to_owned(),
11283            verdict: Verdict::Pass,
11284            required: Some(false),
11285            run: None,
11286        }
11287    }
11288
11289    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11290        (label.to_owned(), run.map(str::to_owned))
11291    }
11292
11293    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11294        LandReruns {
11295            head: head.to_owned(),
11296            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11297        }
11298    }
11299
11300    #[test]
11301    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11302        let f = [failing("test (macos)", Some("7"))];
11303        assert_eq!(
11304            rerun_step(&f, None, "h", 100),
11305            RerunStep::Rerun(vec!["7".to_owned()])
11306        );
11307        let rec = reran("h", &[("7", 100)]);
11308        let grace = crate::release_watch::RERUN_GRACE;
11309        assert_eq!(
11310            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11311            RerunStep::Grace
11312        );
11313        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11314    }
11315
11316    #[test]
11317    fn a_failure_without_a_run_id_goes_to_the_fixer() {
11318        let f = [failing("a", Some("7")), failing("ci/external", None)];
11319        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11320        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11321    }
11322
11323    #[test]
11324    fn a_moved_head_forgets_the_reruns() {
11325        let f = [failing("a", Some("7"))];
11326        let rec = reran("old", &[("7", 100)]);
11327        assert_eq!(
11328            rerun_step(&f, Some(&rec), "new", 101),
11329            RerunStep::Rerun(vec!["7".to_owned()])
11330        );
11331    }
11332
11333    #[test]
11334    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11335        let f = [
11336            failing("a", Some("7")),
11337            failing("b", Some("7")),
11338            failing("c", Some("8")),
11339        ];
11340        assert_eq!(
11341            rerun_step(&f, None, "h", 0),
11342            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11343        );
11344        let rec = reran("h", &[("7", 0)]);
11345        assert_eq!(
11346            rerun_step(&f, Some(&rec), "h", 1),
11347            RerunStep::Rerun(vec!["8".to_owned()])
11348        );
11349    }
11350
11351    #[test]
11352    fn only_blocking_failures_are_candidates_for_a_rerun() {
11353        let check = |label: &str, verdict, required, run: &str| CheckInfo {
11354            label: label.to_owned(),
11355            verdict,
11356            required,
11357            run: Some(run.to_owned()),
11358        };
11359        let got = rerunnable(&[
11360            check("passed", Verdict::Pass, Some(true), "1"),
11361            check("optional", Verdict::Fail, Some(false), "2"),
11362            check("required", Verdict::Fail, Some(true), "3"),
11363            check("unknown", Verdict::Fail, None, "4"),
11364        ]);
11365        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11366        assert_eq!(labels, ["required", "unknown"]);
11367    }
11368
11369    fn unrelated_ci_fixture() -> CiEvidence {
11370        let failure = CiFailure {
11371            path: "tests/web_render.rs".into(),
11372            start_line: 42,
11373            end_line: 42,
11374            title: "question_identity_disclosure_copy_and_live_updates".into(),
11375            message: "assertion failed".into(),
11376        };
11377        CiEvidence {
11378            head: "a".into(),
11379            base: "base-sha".into(),
11380            changed: vec![
11381                "AGENTS.md".into(),
11382                "src/talk.rs".into(),
11383                "tests/consult_investigation.rs".into(),
11384            ],
11385            checks: vec![CiCheckEvidence {
11386                label: "coverage".into(),
11387                head_check: 70,
11388                base_check: 60,
11389                app: 1,
11390                run: "7".into(),
11391                base_run: "6".into(),
11392                head_failures: vec![failure.clone()],
11393                base_failures: vec![failure],
11394                rerun_exhausted: true,
11395            }],
11396        }
11397    }
11398
11399    #[test]
11400    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11401        let good = unrelated_ci_fixture();
11402        let red = vec!["coverage".into()];
11403        assert!(good.unrelated("a", &red));
11404        assert!(!good.unrelated("another-head", &red));
11405        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11406        assert!(!good.unrelated("a", &[]));
11407        for mutation in 0..8 {
11408            let mut bad = good.clone();
11409            match mutation {
11410                0 => bad.checks[0].rerun_exhausted = false,
11411                1 => bad.checks[0].base_failures.clear(),
11412                2 => bad.checks[0].head_failures.clear(),
11413                3 => bad.changed.push("tests/web_render.rs".into()),
11414                4 => bad.changed.push(".github/workflows/ci.yml".into()),
11415                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11416                6 => bad.checks.push(bad.checks[0].clone()),
11417                _ => bad.base.clear(),
11418            }
11419            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11420        }
11421    }
11422
11423    #[test]
11424    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11425        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11426        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11427        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11428        assert!(matches!(
11429            decide(&pr, 2, 2, CHECKS_GRACE),
11430            Step::GiveUp { .. }
11431        ));
11432        let optional = CheckInfo {
11433            label: "coverage".into(),
11434            verdict: Verdict::Fail,
11435            required: Some(false),
11436            run: Some("7".into()),
11437        };
11438        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11439        assert_eq!(
11440            rerunnable_with(&[optional], true),
11441            vec![("coverage".into(), Some("7".into()))]
11442        );
11443    }
11444
11445    #[tokio::test]
11446    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11447        let mut state = landing_state();
11448        let mut red = coverage_unknown();
11449        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11450        red.pr.failing = vec!["coverage".into()];
11451        let forge = Scripted::new(vec![red], vec![]);
11452        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11453        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11454        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11455        assert!(forge.calls().contains(&"fix"));
11456        assert!(state.land_unrelated.is_some());
11457        assert!(state.parked);
11458        assert!(
11459            !state
11460                .events
11461                .iter()
11462                .any(|e| e.message.contains("fixer produced no commit"))
11463        );
11464    }
11465
11466    fn coverage_unknown() -> Seen {
11467        let mut s = red("a", Some("7"));
11468        s.pr.blocking = Blocking::Unsaid;
11469        s.merge_state = "UNKNOWN".into();
11470        s.pr.failing = vec!["coverage".into()];
11471        s.contexts[0].label = "coverage".into();
11472        s.contexts[0].required = Some(false);
11473        s
11474    }
11475
11476    #[tokio::test]
11477    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11478        let mut state = landing_state();
11479        let unknown = coverage_unknown();
11480        let mut unstable = unknown.clone();
11481        unstable.pr.blocking = Blocking::of("UNSTABLE");
11482        unstable.merge_state = "UNSTABLE".into();
11483        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11484        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11485        assert!(!forge.calls().contains(&"fix"));
11486        assert!(!forge.calls().contains(&"rerun"));
11487        assert_eq!(state.status, RunStatus::Merged);
11488        assert_eq!(state.pr.unwrap().round, 0);
11489    }
11490
11491    #[tokio::test]
11492    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11493        let mut state = landing_state();
11494        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
11495        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11496        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11497        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11498        assert!(!forge.calls().contains(&"fix"));
11499        assert!(state.parked);
11500        assert_eq!(state.status, RunStatus::Landing);
11501        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11502        let hold = state.land_unrelated.as_ref().unwrap();
11503        let q = ask::Questions::open().get(&hold.question).unwrap();
11504        assert!(
11505            q.actions
11506                .values()
11507                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
11508        );
11509        assert!(
11510            state
11511                .events
11512                .iter()
11513                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
11514        );
11515        let first = state.land_unsaid.clone();
11516        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
11517        state.parked = false;
11518        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11519        assert_eq!(state.land_unsaid, first);
11520        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11521    }
11522
11523    fn red(head: &str, run: Option<&str>) -> Seen {
11524        let mut s = seen(head, Checks::Red, "BLOCKED", false);
11525        s.pr.failing = vec!["test (macos)".to_owned()];
11526        s.contexts = vec![CheckInfo {
11527            label: "test (macos)".to_owned(),
11528            verdict: Verdict::Fail,
11529            required: Some(true),
11530            run: run.map(str::to_owned),
11531        }];
11532        s
11533    }
11534
11535    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
11536
11537    #[tokio::test]
11538    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
11539        let mut state = landing_state();
11540        let forge = Scripted::new(
11541            vec![
11542                red("a", Some("7")),
11543                seen("a", Checks::Pending, "BLOCKED", false),
11544                seen("a", Checks::Green, "CLEAN", false),
11545            ],
11546            vec![(true, "")],
11547        );
11548        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11549        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11550        assert!(!forge.calls().contains(&"fix"));
11551        assert_eq!(state.status, RunStatus::Merged);
11552        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11553        let argvs = forge.argvs();
11554        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
11555        assert!(
11556            state
11557                .events
11558                .iter()
11559                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
11560        );
11561    }
11562
11563    #[tokio::test]
11564    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
11565        let mut state = landing_state();
11566        let forge = Scripted::new(
11567            vec![
11568                red("a", Some("7")),
11569                seen("a", Checks::Green, "CLEAN", false),
11570            ],
11571            vec![(true, "")],
11572        );
11573        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11574        // The red view repeats for the grace, then the fixer is asked once.
11575        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11576        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
11577        let calls = forge.calls();
11578        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
11579        let fix_at = calls.iter().position(|c| *c == "fix");
11580        assert!(fix_at.is_none_or(|f| f > rerun_at));
11581    }
11582
11583    #[tokio::test]
11584    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
11585        let mut state = landing_state();
11586        let mut v = red("a", Some("7"));
11587        v.pr.checks = Checks::Pending;
11588        v.contexts.push(CheckInfo {
11589            label: "slow".to_owned(),
11590            verdict: Verdict::Pending,
11591            required: Some(true),
11592            run: Some("8".to_owned()),
11593        });
11594        let forge = Scripted::new(
11595            vec![v, seen("a", Checks::Green, "CLEAN", false)],
11596            vec![(true, "")],
11597        );
11598        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11599        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11600        assert_eq!(state.status, RunStatus::Merged);
11601    }
11602
11603    #[test]
11604    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
11605        let mut v = red("a", Some("7"));
11606        v.contexts.push(CheckInfo {
11607            label: "same run, still going".to_owned(),
11608            verdict: Verdict::Pending,
11609            required: Some(true),
11610            run: Some("7".to_owned()),
11611        });
11612        assert!(rerunnable(&v.contexts).is_empty());
11613    }
11614
11615    #[tokio::test]
11616    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
11617        let mut state = landing_state();
11618        state.config.graph.land_rounds = 0;
11619        let forge = Scripted::new(
11620            vec![
11621                red("a", Some("7")),
11622                seen("a", Checks::Green, "CLEAN", false),
11623            ],
11624            vec![(true, "")],
11625        );
11626        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11627        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11628        assert_eq!(state.status, RunStatus::Merged);
11629        assert!(!forge.calls().contains(&"fix"));
11630        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11631    }
11632
11633    #[tokio::test]
11634    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
11635        let mut state = landing_state();
11636        state.config.graph.land_rounds = 1;
11637        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
11638        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
11639        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11640        assert_eq!(pr.state, PrLifecycle::Open);
11641        assert_eq!(state.status, RunStatus::Blocked);
11642        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11643        assert!(
11644            state.merge_decision.is_none(),
11645            "no ordinary failure handoff"
11646        );
11647        assert!(forge.argvs().is_empty(), "no merge on outage");
11648
11649        let recovered = Scripted::new(
11650            vec![
11651                seen("a", Checks::Green, "CLEAN", true),
11652                seen("b", Checks::Green, "CLEAN", false),
11653            ],
11654            vec![(true, "")],
11655        );
11656        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
11657        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
11658        assert_eq!(state.status, RunStatus::Merged);
11659        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11660        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
11661    }
11662
11663    #[tokio::test]
11664    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
11665        let mut state = landing_state();
11666        state.config.graph.land_rounds = 1;
11667        let forge = Scripted::new(
11668            vec![
11669                seen("a", Checks::Green, "CLEAN", true),
11670                red("b", Some("7")),
11671                seen("b", Checks::Green, "CLEAN", false),
11672            ],
11673            vec![(true, "")],
11674        );
11675        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11676            head: "b".to_owned(),
11677        });
11678        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11679        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11680        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
11681        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11682        assert_eq!(state.status, RunStatus::Merged);
11683        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
11684        assert_eq!(
11685            value_of(&forge.argvs()[0], "--match-head-commit"),
11686            Some("b")
11687        );
11688    }
11689
11690    #[tokio::test]
11691    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
11692        let mut state = landing_state();
11693        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11694        *forge.rerun_fails.lock().unwrap() = true;
11695        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11696        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11697        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
11698        assert_eq!(
11699            forge.calls().iter().filter(|c| **c == "fix").count(),
11700            1,
11701            "{:?}",
11702            forge.calls()
11703        );
11704    }
11705
11706    #[tokio::test]
11707    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
11708        let mut state = landing_state();
11709        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11710        // The record was written just before the previous pass died.
11711        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
11712        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11713        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11714        assert!(forge.reruns.lock().unwrap().is_empty());
11715    }
11716
11717    #[tokio::test]
11718    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
11719        let mut state = landing_state();
11720        state.config.graph.rerun_flaky_checks = false;
11721        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11722        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11723        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11724        assert!(forge.reruns.lock().unwrap().is_empty());
11725        assert!(forge.calls().contains(&"fix"));
11726
11727        let mut state = landing_state();
11728        let forge = Scripted::new(vec![red("a", None)], vec![]);
11729        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11730        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11731        assert!(forge.reruns.lock().unwrap().is_empty());
11732        assert!(forge.calls().contains(&"fix"));
11733    }
11734
11735    fn names(xs: &[&str]) -> BTreeSet<String> {
11736        xs.iter().map(|x| (*x).to_owned()).collect()
11737    }
11738
11739    #[test]
11740    fn a_required_check_the_rollup_never_listed_is_named() {
11741        let req = names(&["build"]);
11742        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
11743        assert!(why.contains("never reported: build"), "{why}");
11744        assert!(!why.contains("probably waiting for a review"), "{why}");
11745    }
11746
11747    #[test]
11748    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
11749        let why = waiting_on("BLOCKED", &[passing("review")], None);
11750        assert!(why.contains("could not be read"), "{why}");
11751        assert!(!why.contains("probably waiting for a review"), "{why}");
11752    }
11753
11754    #[test]
11755    fn all_required_reported_keeps_the_review_guess() {
11756        let req = names(&["build"]);
11757        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11758        assert!(why.contains("probably waiting for a review"), "{why}");
11759        assert!(!why.contains("never reported"), "{why}");
11760    }
11761
11762    #[test]
11763    fn required_names_match_the_rollup_ignoring_case_only() {
11764        let req = names(&["Build"]);
11765        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11766        assert!(!why.contains("never reported"), "{why}");
11767    }
11768
11769    #[test]
11770    fn required_contexts_are_read_from_protection_and_rulesets() {
11771        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
11772        assert_eq!(
11773            parse_classic_required(classic),
11774            Some(names(&["build", "lint"]))
11775        );
11776        let rules = r#"[{"type":"pull_request","parameters":{}},
11777            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
11778        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
11779        assert_eq!(parse_ruleset_required("nope"), None);
11780        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
11781    }
11782
11783    #[test]
11784    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
11785        let shown = BTreeSet::new();
11786        let ok = seen("a", Checks::Green, "CLEAN", false);
11787        let guard = |s: Option<&Seen>| {
11788            direct_merge_is_safe(
11789                s,
11790                "A",
11791                &shown,
11792                0,
11793                4,
11794                Duration::ZERO,
11795                CiExpectation::Expected,
11796            )
11797        };
11798        assert!(guard(Some(&ok)));
11799        assert!(!guard(None));
11800        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
11801        let mut stale = ok.clone();
11802        stale.rollup_head = "old".to_owned();
11803        assert!(!guard(Some(&stale)));
11804        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
11805        assert!(!guard(Some(&merged_view("a"))));
11806    }
11807
11808    #[test]
11809    fn the_rollup_node_carries_whether_each_check_is_required() {
11810        let node = node_json("new", "SUCCESS", false)
11811            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
11812        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
11813        assert_eq!(s.contexts.len(), 1);
11814        assert_eq!(s.contexts[0].required, Some(true));
11815        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
11816        assert_eq!(s.contexts[0].required, None);
11817    }
11818
11819    #[tokio::test]
11820    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
11821        let mut state = landing_state();
11822        state.land_armed_head = Some("a".to_owned());
11823        let forge = Scripted::new(
11824            vec![seen("a", Checks::Green, "CLEAN", true)],
11825            vec![(false, "disable exploded")],
11826        );
11827        land_with(&mut state, URL, &forge).await.unwrap();
11828        assert!(!forge.calls().contains(&"fix"));
11829        assert_eq!(state.status, RunStatus::Blocked);
11830        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
11831        let why = state.merge.as_ref().unwrap().detail.clone();
11832        assert!(why.contains("disable exploded"), "{why}");
11833    }
11834}